Debian Codegraph @

tests/test_dir2.py

raw
1 from IPython.utils.dir2 import dir2
2
3 import pytest
4
5
6 class Base(object):
7 x = 1
8 z = 23
9
10
11 def test_base():
12 res = dir2(Base())
13 assert "x" in res
14 assert "z" in res
15 assert "y" not in res
16 assert "__class__" in res
17 assert res.count("x") == 1
18 assert res.count("__class__") == 1
19
20
21 def test_SubClass():
22 class SubClass(Base):
23 y = 2
24
25 res = dir2(SubClass())
26 assert "y" in res
27 assert res.count("y") == 1
28 assert res.count("x") == 1
29
30
31 def test_SubClass_with_trait_names_attr():
32 # usecase: trait_names is used in a class describing psychological classification
33
34 class SubClass(Base):
35 y = 2
36 trait_names = 44
37
38 res = dir2(SubClass())
39 assert "trait_names" in res
40
41
42 def test_misbehaving_object_without_trait_names():
43 # dir2 shouldn't raise even when objects are dumb and raise
44 # something other than AttribteErrors on bad getattr.
45
46 class MisbehavingGetattr:
47 def __getattr__(self, attr):
48 raise KeyError("I should be caught")
49
50 def some_method(self):
51 return True
52
53 class SillierWithDir(MisbehavingGetattr):
54 def __dir__(self):
55 return ["some_method"]
56
57 for bad_klass in (MisbehavingGetattr, SillierWithDir):
58 obj = bad_klass()
59
60 assert obj.some_method()
61
62 with pytest.raises(KeyError):
63 obj.other_method()
64
65 res = dir2(obj)
66 assert "some_method" in res