Debian Codegraph @

Lib/test/test_email/__init__.py

raw
1 import os
2 import unittest
3 import collections
4 import email
5 from email.message import Message
6 from email._policybase import compat32
7 from test.support import load_package_tests
8 from test.support.testcase import ExtraAssertions
9 from test.test_email import __file__ as landmark
10
11 # Load all tests in package
12 def load_tests(*args):
13 return load_package_tests(os.path.dirname(__file__), *args)
14
15
16 # helper code used by a number of test modules.
17
18 def openfile(filename, *args, **kws):
19 path = os.path.join(os.path.dirname(landmark), 'data', filename)
20 return open(path, *args, **kws)
21
22
23 # Base test class
24 class TestEmailBase(unittest.TestCase, ExtraAssertions):
25
26 maxDiff = None
27 # Currently the default policy is compat32. By setting that as the default
28 # here we make minimal changes in the test_email tests compared to their
29 # pre-3.3 state.
30 policy = compat32
31 # Likewise, the default message object is Message.
32 message = Message
33
34 def __init__(self, *args, **kw):
35 super().__init__(*args, **kw)
36 self.addTypeEqualityFunc(bytes, self.assertBytesEqual)
37
38 # Backward compatibility to minimize test_email test changes.
39 ndiffAssertEqual = unittest.TestCase.assertEqual
40
41 def _msgobj(self, filename):
42 with openfile(filename, encoding="utf-8") as fp:
43 return email.message_from_file(fp, policy=self.policy)
44
45 def _str_msg(self, string, message=None, policy=None):
46 if policy is None:
47 policy = self.policy
48 if message is None:
49 message = self.message
50 return email.message_from_string(string, message, policy=policy)
51
52 def _bytes_msg(self, bytestring, message=None, policy=None):
53 if policy is None:
54 policy = self.policy
55 if message is None:
56 message = self.message
57 return email.message_from_bytes(bytestring, message, policy=policy)
58
59 def _make_message(self):
60 return self.message(policy=self.policy)
61
62 def _bytes_repr(self, b):
63 return [repr(x) for x in b.splitlines(keepends=True)]
64
65 def assertBytesEqual(self, first, second, msg):
66 """Our byte strings are really encoded strings; improve diff output"""
67 self.assertEqual(self._bytes_repr(first), self._bytes_repr(second))
68
69 def assertDefectsEqual(self, actual, expected):
70 self.assertEqual(len(actual), len(expected), actual)
71 for i in range(len(actual)):
72 self.assertIsInstance(actual[i], expected[i],
73 'item {}'.format(i))
74
75
76 def parameterize(cls):
77 """A test method parameterization class decorator.
78
79 Parameters are specified as the value of a class attribute that ends with
80 the string '_params'. Call the portion before '_params' the prefix. Then
81 a method to be parameterized must have the same prefix, the string
82 '_as_', and an arbitrary suffix.
83
84 The value of the _params attribute may be either a dictionary or a list.
85 The values in the dictionary and the elements of the list may either be
86 single values, or a list. If single values, they are turned into single
87 element tuples. However derived, the resulting sequence is passed via
88 *args to the parameterized test function.
89
90 In a _params dictionary, the keys become part of the name of the generated
91 tests. In a _params list, the values in the list are converted into a
92 string by joining the string values of the elements of the tuple by '_' and
93 converting any blanks into '_'s, and this become part of the name.
94 The full name of a generated test is a 'test_' prefix, the portion of the
95 test function name after the '_as_' separator, plus an '_', plus the name
96 derived as explained above.
97
98 For example, if we have:
99
100 count_params = range(2)
101
102 def count_as_foo_arg(self, foo):
103 self.assertEqual(foo+1, myfunc(foo))
104
105 we will get parameterized test methods named:
106 test_foo_arg_0
107 test_foo_arg_1
108 test_foo_arg_2
109
110 Or we could have:
111
112 example_params = {'foo': ('bar', 1), 'bing': ('bang', 2)}
113
114 def example_as_myfunc_input(self, name, count):
115 self.assertEqual(name+str(count), myfunc(name, count))
116
117 and get:
118 test_myfunc_input_foo
119 test_myfunc_input_bing
120
121 Note: if and only if the generated test name is a valid identifier can it
122 be used to select the test individually from the unittest command line.
123
124 The values in the params dict can be a single value, a tuple, or a
125 dict. If a single value of a tuple, it is passed to the test function
126 as positional arguments. If a dict, it is a passed via **kw.
127
128 """
129 paramdicts = {}
130 testers = collections.defaultdict(list)
131 for name, attr in cls.__dict__.items():
132 if name.endswith('_params'):
133 if not hasattr(attr, 'keys'):
134 d = {}
135 for x in attr:
136 if not hasattr(x, '__iter__'):
137 x = (x,)
138 n = '_'.join(str(v) for v in x).replace(' ', '_')
139 d[n] = x
140 attr = d
141 paramdicts[name[:-7] + '_as_'] = attr
142 if '_as_' in name:
143 testers[name.split('_as_')[0] + '_as_'].append(name)
144 testfuncs = {}
145 for name in paramdicts:
146 if name not in testers:
147 raise ValueError("No tester found for {}".format(name))
148 for name in testers:
149 if name not in paramdicts:
150 raise ValueError("No params found for {}".format(name))
151 for name, attr in cls.__dict__.items():
152 for paramsname, paramsdict in paramdicts.items():
153 if name.startswith(paramsname):
154 testnameroot = 'test_' + name[len(paramsname):]
155 for paramname, params in paramsdict.items():
156 if hasattr(params, 'keys'):
157 test = (lambda self, name=name, params=params:
158 getattr(self, name)(**params))
159 else:
160 test = (lambda self, name=name, params=params:
161 getattr(self, name)(*params))
162 testname = testnameroot + '_' + paramname
163 test.__name__ = testname
164 testfuncs[testname] = test
165 for key, value in testfuncs.items():
166 setattr(cls, key, value)
167 return cls