test_dir2.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import nose.tools as nt
  2. from IPython.utils.dir2 import dir2
  3. class Base(object):
  4. x = 1
  5. z = 23
  6. def test_base():
  7. res = dir2(Base())
  8. assert ('x' in res)
  9. assert ('z' in res)
  10. assert ('y' not in res)
  11. assert ('__class__' in res)
  12. nt.assert_equal(res.count('x'), 1)
  13. nt.assert_equal(res.count('__class__'), 1)
  14. def test_SubClass():
  15. class SubClass(Base):
  16. y = 2
  17. res = dir2(SubClass())
  18. assert ('y' in res)
  19. nt.assert_equal(res.count('y'), 1)
  20. nt.assert_equal(res.count('x'), 1)
  21. def test_SubClass_with_trait_names_attr():
  22. # usecase: trait_names is used in a class describing psychological classification
  23. class SubClass(Base):
  24. y = 2
  25. trait_names = 44
  26. res = dir2(SubClass())
  27. assert('trait_names' in res)
  28. def test_misbehaving_object_without_trait_names():
  29. # dir2 shouldn't raise even when objects are dumb and raise
  30. # something other than AttribteErrors on bad getattr.
  31. class MisbehavingGetattr(object):
  32. def __getattr__(self):
  33. raise KeyError("I should be caught")
  34. def some_method(self):
  35. pass
  36. class SillierWithDir(MisbehavingGetattr):
  37. def __dir__(self):
  38. return ['some_method']
  39. for bad_klass in (MisbehavingGetattr, SillierWithDir):
  40. res = dir2(bad_klass())
  41. assert('some_method' in res)