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

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

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