This repository has been archived by the owner on Dec 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathBaseTestClasses.py
434 lines (348 loc) · 15.2 KB
/
BaseTestClasses.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
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
from PyPDF2 import PdfFileReader
from datetime import datetime
from datetime import timedelta
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
from reportlab.pdfgen import canvas
from requests.exceptions import RequestException
from subprocess import Popen, PIPE
import io
import imghdr
import logging
import inspect
import os
import os.path
import pdfminer.high_level
import requests
import shutil
import sys
import tempfile
import unittest
class Email2PDFTestCase(unittest.TestCase):
isOnline = None
examineDir = None
time_invoked = None
time_completed = None
NONEXIST_IMG = 'http://www.andrewferrier.com/nonexist.jpg'
NONEXIST_IMG_BLACKLIST = 'http://www.emltrk.com/nonexist.jpg'
EXIST_IMG = 'https://raw.githubusercontent.com/andrewferrier/email2pdf/master/tests/basi2c16.png'
EXIST_IMG_UPPERCASE = 'https://raw.githubusercontent.com/andrewferrier/email2pdf/master/tests/UPPERCASE.png'
COMMAND = os.path.normpath(os.path.join(os.getcwd(), 'email2pdf'))
DEFAULT_FROM = "[email protected]"
DEFAULT_TO = "[email protected]"
DEFAULT_SUBJECT = "Subject of the email"
JPG_FILENAME = 'tests/jpeg444.jpg'
PNG_FILENAME = 'tests/basi2c16.png'
JPG_SIZE = os.path.getsize(JPG_FILENAME)
PNG_SIZE = os.path.getsize(PNG_FILENAME)
WARNINGS_AND_ERRORS_POSTFIX = "_warnings_and_errors.txt"
ORIGINAL_EMAIL_POSTFIX = "_original.eml"
def setUp(self):
self.workingDir = tempfile.mkdtemp(dir='/tmp')
self._check_online()
self._check_examine_dir()
def getTimeStamp(self, my_time):
return my_time.strftime("%Y-%m-%dT%H-%M-%S")
def existsByTime(self, path=None):
if self.getTimedFilename(path):
return True
else:
return False
def existsByTimeWarning(self):
if self.getTimedFilename(postfix=self.WARNINGS_AND_ERRORS_POSTFIX):
return True
else:
return False
def existsByTimeOriginal(self):
if self.getTimedFilename(postfix=self.ORIGINAL_EMAIL_POSTFIX):
return True
else:
return False
def getWarningFileContents(self):
filename = self.getTimedFilename(postfix=self.WARNINGS_AND_ERRORS_POSTFIX)
with open(filename) as f:
return f.read()
def assertValidOriginalFileContents(self, filename=None):
try:
if not filename:
filename = self.getTimedFilename(postfix=self.ORIGINAL_EMAIL_POSTFIX)
with open(filename, 'rb') as f:
contents = f.read()
assert(contents == self.msg.as_bytes())
except:
raise AssertionError("General error validating email, contents=" + contents +
"\n, self.msg.as_string=" + self.msg.as_string())
def getTimedFilename(self, path=None, postfix=".pdf"):
if path is None:
path = self.workingDir
for single_time in self._timerange(self.time_invoked, self.time_completed):
filename = os.path.join(path, self.getTimeStamp(single_time) + postfix)
if os.path.exists(filename):
return filename
return None
def addHeaders(self, frm=DEFAULT_FROM, to=DEFAULT_TO, subject=DEFAULT_SUBJECT, subject_encoding=None):
if subject:
if subject_encoding:
assert isinstance(subject, bytes)
header = Header(subject, subject_encoding)
self.msg['Subject'] = header
else:
assert isinstance(subject, str)
self.msg['Subject'] = subject
if frm:
self.msg['From'] = frm
if to:
self.msg['To'] = to
self.msg['Date'] = formatdate()
def invokeAsSubprocess(self, inputFile=False, outputDirectory=None, outputFile=None, extraParams=None,
expectOutput=False, okToExist=False):
if type(inputFile) is str:
input_content = bytes(inputFile, 'utf-8')
else:
input_content = self.msg.as_bytes()
options = [Email2PDFTestCase.COMMAND]
if inputFile:
input_file_handle = tempfile.NamedTemporaryFile()
options.extend(['-i', input_file_handle.name])
input_file_handle.write(input_content)
input_file_handle.flush()
my_stdin = None
my_input = None
else:
my_stdin = PIPE
my_input = input_content
if outputDirectory:
options.extend(['-d', outputDirectory])
if outputFile:
options.extend(['-o', outputFile])
if not okToExist:
assert not os.path.exists(outputFile)
if extraParams is None:
extraParams = []
options.extend(extraParams)
self.time_invoked = datetime.now()
if outputDirectory is None:
my_cwd = self.workingDir
else:
my_cwd = None
email2pdf_process = Popen(options, stdin=my_stdin, stdout=PIPE, stderr=PIPE, cwd=my_cwd)
output, error = email2pdf_process.communicate(my_input)
email2pdf_process.wait()
self.time_completed = datetime.now()
output = str(output, "utf-8")
error = str(error, "utf-8")
if expectOutput:
self.assertNotEqual("", output)
else:
self.assertEqual("", output)
if inputFile:
input_file_handle.close()
return (email2pdf_process.returncode, output, error)
def invokeDirectly(self, outputDirectory=None, outputFile=None, extraParams=None, completeMessage=None, okToExist=False):
module_path = self._get_original_script_path()
email2pdf = self._get_email2pdf_object(module_path)
if completeMessage:
bytes_message = bytes(completeMessage, 'utf-8')
else:
bytes_message = self.msg.as_bytes()
with tempfile.NamedTemporaryFile() as input_file_handle:
options = [module_path, '-i', input_file_handle.name]
input_file_handle.write(bytes_message)
input_file_handle.flush()
options.extend(['-d', outputDirectory if outputDirectory else self.workingDir])
if outputFile:
options.extend(['-o', outputFile])
if not okToExist:
assert not os.path.exists(outputFile)
if extraParams is None:
extraParams = []
options.extend(extraParams)
stream = io.StringIO()
stream_handler = logging.StreamHandler(stream)
log = logging.getLogger('email2pdf')
log.propagate = False
log.setLevel(logging.DEBUG)
log.addHandler(stream_handler)
self.time_invoked = datetime.now()
try:
email2pdf.main(options, None, stream_handler)
finally:
self.time_completed = datetime.now()
for handler in log.handlers:
handler.close()
log.removeHandler(handler)
for log_filter in log.filters:
log.removeFilter(log_filter)
stream_handler.close()
error = stream.getvalue()
return error
def setPlainContent(self, content, charset='UTF-8'):
if isinstance(self.msg, MIMEMultipart):
raise Exception("Cannot call setPlainContent() on a MIME-based message.")
else:
self.msg.set_default_type("text/plain")
self.msg.set_payload(content)
self.msg.set_charset(charset)
def attachHTML(self, content, charset=None):
assert isinstance(self.msg, MIMEMultipart)
# According to the docs
# (https://docs.python.org/3.3/library/email.mime.html), setting
# charset explicitly to None is different from not setting it. Not
# sure how that works. But for the moment, sticking with this
# style of invocation to be safe.
if charset:
self.msg.attach(MIMEText(content, 'html', charset))
else:
self.msg.attach(MIMEText(content, 'html'))
def attachText(self, content, charset=None):
assert isinstance(self.msg, MIMEMultipart)
if charset:
self.msg.attach(MIMEText(content, 'plain', charset))
else:
self.msg.attach(MIMEText(content, 'plain'))
def attachPDF(self, string, filePrefix="email2pdf_unittest_file",
extension="pdf", mainContentType="application", subContentType="pdf", no_filename=False):
_, file_name = tempfile.mkstemp(prefix=filePrefix, suffix="." + extension)
try:
pdf_canvas = canvas.Canvas(file_name)
pdf_canvas.drawString(0, 500, string)
pdf_canvas.save()
with open(file_name, "rb") as open_handle:
if no_filename:
self.attachAttachment(mainContentType, subContentType, open_handle.read(), None)
else:
self.attachAttachment(mainContentType, subContentType, open_handle.read(), file_name)
return os.path.basename(file_name)
finally:
os.unlink(file_name)
def attachImage(self, content_id=None, jpeg=True, content_type=None, content_type_add_filename=False, inline=False, force_filename=False, extension=None):
if jpeg:
real_filename = self.JPG_FILENAME
file_suffix = 'jpg' if extension is None else extension
else:
real_filename = self.PNG_FILENAME
file_suffix = 'png' if extension is None else extension
if file_suffix != '':
suffix = "." + file_suffix
else:
suffix = file_suffix
with tempfile.NamedTemporaryFile(prefix="email2pdf_unittest_image", suffix=suffix) as temp_file:
_, basic_file_name = os.path.split(temp_file.name)
with open(real_filename, 'rb') as image_file:
image = MIMEImage(image_file.read())
if content_id:
image.add_header('Content-ID', content_id)
if content_type:
self._replace_header(image, 'Content-Type', content_type)
if content_type_add_filename:
image.set_param('name', basic_file_name, header='Content-Type')
if inline:
if force_filename:
self._replace_header(image, 'Content-Disposition', 'inline; filename="%s"' % basic_file_name)
else:
self._replace_header(image, 'Content-Disposition', 'inline')
else:
self._replace_header(image, 'Content-Disposition', 'attachment; filename="%s"' % basic_file_name)
self.msg.attach(image)
if inline and not force_filename:
return None
else:
return basic_file_name
def attachAttachment(self, mainContentType, subContentType, data, file_name=None, file_name_encoding=None):
assert isinstance(self.msg, MIMEMultipart)
part = MIMEBase(mainContentType, subContentType)
part.set_payload(data)
encoders.encode_base64(part)
if file_name:
if file_name_encoding:
# I would like to use a more simple implementation here based
# on part.add_header, but the encoding mechanism provided for
# that gives a different output, placing the filename in
# Content-Disposition, with it subtly differently encoded.
# This doesn't match a real-world problematic email which was
# observed like this:
#
# Content-Type: APPLICATION/pdf; NAME="=?UTF-8?Q?123.pdf?="
# Content-Transfer-Encoding: QUOTED-PRINTABLE
# Content-Disposition: attachment
header = mainContentType + '/' + subContentType
header += '; name="' + Header(os.path.basename(file_name), file_name_encoding).encode() + '"'
del part['Content-Type']
part['Content-Type'] = header
part.add_header('Content-Disposition', 'attachment')
else:
part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_name))
else:
part.add_header('Content-Disposition', 'inline')
self.msg.attach(part)
def assertIsJPG(self, filename):
self.assertEqual(imghdr.what(filename), 'jpeg')
def getMetadataField(self, pdf_filename, field_name):
with open(pdf_filename, 'rb') as file_input:
input_f = PdfFileReader(file_input)
document_info = input_f.getDocumentInfo()
key = '/' + field_name
if key in document_info.keys():
return document_info[key]
else:
return None
def getPDFText(self, filename):
if os.path.exists(filename):
try:
text = pdfminer.high_level.extract_text(filename)
except pdfminer.pdfparser.PDFSyntaxError:
return None
text = text.replace("\t", " ")
return text
else:
return None
def touch(self, fname):
open(fname, 'w').close()
def find_mount_point(self, path):
while not os.path.ismount(path):
path = os.path.dirname(path)
return path
def _timerange(self, start_time, end_time):
start_time = start_time.replace(microsecond=0)
end_time = end_time.replace(microsecond=0)
for step in range(int((end_time - start_time).seconds) + 1):
yield start_time + timedelta(0, step)
def _replace_header(self, mime_base, header, value):
mime_base.__delitem__(header)
mime_base.add_header(header, value)
@classmethod
def _get_original_script_path(cls):
module_path = inspect.getfile(inspect.currentframe())
module_path = os.path.join(os.path.dirname(os.path.dirname(module_path)), 'email2pdf')
return module_path
@classmethod
def _get_email2pdf_object(cls, module_path):
import importlib.machinery
loader = importlib.machinery.SourceFileLoader('email2pdf', module_path)
return loader.load_module()
@classmethod
def _check_examine_dir(cls):
if Email2PDFTestCase.examineDir is None:
Email2PDFTestCase.examineDir = '/tmp'
Email2PDFTestCase.examineDir = tempfile.mkdtemp(dir=Email2PDFTestCase.examineDir)
print("Output examination directory: " + Email2PDFTestCase.examineDir)
@classmethod
def _check_online(cls):
if Email2PDFTestCase.isOnline is None:
print("Checking if online... ", end="")
sys.stdout.flush()
try:
request = requests.get(Email2PDFTestCase.EXIST_IMG, headers={'Connection': 'close'})
request.raise_for_status()
Email2PDFTestCase.isOnline = True
print("Yes.")
except RequestException as exception:
Email2PDFTestCase.isOnline = False
print("No (" + str(exception) + ")")
def tearDown(self):
shutil.rmtree(self.workingDir)