summaryrefslogtreecommitdiffstats
path: root/tests/auto/qxmlstream/tst_qxmlstream.cpp
blob: 7d5e3b7f8ceb43029f26a0624145c4c241c599ff (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** 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 Technology Preview License Agreement accompanying
** this package.
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/


#include <QDirIterator>
#include <QEventLoop>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QtTest/QtTest>
#include <QUrl>
#include <QXmlDefaultHandler>
#include <QXmlStreamReader>

#include "qc14n.h"

//TESTED_CLASS=QXmlStreamReader QXmlStreamWriter
//TESTED_FILES=corelib/xml/stream/qxmlutils.cpp corelib/xml/stream/qxmlstream.cpp corelib/xml/stream/qxmlstream_p.h

Q_DECLARE_METATYPE(QXmlStreamReader::ReadElementTextBehaviour)

static const char *const catalogFile = SRCDIR "XML-Test-Suite/xmlconf/finalCatalog.xml";
static const int expectedRunCount = 1646;
static const int expectedSkipCount = 532;

static inline int best(int a, int b)
{
    if (a < 0)
        return b;
    if (b < 0)
        return a;
    return qMin(a, b);
}

static inline int best(int a, int b, int c)
{
    if (a < 0)
        return best(b, c);
    if (b < 0)
        return best(a, c);
    if (c < 0)
        return best(a, b);
    return qMin(qMin(a, b), c);
}

/**
 *  Opens @p filename and returns content produced as per
 *  xmlconf/xmltest/canonxml.html.
 *
 *  @p docType is the DOCTYPE name that the returned output should
 *  have, if it doesn't already have one.
 */
static QByteArray makeCanonical(const QString &filename,
                                const QString &docType,
                                bool &hasError,
                                bool testIncremental = false)
{
    QFile file(filename);
    file.open(QIODevice::ReadOnly);

    QXmlStreamReader reader;

    QByteArray buffer;
    int bufferPos = 0;

    if (testIncremental)
        buffer = file.readAll();
    else
        reader.setDevice(&file);

    QByteArray outarray;
    QXmlStreamWriter writer(&outarray);

    forever {
        while (!reader.atEnd()) {
            reader.readNext();
            if (reader.isDTD()) {
                if (!reader.notationDeclarations().isEmpty()) {
                    QString dtd;
                    QTextStream writeDtd(&dtd);

                    writeDtd << "<!DOCTYPE ";
                    writeDtd << docType;
                    writeDtd << " [";
                    writeDtd << endl;
                    QMap<QString, QXmlStreamNotationDeclaration> sortedNotationDeclarations;
                    foreach (QXmlStreamNotationDeclaration notation, reader.notationDeclarations())
                        sortedNotationDeclarations.insert(notation.name().toString(), notation);
                    foreach (QXmlStreamNotationDeclaration notation, sortedNotationDeclarations.values()) {
                        writeDtd << "<!NOTATION ";
                        writeDtd << notation.name().toString();
                        if (notation.publicId().isEmpty()) {
                            writeDtd << " SYSTEM \'";
                            writeDtd << notation.systemId().toString();
                            writeDtd << "\'";
                        } else {
                            writeDtd << " PUBLIC \'";
                            writeDtd << notation.publicId().toString();
                            writeDtd << "\'";
                            if (!notation.systemId().isEmpty() ) {
                                writeDtd << " \'";
                                writeDtd << notation.systemId().toString();
                                writeDtd << "\'";
                            }
                        }
                        writeDtd << ">";
                        writeDtd << endl;
                    }

                    writeDtd << "]>";
                    writeDtd << endl;
                    writer.writeDTD(dtd);
                }
            } else if (reader.isStartElement()) {
                writer.writeStartElement(reader.namespaceUri().toString(), reader.name().toString());

                QMap<QString, QXmlStreamAttribute> sortedAttributes;
                foreach(QXmlStreamAttribute attribute, reader.attributes())
                    sortedAttributes.insert(attribute.name().toString(), attribute);
                foreach(QXmlStreamAttribute attribute, sortedAttributes.values())
                    writer.writeAttribute(attribute);
                writer.writeCharacters(QString()); // write empty string to avoid having empty xml tags
            } else if (reader.isCharacters()) {
                // make canonical

                QString text = reader.text().toString();
                int i = 0;
                int p = 0;
                while ((i = best(text.indexOf(QLatin1Char(10), p),
                                 text.indexOf(QLatin1Char(13), p),
                                 text.indexOf(QLatin1Char(9), p))) >= 0) {
                    writer.writeCharacters(text.mid(p, i - p));
                    writer.writeEntityReference(QString("#%1").arg(text.at(i).unicode()));
                    p = i + 1;
                }
                writer.writeCharacters(text.mid(p));
            } else if (reader.isStartDocument() || reader.isEndDocument() || reader.isComment()){
                // canonical does not want any of those
            } else if (reader.isProcessingInstruction() && reader.processingInstructionData().isEmpty()) {
                // for some reason canonical wants a space
                writer.writeProcessingInstruction(reader.processingInstructionTarget().toString(), QLatin1String(""));
            } else if (!reader.hasError()){
                writer.writeCurrentToken(reader);
            }
        }
        if (testIncremental && bufferPos < buffer.size()) {
            reader.addData(QByteArray(buffer.data() + (bufferPos++), 1));
        } else {
            break;
        }
    }

    if (reader.hasError()) {
        hasError = true;
        outarray += "ERROR:";
        outarray += reader.errorString().toLatin1();
    }
    else
        hasError = false;

    return outarray;
}

/**
 * @short Returns the lexical QName of the document element in
 * @p document.
 *
 * It is assumed that @p document is a well-formed XML document.
 */
static QString documentElement(const QByteArray &document)
{
    QXmlStreamReader reader(document);

    while(!reader.atEnd())
    {
        if(reader.isStartElement())
            return reader.qualifiedName().toString();

        reader.readNext();
    }

    Q_ASSERT_X(false, Q_FUNC_INFO,
               qPrintable(QString::fromLatin1("The input %1 didn't contain an element.").arg(QString::fromUtf8(document.constData()))));
    return QString();
}

/**
 * @short Loads W3C's XML conformance test suite and runs it on QXmlStreamReader.
 *
 * Since this suite is fairly large, it runs the tests sequentially in order to not
 * have them all loaded into memory at once. In this way, the maximum memory usage stays
 * low, which means one can run valgrind on this test. However, the drawback is that
 * QTestLib's usual error reporting and testing mechanisms are slightly bypassed.
 *
 * Part of this code is a manual, ad-hoc implementation of xml:base.
 *
 * @see <a href="http://www.w3.org/XML/Test/">Extensible
 * Markup Language (XML) Conformance Test Suites</a>
 */
class TestSuiteHandler : public QXmlDefaultHandler
{
public:
    /**
     * The first string is the test ID, the second is
     * a description of what went wrong.
     */
    typedef QPair<QString, QString> GeneralFailure;

    /**
     * The string is the test ID.
     */
    QStringList successes;

    /**
     * The first value is the baseline, while the se
     */
    class MissedBaseline
    {
    public:
        MissedBaseline(const QString &aId,
                       const QByteArray &aExpected,
                       const QByteArray &aOutput) : id(aId),
                                                    expected(aExpected),
                                                    output(aOutput)
        {
            Q_ASSERT(!aId.isEmpty());
        }

        QString     id;
        QByteArray  expected;
        QByteArray  output;
    };

    QList<GeneralFailure> failures;
    QList<MissedBaseline> missedBaselines;

    /**
     * The count of how many tests that were run.
     */
    int runCount;

    int skipCount;

    /**
     * @p baseURI is the the URI of where the catalog file resides.
     */
    TestSuiteHandler(const QUrl &baseURI) : runCount(0),
                                            skipCount(0)
    {
        Q_ASSERT(baseURI.isValid());
        m_baseURI.push(baseURI);
    }

    virtual bool characters(const QString &chars)
    {
        m_ch = chars;
        return true;
    }

    virtual bool startElement(const QString &,
                              const QString &,
                              const QString &,
                              const QXmlAttributes &atts)
    {
        m_atts.push(atts);
        const int i = atts.index(QLatin1String("xml:base"));

        if(i != -1)
            m_baseURI.push(m_baseURI.top().resolved(atts.value(i)));

        return true;
    }

    virtual bool endElement(const QString &,
                            const QString &localName,
                            const QString &)
    {
        if(localName == QLatin1String("TEST"))
        {
            /* We don't want tests for XML 1.1.0, in fact). */
            if(m_atts.top().value(QString(), QLatin1String("VERSION")) == QLatin1String("1.1"))
            {
                ++skipCount;
                m_atts.pop();
                return true;
            }

            /* We don't want tests that conflict with the namespaces spec. Our parser is a
             * namespace-aware parser. */
            else if(m_atts.top().value(QString(), QLatin1String("NAMESPACE")) == QLatin1String("no"))
            {
                ++skipCount;
                m_atts.pop();
                return true;
            }

            const QString inputFilePath(m_baseURI.top().resolved(m_atts.top().value(QString(), QLatin1String("URI")))
                                                                .toLocalFile());
            const QString id(m_atts.top().value(QString(), QLatin1String("ID")));
            const QString type(m_atts.top().value(QString(), QLatin1String("TYPE")));

            QString expectedFilePath;
            const int index = m_atts.top().index(QString(), QLatin1String("OUTPUT"));

            //qDebug() << "Running test case:" << id;

            if(index != -1)
            {
                expectedFilePath = m_baseURI.top().resolved(m_atts.top().value(QString(),
                                                            QLatin1String("OUTPUT"))).toLocalFile();
            }

            /* testcases.dtd: 'No parser should accept a "not-wf" testcase
             * unless it's a nonvalidating parser and the test contains
             * external entities that the parser doesn't read.'
             *
             * We also let this apply to "valid", "invalid" and "error" tests, although
             * I'm not fully sure this is correct. */
            const QString ents(m_atts.top().value(QString(), QLatin1String("ENTITIES")));
            m_atts.pop();

            if(ents == QLatin1String("both") ||
               ents == QLatin1String("general") ||
               ents == QLatin1String("parameter"))
            {
                ++skipCount;
                return true;
            }

            ++runCount;

            QFile inputFile(inputFilePath);
            if(!inputFile.open(QIODevice::ReadOnly))
            {
                failures.append(qMakePair(id, QString::fromLatin1("Failed to open input file %1").arg(inputFilePath)));
                return true;
            }

            if(type == QLatin1String("not-wf"))
            {
                if(isWellformed(&inputFile, ParseSinglePass))
                {
                     failures.append(qMakePair(id, QString::fromLatin1("Failed to flag %1 as not well-formed.")
                                                   .arg(inputFilePath)));

                     /* Exit, the incremental test will fail as well, no need to flood the output. */
                     return true;
                }
                else
                    successes.append(id);

                if(isWellformed(&inputFile, ParseIncrementally))
                {
                     failures.append(qMakePair(id, QString::fromLatin1("Failed to flag %1 as not well-formed with incremental parsing.")
                                                   .arg(inputFilePath)));
                }
                else
                    successes.append(id);

                return true;
            }

            QXmlStreamReader reader(&inputFile);

            /* See testcases.dtd which reads: 'Nonvalidating parsers
             * must also accept "invalid" testcases, but validating ones must reject them.' */
            if(type == QLatin1String("invalid") || type == QLatin1String("valid"))
            {
                QByteArray expected;
                QString docType;

                /* We only want to compare against a baseline when we have
                 * one. Some "invalid"-tests, for instance, doesn't have baselines. */
                if(!expectedFilePath.isEmpty())
                {
                    QFile expectedFile(expectedFilePath);

                    if(!expectedFile.open(QIODevice::ReadOnly))
                    {
                        failures.append(qMakePair(id, QString::fromLatin1("Failed to open baseline %1").arg(expectedFilePath)));
                        return true;
                    }

                    expected = expectedFile.readAll();
                    docType = documentElement(expected);
                }
                else
                    docType = QLatin1String("dummy");

                bool hasError = true;
                bool incremental = false;

                QByteArray input(makeCanonical(inputFilePath, docType, hasError, incremental));

                if (!hasError && !expectedFilePath.isEmpty() && input == expected)
                    input = makeCanonical(inputFilePath, docType, hasError, (incremental = true));

                if(hasError)
                    failures.append(qMakePair(id, QString::fromLatin1("Failed to parse %1%2")
                                              .arg(incremental?"(incremental run only) ":"")
                                              .arg(inputFilePath)));

                if(!expectedFilePath.isEmpty() && input != expected)
                {
                    missedBaselines.append(MissedBaseline(id, expected, input));
                    return true;
                }
                else
                {
                    successes.append(id);
                    return true;
                }
            }
            else if(type == QLatin1String("error"))
            {
                /* Not yet sure about this one. */
                // TODO
                return true;
            }
            else
            {
                Q_ASSERT_X(false, Q_FUNC_INFO, "The input catalog is invalid.");
                return false;
            }
        }
        else if(localName == QLatin1String("TESTCASES") && m_atts.top().index(QLatin1String("xml:base")) != -1)
            m_baseURI.pop();

        m_atts.pop();

        return true;
    }

    enum ParseMode
    {
        ParseIncrementally,
        ParseSinglePass
    };

    static bool isWellformed(QIODevice *const inputFile, const ParseMode mode)
    {
        Q_ASSERT(inputFile);
        Q_ASSERT_X(inputFile->isOpen(), Q_FUNC_INFO, "The caller is responsible for opening the device.");
        Q_ASSERT(mode == ParseIncrementally || mode == ParseSinglePass);

        if(mode == ParseIncrementally)
        {
            QXmlStreamReader reader;
            QByteArray buffer;
            int bufferPos = 0;

            buffer = inputFile->readAll();

            while(true)
            {
                while(!reader.atEnd())
                    reader.readNext();

                if(bufferPos < buffer.size())
                {
                    ++bufferPos;
                    reader.addData(QByteArray(buffer.data() + bufferPos, 1));
                }
                else
                    break;
            }

            return !reader.hasError();
        }
        else
        {
            QXmlStreamReader reader;
            reader.setDevice(inputFile);

            while(!reader.atEnd())
                reader.readNext();

            return !reader.hasError();
        }
    }

private:
    QStack<QXmlAttributes>  m_atts;
    QString                 m_ch;
    QStack<QUrl>            m_baseURI;
};

class tst_QXmlStream: public QObject
{
    Q_OBJECT
public:
    tst_QXmlStream() : m_handler(QUrl::fromLocalFile(QLatin1String(catalogFile)))
    {
    }

private slots:
    void initTestCase();
    void reportFailures() const;
    void reportFailures_data();
    void checkBaseline() const;
    void checkBaseline_data() const;
    void testReader() const;
    void testReader_data() const;
    void reportSuccess() const;
    void reportSuccess_data() const;
    void parseXSLTTestSuite() const;
    void writerHangs() const;
    void writerAutoFormattingWithComments() const;
    void writerAutoFormattingWithTabs() const;
    void writerAutoFormattingWithProcessingInstructions() const;
    void writerAutoEmptyTags() const;
    void writeAttributesWithSpace() const;
    void addExtraNamespaceDeclarations();
    void setEntityResolver();
    void readFromQBuffer() const;
    void readFromQBufferInvalid() const;
    void readNextStartElement() const;
    void readElementText() const;
    void readElementText_data() const;
    void crashInUTF16Codec() const;
    void hasAttributeSignature() const;
    void hasAttribute() const;
    void writeWithCodec() const;
    void writeWithUtf8Codec() const;
    void writeWithStandalone() const;
    void entitiesAndWhitespace_1() const;
    void entitiesAndWhitespace_2() const;
    void testFalsePrematureError() const;
    void garbageInXMLPrologDefaultCodec() const;
    void garbageInXMLPrologUTF8Explicitly() const;
    void clear() const;
    void checkCommentIndentation() const;
    void checkCommentIndentation_data() const;
    void qtbug9196_crash() const;

private:
    static QByteArray readFile(const QString &filename);

    TestSuiteHandler m_handler;
};

void tst_QXmlStream::initTestCase()
{
    QFile file(QString::fromLatin1(catalogFile));
    QVERIFY2(file.open(QIODevice::ReadOnly),
             qPrintable(QString::fromLatin1("Failed to open the test suite catalog; %1").arg(file.fileName())));

    QXmlInputSource source(&file);
    QXmlSimpleReader reader;
    reader.setContentHandler(&m_handler);

    QVERIFY(reader.parse(&source, false));
}

void tst_QXmlStream::reportFailures() const
{
    QFETCH(bool, isError);
    QFETCH(QString, description);

    QVERIFY2(!isError, qPrintable(description));
}

void tst_QXmlStream::reportFailures_data()
{
    const int len = m_handler.failures.count();

    QTest::addColumn<bool>("isError");
    QTest::addColumn<QString>("description");

    /* We loop over all our failures(if any!), and output them such
     * that they appear in the QTestLib log. */
    for(int i = 0; i < len; ++i)
        QTest::newRow(m_handler.failures.at(i).first.toLatin1().constData()) << true << m_handler.failures.at(i).second;

    /* We need to add at least one column of test data, otherwise QTestLib complains. */
    if(len == 0)
        QTest::newRow("Whole test suite passed") << false << QString();

    /* We compare the test case counts to ensure that we've actually run test cases, that
     * the driver hasn't been broken or changed without updating the expected count, and
     * similar reasons. */
    QCOMPARE(m_handler.runCount, expectedRunCount);
    QCOMPARE(m_handler.skipCount, expectedSkipCount);
}

void tst_QXmlStream::checkBaseline() const
{
    QFETCH(bool, isError);
    QFETCH(QString, expected);
    QFETCH(QString, output);

    if(isError)
        QCOMPARE(output, expected);
}

void tst_QXmlStream::checkBaseline_data() const
{
    QTest::addColumn<bool>("isError");
    QTest::addColumn<QString>("expected");
    QTest::addColumn<QString>("output");

    const int len = m_handler.missedBaselines.count();

    for(int i = 0; i < len; ++i)
    {
        const TestSuiteHandler::MissedBaseline &b = m_handler.missedBaselines.at(i);

        /* We indeed don't know what encoding the content is in so in some cases fromUtf8
         * is all wrong, but it's an acceptable guess for error reporting. */
        QTest::newRow(b.id.toLatin1().constData())
                << true
                << QString::fromUtf8(b.expected.constData())
                << QString::fromUtf8(b.output.constData());
    }

    if(len == 0)
        QTest::newRow("dummy") << false << QString() << QString();
}

void tst_QXmlStream::reportSuccess() const
{
    QFETCH(bool, isError);

    QVERIFY(!isError);
}

void tst_QXmlStream::reportSuccess_data() const
{
    QTest::addColumn<bool>("isError");

    const int len = m_handler.successes.count();

    for(int i = 0; i < len; ++i)
        QTest::newRow(m_handler.successes.at(i).toLatin1().constData()) << false;

    if(len == 0)
        QTest::newRow("No test cases succeeded.") << true;
}

QByteArray tst_QXmlStream::readFile(const QString &filename)
{
    QFile file(filename);
    file.open(QIODevice::ReadOnly);

    QXmlStreamReader reader;

    reader.setDevice(&file);
    QByteArray outarray;
    QTextStream writer(&outarray);
	// We always want UTF-8, and not what the system picks up.
	writer.setCodec("UTF-8");

    while (!reader.atEnd()) {
        reader.readNext();
        writer << reader.tokenString() << "(";
        if (reader.isWhitespace())
            writer << " whitespace";
        if (reader.isCDATA())
            writer << " CDATA";
        if (reader.isStartDocument() && reader.isStandaloneDocument())
            writer << " standalone";
        if (!reader.text().isEmpty())
            writer << " text=\"" << reader.text().toString() << "\"";
        if (!reader.processingInstructionTarget().isEmpty())
            writer << " processingInstructionTarget=\"" << reader.processingInstructionTarget().toString() << "\"";
        if (!reader.processingInstructionData().isEmpty())
            writer << " processingInstructionData=\"" << reader.processingInstructionData().toString() << "\"";
        if (!reader.dtdName().isEmpty())
            writer << " dtdName=\"" << reader.dtdName().toString() << "\"";
        if (!reader.dtdPublicId().isEmpty())
            writer << " dtdPublicId=\"" << reader.dtdPublicId().toString() << "\"";
        if (!reader.dtdSystemId().isEmpty())
            writer << " dtdSystemId=\"" << reader.dtdSystemId().toString() << "\"";
        if (!reader.documentVersion().isEmpty())
            writer << " documentVersion=\"" << reader.documentVersion().toString() << "\"";
        if (!reader.documentEncoding().isEmpty())
            writer << " documentEncoding=\"" << reader.documentEncoding().toString() << "\"";
        if (!reader.name().isEmpty())
            writer << " name=\"" << reader.name().toString() << "\"";
        if (!reader.namespaceUri().isEmpty())
            writer << " namespaceUri=\"" << reader.namespaceUri().toString() << "\"";
        if (!reader.qualifiedName().isEmpty())
            writer << " qualifiedName=\"" << reader.qualifiedName().toString() << "\"";
        if (!reader.prefix().isEmpty())
            writer << " prefix=\"" << reader.prefix().toString() << "\"";
        if (reader.attributes().size()) {
            foreach(QXmlStreamAttribute attribute, reader.attributes()) {
                writer << endl << "    Attribute(";
                if (!attribute.name().isEmpty())
                    writer << " name=\"" << attribute.name().toString() << "\"";
                if (!attribute.namespaceUri().isEmpty())
                    writer << " namespaceUri=\"" << attribute.namespaceUri().toString() << "\"";
                if (!attribute.qualifiedName().isEmpty())
                    writer << " qualifiedName=\"" << attribute.qualifiedName().toString() << "\"";
                if (!attribute.prefix().isEmpty())
                    writer << " prefix=\"" << attribute.prefix().toString() << "\"";
                if (!attribute.value().isEmpty())
                    writer << " value=\"" << attribute.value().toString() << "\"";
                writer << " )" << endl;
            }
        }
        if (reader.namespaceDeclarations().size()) {
            foreach(QXmlStreamNamespaceDeclaration namespaceDeclaration, reader.namespaceDeclarations()) {
                writer << endl << "    NamespaceDeclaration(";
                if (!namespaceDeclaration.prefix().isEmpty())
                    writer << " prefix=\"" << namespaceDeclaration.prefix().toString() << "\"";
                if (!namespaceDeclaration.namespaceUri().isEmpty())
                    writer << " namespaceUri=\"" << namespaceDeclaration.namespaceUri().toString() << "\"";
                writer << " )" << endl;
            }
        }
        if (reader.notationDeclarations().size()) {
            foreach(QXmlStreamNotationDeclaration notationDeclaration, reader.notationDeclarations()) {
                writer << endl << "    NotationDeclaration(";
                if (!notationDeclaration.name().isEmpty())
                    writer << " name=\"" << notationDeclaration.name().toString() << "\"";
                if (!notationDeclaration.systemId().isEmpty())
                    writer << " systemId=\"" << notationDeclaration.systemId().toString() << "\"";
                if (!notationDeclaration.publicId().isEmpty())
                    writer << " publicId=\"" << notationDeclaration.publicId().toString() << "\"";
                writer << " )" << endl;
            }
        }
        if (reader.entityDeclarations().size()) {
            foreach(QXmlStreamEntityDeclaration entityDeclaration, reader.entityDeclarations()) {
                writer << endl << "    EntityDeclaration(";
                if (!entityDeclaration.name().isEmpty())
                    writer << " name=\"" << entityDeclaration.name().toString() << "\"";
                if (!entityDeclaration.notationName().isEmpty())
                    writer << " notationName=\"" << entityDeclaration.notationName().toString() << "\"";
                if (!entityDeclaration.systemId().isEmpty())
                    writer << " systemId=\"" << entityDeclaration.systemId().toString() << "\"";
                if (!entityDeclaration.publicId().isEmpty())
                    writer << " publicId=\"" << entityDeclaration.publicId().toString() << "\"";
                if (!entityDeclaration.value().isEmpty())
                    writer << " value=\"" << entityDeclaration.value().toString() << "\"";
                writer << " )" << endl;
            }
        }
        writer << " )" << endl;
    }
    if (reader.hasError())
        writer << "ERROR: " << reader.errorString() << endl;
    return outarray;
}

void tst_QXmlStream::testReader() const
{
    QFETCH(QString, xml);
    QFETCH(QString, ref);
    QFile file(ref);
    if (!file.exists()) {
        QByteArray reference = readFile(xml);
        QVERIFY(file.open(QIODevice::WriteOnly));
        file.write(reference);
        file.close();
    } else {
        QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text));
        QString reference = QString::fromUtf8(file.readAll());
        QString qxmlstream = QString::fromUtf8(readFile(xml));
        QCOMPARE(qxmlstream, reference);
    }
}

void tst_QXmlStream::testReader_data() const
{
    QTest::addColumn<QString>("xml");
    QTest::addColumn<QString>("ref");
    QDir dir;
    dir.cd(SRCDIR "data/");
    foreach(QString filename , dir.entryList(QStringList() << "*.xml")) {
        QString reference =  QFileInfo(filename).baseName() + ".ref";
        QTest::newRow(dir.filePath(filename).toLatin1().data()) << dir.filePath(filename) << dir.filePath(reference);
    }
}

void tst_QXmlStream::parseXSLTTestSuite() const
{
    /* We disable this test for now, so it doesn't show up as an XFAIL. */
#if 0
    QEXPECT_FAIL("", "Two problems needs to be solved in order to enable this test: \n"
                     "* The XSLT suite is 69 MB large, which is quite a lot compared to the existing XML suite on 2 mb.\n"
                     "* We need a c14n-like implementation in order to compare the outputs.", Abort);
    QVERIFY(false);

    /* We don't yet know this. TODO */
    int xsltExpectedRunCount = -1;

    QStringList nameFilters;
    nameFilters.append("*.xsl");
    nameFilters.append("*.xml");

    QDirIterator dirIterator("XSLT-Test-Suite/", nameFilters,
                             QDir::AllEntries, QDirIterator::Subdirectories);

    int filesParsed = 0;

    while(dirIterator.hasNext())
    {
        dirIterator.next();

        const QString fp(dirIterator.filePath());
        qDebug() << "Found" << fp;

        QFile inputFile(fp);
        QVERIFY(inputFile.open(QIODevice::ReadOnly));

        /* Read in and write out to the QByteArray. */
        QByteArray outputArray;
        {
            QXmlStreamReader reader(&inputFile);

            QXmlStreamWriter writer(&outputArray);

            while(!reader.atEnd())
            {
                writer.writeCurrentToken(reader);
                reader.readNext();

                QVERIFY2(!reader.hasError(), qPrintable(reader.errorString()));
            }
            /* Might be we got an error here, but we don't care. */
        }

        /* Read in the two files, and compare them. */
        {
            QBuffer outputBuffer(&outputArray);
            outputBuffer.open(QIODevice::ReadOnly);
            inputFile.close();
            inputFile.open(QIODevice::ReadOnly);

            QString message;
            const bool isEqual = QC14N::isEqual(&inputFile, &outputBuffer, &message);

            QVERIFY2(isEqual, message.toLatin1().constData());

            ++filesParsed;
        }
    }

    QCOMPARE(xsltExpectedRunCount, filesParsed);
#endif
}

void tst_QXmlStream::addExtraNamespaceDeclarations()
{
    const char *data = "<bla><undeclared:foo/><undeclared_too:foo/></bla>";
    {
        QXmlStreamReader xml(data);
        while (!xml.atEnd()) {
            xml.readNext();
        }
        QVERIFY2(xml.hasError(), "namespaces undeclared");
    }
    {
        QXmlStreamReader xml(data);
        xml.addExtraNamespaceDeclaration(QXmlStreamNamespaceDeclaration("undeclared", "blabla"));
        xml.addExtraNamespaceDeclaration(QXmlStreamNamespaceDeclaration("undeclared_too", "foofoo"));
        while (!xml.atEnd()) {
            xml.readNext();
        }
        QVERIFY2(!xml.hasError(), xml.errorString().toLatin1().constData());
    }
}


class EntityResolver : public QXmlStreamEntityResolver {
public:
    QString resolveUndeclaredEntity(const QString &name) {
        static int count = 0;
        return name.toUpper() + QString::number(++count);
    }
};
void tst_QXmlStream::setEntityResolver()
{
    const char *data = "<bla foo=\"&undeclared;\">&undeclared_too;</bla>";
    {
        QXmlStreamReader xml(data);
        while (!xml.atEnd()) {
            xml.readNext();
        }
        QVERIFY2(xml.hasError(), "undeclared entities");
    }
    {
        QString foo;
        QString bla_text;
        QXmlStreamReader xml(data);
        EntityResolver resolver;
        xml.setEntityResolver(&resolver);
        while (!xml.atEnd()) {
            xml.readNext();
            if (xml.isStartElement())
                foo = xml.attributes().value("foo").toString();
            if (xml.isCharacters())
                bla_text += xml.text().toString();
        }
        QVERIFY2(!xml.hasError(), xml.errorString().toLatin1().constData());
        QCOMPARE(foo, QLatin1String("UNDECLARED1"));
        QCOMPARE(bla_text, QLatin1String("UNDECLARED_TOO2"));
    }
}

void tst_QXmlStream::testFalsePrematureError() const // task 179320
{
    const char *illegal_start = "illegal<sta";
    const char *legal_start = "<sta";
    const char* end = "rt/>";
    {
        QXmlStreamReader xml("");
        while (!xml.atEnd()) {
            xml.readNext();
        }
        QVERIFY(xml.error() == QXmlStreamReader::PrematureEndOfDocumentError);
        QCOMPARE(xml.errorString(), QLatin1String("Premature end of document."));
        xml.addData(legal_start);
        while (!xml.atEnd()) {
            xml.readNext();
        }
        QVERIFY(xml.error() == QXmlStreamReader::PrematureEndOfDocumentError);
        QCOMPARE(xml.errorString(), QLatin1String("Premature end of document."));
        xml.addData(end);
        while (!xml.atEnd()) {
            xml.readNext();
        }
        QVERIFY(!xml.hasError());
    }
    {
        QXmlStreamReader xml(illegal_start);
        while (!xml.atEnd()) {
            xml.readNext();
        }
        QVERIFY(xml.hasError());
        QCOMPARE(xml.errorString(), QLatin1String("Start tag expected."));
        QVERIFY(xml.error() == QXmlStreamReader::NotWellFormedError);
    }
}

/*!
 See task 188737. Crash due to using empty QStack.
 */
void tst_QXmlStream::writerHangs() const
{
    QFile file("test.xml");

    QVERIFY(file.open(QIODevice::WriteOnly));

    QXmlStreamWriter  writer(&file);
    double radius = 4.0;
    writer.setAutoFormatting(true);
    writer.writeStartDocument();
    writer.writeEmptyElement("circle");
    writer.writeAttribute("radius", QString::number(radius));
    writer.writeEndElement();
    writer.writeEndDocument();
}
/*!
  Task 189611
*/
void tst_QXmlStream::writerAutoFormattingWithComments() const
{
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);

    QXmlStreamWriter writer(&buffer);
    writer.setAutoFormatting(true);
    writer.writeStartDocument();
    writer.writeComment("This is a comment");
    writer.writeEndDocument();
    const char *str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--This is a comment-->\n";
    QCOMPARE(buffer.buffer().data(), str);
}


/*!
  Task 206782
*/
void tst_QXmlStream::writerAutoFormattingWithTabs() const
{
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);


    QXmlStreamWriter writer(&buffer);
    writer.setAutoFormatting(true);
    writer.setAutoFormattingIndent(-1);
    QCOMPARE(writer.autoFormattingIndent(), -1);
    writer.writeStartDocument();
    writer.writeStartElement("A");
    writer.writeStartElement("B");
    writer.writeEndDocument();
    const char *str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<A>\n\t<B/>\n</A>\n";
    QCOMPARE(buffer.buffer().data(), str);
}

void tst_QXmlStream::writerAutoFormattingWithProcessingInstructions() const
{
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);

    QXmlStreamWriter writer(&buffer);
    writer.setAutoFormatting(true);
    writer.writeStartDocument();
    writer.writeProcessingInstruction("B", "C");
    writer.writeStartElement("A");
    writer.writeEndElement();
    writer.writeEndDocument();
    const char *str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?B C?>\n<A/>\n";
    QCOMPARE(buffer.buffer().data(), str);
}

/*!
  Task 204822
*/
void tst_QXmlStream::writeAttributesWithSpace() const
{
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);


    QXmlStreamWriter writer(&buffer);
    writer.writeStartDocument();
    writer.writeEmptyElement("A");
    writer.writeAttribute("attribute", QString("value")+QChar::Nbsp);
    writer.writeEndDocument();
    QString s = QString("<?xml version=\"1.0\" encoding=\"UTF-8\"?><A attribute=\"value%1\"/>\n").arg(QChar(QChar::Nbsp));
    QCOMPARE(buffer.buffer().data(), s.toUtf8().data());
}

/*!
  Task 209340
*/
void tst_QXmlStream::writerAutoEmptyTags() const
{
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);


    QXmlStreamWriter writer(&buffer);

    writer.writeStartDocument();

    writer.writeStartElement("Hans");
    writer.writeAttribute("key", "value");
    writer.writeEndElement();

    writer.writeStartElement("Hans");
    writer.writeAttribute("key", "value");
    writer.writeEmptyElement("Leer");
    writer.writeAttribute("key", "value");
    writer.writeEndElement();

    writer.writeStartElement("Hans");
    writer.writeAttribute("key", "value");
    writer.writeCharacters("stuff");
    writer.writeEndElement();

    writer.writeEndDocument();

    QString s = QString("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Hans key=\"value\"/><Hans key=\"value\"><Leer key=\"value\"/></Hans><Hans key=\"value\">stuff</Hans>\n");
    QCOMPARE(buffer.buffer().data(), s.toUtf8().data());
}

void tst_QXmlStream::readFromQBuffer() const
{
    QByteArray in("<e/>");
    QBuffer buffer(&in);
    QVERIFY(buffer.open(QIODevice::ReadOnly));

    QXmlStreamReader reader(&buffer);

    while(!reader.atEnd())
    {
        reader.readNext();
    }

    QVERIFY(!reader.hasError());
}

void tst_QXmlStream::readFromQBufferInvalid() const
{
    QByteArray in("<e/><e/>");
    QBuffer buffer(&in);
    QVERIFY(buffer.open(QIODevice::ReadOnly));

    QXmlStreamReader reader(&buffer);

    while(!reader.atEnd())
    {
        reader.readNext();
    }

    QVERIFY(reader.hasError());
}

void tst_QXmlStream::readNextStartElement() const
{
    QLatin1String in("<?xml version=\"1.0\"?><A><!-- blah --><B><C/></B><B attr=\"value\"/>text</A>");
    QXmlStreamReader reader(in);

    QVERIFY(reader.readNextStartElement());
    QVERIFY(reader.isStartElement() && reader.name() == "A");

    int amountOfB = 0;
    while (reader.readNextStartElement()) {
        QVERIFY(reader.isStartElement() && reader.name() == "B");
        ++amountOfB;
        reader.skipCurrentElement();
    }

    QCOMPARE(amountOfB, 2);
}

void tst_QXmlStream::readElementText() const
{
    QFETCH(QXmlStreamReader::ReadElementTextBehaviour, behaviour);
    QFETCH(QString, input);
    QFETCH(QString, expected);

    QXmlStreamReader reader(input);

    QVERIFY(reader.readNextStartElement());
    QCOMPARE(reader.readElementText(behaviour), expected);
}

void tst_QXmlStream::readElementText_data() const
{
    QTest::addColumn<QXmlStreamReader::ReadElementTextBehaviour>("behaviour");
    QTest::addColumn<QString>("input");
    QTest::addColumn<QString>("expected");

    QString validInput("<p>He was <em>never</em> going to admit<!-- TODO: rephrase --> his mistake.</p>");
    QString invalidInput("<p>invalid...<p>");
    QString invalidOutput("invalid...");

    QTest::newRow("ErrorOnUnexpectedElement")
            << QXmlStreamReader::ErrorOnUnexpectedElement
            << validInput << QString("He was ");

    QTest::newRow("IncludeChildElements")
            << QXmlStreamReader::IncludeChildElements
            << validInput << QString("He was never going to admit his mistake.");

    QTest::newRow("SkipChildElements")
            << QXmlStreamReader::SkipChildElements
            << validInput << QString("He was  going to admit his mistake.");

    QTest::newRow("ErrorOnUnexpectedElement Invalid")
            << QXmlStreamReader::ErrorOnUnexpectedElement
            << invalidInput << invalidOutput;

    QTest::newRow("IncludeChildElements Invalid")
            << QXmlStreamReader::IncludeChildElements
            << invalidInput << invalidOutput;

    QTest::newRow("SkipChildElements Invalid")
            << QXmlStreamReader::SkipChildElements
            << invalidInput << invalidOutput;
}

void tst_QXmlStream::crashInUTF16Codec() const
{
    QEventLoop eventLoop;

    QNetworkAccessManager networkManager;
    QNetworkRequest request(QUrl::fromLocalFile(QLatin1String(SRCDIR "data/051reduced.xml")));
    QNetworkReply *const reply = networkManager.get(request);
    eventLoop.connect(reply, SIGNAL(finished()), SLOT(quit()));

    QCOMPARE(eventLoop.exec(), 0);

    QXmlStreamReader reader(reply);
    while(!reader.atEnd())
    {
        reader.readNext();
        continue;
    }

    QVERIFY(!reader.hasError());
}

/*
  In addition to QTestLib's flags, one can specify "-c <filename>" and have that file output in its canonical form.
*/
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    if (argc == 3 && QByteArray(argv[1]).startsWith("-c")) {
        // output canonical only
        bool error = false;
        QByteArray canonical = makeCanonical(argv[2], "doc", error);
        QTextStream myStdOut(stdout);
        myStdOut << canonical << endl;
        exit(0);
    }

    tst_QXmlStream tc;
    return QTest::qExec(&tc, argc, argv);
}

void tst_QXmlStream::hasAttributeSignature() const
{
    /* These functions should be const so invoke all
     * of them on a const object. */
    const QXmlStreamAttributes atts;
    atts.hasAttribute(QLatin1String("localName"));
    atts.hasAttribute(QString::fromLatin1("localName"));
    atts.hasAttribute(QString::fromLatin1("http://example.com/"), QLatin1String("localName"));

    /* The input arguments should be const references, not mutable references
     * so pass const references. */
    const QLatin1String latin1StringLocalName(QLatin1String("localName"));
    const QString qStringLocalname(QLatin1String("localName"));
    const QString namespaceURI(QLatin1String("http://example.com/"));

    /* QLatin1String overload. */
    atts.hasAttribute(latin1StringLocalName);

    /* QString overload. */
    atts.hasAttribute(latin1StringLocalName);

    /* namespace/local name overload. */
    atts.hasAttribute(namespaceURI, qStringLocalname);
}

void tst_QXmlStream::hasAttribute() const
{
    QXmlStreamReader reader(QLatin1String("<e xmlns:p='http://example.com/2' xmlns='http://example.com/' "
                                          "attr1='value' attr2='value2' p:attr3='value3' emptyAttr=''><noAttributes/></e>"));

    QCOMPARE(reader.readNext(), QXmlStreamReader::StartDocument);
    QCOMPARE(reader.readNext(), QXmlStreamReader::StartElement);
    const QXmlStreamAttributes &atts = reader.attributes();

    /* QLatin1String overload. */
    QVERIFY(atts.hasAttribute(QLatin1String("attr1")));
    QVERIFY(atts.hasAttribute(QLatin1String("attr2")));
    QVERIFY(atts.hasAttribute(QLatin1String("p:attr3")));
    QVERIFY(atts.hasAttribute(QLatin1String("emptyAttr")));
    QVERIFY(!atts.hasAttribute(QLatin1String("DOESNOTEXIST")));

    /* Test with an empty & null namespaces. */
    QVERIFY(atts.hasAttribute(QString(), QLatin1String("attr2"))); /* A null string. */
    QVERIFY(atts.hasAttribute(QLatin1String(""), QLatin1String("attr2"))); /* An empty string. */

    /* QString overload. */
    QVERIFY(atts.hasAttribute(QString::fromLatin1("attr1")));
    QVERIFY(atts.hasAttribute(QString::fromLatin1("attr2")));
    QVERIFY(atts.hasAttribute(QString::fromLatin1("p:attr3")));
    QVERIFY(atts.hasAttribute(QString::fromLatin1("emptyAttr")));
    QVERIFY(!atts.hasAttribute(QString::fromLatin1("DOESNOTEXIST")));

    /* namespace/local name overload. */
    QVERIFY(atts.hasAttribute(QString(), QString::fromLatin1("attr1")));
    /* Attributes do not pick up the default namespace. */
    QVERIFY(!atts.hasAttribute(QLatin1String("http://example.com/"), QString::fromLatin1("attr1")));
    QVERIFY(atts.hasAttribute(QLatin1String("http://example.com/2"), QString::fromLatin1("attr3")));
    QVERIFY(atts.hasAttribute(QString(), QString::fromLatin1("emptyAttr")));
    QVERIFY(!atts.hasAttribute(QLatin1String("http://example.com/2"), QString::fromLatin1("DOESNOTEXIST")));
    QVERIFY(!atts.hasAttribute(QLatin1String("WRONG_NAMESPACE"), QString::fromLatin1("attr3")));

    /* Invoke on an QXmlStreamAttributes that has no attributes at all. */
    QCOMPARE(reader.readNext(), QXmlStreamReader::StartElement);

    const QXmlStreamAttributes &atts2 = reader.attributes();
    QVERIFY(atts2.isEmpty());

    /* QLatin1String overload. */
    QVERIFY(!atts.hasAttribute(QLatin1String("arbitraryName")));

    /* QString overload. */
    QVERIFY(!atts.hasAttribute(QString::fromLatin1("arbitraryName")));

    /* namespace/local name overload. */
    QVERIFY(!atts.hasAttribute(QLatin1String("http://example.com/"), QString::fromLatin1("arbitraryName")));

    while(!reader.atEnd())
        reader.readNext();

    QVERIFY(!reader.hasError());
}


void tst_QXmlStream::writeWithCodec() const
{
    QByteArray outarray;
    QXmlStreamWriter writer(&outarray);
    writer.setAutoFormatting(true);

    QTextCodec *codec = QTextCodec::codecForName("ISO 8859-15");
    QVERIFY(codec);
    writer.setCodec(codec);

    const char *latin2 = "hé hé";
    const QString string = codec->toUnicode(latin2);


    writer.writeStartDocument("1.0");

    writer.writeTextElement("foo", string);
    writer.writeEndElement();
    writer.writeEndDocument();

    QVERIFY(outarray.contains(latin2));
    QVERIFY(outarray.contains(codec->name()));
}

void tst_QXmlStream::writeWithUtf8Codec() const
{
    QByteArray outarray;
    QXmlStreamWriter writer(&outarray);

    QTextCodec *codec = QTextCodec::codecForMib(106); // utf-8
    QVERIFY(codec);
    writer.setCodec(codec);

    writer.writeStartDocument("1.0");
    static const char begin[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    QVERIFY(outarray.startsWith(begin));
}

void tst_QXmlStream::writeWithStandalone() const
{
    {
        QByteArray outarray;
        QXmlStreamWriter writer(&outarray);
        writer.setAutoFormatting(true);
        writer.writeStartDocument("1.0", true);
        writer.writeEndDocument();
        const char *ref = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
        QCOMPARE(outarray.constData(), ref);
    }
    {
        QByteArray outarray;
        QXmlStreamWriter writer(&outarray);
        writer.setAutoFormatting(true);
        writer.writeStartDocument("1.0", false);
        writer.writeEndDocument();
        const char *ref = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
        QCOMPARE(outarray.constData(), ref);
    }
}

void tst_QXmlStream::entitiesAndWhitespace_1() const
{
    QXmlStreamReader reader(QLatin1String("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\"><test>&extEnt;</test>"));

    int entityCount = 0;
    int characterCount = 0;
    while(!reader.atEnd())
    {
        QXmlStreamReader::TokenType token = reader.readNext();
        switch(token)
        {
            case QXmlStreamReader::Characters:
                characterCount++;
                break;
            case QXmlStreamReader::EntityReference:
                entityCount++;
                break;
            default:
                ;
        }
    }

    QCOMPARE(entityCount, 1);
    QCOMPARE(characterCount, 0);
    QVERIFY(!reader.hasError());
}

void tst_QXmlStream::entitiesAndWhitespace_2() const
{
    QXmlStreamReader reader(QLatin1String("<test>&extEnt;</test>"));

    int entityCount = 0;
    int characterCount = 0;
    while(!reader.atEnd())
    {
        QXmlStreamReader::TokenType token = reader.readNext();
        switch(token)
        {
            case QXmlStreamReader::Characters:
                characterCount++;
                break;
            case QXmlStreamReader::EntityReference:
                entityCount++;
                break;
            default:
                ;
        }
    }

    QCOMPARE(entityCount, 0);
    QCOMPARE(characterCount, 0);
    QVERIFY(reader.hasError());
}

void tst_QXmlStream::garbageInXMLPrologDefaultCodec() const
{
    QBuffer out;
    QVERIFY(out.open(QIODevice::ReadWrite));

    QXmlStreamWriter writer (&out);
    writer.writeStartDocument();
    writer.writeEmptyElement("Foo");
    writer.writeEndDocument();

    QCOMPARE(out.data(), QByteArray("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Foo/>\n"));
}

void tst_QXmlStream::garbageInXMLPrologUTF8Explicitly() const
{
    QBuffer out;
    QVERIFY(out.open(QIODevice::ReadWrite));

    QXmlStreamWriter writer (&out);
    writer.setCodec("UTF-8");
    writer.writeStartDocument();
    writer.writeEmptyElement("Foo");
    writer.writeEndDocument();

    QCOMPARE(out.data(), QByteArray("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Foo/>\n"));
}

void tst_QXmlStream::clear() const // task 228768
{
    QString xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><body></body>";
    QXmlStreamReader reader;

    reader.addData(xml);
    while (!reader.atEnd()) {
        reader.readNext();
    }
    QCOMPARE(reader.tokenType(), QXmlStreamReader::EndDocument);

    reader.clear();
    reader.addData(xml);
    while (!reader.atEnd()) {
        reader.readNext();
    }
    QCOMPARE(reader.tokenType(), QXmlStreamReader::EndDocument);


    // now we stop in the middle to check whether clear really works
    reader.clear();
    reader.addData(xml);
    reader.readNext();
    reader.readNext();
    QCOMPARE(reader.tokenType(), QXmlStreamReader::StartElement);

    // and here the final read
    reader.clear();
    reader.addData(xml);
    while (!reader.atEnd()) {
        reader.readNext();
    }
    QCOMPARE(reader.tokenType(), QXmlStreamReader::EndDocument);
}

void tst_QXmlStream::checkCommentIndentation_data() const
{

    QTest::addColumn<QString>("input");
    QTest::addColumn<QString>("expectedOutput");

    QString simpleInput = "<a><!-- bla --></a>";
    QString simpleOutput = "<?xml version=\"1.0\"?>\n"
                           "<a>\n"
                           "   <!-- bla -->\n"
                           "</a>\n";
    QTest::newRow("simple-comment") << simpleInput << simpleOutput;

    QString advancedInput = "<a><!-- bla --><!-- bla --><b><!-- bla --><c><!-- bla --></c><!-- bla --></b></a>";
    QString advancedOutput = "<?xml version=\"1.0\"?>\n"
                           "<a>\n"
                           "   <!-- bla -->\n"
                           "   <!-- bla -->\n"
                           "   <b>\n"
                           "      <!-- bla -->\n"
                           "      <c>\n"
                           "         <!-- bla -->\n"
                           "      </c>\n"
                           "      <!-- bla -->\n"
                           "   </b>\n"
                           "</a>\n";
    QTest::newRow("advanced-comment") << advancedInput << advancedOutput;
}

void tst_QXmlStream::checkCommentIndentation() const // task 256468
{
    QFETCH(QString, input);
    QFETCH(QString, expectedOutput);
    QString output;
    QXmlStreamReader reader(input);
    QXmlStreamWriter writer(&output);
    writer.setAutoFormatting(true);
    writer.setAutoFormattingIndent(3);

    while (!reader.atEnd()) {
        reader.readNext();
        if (reader.error()) {
            QFAIL("error reading XML input");
        } else {
            writer.writeCurrentToken(reader);
        }
    }
    QCOMPARE(output, expectedOutput);
}

void tst_QXmlStream::qtbug9196_crash() const
{
    // the following input used to produce a crash in the stream reader
    QByteArray ba("<a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a>"
                  "<a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a><a></a>");
    QXmlStreamReader xml(ba);
    while (!xml.atEnd()) {
         xml.readNext();
    }
}

#include "tst_qxmlstream.moc"
// vim: et:ts=4:sw=4:sts=4