ยปCore Development>Code coverage>Lib/test/test_email/test_inversion.py

Python code coverage for Lib/test/test_email/test_inversion.py

#countcontent
1n/a"""Test the parser and generator are inverses.
2n/a
3n/aNote that this is only strictly true if we are parsing RFC valid messages and
4n/aproducing RFC valid messages.
5n/a"""
6n/a
7n/aimport io
8n/aimport unittest
9n/afrom email import policy, message_from_bytes
10n/afrom email.message import EmailMessage
11n/afrom email.generator import BytesGenerator
12n/afrom test.test_email import TestEmailBase, parameterize
13n/a
14n/a# This is like textwrap.dedent for bytes, except that it uses \r\n for the line
15n/a# separators on the rebuilt string.
16n/adef dedent(bstr):
17n/a lines = bstr.splitlines()
18n/a if not lines[0].strip():
19n/a raise ValueError("First line must contain text")
20n/a stripamt = len(lines[0]) - len(lines[0].lstrip())
21n/a return b'\r\n'.join(
22n/a [x[stripamt:] if len(x)>=stripamt else b''
23n/a for x in lines])
24n/a
25n/a
26n/a@parameterize
27n/aclass TestInversion(TestEmailBase):
28n/a
29n/a policy = policy.default
30n/a message = EmailMessage
31n/a
32n/a def msg_as_input(self, msg):
33n/a m = message_from_bytes(msg, policy=policy.SMTP)
34n/a b = io.BytesIO()
35n/a g = BytesGenerator(b)
36n/a g.flatten(m)
37n/a self.assertEqual(b.getvalue(), msg)
38n/a
39n/a # XXX: spaces are not preserved correctly here yet in the general case.
40n/a msg_params = {
41n/a 'header_with_one_space_body': (dedent(b"""\
42n/a From: abc@xyz.com
43n/a X-Status:\x20
44n/a Subject: test
45n/a
46n/a foo
47n/a """),),
48n/a
49n/a }
50n/a
51n/a payload_params = {
52n/a 'plain_text': dict(payload='This is a test\n'*20),
53n/a 'base64_text': dict(payload=(('xy a'*40+'\n')*5), cte='base64'),
54n/a 'qp_text': dict(payload=(('xy a'*40+'\n')*5), cte='quoted-printable'),
55n/a }
56n/a
57n/a def payload_as_body(self, payload, **kw):
58n/a msg = self._make_message()
59n/a msg['From'] = 'foo'
60n/a msg['To'] = 'bar'
61n/a msg['Subject'] = 'payload round trip test'
62n/a msg.set_content(payload, **kw)
63n/a b = bytes(msg)
64n/a msg2 = message_from_bytes(b, policy=self.policy)
65n/a self.assertEqual(bytes(msg2), b)
66n/a self.assertEqual(msg2.get_content(), payload)
67n/a
68n/a
69n/aif __name__ == '__main__':
70n/a unittest.main()