-
Notifications
You must be signed in to change notification settings - Fork 149
/
conftest.py
300 lines (213 loc) · 8.51 KB
/
conftest.py
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
"""
Copyright (c) 2020, Stephen Finucane <stephen@that.guru>
Automated testing for rst2pdf.
See LICENSE.txt for licensing terms
"""
import glob
import os
import shlex
import shutil
import subprocess
import tempfile
import fitz
from packaging import version
import pytest
ROOT_DIR = os.path.realpath(os.path.dirname(__file__))
INPUT_DIR = os.path.join(ROOT_DIR, 'input')
OUTPUT_DIR = os.path.join(ROOT_DIR, 'output')
REFERENCE_DIR = os.path.join(ROOT_DIR, 'reference')
def _get_metadata(pdf):
metadata = pdf.metadata
del metadata['creationDate']
del metadata['modDate']
return metadata
def _get_pages(pdf):
pages = []
for page in pdf.pages():
pages.append(page.getText('blocks'))
return pages
def compare_pdfs(path_a, path_b):
pdf_a = fitz.open(path_a)
pdf_b = fitz.open(path_b)
# sanity check
assert pdf_a.isPDF
assert pdf_b.isPDF
# compare metadata
assert _get_metadata(pdf_a) == _get_metadata(pdf_b)
# compare content
pages_a = _get_pages(pdf_a)
pages_b = _get_pages(pdf_b)
def fuzzy_coord_diff(coord_a, coord_b):
diff = abs(coord_a - coord_b)
assert diff / max(coord_a, coord_b) < 0.04 # allow an arbitrary diff
def fuzzy_string_diff(string_a, string_b):
words_a = string_a.split()
words_b = string_a.split()
assert words_a == words_b
assert len(pages_a) == len(pages_b)
for page_a, page_b in zip(pages_a, pages_b):
assert len(page_a) == len(page_b)
for block_a, block_b in zip(page_a, page_b):
# each block has the following format:
#
# (x0, y0, x1, y1, "lines in block", block_type, block_no)
#
# block_type and block_no should remain unchanged, but it's
# possible for the blocks to move around the document slightly and
# the text refold without breaking entirely
fuzzy_coord_diff(block_a[0], block_b[0])
fuzzy_coord_diff(block_a[1], block_b[1])
fuzzy_coord_diff(block_a[2], block_b[2])
fuzzy_coord_diff(block_a[3], block_b[3])
fuzzy_string_diff(block_a[4], block_b[4])
assert block_a[5] == block_b[5]
assert block_a[6] == block_b[6]
class File(pytest.File):
if version.parse(pytest.__version__) < version.parse('5.4.0'):
@classmethod
def from_parent(cls, parent, fspath):
return cls(parent=parent, fspath=fspath)
class TxtFile(File):
def collect(self):
name = os.path.splitext(self.fspath.basename)[0]
yield TxtItem.from_parent(parent=self, name=name)
class SphinxFile(File):
def collect(self):
name = os.path.split(self.fspath.dirname)[-1]
yield SphinxItem.from_parent(parent=self, name=name)
class Item(pytest.Item):
if version.parse(pytest.__version__) < version.parse('5.4.0'):
@classmethod
def from_parent(cls, parent, name):
return cls(parent=parent, name=name)
def _build(self):
raise NotImplementedError
def runtest(self):
__tracebackhide__ = True
# if '.ignore' file present, skip test
ignore_file = os.path.join(INPUT_DIR, self.name + '.ignore')
if os.path.exists(ignore_file):
with open(ignore_file) as fh:
ignore_reason = fh.read()
pytest.skip(ignore_reason)
# run the actual test
retcode, output = self._build()
# verify results
if retcode:
pytest.fail('Call failed with %d:\n\n%s' % (retcode, output))
no_pdf = os.path.exists(os.path.join(INPUT_DIR, self.name + '.nopdf'))
if no_pdf:
return
output_file = os.path.join(OUTPUT_DIR, self.name + '.pdf')
reference_file = os.path.join(REFERENCE_DIR, self.name + '.pdf')
if os.path.isdir(output_file):
assert os.path.isdir(reference_file), (
'Mismatch between type of output (dir) and reference (file)'
)
output_files = glob.glob(os.path.join(output_file, '*.pdf'))
reference_files = glob.glob(os.path.join(reference_file, '*.pdf'))
else:
assert os.path.isfile(reference_file), (
'Mismatch between type of output (file) and reference (dir)'
)
output_files = [output_file]
reference_files = [reference_file]
assert len(reference_files) == len(output_files), (
'Mismatch between number of files expected and number generated'
)
reference_files.sort()
output_files.sort()
for ref_pdf, out_pdf in zip(reference_files, output_files):
try:
compare_pdfs(ref_pdf, out_pdf)
except AssertionError as exc:
raise CompareException(exc)
def repr_failure(self, excinfo):
""" called when self.runtest() raises an exception. """
if isinstance(excinfo.value, CompareException):
return excinfo.exconly()
return super(Item, self).repr_failure(excinfo)
def reportinfo(self):
return self.fspath, 0, self.name
class TxtItem(Item):
def _build(self):
input_ref = self.name + '.txt'
output_pdf = os.path.join(OUTPUT_DIR, self.name + '.pdf')
output_log = os.path.join(OUTPUT_DIR, self.name + '.log')
for path in (output_log, output_pdf):
if os.path.exists(path):
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
cmd = ['rst2pdf', '--date-invariant', '-v', input_ref]
cli_file = os.path.join(INPUT_DIR, self.name + '.cli')
if os.path.exists(cli_file):
with open(cli_file) as fh:
cmd += shlex.split(fh.read())
style_file = os.path.join(INPUT_DIR, self.name + '.style')
if os.path.exists(style_file):
cmd += ['-s', os.path.basename(style_file)]
cmd += ['-o', output_pdf]
try:
output = subprocess.check_output(
cmd, cwd=INPUT_DIR, stderr=subprocess.STDOUT,
)
retcode = 0
except subprocess.CalledProcessError as exc:
output = exc.output
retcode = exc.returncode
with open(output_log, 'wb') as fh:
fh.write(output)
output_file = os.path.join(OUTPUT_DIR, self.name + '.pdf')
no_pdf = os.path.exists(os.path.join(INPUT_DIR, self.name + '.nopdf'))
if not os.path.exists(output_file):
assert no_pdf, 'File %s not generated' % os.path.basename(
output_file
)
return retcode, output
class SphinxItem(Item):
def _build(self):
__tracebackhide__ = True
output_pdf = os.path.join(OUTPUT_DIR, self.name + '.pdf')
output_log = os.path.join(OUTPUT_DIR, self.name + '.log')
for path in (output_log, output_pdf):
if os.path.exists(path):
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
input_dir = os.path.join(INPUT_DIR, self.name)
build_dir = tempfile.mkdtemp(prefix='rst2pdf-sphinx-')
cmd = ['sphinx-build', '-b', 'pdf', input_dir, build_dir]
try:
output = subprocess.check_output(
cmd, cwd=INPUT_DIR, stderr=subprocess.STDOUT,
)
retcode = 0
except subprocess.CalledProcessError as exc:
output = exc.output
retcode = exc.returncode
with open(output_log, 'wb') as fh:
fh.write(output)
pdf_files = glob.glob(os.path.join(build_dir, '*.pdf'))
if pdf_files:
if len(pdf_files) == 1:
shutil.copyfile(pdf_files[0], output_pdf)
else:
shutil.copytree(build_dir, output_pdf)
else:
pytest.fail('Output PDF not generated')
shutil.rmtree(build_dir)
return retcode, output
class CompareException(Exception):
"""Custom exception for error reporting."""
def pytest_collect_file(parent, path):
if not (path.fnmatch('*/input') or path.fnmatch('*/input/*')):
return
parent_dir = os.path.split(path.dirname)[-1]
if path.ext == '.txt' and parent_dir == 'input':
return TxtFile.from_parent(parent=parent, fspath=path)
elif path.basename == 'conf.py' and parent_dir.startswith('sphinx'):
return SphinxFile.from_parent(parent=parent, fspath=path)
collect_ignore = ['rst2pdf/tests/input/*.py']