aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/lore/test/test_lore.py
blob: 3f399d99f5194f6be0ae42ce13dc5a96e57314da (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
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

# ++ single anchor added to individual output file
# ++ two anchors added to individual output file
# ++ anchors added to individual output files
# ++ entry added to index
# ++ index entry pointing to correct file and anchor
# ++ multiple entries added to index
# ++ multiple index entries pointing to correct files and anchors
# __ all of above for files in deep directory structure
#
# ++ group index entries by indexed term
# ++ sort index entries by indexed term
# __ hierarchical index entries (e.g. language!programming)
#
# ++ add parameter for what the index filename should be
# ++ add (default) ability to NOT index (if index not specified)
#
# ++ put actual index filename into INDEX link (if any) in the template
# __ make index links RELATIVE!
# __ make index pay attention to the outputdir!
#
# __ make index look nice
#
# ++ add section numbers to headers in lore output
# ++ make text of index entry links be chapter numbers
# ++ make text of index entry links be section numbers
#
# __ put all of our test files someplace neat and tidy
#

import os, shutil, errno, time
from StringIO import StringIO
from xml.dom import minidom as dom

from twisted.trial import unittest
from twisted.python.filepath import FilePath

from twisted.lore import tree, process, indexer, numberer, htmlbook, default
from twisted.lore.default import factory
from twisted.lore.latex import LatexSpitter

from twisted.python.util import sibpath

from twisted.lore.scripts import lore

from twisted.web import domhelpers

def sp(originalFileName):
    return sibpath(__file__, originalFileName)

options = {"template" : sp("template.tpl"), 'baseurl': '%s', 'ext': '.xhtml' }
d = options


class _XMLAssertionMixin:
    """
    Test mixin defining a method for comparing serialized XML documents.
    """
    def assertXMLEqual(self, first, second):
        """
        Verify that two strings represent the same XML document.
        """
        self.assertEqual(
            dom.parseString(first).toxml(),
            dom.parseString(second).toxml())


class TestFactory(unittest.TestCase, _XMLAssertionMixin):

    file = sp('simple.html')
    linkrel = ""

    def assertEqualFiles1(self, exp, act):
        if (exp == act): return True
        fact = open(act)
        self.assertEqualsFile(exp, fact.read())

    def assertEqualFiles(self, exp, act):
        if (exp == act): return True
        fact = open(sp(act))
        self.assertEqualsFile(exp, fact.read())

    def assertEqualsFile(self, exp, act):
        expected = open(sp(exp)).read()
        self.assertEqual(expected, act)

    def makeTemp(self, *filenames):
        tmp = self.mktemp()
        os.mkdir(tmp)
        for filename in filenames:
            tmpFile = os.path.join(tmp, filename)
            shutil.copyfile(sp(filename), tmpFile)
        return tmp

########################################

    def setUp(self):
        indexer.reset()
        numberer.reset()

    def testProcessingFunctionFactory(self):
        base = FilePath(self.mktemp())
        base.makedirs()

        simple = base.child('simple.html')
        FilePath(__file__).sibling('simple.html').copyTo(simple)

        htmlGenerator = factory.generate_html(options)
        htmlGenerator(simple.path, self.linkrel)

        self.assertXMLEqual(
            """\
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head><title>Twisted Documentation: My Test Lore Input</title></head>
  <body bgcolor="white">
    <h1 class="title">My Test Lore Input</h1>
    <div class="content">
<span/>
<p>A Body.</p>
</div>
    <a href="index.xhtml">Index</a>
  </body>
</html>""",
            simple.sibling('simple.xhtml').getContent())


    def testProcessingFunctionFactoryWithFilenameGenerator(self):
        base = FilePath(self.mktemp())
        base.makedirs()

        def filenameGenerator(originalFileName, outputExtension):
            name = os.path.splitext(FilePath(originalFileName).basename())[0]
            return base.child(name + outputExtension).path

        htmlGenerator = factory.generate_html(options, filenameGenerator)
        htmlGenerator(self.file, self.linkrel)
        self.assertXMLEqual(
            """\
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head><title>Twisted Documentation: My Test Lore Input</title></head>
  <body bgcolor="white">
    <h1 class="title">My Test Lore Input</h1>
    <div class="content">
<span/>
<p>A Body.</p>
</div>
    <a href="index.xhtml">Index</a>
  </body>
</html>""",
            base.child("simple.xhtml").getContent())


    def test_doFile(self):
        base = FilePath(self.mktemp())
        base.makedirs()

        simple = base.child('simple.html')
        FilePath(__file__).sibling('simple.html').copyTo(simple)

        templ = dom.parse(open(d['template']))

        tree.doFile(simple.path, self.linkrel, d['ext'], d['baseurl'], templ, d)
        self.assertXMLEqual(
            """\
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head><title>Twisted Documentation: My Test Lore Input</title></head>
  <body bgcolor="white">
    <h1 class="title">My Test Lore Input</h1>
    <div class="content">
<span/>
<p>A Body.</p>
</div>
    <a href="index.xhtml">Index</a>
  </body>
</html>""",
            base.child("simple.xhtml").getContent())


    def test_doFile_withFilenameGenerator(self):
        base = FilePath(self.mktemp())
        base.makedirs()

        def filenameGenerator(originalFileName, outputExtension):
            name = os.path.splitext(FilePath(originalFileName).basename())[0]
            return base.child(name + outputExtension).path

        templ = dom.parse(open(d['template']))
        tree.doFile(self.file, self.linkrel, d['ext'], d['baseurl'], templ, d, filenameGenerator)

        self.assertXMLEqual(
            """\
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head><title>Twisted Documentation: My Test Lore Input</title></head>
  <body bgcolor="white">
    <h1 class="title">My Test Lore Input</h1>
    <div class="content">
<span/>
<p>A Body.</p>
</div>
    <a href="index.xhtml">Index</a>
  </body>
</html>""",
            base.child("simple.xhtml").getContent())


    def test_munge(self):
        indexer.setIndexFilename("lore_index_file.html")
        doc = dom.parse(open(self.file))
        node = dom.parse(open(d['template']))
        tree.munge(doc, node, self.linkrel,
                   os.path.dirname(self.file),
                   self.file,
                   d['ext'], d['baseurl'], d)

        self.assertXMLEqual(
            """\
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head><title>Twisted Documentation: My Test Lore Input</title></head>
  <body bgcolor="white">
    <h1 class="title">My Test Lore Input</h1>
    <div class="content">
<span/>
<p>A Body.</p>
</div>
    <a href="lore_index_file.html">Index</a>
  </body>
</html>""",
            node.toxml())


    def test_mungeAuthors(self):
        """
        If there is a node with a I{class} attribute set to C{"authors"},
        L{tree.munge} adds anchors as children to it, takeing the necessary
        information from any I{link} nodes in the I{head} with their I{rel}
        attribute set to C{"author"}.
        """
        document = dom.parseString(
            """\
<html>
  <head>
    <title>munge authors</title>
    <link rel="author" title="foo" href="bar"/>
    <link rel="author" title="baz" href="quux"/>
    <link rel="author" title="foobar" href="barbaz"/>
  </head>
  <body>
    <h1>munge authors</h1>
  </body>
</html>""")
        template = dom.parseString(
            """\
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <title />
  </head>

  <body>
    <div class="body" />
    <div class="authors" />
  </body>
</html>
""")
        tree.munge(
            document, template, self.linkrel, os.path.dirname(self.file),
            self.file, d['ext'], d['baseurl'], d)

        self.assertXMLEqual(
            template.toxml(),
            """\
<?xml version="1.0" ?><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>munge authors</title>
  <link href="bar" rel="author" title="foo"/><link href="quux" rel="author" title="baz"/><link href="barbaz" rel="author" title="foobar"/></head>

  <body>
    <div class="content">
    <span/>
  </div>
    <div class="authors"><span><a href="bar">foo</a>, <a href="quux">baz</a>, and <a href="barbaz">foobar</a></span></div>
  </body>
</html>""")


    def test_getProcessor(self):

        base = FilePath(self.mktemp())
        base.makedirs()
        input = base.child("simple3.html")
        FilePath(__file__).sibling("simple3.html").copyTo(input)

        options = { 'template': sp('template.tpl'), 'ext': '.xhtml', 'baseurl': 'burl',
                    'filenameMapping': None }
        p = process.getProcessor(default, "html", options)
        p(input.path, self.linkrel)
        self.assertXMLEqual(
            """\
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head><title>Twisted Documentation: My Test Lore Input</title></head>
  <body bgcolor="white">
    <h1 class="title">My Test Lore Input</h1>
    <div class="content">
<span/>
<p>A Body.</p>
</div>
    <a href="index.xhtml">Index</a>
  </body>
</html>""",
            base.child("simple3.xhtml").getContent())

    def test_outputdirGenerator(self):
        normp = os.path.normpath; join = os.path.join
        inputdir  = normp(join("/", 'home', 'joe'))
        outputdir = normp(join("/", 'away', 'joseph'))
        actual = process.outputdirGenerator(join("/", 'home', 'joe', "myfile.html"),
                                            '.xhtml', inputdir, outputdir)
        expected = normp(join("/", 'away', 'joseph', 'myfile.xhtml'))
        self.assertEqual(expected, actual)

    def test_outputdirGeneratorBadInput(self):
        options = {'outputdir': '/away/joseph/', 'inputdir': '/home/joe/' }
        self.assertRaises(ValueError, process.outputdirGenerator, '.html', '.xhtml', **options)

    def test_makeSureDirectoryExists(self):
        dirname = os.path.join("tmp", 'nonexistentdir')
        if os.path.exists(dirname):
            os.rmdir(dirname)
        self.failIf(os.path.exists(dirname), "Hey: someone already created the dir")
        filename = os.path.join(dirname, 'newfile')
        tree.makeSureDirectoryExists(filename)
        self.failUnless(os.path.exists(dirname), 'should have created dir')
        os.rmdir(dirname)


    def test_indexAnchorsAdded(self):
        indexer.setIndexFilename('theIndexFile.html')
        # generate the output file
        templ = dom.parse(open(d['template']))
        tmp = self.makeTemp('lore_index_test.xhtml')

        tree.doFile(os.path.join(tmp, 'lore_index_test.xhtml'),
                    self.linkrel, '.html', d['baseurl'], templ, d)

        self.assertXMLEqual(
            """\
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head><title>Twisted Documentation: The way of the program</title></head>
  <body bgcolor="white">
    <h1 class="title">The way of the program</h1>
    <div class="content">

<span/>

<p>The first paragraph.</p>


<h2>The Python programming language<a name="auto0"/></h2>
<a name="index01"/>
<a name="index02"/>

<p>The second paragraph.</p>


</div>
    <a href="theIndexFile.html">Index</a>
  </body>
</html>""",
            FilePath(tmp).child("lore_index_test.html").getContent())


    def test_indexEntriesAdded(self):
        indexer.addEntry('lore_index_test.html', 'index02', 'language of programming', '1.3')
        indexer.addEntry('lore_index_test.html', 'index01', 'programming language', '1.2')
        indexer.setIndexFilename("lore_index_file.html")
        indexer.generateIndex()
        self.assertEqualFiles1("lore_index_file_out.html", "lore_index_file.html")

    def test_book(self):
        tmp = self.makeTemp()
        inputFilename = sp('lore_index_test.xhtml')

        bookFilename = os.path.join(tmp, 'lore_test_book.book')
        bf = open(bookFilename, 'w')
        bf.write('Chapter(r"%s", None)\r\n' % inputFilename)
        bf.close()

        book = htmlbook.Book(bookFilename)
        expected = {'indexFilename': None,
                    'chapters': [(inputFilename, None)],
                    }
        dct = book.__dict__
        for k in dct:
            self.assertEqual(dct[k], expected[k])

    def test_runningLore(self):
        options = lore.Options()
        tmp = self.makeTemp('lore_index_test.xhtml')

        templateFilename = sp('template.tpl')
        inputFilename = os.path.join(tmp, 'lore_index_test.xhtml')
        indexFilename = 'theIndexFile'

        bookFilename = os.path.join(tmp, 'lore_test_book.book')
        bf = open(bookFilename, 'w')
        bf.write('Chapter(r"%s", None)\n' % inputFilename)
        bf.close()

        options.parseOptions(['--null', '--book=%s' % bookFilename,
                              '--config', 'template=%s' % templateFilename,
                              '--index=%s' % indexFilename
                              ])
        result = lore.runGivenOptions(options)
        self.assertEqual(None, result)
        self.assertEqualFiles1("lore_index_file_unnumbered_out.html", indexFilename + ".html")


    def test_runningLoreMultipleFiles(self):
        tmp = self.makeTemp('lore_index_test.xhtml', 'lore_index_test2.xhtml')
        templateFilename = sp('template.tpl')
        inputFilename = os.path.join(tmp, 'lore_index_test.xhtml')
        inputFilename2 = os.path.join(tmp, 'lore_index_test2.xhtml')
        indexFilename = 'theIndexFile'

        bookFilename = os.path.join(tmp, 'lore_test_book.book')
        bf = open(bookFilename, 'w')
        bf.write('Chapter(r"%s", None)\n' % inputFilename)
        bf.write('Chapter(r"%s", None)\n' % inputFilename2)
        bf.close()

        options = lore.Options()
        options.parseOptions(['--null', '--book=%s' % bookFilename,
                              '--config', 'template=%s' % templateFilename,
                              '--index=%s' % indexFilename
                              ])
        result = lore.runGivenOptions(options)
        self.assertEqual(None, result)

        self.assertEqual(
            # XXX This doesn't seem like a very good index file.
            """\
aahz: <a href="lore_index_test2.html#index03">link</a><br />
aahz2: <a href="lore_index_test2.html#index02">link</a><br />
language of programming: <a href="lore_index_test.html#index02">link</a>, <a href="lore_index_test2.html#index01">link</a><br />
programming language: <a href="lore_index_test.html#index01">link</a><br />
""",
            file(FilePath(indexFilename + ".html").path).read())

        self.assertXMLEqual(
            """\
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head><title>Twisted Documentation: The way of the program</title></head>
  <body bgcolor="white">
    <h1 class="title">The way of the program</h1>
    <div class="content">

<span/>

<p>The first paragraph.</p>


<h2>The Python programming language<a name="auto0"/></h2>
<a name="index01"/>
<a name="index02"/>

<p>The second paragraph.</p>


</div>
    <a href="theIndexFile.html">Index</a>
  </body>
</html>""",
            FilePath(tmp).child("lore_index_test.html").getContent())

        self.assertXMLEqual(
            """\
<?xml version="1.0" ?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head><title>Twisted Documentation: The second page to index</title></head>
  <body bgcolor="white">
    <h1 class="title">The second page to index</h1>
    <div class="content">

<span/>

<p>The first paragraph of the second page.</p>


<h2>The Jython programming language<a name="auto0"/></h2>
<a name="index01"/>
<a name="index02"/>
<a name="index03"/>

<p>The second paragraph of the second page.</p>


</div>
    <a href="theIndexFile.html">Index</a>
  </body>
</html>""",
            FilePath(tmp).child("lore_index_test2.html").getContent())



    def XXXtest_NumberedSections(self):
        # run two files through lore, with numbering turned on
        # every h2 should be numbered:
        # first  file's h2s should be 1.1, 1.2
        # second file's h2s should be 2.1, 2.2
        templateFilename = sp('template.tpl')
        inputFilename = sp('lore_numbering_test.xhtml')
        inputFilename2 = sp('lore_numbering_test2.xhtml')
        indexFilename = 'theIndexFile'

        # you can number without a book:
        options = lore.Options()
        options.parseOptions(['--null',
                              '--index=%s' % indexFilename,
                              '--config', 'template=%s' % templateFilename,
                              '--config', 'ext=%s' % ".tns",
                              '--number',
                              inputFilename, inputFilename2])
        result = lore.runGivenOptions(options)

        self.assertEqual(None, result)
        #self.assertEqualFiles1("lore_index_file_out_multiple.html", indexFilename + ".tns")
        #                       VVV change to new, numbered files
        self.assertEqualFiles("lore_numbering_test_out.html", "lore_numbering_test.tns")
        self.assertEqualFiles("lore_numbering_test_out2.html", "lore_numbering_test2.tns")


    def test_setTitle(self):
        """
        L{tree.setTitle} inserts the given title into the first I{title}
        element and the first element with the I{title} class in the given
        template.
        """
        parent = dom.Element('div')
        firstTitle = dom.Element('title')
        parent.appendChild(firstTitle)
        secondTitle = dom.Element('span')
        secondTitle.setAttribute('class', 'title')
        parent.appendChild(secondTitle)

        titleNodes = [dom.Text()]
        # minidom has issues with cloning documentless-nodes.  See Python issue
        # 4851.
        titleNodes[0].ownerDocument = dom.Document()
        titleNodes[0].data = 'foo bar'

        tree.setTitle(parent, titleNodes, None)
        self.assertEqual(firstTitle.toxml(), '<title>foo bar</title>')
        self.assertEqual(
            secondTitle.toxml(), '<span class="title">foo bar</span>')


    def test_setTitleWithChapter(self):
        """
        L{tree.setTitle} includes a chapter number if it is passed one.
        """
        document = dom.Document()

        parent = dom.Element('div')
        parent.ownerDocument = document

        title = dom.Element('title')
        parent.appendChild(title)

        titleNodes = [dom.Text()]
        titleNodes[0].ownerDocument = document
        titleNodes[0].data = 'foo bar'

        # Oh yea.  The numberer has to agree to put the chapter number in, too.
        numberer.setNumberSections(True)

        tree.setTitle(parent, titleNodes, '13')
        self.assertEqual(title.toxml(), '<title>13. foo bar</title>')


    def test_setIndexLink(self):
        """
        Tests to make sure that index links are processed when an index page
        exists and removed when there is not.
        """
        templ = dom.parse(open(d['template']))
        indexFilename = 'theIndexFile'
        numLinks = len(domhelpers.findElementsWithAttribute(templ,
                                                            "class",
                                                            "index-link"))

        # if our testing template has no index-link nodes, complain about it
        self.assertNotEquals(
            [],
            domhelpers.findElementsWithAttribute(templ,
                                                 "class",
                                                 "index-link"))

        tree.setIndexLink(templ, indexFilename)

        self.assertEqual(
            [],
            domhelpers.findElementsWithAttribute(templ,
                                                 "class",
                                                 "index-link"))

        indexLinks = domhelpers.findElementsWithAttribute(templ,
                                                          "href",
                                                          indexFilename)
        self.assertTrue(len(indexLinks) >= numLinks)

        templ = dom.parse(open(d['template']))
        self.assertNotEquals(
            [],
            domhelpers.findElementsWithAttribute(templ,
                                                 "class",
                                                 "index-link"))
        indexFilename = None

        tree.setIndexLink(templ, indexFilename)

        self.assertEqual(
            [],
            domhelpers.findElementsWithAttribute(templ,
                                                 "class",
                                                 "index-link"))


    def test_addMtime(self):
        """
        L{tree.addMtime} inserts a text node giving the last modification time
        of the specified file wherever it encounters an element with the
        I{mtime} class.
        """
        path = FilePath(self.mktemp())
        path.setContent('')
        when = time.ctime(path.getModificationTime())

        parent = dom.Element('div')
        mtime = dom.Element('span')
        mtime.setAttribute('class', 'mtime')
        parent.appendChild(mtime)

        tree.addMtime(parent, path.path)
        self.assertEqual(
            mtime.toxml(), '<span class="mtime">' + when + '</span>')


    def test_makeLineNumbers(self):
        """
        L{tree._makeLineNumbers} takes an integer and returns a I{p} tag with
        that number of line numbers in it.
        """
        numbers = tree._makeLineNumbers(1)
        self.assertEqual(numbers.tagName, 'p')
        self.assertEqual(numbers.getAttribute('class'), 'py-linenumber')
        self.assertIsInstance(numbers.firstChild, dom.Text)
        self.assertEqual(numbers.firstChild.nodeValue, '1\n')

        numbers = tree._makeLineNumbers(10)
        self.assertEqual(numbers.tagName, 'p')
        self.assertEqual(numbers.getAttribute('class'), 'py-linenumber')
        self.assertIsInstance(numbers.firstChild, dom.Text)
        self.assertEqual(
            numbers.firstChild.nodeValue,
            ' 1\n 2\n 3\n 4\n 5\n'
            ' 6\n 7\n 8\n 9\n10\n')


    def test_fontifyPythonNode(self):
        """
        L{tree.fontifyPythonNode} accepts a text node and replaces it in its
        parent with a syntax colored and line numbered version of the Python
        source it contains.
        """
        parent = dom.Element('div')
        source = dom.Text()
        source.data = 'def foo():\n    pass\n'
        parent.appendChild(source)

        tree.fontifyPythonNode(source)

        expected = """\
<div><pre class="python"><p class="py-linenumber">1
2
</p><span class="py-src-keyword">def</span> <span class="py-src-identifier">foo</span>():
    <span class="py-src-keyword">pass</span>
</pre></div>"""

        self.assertEqual(parent.toxml(), expected)


    def test_addPyListings(self):
        """
        L{tree.addPyListings} accepts a document with nodes with their I{class}
        attribute set to I{py-listing} and replaces those nodes with Python
        source listings from the file given by the node's I{href} attribute.
        """
        listingPath = FilePath(self.mktemp())
        listingPath.setContent('def foo():\n    pass\n')

        parent = dom.Element('div')
        listing = dom.Element('a')
        listing.setAttribute('href', listingPath.basename())
        listing.setAttribute('class', 'py-listing')
        parent.appendChild(listing)

        tree.addPyListings(parent, listingPath.dirname())

        expected = """\
<div><div class="py-listing"><pre><p class="py-linenumber">1
2
</p><span class="py-src-keyword">def</span> <span class="py-src-identifier">foo</span>():
    <span class="py-src-keyword">pass</span>
</pre><div class="caption"> - <a href="temp"><span class="filename">temp</span></a></div></div></div>"""

        self.assertEqual(parent.toxml(), expected)


    def test_addPyListingsSkipLines(self):
        """
        If a node with the I{py-listing} class also has a I{skipLines}
        attribute, that number of lines from the beginning of the source
        listing are omitted.
        """
        listingPath = FilePath(self.mktemp())
        listingPath.setContent('def foo():\n    pass\n')

        parent = dom.Element('div')
        listing = dom.Element('a')
        listing.setAttribute('href', listingPath.basename())
        listing.setAttribute('class', 'py-listing')
        listing.setAttribute('skipLines', 1)
        parent.appendChild(listing)

        tree.addPyListings(parent, listingPath.dirname())

        expected = """\
<div><div class="py-listing"><pre><p class="py-linenumber">1
</p>    <span class="py-src-keyword">pass</span>
</pre><div class="caption"> - <a href="temp"><span class="filename">temp</span></a></div></div></div>"""

        self.assertEqual(parent.toxml(), expected)


    def test_fixAPI(self):
        """
        The element passed to L{tree.fixAPI} has all of its children with the
        I{API} class rewritten to contain links to the API which is referred to
        by the text they contain.
        """
        parent = dom.Element('div')
        link = dom.Element('span')
        link.setAttribute('class', 'API')
        text = dom.Text()
        text.data = 'foo'
        link.appendChild(text)
        parent.appendChild(link)

        tree.fixAPI(parent, 'http://example.com/%s')
        self.assertEqual(
            parent.toxml(),
            '<div><span class="API">'
            '<a href="http://example.com/foo" title="foo">foo</a>'
            '</span></div>')


    def test_fixAPIBase(self):
        """
        If a node with the I{API} class and a value for the I{base} attribute
        is included in the DOM passed to L{tree.fixAPI}, the link added to that
        node refers to the API formed by joining the value of the I{base}
        attribute to the text contents of the node.
        """
        parent = dom.Element('div')
        link = dom.Element('span')
        link.setAttribute('class', 'API')
        link.setAttribute('base', 'bar')
        text = dom.Text()
        text.data = 'baz'
        link.appendChild(text)
        parent.appendChild(link)

        tree.fixAPI(parent, 'http://example.com/%s')

        self.assertEqual(
            parent.toxml(),
            '<div><span class="API">'
            '<a href="http://example.com/bar.baz" title="bar.baz">baz</a>'
            '</span></div>')


    def test_fixLinks(self):
        """
        Links in the nodes of the DOM passed to L{tree.fixLinks} have their
        extensions rewritten to the given extension.
        """
        parent = dom.Element('div')
        link = dom.Element('a')
        link.setAttribute('href', 'foo.html')
        parent.appendChild(link)

        tree.fixLinks(parent, '.xhtml')

        self.assertEqual(parent.toxml(), '<div><a href="foo.xhtml"/></div>')


    def test_setVersion(self):
        """
        Nodes of the DOM passed to L{tree.setVersion} which have the I{version}
        class have the given version added to them a child.
        """
        parent = dom.Element('div')
        version = dom.Element('span')
        version.setAttribute('class', 'version')
        parent.appendChild(version)

        tree.setVersion(parent, '1.2.3')

        self.assertEqual(
            parent.toxml(), '<div><span class="version">1.2.3</span></div>')


    def test_footnotes(self):
        """
        L{tree.footnotes} finds all of the nodes with the I{footnote} class in
        the DOM passed to it and adds a footnotes section to the end of the
        I{body} element which includes them.  It also inserts links to those
        footnotes from the original definition location.
        """
        parent = dom.Element('div')
        body = dom.Element('body')
        footnote = dom.Element('span')
        footnote.setAttribute('class', 'footnote')
        text = dom.Text()
        text.data = 'this is the footnote'
        footnote.appendChild(text)
        body.appendChild(footnote)
        body.appendChild(dom.Element('p'))
        parent.appendChild(body)

        tree.footnotes(parent)

        self.assertEqual(
            parent.toxml(),
            '<div><body>'
            '<a href="#footnote-1" title="this is the footnote">'
            '<super>1</super>'
            '</a>'
            '<p/>'
            '<h2>Footnotes</h2>'
            '<ol><li><a name="footnote-1">'
            '<span class="footnote">this is the footnote</span>'
            '</a></li></ol>'
            '</body></div>')


    def test_generateTableOfContents(self):
        """
        L{tree.generateToC} returns an element which contains a table of
        contents generated from the headers in the document passed to it.
        """
        parent = dom.Element('body')
        header = dom.Element('h2')
        text = dom.Text()
        text.data = u'header & special character'
        header.appendChild(text)
        parent.appendChild(header)
        subheader = dom.Element('h3')
        text = dom.Text()
        text.data = 'subheader'
        subheader.appendChild(text)
        parent.appendChild(subheader)

        tableOfContents = tree.generateToC(parent)
        self.assertEqual(
            tableOfContents.toxml(),
            '<ol><li><a href="#auto0">header &amp; special character</a></li><ul><li><a href="#auto1">subheader</a></li></ul></ol>')

        self.assertEqual(
            header.toxml(),
            '<h2>header &amp; special character<a name="auto0"/></h2>')

        self.assertEqual(
            subheader.toxml(),
            '<h3>subheader<a name="auto1"/></h3>')


    def test_putInToC(self):
        """
        L{tree.putInToC} replaces all of the children of the first node with
        the I{toc} class with the given node representing a table of contents.
        """
        parent = dom.Element('div')
        toc = dom.Element('span')
        toc.setAttribute('class', 'toc')
        toc.appendChild(dom.Element('foo'))
        parent.appendChild(toc)

        tree.putInToC(parent, dom.Element('toc'))

        self.assertEqual(toc.toxml(), '<span class="toc"><toc/></span>')


    def test_invalidTableOfContents(self):
        """
        If passed a document with I{h3} elements before any I{h2} element,
        L{tree.generateToC} raises L{ValueError} explaining that this is not a
        valid document.
        """
        parent = dom.Element('body')
        parent.appendChild(dom.Element('h3'))
        err = self.assertRaises(ValueError, tree.generateToC, parent)
        self.assertEqual(
            str(err), "No H3 element is allowed until after an H2 element")


    def test_notes(self):
        """
        L{tree.notes} inserts some additional markup before the first child of
        any node with the I{note} class.
        """
        parent = dom.Element('div')
        noteworthy = dom.Element('span')
        noteworthy.setAttribute('class', 'note')
        noteworthy.appendChild(dom.Element('foo'))
        parent.appendChild(noteworthy)

        tree.notes(parent)

        self.assertEqual(
            noteworthy.toxml(),
            '<span class="note"><strong>Note: </strong><foo/></span>')


    def test_findNodeJustBefore(self):
        """
        L{tree.findNodeJustBefore} returns the previous sibling of the node it
        is passed.  The list of nodes passed in is ignored.
        """
        parent = dom.Element('div')
        result = dom.Element('foo')
        target = dom.Element('bar')
        parent.appendChild(result)
        parent.appendChild(target)

        self.assertIdentical(
            tree.findNodeJustBefore(target, [parent, result]),
            result)

        # Also, support other configurations.  This is a really not nice API.
        newTarget = dom.Element('baz')
        target.appendChild(newTarget)
        self.assertIdentical(
            tree.findNodeJustBefore(newTarget, [parent, result]),
            result)


    def test_getSectionNumber(self):
        """
        L{tree.getSectionNumber} accepts an I{H2} element and returns its text
        content.
        """
        header = dom.Element('foo')
        text = dom.Text()
        text.data = 'foobar'
        header.appendChild(text)
        self.assertEqual(tree.getSectionNumber(header), 'foobar')


    def test_numberDocument(self):
        """
        L{tree.numberDocument} inserts section numbers into the text of each
        header.
        """
        parent = dom.Element('foo')
        section = dom.Element('h2')
        text = dom.Text()
        text.data = 'foo'
        section.appendChild(text)
        parent.appendChild(section)

        tree.numberDocument(parent, '7')

        self.assertEqual(section.toxml(), '<h2>7.1 foo</h2>')


    def test_parseFileAndReport(self):
        """
        L{tree.parseFileAndReport} parses the contents of the filename passed
        to it and returns the corresponding DOM.
        """
        path = FilePath(self.mktemp())
        path.setContent('<foo bar="baz">hello</foo>\n')

        document = tree.parseFileAndReport(path.path)
        self.assertXMLEqual(
            document.toxml(),
            '<?xml version="1.0" ?><foo bar="baz">hello</foo>')


    def test_parseFileAndReportMismatchedTags(self):
        """
        If the contents of the file passed to L{tree.parseFileAndReport}
        contain a mismatched tag, L{process.ProcessingFailure} is raised
        indicating the location of the open and close tags which were
        mismatched.
        """
        path = FilePath(self.mktemp())
        path.setContent('  <foo>\n\n  </bar>')

        err = self.assertRaises(
            process.ProcessingFailure, tree.parseFileAndReport, path.path)
        self.assertEqual(
            str(err),
            "mismatched close tag at line 3, column 4; expected </foo> "
            "(from line 1, column 2)")

        # Test a case which requires involves proper close tag handling.
        path.setContent('<foo><bar></bar>\n  </baz>')

        err = self.assertRaises(
            process.ProcessingFailure, tree.parseFileAndReport, path.path)
        self.assertEqual(
            str(err),
            "mismatched close tag at line 2, column 4; expected </foo> "
            "(from line 1, column 0)")


    def test_parseFileAndReportParseError(self):
        """
        If the contents of the file passed to L{tree.parseFileAndReport} cannot
        be parsed for a reason other than mismatched tags,
        L{process.ProcessingFailure} is raised with a string describing the
        parse error.
        """
        path = FilePath(self.mktemp())
        path.setContent('\n   foo')

        err = self.assertRaises(
            process.ProcessingFailure, tree.parseFileAndReport, path.path)
        self.assertEqual(str(err), 'syntax error at line 2, column 3')


    def test_parseFileAndReportIOError(self):
        """
        If an L{IOError} is raised while reading from the file specified to
        L{tree.parseFileAndReport}, a L{process.ProcessingFailure} is raised
        indicating what the error was.  The file should be closed by the
        time the exception is raised to the caller.
        """
        class FakeFile:
            _open = True
            def read(self, bytes=None):
                raise IOError(errno.ENOTCONN, 'socket not connected')

            def close(self):
                self._open = False

        theFile = FakeFile()
        def fakeOpen(filename):
            return theFile

        err = self.assertRaises(
            process.ProcessingFailure, tree.parseFileAndReport, "foo", fakeOpen)
        self.assertEqual(str(err), "socket not connected, filename was 'foo'")
        self.assertFalse(theFile._open)



class XMLParsingTests(unittest.TestCase):
    """
    Tests for various aspects of parsing a Lore XML input document using
    L{tree.parseFileAndReport}.
    """
    def _parseTest(self, xml):
        path = FilePath(self.mktemp())
        path.setContent(xml)
        return tree.parseFileAndReport(path.path)


    def test_withoutDocType(self):
        """
        A Lore XML input document may omit a I{DOCTYPE} declaration.  If it
        does so, the XHTML1 Strict DTD is used.
        """
        # Parsing should succeed.
        document = self._parseTest("<foo>uses an xhtml entity: &copy;</foo>")
        # But even more than that, the &copy; entity should be turned into the
        # appropriate unicode codepoint.
        self.assertEqual(
            domhelpers.gatherTextNodes(document.documentElement),
            u"uses an xhtml entity: \N{COPYRIGHT SIGN}")


    def test_withTransitionalDocType(self):
        """
        A Lore XML input document may include a I{DOCTYPE} declaration
        referring to the XHTML1 Transitional DTD.
        """
        # Parsing should succeed.
        document = self._parseTest("""\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<foo>uses an xhtml entity: &copy;</foo>
""")
        # But even more than that, the &copy; entity should be turned into the
        # appropriate unicode codepoint.
        self.assertEqual(
            domhelpers.gatherTextNodes(document.documentElement),
            u"uses an xhtml entity: \N{COPYRIGHT SIGN}")


    def test_withStrictDocType(self):
        """
        A Lore XML input document may include a I{DOCTYPE} declaration
        referring to the XHTML1 Strict DTD.
        """
        # Parsing should succeed.
        document = self._parseTest("""\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<foo>uses an xhtml entity: &copy;</foo>
""")
        # But even more than that, the &copy; entity should be turned into the
        # appropriate unicode codepoint.
        self.assertEqual(
            domhelpers.gatherTextNodes(document.documentElement),
            u"uses an xhtml entity: \N{COPYRIGHT SIGN}")


    def test_withDisallowedDocType(self):
        """
        A Lore XML input document may not include a I{DOCTYPE} declaration
        referring to any DTD other than XHTML1 Transitional or XHTML1 Strict.
        """
        self.assertRaises(
            process.ProcessingFailure,
            self._parseTest,
            """\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<foo>uses an xhtml entity: &copy;</foo>
""")



class XMLSerializationTests(unittest.TestCase, _XMLAssertionMixin):
    """
    Tests for L{tree._writeDocument}.
    """
    def test_nonASCIIData(self):
        """
        A document which contains non-ascii characters is serialized to a
        file using UTF-8.
        """
        document = dom.Document()
        parent = dom.Element('foo')
        text = dom.Text()
        text.data = u'\N{SNOWMAN}'
        parent.appendChild(text)
        document.appendChild(parent)
        outFile = self.mktemp()
        tree._writeDocument(outFile, document)
        self.assertXMLEqual(
            FilePath(outFile).getContent(),
            u'<foo>\N{SNOWMAN}</foo>'.encode('utf-8'))



class LatexSpitterTestCase(unittest.TestCase):
    """
    Tests for the Latex output plugin.
    """
    def test_indexedSpan(self):
        """
        Test processing of a span tag with an index class results in a latex
        \\index directive the correct value.
        """
        doc = dom.parseString('<span class="index" value="name" />').documentElement
        out = StringIO()
        spitter = LatexSpitter(out.write)
        spitter.visitNode(doc)
        self.assertEqual(out.getvalue(), u'\\index{name}\n')



class ScriptTests(unittest.TestCase):
    """
    Tests for L{twisted.lore.scripts.lore}, the I{lore} command's
    implementation,
    """
    def test_getProcessor(self):
        """
        L{lore.getProcessor} loads the specified output plugin from the
        specified input plugin.
        """
        processor = lore.getProcessor("lore", "html", options)
        self.assertNotIdentical(processor, None)