-
Notifications
You must be signed in to change notification settings - Fork 977
/
tst_qfile.cpp
3868 lines (3338 loc) · 117 KB
/
tst_qfile.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2016 Intel Corporation.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qplatformdefs.h>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTemporaryDir>
#include <private/qabstractfileengine_p.h>
#include <private/qfsfileengine_p.h>
#include <private/qfilesystemengine_p.h>
#include "emulationdetector.h"
#ifdef Q_OS_WIN
QT_BEGIN_NAMESPACE
extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;
QT_END_NAMESPACE
#endif
#if !defined(QT_NO_NETWORK)
#include <QHostInfo>
#endif
#if QT_CONFIG(process)
# include <QProcess>
#endif
#ifdef Q_OS_WIN
# include <qt_windows.h>
#else
# include <sys/types.h>
# include <unistd.h>
#endif
#ifdef Q_OS_MAC
# include <sys/mount.h>
#elif defined(Q_OS_LINUX)
# include <sys/vfs.h>
#elif defined(Q_OS_FREEBSD)
# include <sys/param.h>
# include <sys/mount.h>
#elif defined(Q_OS_VXWORKS)
# include <fcntl.h>
#if defined(_WRS_KERNEL)
#undef QT_OPEN
#define QT_OPEN(path, oflag) ::open(path, oflag, 0)
#endif
#endif
#ifdef Q_OS_QNX
#ifdef open
#undef open
#endif
#endif
#include <stdio.h>
#include <errno.h>
#ifdef Q_OS_ANDROID
// Android introduces a braindamaged fileno macro that isn't
// compatible with the POSIX fileno or its own FILE type.
# undef fileno
#endif
#if defined(Q_OS_WIN)
#include "../../../network-settings.h"
#endif
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
#define STDERR_FILENO 2
#endif
#ifndef QT_OPEN_BINARY
#define QT_OPEN_BINARY 0
#endif
Q_DECLARE_METATYPE(QFile::FileError)
class StdioFileGuard
{
Q_DISABLE_COPY(StdioFileGuard)
public:
explicit StdioFileGuard(FILE *f = nullptr) : m_file(f) {}
~StdioFileGuard() { close(); }
operator FILE *() const { return m_file; }
void close();
private:
FILE * m_file;
};
void StdioFileGuard::close()
{
if (m_file != nullptr) {
fclose(m_file);
m_file = nullptr;
}
}
class tst_QFile : public QObject
{
Q_OBJECT
public:
tst_QFile();
private slots:
void init();
void cleanup();
void initTestCase();
void cleanupTestCase();
void exists();
void open_data();
void open();
void openUnbuffered();
void size_data();
void size();
void sizeNoExist();
void seek();
void setSize();
void setSizeSeek();
void atEnd();
void readLine();
void readLine2();
void readLineNullInLine();
void readAll_data();
void readAll();
void readAllBuffer();
void readAllStdin();
void readLineStdin();
void readLineStdin_lineByLine();
void text();
void missingEndOfLine();
void readBlock();
void getch();
void ungetChar();
void createFile();
void createFileNewOnly();
void openFileExistingOnly();
void append();
void permissions_data();
void permissions();
#ifdef Q_OS_WIN
void permissionsNtfs_data();
void permissionsNtfs();
#endif
void setPermissions();
void copy();
void copyAfterFail();
void copyRemovesTemporaryFile() const;
void copyShouldntOverwrite();
void copyFallback();
#ifndef Q_OS_WINRT
void link();
void linkToDir();
void absolutePathLinkToRelativePath();
void readBrokenLink();
#endif
void readTextFile_data();
void readTextFile();
void readTextFile2();
void writeTextFile_data();
void writeTextFile();
/* void largeFileSupport(); */
#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
void largeUncFileSupport();
#endif
void flush();
void bufferedRead();
#ifdef Q_OS_UNIX
void isSequential();
#endif
void encodeName();
void truncate();
void seekToPos();
void seekAfterEndOfFile();
void FILEReadWrite();
void i18nFileName_data();
void i18nFileName();
void longFileName_data();
void longFileName();
void fileEngineHandler();
#ifdef QT_BUILD_INTERNAL
void useQFileInAFileHandler();
#endif
void getCharFF();
void remove_and_exists();
void removeOpenFile();
void fullDisk();
void writeLargeDataBlock_data();
void writeLargeDataBlock();
void readFromWriteOnlyFile();
void writeToReadOnlyFile();
#if defined(Q_OS_LINUX) || defined(Q_OS_AIX) || defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD)
void virtualFile();
#endif
void textFile();
void rename_data();
void rename();
void renameWithAtEndSpecialFile() const;
void renameFallback();
void renameMultiple();
void appendAndRead();
void miscWithUncPathAsCurrentDir();
void standarderror();
void handle();
void nativeHandleLeaks();
void readEof_data();
void readEof();
void map_data();
void map();
void mapResource_data();
void mapResource();
void mapOpenMode_data();
void mapOpenMode();
void mapWrittenFile_data();
void mapWrittenFile();
void openStandardStreamsFileDescriptors();
void openStandardStreamsBufferedStreams();
void resize_data();
void resize();
void objectConstructors();
void caseSensitivity();
void autocloseHandle();
void posAfterFailedStat();
void openDirectory();
void writeNothing();
void invalidFile_data();
void invalidFile();
void reuseQFile();
void moveToTrash_data();
void moveToTrash();
void stdfilesystem();
private:
#ifdef BUILTIN_TESTDATA
QSharedPointer<QTemporaryDir> m_dataDir;
#endif
enum FileType {
OpenQFile,
OpenFd,
OpenStream,
NumberOfFileTypes
};
bool openFd(QFile &file, QIODevice::OpenMode mode, QFile::FileHandleFlags handleFlags)
{
int fdMode = QT_OPEN_LARGEFILE | QT_OPEN_BINARY;
// File will be truncated if in Write mode.
if (mode & QIODevice::WriteOnly)
fdMode |= QT_OPEN_WRONLY | QT_OPEN_TRUNC;
if (mode & QIODevice::ReadOnly)
fdMode |= QT_OPEN_RDONLY;
fd_ = QT_OPEN(qPrintable(file.fileName()), fdMode);
return (-1 != fd_) && file.open(fd_, mode, handleFlags);
}
bool openStream(QFile &file, QIODevice::OpenMode mode, QFile::FileHandleFlags handleFlags)
{
char const *streamMode = "";
// File will be truncated if in Write mode.
if (mode & QIODevice::WriteOnly)
streamMode = "wb+";
else if (mode & QIODevice::ReadOnly)
streamMode = "rb";
stream_ = QT_FOPEN(qPrintable(file.fileName()), streamMode);
return stream_ && file.open(stream_, mode, handleFlags);
}
bool openFile(QFile &file, QIODevice::OpenMode mode, FileType type = OpenQFile, QFile::FileHandleFlags handleFlags = QFile::DontCloseHandle)
{
if (mode & QIODevice::WriteOnly && !file.exists())
{
// Make sure the file exists
QFile createFile(file.fileName());
if (!createFile.open(QIODevice::ReadWrite))
return false;
}
// Note: openFd and openStream will truncate the file if write mode.
switch (type)
{
case OpenQFile:
return file.open(mode);
case OpenFd:
return openFd(file, mode, handleFlags);
case OpenStream:
return openStream(file, mode, handleFlags);
case NumberOfFileTypes:
break;
}
return false;
}
void closeFile(QFile &file)
{
file.close();
if (-1 != fd_)
QT_CLOSE(fd_);
if (stream_)
::fclose(stream_);
fd_ = -1;
stream_ = 0;
}
int fd_;
FILE *stream_;
QTemporaryDir m_temporaryDir;
const QString m_oldDir;
QString m_stdinProcess;
QString m_testSourceFile;
QString m_testLogFile;
QString m_dosFile;
QString m_forCopyingFile;
QString m_forRenamingFile;
QString m_twoDotsFile;
QString m_testFile;
QString m_resourcesDir;
QString m_noEndOfLineFile;
};
static const char noReadFile[] = "noreadfile";
static const char readOnlyFile[] = "readonlyfile";
void tst_QFile::init()
{
fd_ = -1;
stream_ = 0;
}
void tst_QFile::cleanup()
{
if (-1 != fd_)
QT_CLOSE(fd_);
fd_ = -1;
if (stream_)
::fclose(stream_);
stream_ = 0;
// Windows UNC tests set a different working directory which might not be restored on failures.
if (QDir::currentPath() != m_temporaryDir.path())
QVERIFY(QDir::setCurrent(m_temporaryDir.path()));
// Clean out everything except the readonly-files.
const QDir dir(m_temporaryDir.path());
foreach (const QFileInfo &fi, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
const QString fileName = fi.fileName();
if (fileName != QLatin1String(noReadFile) && fileName != QLatin1String(readOnlyFile)) {
const QString absoluteFilePath = fi.absoluteFilePath();
if (fi.isDir() && !fi.isSymLink()) {
QDir remainingDir(absoluteFilePath);
QVERIFY2(remainingDir.removeRecursively(), qPrintable(absoluteFilePath));
} else {
if (!(QFile::permissions(absoluteFilePath) & QFile::WriteUser))
QVERIFY2(QFile::setPermissions(absoluteFilePath, QFile::WriteUser), qPrintable(absoluteFilePath));
QVERIFY2(QFile::remove(absoluteFilePath), qPrintable(absoluteFilePath));
}
}
}
}
tst_QFile::tst_QFile() : m_oldDir(QDir::currentPath())
{
}
static QByteArray msgOpenFailed(QIODevice::OpenMode om, const QFile &file)
{
QString result;
QDebug(&result).noquote().nospace() << "Could not open \""
<< QDir::toNativeSeparators(file.fileName()) << "\" using "
<< om << ": " << file.errorString();
return result.toLocal8Bit();
}
static QByteArray msgOpenFailed(const QFile &file)
{
return (QLatin1String("Could not open \"") + QDir::toNativeSeparators(file.fileName())
+ QLatin1String("\": ") + file.errorString()).toLocal8Bit();
}
static QByteArray msgFileDoesNotExist(const QString &name)
{
return (QLatin1Char('"') + QDir::toNativeSeparators(name)
+ QLatin1String("\" does not exist.")).toLocal8Bit();
}
void tst_QFile::initTestCase()
{
QVERIFY2(m_temporaryDir.isValid(), qPrintable(m_temporaryDir.errorString()));
#if QT_CONFIG(process)
#if defined(Q_OS_ANDROID)
m_stdinProcess = QCoreApplication::applicationDirPath() + QLatin1String("/libstdinprocess_helper.so");
#elif defined(Q_OS_WIN)
m_stdinProcess = QFINDTESTDATA("stdinprocess_helper.exe");
#else
m_stdinProcess = QFINDTESTDATA("stdinprocess_helper");
#endif
QVERIFY(!m_stdinProcess.isEmpty());
#endif
m_testLogFile = QFINDTESTDATA("testlog.txt");
QVERIFY(!m_testLogFile.isEmpty());
m_dosFile = QFINDTESTDATA("dosfile.txt");
QVERIFY(!m_dosFile.isEmpty());
m_forCopyingFile = QFINDTESTDATA("forCopying.txt");
QVERIFY(!m_forCopyingFile .isEmpty());
m_forRenamingFile = QFINDTESTDATA("forRenaming.txt");
QVERIFY(!m_forRenamingFile.isEmpty());
m_twoDotsFile = QFINDTESTDATA("two.dots.file");
QVERIFY(!m_twoDotsFile.isEmpty());
#ifndef BUILTIN_TESTDATA
m_testSourceFile = QFINDTESTDATA("tst_qfile.cpp");
QVERIFY(!m_testSourceFile.isEmpty());
m_testFile = QFINDTESTDATA("testfile.txt");
QVERIFY(!m_testFile.isEmpty());
m_resourcesDir = QFINDTESTDATA("resources");
QVERIFY(!m_resourcesDir.isEmpty());
#else
m_dataDir = QEXTRACTTESTDATA("/");
QVERIFY2(!m_dataDir.isNull(), qPrintable("Could not extract test data"));
m_testFile = m_dataDir->path() + "/testfile.txt";
m_testSourceFile = m_dataDir->path() + "/tst_qfile.cpp";
m_resourcesDir = m_dataDir->path() + "/resources";
#endif
m_noEndOfLineFile = QFINDTESTDATA("noendofline.txt");
QVERIFY(!m_noEndOfLineFile.isEmpty());
QVERIFY(QDir::setCurrent(m_temporaryDir.path()));
// create a file and make it read-only
QFile file(QString::fromLatin1(readOnlyFile));
QVERIFY2(file.open(QFile::WriteOnly), msgOpenFailed(file).constData());
file.write("a", 1);
file.close();
QVERIFY2(file.setPermissions(QFile::ReadOwner), qPrintable(file.errorString()));
// create another file and make it not readable
file.setFileName(QString::fromLatin1(noReadFile));
QVERIFY2(file.open(QFile::WriteOnly), msgOpenFailed(file).constData());
file.write("b", 1);
file.close();
#ifndef Q_OS_WIN // Not supported on Windows.
QVERIFY2(file.setPermissions({ }), qPrintable(file.errorString()));
#else
QVERIFY2(file.open(QFile::WriteOnly), msgOpenFailed(file).constData());
#endif
}
void tst_QFile::cleanupTestCase()
{
QFile file(QString::fromLatin1(readOnlyFile));
QVERIFY(file.setPermissions(QFile::ReadOwner | QFile::WriteOwner));
file.setFileName(QString::fromLatin1(noReadFile));
QVERIFY(file.setPermissions(QFile::ReadOwner | QFile::WriteOwner));
QVERIFY(QDir::setCurrent(m_oldDir)); //release test directory for removal
}
//------------------------------------------
// The 'testfile' is currently just a
// testfile. The path of this file, the
// attributes and the contents itself
// will be changed as far as we have a
// proper way to handle files in the
// testing environment.
//------------------------------------------
void tst_QFile::exists()
{
QFile f( m_testFile );
QVERIFY2(f.exists(), msgFileDoesNotExist(m_testFile));
QFile file("nobodyhassuchafile");
file.remove();
QVERIFY(!file.exists());
QFile file2("nobodyhassuchafile");
QVERIFY2(file2.open(QIODevice::WriteOnly), msgOpenFailed(file2).constData());
file2.close();
QVERIFY(file.exists());
QVERIFY2(file.open(QIODevice::WriteOnly), msgOpenFailed(file).constData());
file.close();
QVERIFY(file.exists());
file.remove();
QVERIFY(!file.exists());
#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
const QString uncPath = "//" + QtNetworkSettings::winServerName() + "/testshare/readme.txt";
QFile unc(uncPath);
QVERIFY2(unc.exists(), msgFileDoesNotExist(uncPath).constData());
#endif
QTest::ignoreMessage(QtWarningMsg, "Broken filename passed to function");
QVERIFY(!QFile::exists(QDir::currentPath() + QLatin1Char('/') +
QChar(QChar::Null) + QLatin1String("x/y")));
}
void tst_QFile::open_data()
{
QTest::addColumn<QString>("filename");
QTest::addColumn<int>("mode");
QTest::addColumn<bool>("ok");
QTest::addColumn<QFile::FileError>("status");
QTest::newRow( "exist_readOnly" )
<< m_testFile << int(QIODevice::ReadOnly)
<< true << QFile::NoError;
QTest::newRow( "exist_writeOnly" )
<< QString::fromLatin1(readOnlyFile)
<< int(QIODevice::WriteOnly)
<< false
<< QFile::OpenError;
QTest::newRow( "exist_append" )
<< QString::fromLatin1(readOnlyFile) << int(QIODevice::Append)
<< false << QFile::OpenError;
QTest::newRow( "nonexist_readOnly" )
<< QString("nonExist.txt") << int(QIODevice::ReadOnly)
<< false << QFile::OpenError;
QTest::newRow("emptyfile")
<< QString("")
<< int(QIODevice::ReadOnly)
<< false
<< QFile::OpenError;
QTest::newRow("nullfile") << QString() << int(QIODevice::ReadOnly) << false
<< QFile::OpenError;
QTest::newRow("two-dots") << m_twoDotsFile << int(QIODevice::ReadOnly) << true
<< QFile::NoError;
QTest::newRow("readonlyfile") << QString::fromLatin1(readOnlyFile) << int(QIODevice::WriteOnly)
<< false << QFile::OpenError;
QTest::newRow("noreadfile") << QString::fromLatin1(noReadFile) << int(QIODevice::ReadOnly)
<< false << QFile::OpenError;
QTest::newRow("resource_file") << QString::fromLatin1(":/does/not/exist")
<< int(QIODevice::ReadOnly)
<< false
<< QFile::OpenError;
#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
//opening devices requires administrative privileges (and elevation).
HANDLE hTest = CreateFile(_T("\\\\.\\PhysicalDrive0"), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hTest != INVALID_HANDLE_VALUE) {
CloseHandle(hTest);
QTest::newRow("//./PhysicalDrive0") << QString("//./PhysicalDrive0") << int(QIODevice::ReadOnly)
<< true << QFile::NoError;
} else {
QTest::newRow("//./PhysicalDrive0") << QString("//./PhysicalDrive0") << int(QIODevice::ReadOnly)
<< false << QFile::OpenError;
}
QTest::newRow("uncFile") << "//" + QtNetworkSettings::winServerName() + "/testshare/test.pri" << int(QIODevice::ReadOnly)
<< true << QFile::NoError;
#endif
}
void tst_QFile::open()
{
QFETCH( QString, filename );
QFETCH( int, mode );
QFile f( filename );
QFETCH( bool, ok );
#if defined(Q_OS_UNIX) && !defined(Q_OS_VXWORKS)
if (::getuid() == 0)
// root and Chuck Norris don't care for file permissions. Skip.
QSKIP("Running this test as root doesn't make sense");
#endif
#if defined(Q_OS_WIN32) || defined(Q_OS_WINRT)
QEXPECT_FAIL("noreadfile", "Windows does not currently support non-readable files.", Abort);
#endif
if (filename.isEmpty())
QTest::ignoreMessage(QtWarningMsg, "QFSFileEngine::open: No file name specified");
const QIODevice::OpenMode om(mode);
const bool succeeded = f.open(om);
if (ok)
QVERIFY2(succeeded, msgOpenFailed(om, f).constData());
else
QVERIFY(!succeeded);
QTEST( f.error(), "status" );
}
void tst_QFile::openUnbuffered()
{
QFile file(m_testFile);
QVERIFY2(file.open(QIODevice::ReadOnly | QIODevice::Unbuffered), msgOpenFailed(file).constData());
char c = '\0';
QVERIFY(file.seek(1));
QCOMPARE(file.pos(), qint64(1));
QVERIFY(file.getChar(&c));
QCOMPARE(file.pos(), qint64(2));
char d = '\0';
QVERIFY(file.seek(3));
QCOMPARE(file.pos(), qint64(3));
QVERIFY(file.getChar(&d));
QCOMPARE(file.pos(), qint64(4));
QVERIFY(file.seek(1));
QCOMPARE(file.pos(), qint64(1));
char c2 = '\0';
QVERIFY(file.getChar(&c2));
QCOMPARE(file.pos(), qint64(2));
QVERIFY(file.seek(3));
QCOMPARE(file.pos(), qint64(3));
char d2 = '\0';
QVERIFY(file.getChar(&d2));
QCOMPARE(file.pos(), qint64(4));
QCOMPARE(c, c2);
QCOMPARE(d, d2);
QCOMPARE(c, '-');
QCOMPARE(d, '-');
}
void tst_QFile::size_data()
{
QTest::addColumn<QString>("filename");
QTest::addColumn<qint64>("size");
QTest::newRow( "exist01" ) << m_testFile << (qint64)245;
#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
// Only test UNC on Windows./
QTest::newRow("unc") << "//" + QString(QtNetworkSettings::winServerName() + "/testshare/test.pri") << (qint64)34;
#endif
}
void tst_QFile::size()
{
QFETCH( QString, filename );
QFETCH( qint64, size );
{
QFile f( filename );
QCOMPARE( f.size(), size );
QVERIFY2(f.open(QIODevice::ReadOnly), msgOpenFailed(f).constData());
QCOMPARE( f.size(), size );
}
{
StdioFileGuard stream(QT_FOPEN(filename.toLocal8Bit().constData(), "rb"));
QVERIFY( stream );
QFile f;
QVERIFY( f.open(stream, QIODevice::ReadOnly) );
QCOMPARE( f.size(), size );
f.close();
}
{
QFile f;
int fd = QT_OPEN(filename.toLocal8Bit().constData(), QT_OPEN_RDONLY);
QVERIFY( fd != -1 );
QVERIFY( f.open(fd, QIODevice::ReadOnly) );
QCOMPARE( f.size(), size );
f.close();
QT_CLOSE(fd);
}
}
void tst_QFile::sizeNoExist()
{
QFile file("nonexist01");
QVERIFY( !file.exists() );
QCOMPARE( file.size(), (qint64)0 );
QVERIFY( !file.open(QIODevice::ReadOnly) );
}
void tst_QFile::seek()
{
QFile file("newfile.txt");
QVERIFY2(file.open(QIODevice::WriteOnly), msgOpenFailed(file).constData());
QCOMPARE(file.size(), qint64(0));
QCOMPARE(file.pos(), qint64(0));
QVERIFY(file.seek(10));
QCOMPARE(file.pos(), qint64(10));
QCOMPARE(file.size(), qint64(0));
file.close();
}
void tst_QFile::setSize()
{
QFile f("createme.txt");
QVERIFY2(f.open(QIODevice::Truncate | QIODevice::ReadWrite), msgOpenFailed(f).constData());
f.putChar('a');
f.seek(0);
char c = '\0';
f.getChar(&c);
QCOMPARE(c, 'a');
QCOMPARE(f.size(), (qlonglong)1);
bool ok = f.resize(99);
QVERIFY(ok);
QCOMPARE(f.size(), (qlonglong)99);
f.seek(0);
c = '\0';
f.getChar(&c);
QCOMPARE(c, 'a');
QVERIFY(f.resize(1));
QCOMPARE(f.size(), (qlonglong)1);
f.seek(0);
c = '\0';
f.getChar(&c);
QCOMPARE(c, 'a');
f.close();
QCOMPARE(f.size(), (qlonglong)1);
QVERIFY(f.resize(100));
QCOMPARE(f.size(), (qlonglong)100);
QVERIFY(f.resize(50));
QCOMPARE(f.size(), (qlonglong)50);
}
void tst_QFile::setSizeSeek()
{
QFile f("setsizeseek.txt");
QVERIFY2(f.open(QFile::WriteOnly), msgOpenFailed(f).constData());
f.write("ABCD");
QCOMPARE(f.pos(), qint64(4));
f.resize(2);
QCOMPARE(f.pos(), qint64(2));
f.resize(4);
QCOMPARE(f.pos(), qint64(2));
f.resize(0);
QCOMPARE(f.pos(), qint64(0));
f.resize(4);
QCOMPARE(f.pos(), qint64(0));
f.seek(3);
QCOMPARE(f.pos(), qint64(3));
f.resize(2);
QCOMPARE(f.pos(), qint64(2));
}
void tst_QFile::atEnd()
{
QFile f( m_testFile );
QVERIFY2(f.open(QFile::ReadOnly), msgOpenFailed(f).constData());
int size = f.size();
f.seek( size );
bool end = f.atEnd();
f.close();
QVERIFY(end);
}
void tst_QFile::readLine()
{
QFile f( m_testFile );
QVERIFY2(f.open(QFile::ReadOnly), msgOpenFailed(f).constData());
int i = 0;
char p[128];
int foo;
while ( (foo=f.readLine( p, 128 )) > 0 ) {
++i;
if ( i == 5 ) {
QCOMPARE( p[0], 'T' );
QCOMPARE( p[3], 's' );
QCOMPARE( p[11], 'i' );
}
}
f.close();
QCOMPARE( i, 6 );
}
void tst_QFile::readLine2()
{
QFile f( m_testFile );
QVERIFY2(f.open(QFile::ReadOnly), msgOpenFailed(f).constData());
char p[128];
QCOMPARE(f.readLine(p, 60), qlonglong(59));
QCOMPARE(f.readLine(p, 60), qlonglong(59));
memset(p, '@', sizeof(p));
QCOMPARE(f.readLine(p, 60), qlonglong(59));
QCOMPARE(p[57], '-');
QCOMPARE(p[58], '\n');
QCOMPARE(p[59], '\0');
QCOMPARE(p[60], '@');
}
void tst_QFile::readLineNullInLine()
{
QFile::remove("nullinline.txt");
QFile file("nullinline.txt");
QVERIFY2(file.open(QFile::ReadWrite), msgOpenFailed(file).constData());
QVERIFY(file.write("linewith\0null\nanotherline\0withnull\n\0\nnull\0", 42) > 0);
QVERIFY(file.flush());
file.reset();
QCOMPARE(file.readLine(), QByteArray("linewith\0null\n", 14));
QCOMPARE(file.readLine(), QByteArray("anotherline\0withnull\n", 21));
QCOMPARE(file.readLine(), QByteArray("\0\n", 2));
QCOMPARE(file.readLine(), QByteArray("null\0", 5));
QCOMPARE(file.readLine(), QByteArray());
}
void tst_QFile::readAll_data()
{
QTest::addColumn<bool>("textMode");
QTest::addColumn<QString>("fileName");
QTest::newRow( "TextMode unixfile" ) << true << m_testFile;
QTest::newRow( "BinaryMode unixfile" ) << false << m_testFile;
QTest::newRow( "TextMode dosfile" ) << true << m_dosFile;
QTest::newRow( "BinaryMode dosfile" ) << false << m_dosFile;
QTest::newRow( "TextMode bigfile" ) << true << m_testSourceFile;
QTest::newRow( "BinaryMode bigfile" ) << false << m_testSourceFile;
QVERIFY(QFile(m_testSourceFile).size() > 64*1024);
}
void tst_QFile::readAll()
{
QFETCH( bool, textMode );
QFETCH( QString, fileName );
QFile file(fileName);
const QIODevice::OpenMode om = textMode ? (QFile::Text | QFile::ReadOnly) : QFile::ReadOnly;
QVERIFY2(file.open(om), msgOpenFailed(om, file).constData());
QByteArray a = file.readAll();
file.reset();
QCOMPARE(file.pos(), 0);
QVERIFY(file.bytesAvailable() > 7);
QByteArray b = file.read(1);
char x;
file.getChar(&x);
b.append(x);
b.append(file.read(5));
b.append(file.readAll());
QCOMPARE(a, b);
}
void tst_QFile::readAllBuffer()
{
QString fileName = QLatin1String("readAllBuffer.txt");
QFile::remove(fileName);
QFile writer(fileName);
QFile reader(fileName);
QByteArray data1("This is arguably a very simple text.");
QByteArray data2("This is surely not as simple a test.");
QVERIFY2(writer.open(QIODevice::ReadWrite | QIODevice::Unbuffered), msgOpenFailed(writer).constData());
QVERIFY2(reader.open(QIODevice::ReadOnly), msgOpenFailed(reader).constData());
QCOMPARE( writer.write(data1), qint64(data1.size()) );
QVERIFY( writer.seek(0) );
QByteArray result;
result = reader.read(18);
QCOMPARE( result.size(), 18 );
QCOMPARE( writer.write(data2), qint64(data2.size()) ); // new data, old version buffered in reader
QCOMPARE( writer.write(data2), qint64(data2.size()) ); // new data, unbuffered in reader
result += reader.readAll();
QCOMPARE( result, data1 + data2 );
QFile::remove(fileName);
}
#if QT_CONFIG(process)
class StdinReaderProcessGuard { // Ensure the stdin reader process is stopped on destruction.
Q_DISABLE_COPY(StdinReaderProcessGuard)
public:
StdinReaderProcessGuard(QProcess *p) : m_process(p) {}
~StdinReaderProcessGuard() { stop(); }
bool stop(int msecs = 30000)
{
if (m_process->state() != QProcess::Running)
return true;
m_process->closeWriteChannel();
if (m_process->waitForFinished(msecs))
return m_process->exitStatus() == QProcess::NormalExit && !m_process->exitCode();
m_process->terminate();
if (!m_process->waitForFinished())
m_process->kill();
return false;
}
private:
QProcess *m_process;
};
#endif // QT_CONFIG(process)
void tst_QFile::readAllStdin()
{
#if !QT_CONFIG(process)
QSKIP("No qprocess support", SkipAll);
#else
#if defined(Q_OS_ANDROID)
QSKIP("This test crashes when doing nanosleep. See QTBUG-69034.");
#endif
QByteArray lotsOfData(1024, '@'); // 10 megs
QProcess process;
StdinReaderProcessGuard processGuard(&process);
process.start(m_stdinProcess, QStringList(QStringLiteral("all")));
QVERIFY2(process.waitForStarted(), qPrintable(process.errorString()));
for (int i = 0; i < 5; ++i) {
QTest::qWait(1000);
process.write(lotsOfData);
while (process.bytesToWrite() > 0)
QVERIFY(process.waitForBytesWritten());
}
QVERIFY(processGuard.stop());
QCOMPARE(process.readAll().size(), lotsOfData.size() * 5);
#endif