1#!/bin/env python
2#Copyright ReportLab Europe Ltd. 2000-2017
3#see license.txt for license details
4__doc__="""Verfy that if in invariant mode, repeated runs
5make identical file.  This does NOT test across platforms
6or python versions, only a user can do that :-)"""
7__version__='3.3.0'
8from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile, printLocation
9setOutDir(__name__)
10
11import unittest
12from reportlab.pdfgen.canvas import Canvas
13filename = outputfile('test_invariant.pdf')
14
15class InvarTestCase(unittest.TestCase):
16    "Simplest test that makes PDF"
17    def test0(self):
18        import os
19        from reportlab.lib.testutils import testsFolder
20        c = Canvas(filename, invariant=1, pageCompression=0)
21        c.setFont('Helvetica-Bold', 36)
22        c.drawString(100,700, 'Hello World')
23        gif = os.path.join(testsFolder,'pythonpowered.gif')
24        c.drawImage(gif,100,600)
25        c.save()
26
27        with open(filename, 'rb') as f:
28            raw1 = f.read()
29
30        c = Canvas(filename, invariant=1, pageCompression=0)
31        c.setFont('Helvetica-Bold', 36)
32        c.drawString(100,700, 'Hello World')
33        c.drawImage(gif,100,600)
34        c.save()
35
36        with open(filename, 'rb') as f:
37            raw2 = f.read()
38
39        assert raw1 == raw2, 'repeated runs differ!'
40
41    def test1(self):
42        import os
43        from reportlab.lib.testutils import testsFolder
44        filename = outputfile('test_no_helvetica.pdf')
45        c = Canvas(filename, invariant=1, pageCompression=0, initialFontName='Times-Roman')
46        c.drawString(100,700, 'Hello World')
47        c.save()
48        with open(filename, 'rb') as f:
49            raw = f.read()
50        assert b'Helvetica' not in raw and b'Times-Roman' in raw, 'Canvas initialFontName expectations not satisfied!'
51
52def makeSuite():
53    return makeSuiteForClasses(InvarTestCase)
54
55
56#noruntests
57if __name__ == "__main__":
58    # add some diagnostics, useful in invariant tests
59    import sys, os
60    from reportlab.lib.utils import md5, bytestr
61    verbose = ('-v' in sys.argv)
62    unittest.TextTestRunner().run(makeSuite())
63    if verbose:
64        #tell us about the file we produced
65        fileSize = os.stat(filename)[6]
66        raw = open(filename,'rb').read()
67        digest = md5.md5(bytestr(raw)).hexdigest()
68        major, minor = sys.version_info[0:2]
69        print('%s on %s (Python %d.%d):\n    %d bytes, digest %s' % (
70            filename,sys.platform, major, minor, fileSize, digest))
71    printLocation()
72