forked from Trust-Code/python-boleto
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestutils.py
More file actions
206 lines (169 loc) · 6.18 KB
/
testutils.py
File metadata and controls
206 lines (169 loc) · 6.18 KB
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
# -*- coding: utf-8 -*-
from __future__ import with_statement
import difflib
import fnmatch
import os
import re
import sys
import subprocess
import tempfile
import unittest
from xml.etree.ElementTree import fromstring, tostring
import pyboleto
try:
from pyboleto.pdf import BoletoPDF
except ImportError as err:
if sys.version_info >= (3,):
pass # Reportlab doesn;t support Python3
else:
raise(err)
def list_recursively(directory, pattern):
"""Returns files recursively from directory matching pattern
:param directory: directory to list
:param pattern: glob mattern to match
"""
matches = []
for root, _, filenames in os.walk(directory):
for filename in fnmatch.filter(filenames, pattern):
# skip backup files
if (filename.startswith('.#') or
filename.endswith('~')):
continue
matches.append(os.path.join(root, filename))
return matches
def get_sources(root):
for dirpath in ['pyboleto', 'tests']:
path = os.path.join(root, dirpath)
for fname in list_recursively(path, '*.py'):
if fname.endswith('__init__.py'):
continue
yield fname
# yield os.path.join(root, 'setup.py')
def _diff(orig, new, short, verbose):
lines = difflib.unified_diff(orig, new)
if not lines:
return ''
return ''.join('%s: %s' % (short, line) for line in lines)
def diff_files(orig, new, verbose=False):
with open(orig) as f_orig:
with open(new) as f_new:
return _diff(f_orig.readlines(),
f_new.readlines(),
short=os.path.basename(orig),
verbose=verbose)
def diff_pdf_htmls(original_filename, filename):
# REPLACE all generated dates with %%DATE%%
for fname in [original_filename, filename]:
with open(fname) as f:
data = f.read()
data = re.sub(r'name="date" content="(.*)"',
r'name="date" content="%%DATE%%"', data)
data = re.sub(r'<pdf2xml[^>]+>', r'<pdf2xml>', data)
with open(fname, 'w') as f:
f.write(data)
return diff_files(original_filename, filename)
class ClassInittableMetaType(type):
# pylint fails to understand this is a metaclass
def __init__(self, name, bases, namespace):
type.__init__(self, name, bases, namespace)
self.__class_init__(namespace)
class SourceTest(object):
__metaclass__ = ClassInittableMetaType
@classmethod
def __class_init__(cls, namespace):
root = os.path.dirname(os.path.dirname(pyboleto.__file__))
cls.root = root
for filename in get_sources(root):
testname = filename[len(root):]
if not cls.filename_filter(testname):
continue
testname = testname[:-3].replace('/', '_')
name = 'test_%s' % (testname, )
# func = lambda self, r=root, f=filename: self.check_filename(r, f)
def func(self, r=root, f=filename):
self.check_filename(r, f)
func.__name__ = name
setattr(cls, name, func)
def check_filename(self, root, filename):
pass
@classmethod
def filename_filter(cls, filename):
if cls.__name__ == 'SourceTest':
return False
else:
return True
def indent(elem, level=0):
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def pdftoxml(filename, output):
p = subprocess.Popen(['pdftohtml',
'-stdout',
'-xml',
'-noframes',
'-i',
'-q',
filename],
stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
if stderr:
raise SystemExit("Error while runnig pdftohtml: %s" % (stderr, ))
root = fromstring(stdout)
indent(root)
with open(output, 'wb') as f:
f.write(tostring(root))
class BoletoTestCase(unittest.TestCase):
def _get_expected(self, bank, generated):
fname = os.path.join(os.path.dirname(pyboleto.__file__),
"..", "tests", "xml", bank + '-expected.xml')
if not os.path.exists(fname):
with open(fname, 'wb') as f:
with open(generated) as g:
f.write(g.read())
return fname
@unittest.skip("Não Implementado")
def test_pdf_triplo_rendering(self):
bank = type(self.dados[0]).__name__
filename = tempfile.mktemp(prefix="pyboleto-triplo-",
suffix=".pdf")
boleto = BoletoPDF(filename, True)
for d in self.dados:
boleto.drawBoleto(d)
boleto.nextPage()
boleto.save()
generated = filename + '.xml'
pdftoxml(filename, generated)
expected = self._get_expected('Triplo-' + bank, generated)
diff = diff_pdf_htmls(expected, generated)
if diff:
self.fail("Error while checking xml for %r:\n%s" % (
bank, diff))
os.unlink(generated)
@unittest.skip("Não Implementado")
def test_pdf_rendering(self):
dados = self.dados[0]
bank = type(dados).__name__
filename = tempfile.mktemp(prefix="pyboleto-",
suffix=".pdf")
boleto = BoletoPDF(filename, True)
boleto.drawBoleto(dados)
boleto.nextPage()
boleto.save()
generated = filename + '.xml'
pdftoxml(filename, generated)
expected = self._get_expected(bank, generated)
diff = diff_pdf_htmls(expected, generated)
if diff:
self.fail("Error while checking xml for %r:\n%s" % (
bank, diff))
os.unlink(generated)