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

Python code coverage for Lib/test/test_funcattrs.py

#countcontent
1n/aimport types
2n/aimport unittest
3n/a
4n/a
5n/adef global_function():
6n/a def inner_function():
7n/a class LocalClass:
8n/a pass
9n/a global inner_global_function
10n/a def inner_global_function():
11n/a def inner_function2():
12n/a pass
13n/a return inner_function2
14n/a return LocalClass
15n/a return lambda: inner_function
16n/a
17n/a
18n/aclass FuncAttrsTest(unittest.TestCase):
19n/a def setUp(self):
20n/a class F:
21n/a def a(self):
22n/a pass
23n/a def b():
24n/a return 3
25n/a self.fi = F()
26n/a self.F = F
27n/a self.b = b
28n/a
29n/a def cannot_set_attr(self, obj, name, value, exceptions):
30n/a try:
31n/a setattr(obj, name, value)
32n/a except exceptions:
33n/a pass
34n/a else:
35n/a self.fail("shouldn't be able to set %s to %r" % (name, value))
36n/a try:
37n/a delattr(obj, name)
38n/a except exceptions:
39n/a pass
40n/a else:
41n/a self.fail("shouldn't be able to del %s" % name)
42n/a
43n/a
44n/aclass FunctionPropertiesTest(FuncAttrsTest):
45n/a # Include the external setUp method that is common to all tests
46n/a def test_module(self):
47n/a self.assertEqual(self.b.__module__, __name__)
48n/a
49n/a def test_dir_includes_correct_attrs(self):
50n/a self.b.known_attr = 7
51n/a self.assertIn('known_attr', dir(self.b),
52n/a "set attributes not in dir listing of method")
53n/a # Test on underlying function object of method
54n/a self.F.a.known_attr = 7
55n/a self.assertIn('known_attr', dir(self.fi.a), "set attribute on function "
56n/a "implementations, should show up in next dir")
57n/a
58n/a def test_duplicate_function_equality(self):
59n/a # Body of `duplicate' is the exact same as self.b
60n/a def duplicate():
61n/a 'my docstring'
62n/a return 3
63n/a self.assertNotEqual(self.b, duplicate)
64n/a
65n/a def test_copying___code__(self):
66n/a def test(): pass
67n/a self.assertEqual(test(), None)
68n/a test.__code__ = self.b.__code__
69n/a self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily
70n/a
71n/a def test___globals__(self):
72n/a self.assertIs(self.b.__globals__, globals())
73n/a self.cannot_set_attr(self.b, '__globals__', 2,
74n/a (AttributeError, TypeError))
75n/a
76n/a def test___closure__(self):
77n/a a = 12
78n/a def f(): print(a)
79n/a c = f.__closure__
80n/a self.assertIsInstance(c, tuple)
81n/a self.assertEqual(len(c), 1)
82n/a # don't have a type object handy
83n/a self.assertEqual(c[0].__class__.__name__, "cell")
84n/a self.cannot_set_attr(f, "__closure__", c, AttributeError)
85n/a
86n/a def test_empty_cell(self):
87n/a def f(): print(a)
88n/a try:
89n/a f.__closure__[0].cell_contents
90n/a except ValueError:
91n/a pass
92n/a else:
93n/a self.fail("shouldn't be able to read an empty cell")
94n/a a = 12
95n/a
96n/a def test___name__(self):
97n/a self.assertEqual(self.b.__name__, 'b')
98n/a self.b.__name__ = 'c'
99n/a self.assertEqual(self.b.__name__, 'c')
100n/a self.b.__name__ = 'd'
101n/a self.assertEqual(self.b.__name__, 'd')
102n/a # __name__ and __name__ must be a string
103n/a self.cannot_set_attr(self.b, '__name__', 7, TypeError)
104n/a # __name__ must be available when in restricted mode. Exec will raise
105n/a # AttributeError if __name__ is not available on f.
106n/a s = """def f(): pass\nf.__name__"""
107n/a exec(s, {'__builtins__': {}})
108n/a # Test on methods, too
109n/a self.assertEqual(self.fi.a.__name__, 'a')
110n/a self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)
111n/a
112n/a def test___qualname__(self):
113n/a # PEP 3155
114n/a self.assertEqual(self.b.__qualname__, 'FuncAttrsTest.setUp.<locals>.b')
115n/a self.assertEqual(FuncAttrsTest.setUp.__qualname__, 'FuncAttrsTest.setUp')
116n/a self.assertEqual(global_function.__qualname__, 'global_function')
117n/a self.assertEqual(global_function().__qualname__,
118n/a 'global_function.<locals>.<lambda>')
119n/a self.assertEqual(global_function()().__qualname__,
120n/a 'global_function.<locals>.inner_function')
121n/a self.assertEqual(global_function()()().__qualname__,
122n/a 'global_function.<locals>.inner_function.<locals>.LocalClass')
123n/a self.assertEqual(inner_global_function.__qualname__, 'inner_global_function')
124n/a self.assertEqual(inner_global_function().__qualname__, 'inner_global_function.<locals>.inner_function2')
125n/a self.b.__qualname__ = 'c'
126n/a self.assertEqual(self.b.__qualname__, 'c')
127n/a self.b.__qualname__ = 'd'
128n/a self.assertEqual(self.b.__qualname__, 'd')
129n/a # __qualname__ must be a string
130n/a self.cannot_set_attr(self.b, '__qualname__', 7, TypeError)
131n/a
132n/a def test___code__(self):
133n/a num_one, num_two = 7, 8
134n/a def a(): pass
135n/a def b(): return 12
136n/a def c(): return num_one
137n/a def d(): return num_two
138n/a def e(): return num_one, num_two
139n/a for func in [a, b, c, d, e]:
140n/a self.assertEqual(type(func.__code__), types.CodeType)
141n/a self.assertEqual(c(), 7)
142n/a self.assertEqual(d(), 8)
143n/a d.__code__ = c.__code__
144n/a self.assertEqual(c.__code__, d.__code__)
145n/a self.assertEqual(c(), 7)
146n/a # self.assertEqual(d(), 7)
147n/a try:
148n/a b.__code__ = c.__code__
149n/a except ValueError:
150n/a pass
151n/a else:
152n/a self.fail("__code__ with different numbers of free vars should "
153n/a "not be possible")
154n/a try:
155n/a e.__code__ = d.__code__
156n/a except ValueError:
157n/a pass
158n/a else:
159n/a self.fail("__code__ with different numbers of free vars should "
160n/a "not be possible")
161n/a
162n/a def test_blank_func_defaults(self):
163n/a self.assertEqual(self.b.__defaults__, None)
164n/a del self.b.__defaults__
165n/a self.assertEqual(self.b.__defaults__, None)
166n/a
167n/a def test_func_default_args(self):
168n/a def first_func(a, b):
169n/a return a+b
170n/a def second_func(a=1, b=2):
171n/a return a+b
172n/a self.assertEqual(first_func.__defaults__, None)
173n/a self.assertEqual(second_func.__defaults__, (1, 2))
174n/a first_func.__defaults__ = (1, 2)
175n/a self.assertEqual(first_func.__defaults__, (1, 2))
176n/a self.assertEqual(first_func(), 3)
177n/a self.assertEqual(first_func(3), 5)
178n/a self.assertEqual(first_func(3, 5), 8)
179n/a del second_func.__defaults__
180n/a self.assertEqual(second_func.__defaults__, None)
181n/a try:
182n/a second_func()
183n/a except TypeError:
184n/a pass
185n/a else:
186n/a self.fail("__defaults__ does not update; deleting it does not "
187n/a "remove requirement")
188n/a
189n/a
190n/aclass InstancemethodAttrTest(FuncAttrsTest):
191n/a
192n/a def test___class__(self):
193n/a self.assertEqual(self.fi.a.__self__.__class__, self.F)
194n/a self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError)
195n/a
196n/a def test___func__(self):
197n/a self.assertEqual(self.fi.a.__func__, self.F.a)
198n/a self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError)
199n/a
200n/a def test___self__(self):
201n/a self.assertEqual(self.fi.a.__self__, self.fi)
202n/a self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError)
203n/a
204n/a def test___func___non_method(self):
205n/a # Behavior should be the same when a method is added via an attr
206n/a # assignment
207n/a self.fi.id = types.MethodType(id, self.fi)
208n/a self.assertEqual(self.fi.id(), id(self.fi))
209n/a # Test usage
210n/a try:
211n/a self.fi.id.unknown_attr
212n/a except AttributeError:
213n/a pass
214n/a else:
215n/a self.fail("using unknown attributes should raise AttributeError")
216n/a # Test assignment and deletion
217n/a self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)
218n/a
219n/a
220n/aclass ArbitraryFunctionAttrTest(FuncAttrsTest):
221n/a def test_set_attr(self):
222n/a self.b.known_attr = 7
223n/a self.assertEqual(self.b.known_attr, 7)
224n/a try:
225n/a self.fi.a.known_attr = 7
226n/a except AttributeError:
227n/a pass
228n/a else:
229n/a self.fail("setting attributes on methods should raise error")
230n/a
231n/a def test_delete_unknown_attr(self):
232n/a try:
233n/a del self.b.unknown_attr
234n/a except AttributeError:
235n/a pass
236n/a else:
237n/a self.fail("deleting unknown attribute should raise TypeError")
238n/a
239n/a def test_unset_attr(self):
240n/a for func in [self.b, self.fi.a]:
241n/a try:
242n/a func.non_existent_attr
243n/a except AttributeError:
244n/a pass
245n/a else:
246n/a self.fail("using unknown attributes should raise "
247n/a "AttributeError")
248n/a
249n/a
250n/aclass FunctionDictsTest(FuncAttrsTest):
251n/a def test_setting_dict_to_invalid(self):
252n/a self.cannot_set_attr(self.b, '__dict__', None, TypeError)
253n/a from collections import UserDict
254n/a d = UserDict({'known_attr': 7})
255n/a self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError)
256n/a
257n/a def test_setting_dict_to_valid(self):
258n/a d = {'known_attr': 7}
259n/a self.b.__dict__ = d
260n/a # Test assignment
261n/a self.assertIs(d, self.b.__dict__)
262n/a # ... and on all the different ways of referencing the method's func
263n/a self.F.a.__dict__ = d
264n/a self.assertIs(d, self.fi.a.__func__.__dict__)
265n/a self.assertIs(d, self.fi.a.__dict__)
266n/a # Test value
267n/a self.assertEqual(self.b.known_attr, 7)
268n/a self.assertEqual(self.b.__dict__['known_attr'], 7)
269n/a # ... and again, on all the different method's names
270n/a self.assertEqual(self.fi.a.__func__.known_attr, 7)
271n/a self.assertEqual(self.fi.a.known_attr, 7)
272n/a
273n/a def test_delete___dict__(self):
274n/a try:
275n/a del self.b.__dict__
276n/a except TypeError:
277n/a pass
278n/a else:
279n/a self.fail("deleting function dictionary should raise TypeError")
280n/a
281n/a def test_unassigned_dict(self):
282n/a self.assertEqual(self.b.__dict__, {})
283n/a
284n/a def test_func_as_dict_key(self):
285n/a value = "Some string"
286n/a d = {}
287n/a d[self.b] = value
288n/a self.assertEqual(d[self.b], value)
289n/a
290n/a
291n/aclass FunctionDocstringTest(FuncAttrsTest):
292n/a def test_set_docstring_attr(self):
293n/a self.assertEqual(self.b.__doc__, None)
294n/a docstr = "A test method that does nothing"
295n/a self.b.__doc__ = docstr
296n/a self.F.a.__doc__ = docstr
297n/a self.assertEqual(self.b.__doc__, docstr)
298n/a self.assertEqual(self.fi.a.__doc__, docstr)
299n/a self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)
300n/a
301n/a def test_delete_docstring(self):
302n/a self.b.__doc__ = "The docstring"
303n/a del self.b.__doc__
304n/a self.assertEqual(self.b.__doc__, None)
305n/a
306n/a
307n/adef cell(value):
308n/a """Create a cell containing the given value."""
309n/a def f():
310n/a print(a)
311n/a a = value
312n/a return f.__closure__[0]
313n/a
314n/adef empty_cell(empty=True):
315n/a """Create an empty cell."""
316n/a def f():
317n/a print(a)
318n/a # the intent of the following line is simply "if False:"; it's
319n/a # spelt this way to avoid the danger that a future optimization
320n/a # might simply remove an "if False:" code block.
321n/a if not empty:
322n/a a = 1729
323n/a return f.__closure__[0]
324n/a
325n/a
326n/aclass CellTest(unittest.TestCase):
327n/a def test_comparison(self):
328n/a # These tests are here simply to exercise the comparison code;
329n/a # their presence should not be interpreted as providing any
330n/a # guarantees about the semantics (or even existence) of cell
331n/a # comparisons in future versions of CPython.
332n/a self.assertTrue(cell(2) < cell(3))
333n/a self.assertTrue(empty_cell() < cell('saturday'))
334n/a self.assertTrue(empty_cell() == empty_cell())
335n/a self.assertTrue(cell(-36) == cell(-36.0))
336n/a self.assertTrue(cell(True) > empty_cell())
337n/a
338n/a
339n/aclass StaticMethodAttrsTest(unittest.TestCase):
340n/a def test_func_attribute(self):
341n/a def f():
342n/a pass
343n/a
344n/a c = classmethod(f)
345n/a self.assertTrue(c.__func__ is f)
346n/a
347n/a s = staticmethod(f)
348n/a self.assertTrue(s.__func__ is f)
349n/a
350n/a
351n/aclass BuiltinFunctionPropertiesTest(unittest.TestCase):
352n/a # XXX Not sure where this should really go since I can't find a
353n/a # test module specifically for builtin_function_or_method.
354n/a
355n/a def test_builtin__qualname__(self):
356n/a import time
357n/a
358n/a # builtin function:
359n/a self.assertEqual(len.__qualname__, 'len')
360n/a self.assertEqual(time.time.__qualname__, 'time')
361n/a
362n/a # builtin classmethod:
363n/a self.assertEqual(dict.fromkeys.__qualname__, 'dict.fromkeys')
364n/a self.assertEqual(float.__getformat__.__qualname__,
365n/a 'float.__getformat__')
366n/a
367n/a # builtin staticmethod:
368n/a self.assertEqual(str.maketrans.__qualname__, 'str.maketrans')
369n/a self.assertEqual(bytes.maketrans.__qualname__, 'bytes.maketrans')
370n/a
371n/a # builtin bound instance method:
372n/a self.assertEqual([1, 2, 3].append.__qualname__, 'list.append')
373n/a self.assertEqual({'foo': 'bar'}.pop.__qualname__, 'dict.pop')
374n/a
375n/a
376n/aif __name__ == "__main__":
377n/a unittest.main()