summaryrefslogtreecommitdiffstats
path: root/tests/auto/qbuffer/tst_qbuffer.cpp
blob: 5df6cb90d921e3d217e0068dd0651697f207062a (plain)
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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/


#include <QtTest/QtTest>


#include <QBuffer>
#include <QByteArray>

//TESTED_CLASS=
//TESTED_FILES=

class tst_QBuffer : public QObject
{
    Q_OBJECT
public:
    tst_QBuffer();

private slots:
    void getSetCheck();
    void readBlock();
    void readBlockPastEnd();
    void writeBlock_data();
    void writeBlock();
    void seek();
    void seekTest_data();
    void seekTest();
    void read_rawdata();
    void isSequential();
    void signalTest_data();
    void signalTest();
    void isClosedAfterClose();
    void readLine_data();
    void readLine();
    void canReadLine_data();
    void canReadLine();
    void atEnd();
    void readLineBoundaries();
    void writeAfterQByteArrayResize();

protected slots:
    void readyReadSlot();
    void bytesWrittenSlot(qint64 written);

private:
    qint64 totalBytesWritten;
    bool gotReadyRead;
};

// Testing get/set functions
void tst_QBuffer::getSetCheck()
{
    QBuffer obj1;
    // const QByteArray & QBuffer::data()
    // void QBuffer::setData(const QByteArray &)
    QByteArray var1("Bogus data");
    obj1.setData(var1);
    QCOMPARE(var1, obj1.data());
    obj1.setData(QByteArray());
    QCOMPARE(QByteArray(), obj1.data());
}

tst_QBuffer::tst_QBuffer()
{
}

// some status() tests, too
void tst_QBuffer::readBlock()
{
//    QTest::ignoreMessage(QtWarningMsg, "QIODevice::read: File not open");
//    QTest::ignoreMessage(QtWarningMsg, "QIODevice::read: Read operation not permitted");

    const int arraySize = 10;
    char a[arraySize];
    QBuffer b;
    QCOMPARE(b.read(a, arraySize), (qint64) -1); // not opened
    QVERIFY(b.atEnd());

    QByteArray ba;
    ba.resize(arraySize);
    b.setBuffer(&ba);
    b.open(QIODevice::WriteOnly);
    QTest::ignoreMessage(QtWarningMsg, "QIODevice::read: WriteOnly device");
    QCOMPARE(b.read(a, arraySize), (qint64) -1); // no read access
    b.close();

    b.open(QIODevice::ReadOnly);
    QCOMPARE(b.read(a, arraySize), (qint64) arraySize);
    QVERIFY(b.atEnd());

    // up to 3.0.x reading beyond the end was an error while ok
    // this has been made consistent with other QIODevice sub classes in 3.1
    QCOMPARE(b.read(a, 1), qint64(0));
    QVERIFY(b.atEnd());

    // read in two chunks
    b.close();
    b.open(QIODevice::ReadOnly);
    QCOMPARE(b.read(a, arraySize/2), (qint64) arraySize/2);
    QCOMPARE(b.read(a + arraySize/2, arraySize - arraySize/2),
            (qint64)(arraySize - arraySize/2));
    QVERIFY(b.atEnd());
}

void tst_QBuffer::readBlockPastEnd()
{
    QByteArray arr(4096 + 3616, 'd');
    QBuffer buf(&arr);

    buf.open(QIODevice::ReadOnly);
    char dummy[4096];

    buf.read(1);

    QCOMPARE(buf.read(dummy, 4096), qint64(4096));
    QCOMPARE(buf.read(dummy, 4096), qint64(3615));
    QVERIFY(buf.atEnd());
}

void tst_QBuffer::writeBlock_data()
{
    QTest::addColumn<QString>("str");

    QTest::newRow( "small_bytearray" ) << QString("Test");
    QTest::newRow( "large_bytearray" ) << QString("The QBuffer class is an I/O device that operates on a QByteArray.\n"
				       "QBuffer is used to read and write to a memory buffer. It is normally "
				       "used with a QTextStream or a QDataStream. QBuffer has an associated "
				       "QByteArray which holds the buffer data. The size() of the buffer is "
				       "automatically adjusted as data is written.\n"
				       "The constructor QBuffer(QByteArray) creates a QBuffer using an existing "
				       "byte array. The byte array can also be set with setBuffer(). Writing to "
				       "the QBuffer will modify the original byte array because QByteArray is "
				       "explicitly shared.\n"
				       "Use open() to open the buffer before use and to set the mode (read-only, "
				       "write-only, etc.). close() closes the buffer. The buffer must be closed "
				       "before reopening or calling setBuffer().\n"
				       "A common way to use QBuffer is through QDataStream or QTextStream, which "
				       "have constructors that take a QBuffer parameter. For convenience, there "
				       "are also QDataStream and QTextStream constructors that take a QByteArray "
				       "parameter. These constructors create and open an internal QBuffer.\n"
				       "Note that QTextStream can also operate on a QString (a Unicode string); a "
				       "QBuffer cannot.\n"
				       "You can also use QBuffer directly through the standard QIODevice functions "
				       "readBlock(), writeBlock() readLine(), at(), getch(), putch() and ungetch().\n"
				       "See also QFile, QDataStream, QTextStream, QByteArray, Shared Classes, Collection "
				       "Classes and Input/Output and Networking.\n\n"
				       "The QBuffer class is an I/O device that operates on a QByteArray.\n"
				       "QBuffer is used to read and write to a memory buffer. It is normally "
				       "used with a QTextStream or a QDataStream. QBuffer has an associated "
				       "QByteArray which holds the buffer data. The size() of the buffer is "
				       "automatically adjusted as data is written.\n"
				       "The constructor QBuffer(QByteArray) creates a QBuffer using an existing "
				       "byte array. The byte array can also be set with setBuffer(). Writing to "
				       "the QBuffer will modify the original byte array because QByteArray is "
				       "explicitly shared.\n"
				       "Use open() to open the buffer before use and to set the mode (read-only, "
				       "write-only, etc.). close() closes the buffer. The buffer must be closed "
				       "before reopening or calling setBuffer().\n"
				       "A common way to use QBuffer is through QDataStream or QTextStream, which "
				       "have constructors that take a QBuffer parameter. For convenience, there "
				       "are also QDataStream and QTextStream constructors that take a QByteArray "
				       "parameter. These constructors create and open an internal QBuffer.\n"
				       "Note that QTextStream can also operate on a QString (a Unicode string); a "
				       "QBuffer cannot.\n"
				       "You can also use QBuffer directly through the standard QIODevice functions "
				       "readBlock(), writeBlock() readLine(), at(), getch(), putch() and ungetch().\n"
				       "See also QFile, QDataStream, QTextStream, QByteArray, Shared Classes, Collection "
				       "Classes and Input/Output and Networking.\n\n"
				       "The QBuffer class is an I/O device that operates on a QByteArray.\n"
				       "QBuffer is used to read and write to a memory buffer. It is normally "
				       "used with a QTextStream or a QDataStream. QBuffer has an associated "
				       "QByteArray which holds the buffer data. The size() of the buffer is "
				       "automatically adjusted as data is written.\n"
				       "The constructor QBuffer(QByteArray) creates a QBuffer using an existing "
				       "byte array. The byte array can also be set with setBuffer(). Writing to "
				       "the QBuffer will modify the original byte array because QByteArray is "
				       "explicitly shared.\n"
				       "Use open() to open the buffer before use and to set the mode (read-only, "
				       "write-only, etc.). close() closes the buffer. The buffer must be closed "
				       "before reopening or calling setBuffer().\n"
				       "A common way to use QBuffer is through QDataStream or QTextStream, which "
				       "have constructors that take a QBuffer parameter. For convenience, there "
				       "are also QDataStream and QTextStream constructors that take a QByteArray "
				       "parameter. These constructors create and open an internal QBuffer.\n"
				       "Note that QTextStream can also operate on a QString (a Unicode string); a "
				       "QBuffer cannot.\n"
				       "You can also use QBuffer directly through the standard QIODevice functions "
				       "readBlock(), writeBlock() readLine(), at(), getch(), putch() and ungetch().\n"
				       "See also QFile, QDataStream, QTextStream, QByteArray, Shared Classes, Collection "
				       "Classes and Input/Output and Networking.");
}

void tst_QBuffer::writeBlock()
{
    QFETCH( QString, str );

    QByteArray ba;
    QBuffer buf( &ba );
    buf.open(QIODevice::ReadWrite);
    QByteArray data = str.toLatin1();
    QCOMPARE(buf.write( data.constData(), data.size() ), qint64(data.size()));

    QCOMPARE(buf.data(), str.toLatin1());
}

void tst_QBuffer::seek()
{
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);
    QCOMPARE(buffer.size(), qint64(0));
    QCOMPARE(buffer.pos(), qint64(0));
    const qint64 pos = 10;
    QVERIFY(buffer.seek(pos));
    QCOMPARE(buffer.size(), pos);
}

void tst_QBuffer::seekTest_data()
{
    writeBlock_data();
}

#define DO_VALID_SEEK(position) {                                            \
    char c;                                                                  \
    QVERIFY(buf.seek(qint64(position)));                                      \
    QCOMPARE(buf.pos(), qint64(position));                                    \
    QVERIFY(buf.getChar(&c));                                                 \
    QCOMPARE(QChar(c), str.at(qint64(position)));                             \
}
#define DO_INVALID_SEEK(position) {                                          \
    qint64 prev_pos = buf.pos();                                             \
    QVERIFY(!buf.seek(qint64(position)));                                     \
    QCOMPARE(buf.pos(), prev_pos); /* position should not be changed */                  \
}

void tst_QBuffer::seekTest()
{
    QFETCH(QString, str);

    QByteArray ba;
    QBuffer buf(&ba);
#if 0
    QCOMPARE(buf.pos(), qint64(-1));
#endif
    buf.open(QIODevice::ReadWrite);
    QCOMPARE(buf.pos(), qint64(0));

    QByteArray data = str.toLatin1();
    QCOMPARE(buf.write( data.constData(), data.size() ), qint64(data.size()));

    QTest::ignoreMessage(QtWarningMsg, "QBuffer::seek: Invalid pos: -1");
    DO_INVALID_SEEK(-1);

    DO_VALID_SEEK(0);
    DO_VALID_SEEK(str.size() - 1);
    QVERIFY(buf.atEnd());
    DO_VALID_SEEK(str.size() / 2);

    // Special case: valid to seek one position past the buffer.
    // Its then legal to write, but not read.
    {
        char c = 'a';
        QVERIFY(buf.seek(qint64(str.size())));
        QCOMPARE(buf.read(&c, qint64(1)), qint64(0));
        QCOMPARE(c, 'a');
        QCOMPARE(buf.write(&c, qint64(1)), qint64(1));
    }

    // Special case 2: seeking to an arbitrary position beyond the buffer auto-expands it
    // (see Task 184730)
    {
        char c;
        const int offset = 1;
        Q_ASSERT(offset > 0); // any positive integer will do
        const qint64 pos = buf.size() + offset;
        QVERIFY(buf.seek(pos));
        QCOMPARE(buf.pos(), pos);
        QVERIFY(!buf.getChar(&c));
        QVERIFY(buf.seek(pos - 1));
        QVERIFY(buf.getChar(&c));
        QCOMPARE(c, buf.data().at(pos - 1));
        QVERIFY(buf.seek(pos));
        QVERIFY(buf.putChar(c));
    }
}

void tst_QBuffer::read_rawdata()
{
    static const unsigned char mydata[] = {
        0x01, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
        0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99,
        0x6d, 0x5b
    };

    QByteArray data = QByteArray::fromRawData((const char *)mydata, sizeof(mydata));
    QBuffer buffer(&data);
    buffer.open(QIODevice::ReadOnly);
    QDataStream in(&buffer);
    quint8 ch;
    for (int i = 0; i < (int)sizeof(mydata); ++i) {
        QVERIFY(!buffer.atEnd());
        in >> ch;
        QVERIFY(ch == (quint8)mydata[i]);
    }
    QVERIFY(buffer.atEnd());
}

void tst_QBuffer::isSequential()
{
    QBuffer buf;
    QVERIFY(!buf.isSequential());
}

void tst_QBuffer::signalTest_data()
{
    QTest::addColumn<QByteArray>("sample");

    QTest::newRow("empty") << QByteArray();
    QTest::newRow("size 1") << QByteArray("1");
    QTest::newRow("size 2") << QByteArray("11");
    QTest::newRow("size 100") << QByteArray(100, '1');
}

void tst_QBuffer::signalTest()
{
    QFETCH(QByteArray, sample);

    totalBytesWritten = 0;

    QBuffer buf;
    buf.open(QIODevice::WriteOnly);

    buf.buffer().resize(sample.size() * 10);
    connect(&buf, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
    connect(&buf, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWrittenSlot(qint64)));

    for (int i = 0; i < 10; ++i) {
        gotReadyRead = false;
        QCOMPARE(buf.write(sample), qint64(sample.size()));
        if (sample.size() > 0) {
            QTestEventLoop::instance().enterLoop(5);
            if (QTestEventLoop::instance().timeout())
                QFAIL("Timed out when waiting for readyRead()");
            QCOMPARE(totalBytesWritten, qint64(sample.size() * (i + 1)));
            QVERIFY(gotReadyRead);
        } else {
            QCOMPARE(totalBytesWritten, qint64(0));
            QVERIFY(!gotReadyRead);
        }
    }
}

void tst_QBuffer::readyReadSlot()
{
    gotReadyRead = true;
    QTestEventLoop::instance().exitLoop();
}

void tst_QBuffer::bytesWrittenSlot(qint64 written)
{
    totalBytesWritten += written;
}

void tst_QBuffer::isClosedAfterClose()
{
    QBuffer buffer;
    buffer.open(QBuffer::ReadOnly);
    QVERIFY(buffer.isOpen());
    buffer.close();
    QVERIFY(!buffer.isOpen());
}

void tst_QBuffer::readLine_data()
{
    QTest::addColumn<QByteArray>("src");
    QTest::addColumn<int>("maxlen");
    QTest::addColumn<QByteArray>("expected");

    QTest::newRow("1") << QByteArray("line1\nline2\n") << 1024
                    << QByteArray("line1\n");
    QTest::newRow("2") << QByteArray("hi there") << 1024
                    << QByteArray("hi there");
    QTest::newRow("3") << QByteArray("l\n") << 3 << QByteArray("l\n");
    QTest::newRow("4") << QByteArray("l\n") << 2 << QByteArray("l");
}

void tst_QBuffer::readLine()
{
    QFETCH(QByteArray, src);
    QFETCH(int, maxlen);
    QFETCH(QByteArray, expected);

    QBuffer buf;
    buf.setBuffer(&src);
    char *result = new char[maxlen + 1];
    result[maxlen] = '\0';

    QVERIFY(buf.open(QIODevice::ReadOnly));

    qint64 bytes_read = buf.readLine(result, maxlen);

    QCOMPARE(bytes_read, qint64(expected.size()));
    QCOMPARE(QByteArray(result), expected);

    buf.close();
    delete[] result;

}

void tst_QBuffer::canReadLine_data()
{
    QTest::addColumn<QByteArray>("src");
    QTest::addColumn<bool>("expected");

    QTest::newRow("1") << QByteArray("no newline") << false;
    QTest::newRow("2") << QByteArray("two \n lines\n") << true;
    QTest::newRow("3") << QByteArray("\n") << true;
    QTest::newRow("4") << QByteArray() << false;
}

void tst_QBuffer::canReadLine()
{
    QFETCH(QByteArray, src);
    QFETCH(bool, expected);

    QBuffer buf;
    buf.setBuffer(&src);
    QVERIFY(!buf.canReadLine());
    QVERIFY(buf.open(QIODevice::ReadOnly));
    QCOMPARE(buf.canReadLine(), expected);
}

void tst_QBuffer::atEnd()
{
    QBuffer buffer;
    buffer.open(QBuffer::Append);
    buffer.write("heisann");
    buffer.close();

    buffer.open(QBuffer::ReadOnly);
    buffer.seek(buffer.size());
    char c;
    QVERIFY(!buffer.getChar(&c));
    QCOMPARE(buffer.read(&c, 1), qint64(0));
}

void tst_QBuffer::readLineBoundaries()
{
    QByteArray line = "This is a line\n";
    QBuffer buffer;
    buffer.open(QIODevice::ReadWrite);
    while (buffer.size() < 16384)
        buffer.write(line);

/*
    buffer.seek(0);
    QFile out1("out1.txt");
    out1.open(QFile::WriteOnly);
    out1.write(buffer.readAll());
    out1.close();
*/
    buffer.seek(0);

    char c;
    buffer.getChar(&c);
    buffer.ungetChar(c);

    QFile out2("out2.txt");
    out2.open(QFile::WriteOnly);
    while (!buffer.atEnd())
        out2.write(buffer.readLine());
    
    out2.close();
    out2.remove();
}

void tst_QBuffer::writeAfterQByteArrayResize()
{
    QBuffer buffer;
    QVERIFY(buffer.open(QIODevice::WriteOnly));

    buffer.write(QByteArray().fill('a', 1000));
    QCOMPARE(buffer.buffer().size(), 1000);

    // resize the QByteArray behind QBuffer's back
    buffer.buffer().clear();
    buffer.seek(0);
    QCOMPARE(buffer.buffer().size(), 0);

    buffer.write(QByteArray().fill('b', 1000));
    QCOMPARE(buffer.buffer().size(), 1000);
}

QTEST_MAIN(tst_QBuffer)
#include "tst_qbuffer.moc"