PageRenderTime 47ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_email/test_policy.py

https://gitlab.com/unofficial-mirrors/cpython
Python | 346 lines | 284 code | 42 blank | 20 comment | 33 complexity | bb9e1763fb70e78415795b3cdb605cad MD5 | raw file
  1. import io
  2. import types
  3. import textwrap
  4. import unittest
  5. import email.policy
  6. import email.parser
  7. import email.generator
  8. import email.message
  9. from email import headerregistry
  10. def make_defaults(base_defaults, differences):
  11. defaults = base_defaults.copy()
  12. defaults.update(differences)
  13. return defaults
  14. class PolicyAPITests(unittest.TestCase):
  15. longMessage = True
  16. # Base default values.
  17. compat32_defaults = {
  18. 'max_line_length': 78,
  19. 'linesep': '\n',
  20. 'cte_type': '8bit',
  21. 'raise_on_defect': False,
  22. 'mangle_from_': True,
  23. 'message_factory': None,
  24. }
  25. # These default values are the ones set on email.policy.default.
  26. # If any of these defaults change, the docs must be updated.
  27. policy_defaults = compat32_defaults.copy()
  28. policy_defaults.update({
  29. 'utf8': False,
  30. 'raise_on_defect': False,
  31. 'header_factory': email.policy.EmailPolicy.header_factory,
  32. 'refold_source': 'long',
  33. 'content_manager': email.policy.EmailPolicy.content_manager,
  34. 'mangle_from_': False,
  35. 'message_factory': email.message.EmailMessage,
  36. })
  37. # For each policy under test, we give here what we expect the defaults to
  38. # be for that policy. The second argument to make defaults is the
  39. # difference between the base defaults and that for the particular policy.
  40. new_policy = email.policy.EmailPolicy()
  41. policies = {
  42. email.policy.compat32: make_defaults(compat32_defaults, {}),
  43. email.policy.default: make_defaults(policy_defaults, {}),
  44. email.policy.SMTP: make_defaults(policy_defaults,
  45. {'linesep': '\r\n'}),
  46. email.policy.SMTPUTF8: make_defaults(policy_defaults,
  47. {'linesep': '\r\n',
  48. 'utf8': True}),
  49. email.policy.HTTP: make_defaults(policy_defaults,
  50. {'linesep': '\r\n',
  51. 'max_line_length': None}),
  52. email.policy.strict: make_defaults(policy_defaults,
  53. {'raise_on_defect': True}),
  54. new_policy: make_defaults(policy_defaults, {}),
  55. }
  56. # Creating a new policy creates a new header factory. There is a test
  57. # later that proves this.
  58. policies[new_policy]['header_factory'] = new_policy.header_factory
  59. def test_defaults(self):
  60. for policy, expected in self.policies.items():
  61. for attr, value in expected.items():
  62. with self.subTest(policy=policy, attr=attr):
  63. self.assertEqual(getattr(policy, attr), value,
  64. ("change {} docs/docstrings if defaults have "
  65. "changed").format(policy))
  66. def test_all_attributes_covered(self):
  67. for policy, expected in self.policies.items():
  68. for attr in dir(policy):
  69. with self.subTest(policy=policy, attr=attr):
  70. if (attr.startswith('_') or
  71. isinstance(getattr(email.policy.EmailPolicy, attr),
  72. types.FunctionType)):
  73. continue
  74. else:
  75. self.assertIn(attr, expected,
  76. "{} is not fully tested".format(attr))
  77. def test_abc(self):
  78. with self.assertRaises(TypeError) as cm:
  79. email.policy.Policy()
  80. msg = str(cm.exception)
  81. abstract_methods = ('fold',
  82. 'fold_binary',
  83. 'header_fetch_parse',
  84. 'header_source_parse',
  85. 'header_store_parse')
  86. for method in abstract_methods:
  87. self.assertIn(method, msg)
  88. def test_policy_is_immutable(self):
  89. for policy, defaults in self.policies.items():
  90. for attr in defaults:
  91. with self.assertRaisesRegex(AttributeError, attr+".*read-only"):
  92. setattr(policy, attr, None)
  93. with self.assertRaisesRegex(AttributeError, 'no attribute.*foo'):
  94. policy.foo = None
  95. def test_set_policy_attrs_when_cloned(self):
  96. # None of the attributes has a default value of None, so we set them
  97. # all to None in the clone call and check that it worked.
  98. for policyclass, defaults in self.policies.items():
  99. testattrdict = {attr: None for attr in defaults}
  100. policy = policyclass.clone(**testattrdict)
  101. for attr in defaults:
  102. self.assertIsNone(getattr(policy, attr))
  103. def test_reject_non_policy_keyword_when_called(self):
  104. for policyclass in self.policies:
  105. with self.assertRaises(TypeError):
  106. policyclass(this_keyword_should_not_be_valid=None)
  107. with self.assertRaises(TypeError):
  108. policyclass(newtline=None)
  109. def test_policy_addition(self):
  110. expected = self.policy_defaults.copy()
  111. p1 = email.policy.default.clone(max_line_length=100)
  112. p2 = email.policy.default.clone(max_line_length=50)
  113. added = p1 + p2
  114. expected.update(max_line_length=50)
  115. for attr, value in expected.items():
  116. self.assertEqual(getattr(added, attr), value)
  117. added = p2 + p1
  118. expected.update(max_line_length=100)
  119. for attr, value in expected.items():
  120. self.assertEqual(getattr(added, attr), value)
  121. added = added + email.policy.default
  122. for attr, value in expected.items():
  123. self.assertEqual(getattr(added, attr), value)
  124. def test_register_defect(self):
  125. class Dummy:
  126. def __init__(self):
  127. self.defects = []
  128. obj = Dummy()
  129. defect = object()
  130. policy = email.policy.EmailPolicy()
  131. policy.register_defect(obj, defect)
  132. self.assertEqual(obj.defects, [defect])
  133. defect2 = object()
  134. policy.register_defect(obj, defect2)
  135. self.assertEqual(obj.defects, [defect, defect2])
  136. class MyObj:
  137. def __init__(self):
  138. self.defects = []
  139. class MyDefect(Exception):
  140. pass
  141. def test_handle_defect_raises_on_strict(self):
  142. foo = self.MyObj()
  143. defect = self.MyDefect("the telly is broken")
  144. with self.assertRaisesRegex(self.MyDefect, "the telly is broken"):
  145. email.policy.strict.handle_defect(foo, defect)
  146. def test_handle_defect_registers_defect(self):
  147. foo = self.MyObj()
  148. defect1 = self.MyDefect("one")
  149. email.policy.default.handle_defect(foo, defect1)
  150. self.assertEqual(foo.defects, [defect1])
  151. defect2 = self.MyDefect("two")
  152. email.policy.default.handle_defect(foo, defect2)
  153. self.assertEqual(foo.defects, [defect1, defect2])
  154. class MyPolicy(email.policy.EmailPolicy):
  155. defects = None
  156. def __init__(self, *args, **kw):
  157. super().__init__(*args, defects=[], **kw)
  158. def register_defect(self, obj, defect):
  159. self.defects.append(defect)
  160. def test_overridden_register_defect_still_raises(self):
  161. foo = self.MyObj()
  162. defect = self.MyDefect("the telly is broken")
  163. with self.assertRaisesRegex(self.MyDefect, "the telly is broken"):
  164. self.MyPolicy(raise_on_defect=True).handle_defect(foo, defect)
  165. def test_overridden_register_defect_works(self):
  166. foo = self.MyObj()
  167. defect1 = self.MyDefect("one")
  168. my_policy = self.MyPolicy()
  169. my_policy.handle_defect(foo, defect1)
  170. self.assertEqual(my_policy.defects, [defect1])
  171. self.assertEqual(foo.defects, [])
  172. defect2 = self.MyDefect("two")
  173. my_policy.handle_defect(foo, defect2)
  174. self.assertEqual(my_policy.defects, [defect1, defect2])
  175. self.assertEqual(foo.defects, [])
  176. def test_default_header_factory(self):
  177. h = email.policy.default.header_factory('Test', 'test')
  178. self.assertEqual(h.name, 'Test')
  179. self.assertIsInstance(h, headerregistry.UnstructuredHeader)
  180. self.assertIsInstance(h, headerregistry.BaseHeader)
  181. class Foo:
  182. parse = headerregistry.UnstructuredHeader.parse
  183. def test_each_Policy_gets_unique_factory(self):
  184. policy1 = email.policy.EmailPolicy()
  185. policy2 = email.policy.EmailPolicy()
  186. policy1.header_factory.map_to_type('foo', self.Foo)
  187. h = policy1.header_factory('foo', 'test')
  188. self.assertIsInstance(h, self.Foo)
  189. self.assertNotIsInstance(h, headerregistry.UnstructuredHeader)
  190. h = policy2.header_factory('foo', 'test')
  191. self.assertNotIsInstance(h, self.Foo)
  192. self.assertIsInstance(h, headerregistry.UnstructuredHeader)
  193. def test_clone_copies_factory(self):
  194. policy1 = email.policy.EmailPolicy()
  195. policy2 = policy1.clone()
  196. policy1.header_factory.map_to_type('foo', self.Foo)
  197. h = policy1.header_factory('foo', 'test')
  198. self.assertIsInstance(h, self.Foo)
  199. h = policy2.header_factory('foo', 'test')
  200. self.assertIsInstance(h, self.Foo)
  201. def test_new_factory_overrides_default(self):
  202. mypolicy = email.policy.EmailPolicy()
  203. myfactory = mypolicy.header_factory
  204. newpolicy = mypolicy + email.policy.strict
  205. self.assertEqual(newpolicy.header_factory, myfactory)
  206. newpolicy = email.policy.strict + mypolicy
  207. self.assertEqual(newpolicy.header_factory, myfactory)
  208. def test_adding_default_policies_preserves_default_factory(self):
  209. newpolicy = email.policy.default + email.policy.strict
  210. self.assertEqual(newpolicy.header_factory,
  211. email.policy.EmailPolicy.header_factory)
  212. self.assertEqual(newpolicy.__dict__, {'raise_on_defect': True})
  213. # XXX: Need subclassing tests.
  214. # For adding subclassed objects, make sure the usual rules apply (subclass
  215. # wins), but that the order still works (right overrides left).
  216. class TestException(Exception):
  217. pass
  218. class TestPolicyPropagation(unittest.TestCase):
  219. # The abstract methods are used by the parser but not by the wrapper
  220. # functions that call it, so if the exception gets raised we know that the
  221. # policy was actually propagated all the way to feedparser.
  222. class MyPolicy(email.policy.Policy):
  223. def badmethod(self, *args, **kw):
  224. raise TestException("test")
  225. fold = fold_binary = header_fetch_parser = badmethod
  226. header_source_parse = header_store_parse = badmethod
  227. def test_message_from_string(self):
  228. with self.assertRaisesRegex(TestException, "^test$"):
  229. email.message_from_string("Subject: test\n\n",
  230. policy=self.MyPolicy)
  231. def test_message_from_bytes(self):
  232. with self.assertRaisesRegex(TestException, "^test$"):
  233. email.message_from_bytes(b"Subject: test\n\n",
  234. policy=self.MyPolicy)
  235. def test_message_from_file(self):
  236. f = io.StringIO('Subject: test\n\n')
  237. with self.assertRaisesRegex(TestException, "^test$"):
  238. email.message_from_file(f, policy=self.MyPolicy)
  239. def test_message_from_binary_file(self):
  240. f = io.BytesIO(b'Subject: test\n\n')
  241. with self.assertRaisesRegex(TestException, "^test$"):
  242. email.message_from_binary_file(f, policy=self.MyPolicy)
  243. # These are redundant, but we need them for black-box completeness.
  244. def test_parser(self):
  245. p = email.parser.Parser(policy=self.MyPolicy)
  246. with self.assertRaisesRegex(TestException, "^test$"):
  247. p.parsestr('Subject: test\n\n')
  248. def test_bytes_parser(self):
  249. p = email.parser.BytesParser(policy=self.MyPolicy)
  250. with self.assertRaisesRegex(TestException, "^test$"):
  251. p.parsebytes(b'Subject: test\n\n')
  252. # Now that we've established that all the parse methods get the
  253. # policy in to feedparser, we can use message_from_string for
  254. # the rest of the propagation tests.
  255. def _make_msg(self, source='Subject: test\n\n', policy=None):
  256. self.policy = email.policy.default.clone() if policy is None else policy
  257. return email.message_from_string(source, policy=self.policy)
  258. def test_parser_propagates_policy_to_message(self):
  259. msg = self._make_msg()
  260. self.assertIs(msg.policy, self.policy)
  261. def test_parser_propagates_policy_to_sub_messages(self):
  262. msg = self._make_msg(textwrap.dedent("""\
  263. Subject: mime test
  264. MIME-Version: 1.0
  265. Content-Type: multipart/mixed, boundary="XXX"
  266. --XXX
  267. Content-Type: text/plain
  268. test
  269. --XXX
  270. Content-Type: text/plain
  271. test2
  272. --XXX--
  273. """))
  274. for part in msg.walk():
  275. self.assertIs(part.policy, self.policy)
  276. def test_message_policy_propagates_to_generator(self):
  277. msg = self._make_msg("Subject: test\nTo: foo\n\n",
  278. policy=email.policy.default.clone(linesep='X'))
  279. s = io.StringIO()
  280. g = email.generator.Generator(s)
  281. g.flatten(msg)
  282. self.assertEqual(s.getvalue(), "Subject: testXTo: fooXX")
  283. def test_message_policy_used_by_as_string(self):
  284. msg = self._make_msg("Subject: test\nTo: foo\n\n",
  285. policy=email.policy.default.clone(linesep='X'))
  286. self.assertEqual(msg.as_string(), "Subject: testXTo: fooXX")
  287. class TestConcretePolicies(unittest.TestCase):
  288. def test_header_store_parse_rejects_newlines(self):
  289. instance = email.policy.EmailPolicy()
  290. self.assertRaises(ValueError,
  291. instance.header_store_parse,
  292. 'From', 'spam\negg@foo.py')
  293. if __name__ == '__main__':
  294. unittest.main()