test_inheritance.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. __author__ = 'mchat'
  2. import unittest
  3. object_methods = ["__repr__", "__str__", "__hash__", "__eq__", "__ne__",
  4. "__lt__", "__le__", "__gt__", "__ge__", "__getattr__", "__setattr__"]
  5. numeric_methods = ["__abs__", "__neg__", "__pos__", "__int__", "__long__",
  6. "__float__", "__add__", "__radd__", "__sub__", "__rsub__", "__mul__",
  7. "__rmul__", "__div__", "__rdiv__", "__floordiv__", "__rfloordiv__",
  8. "__mod__", "__rmod__", "__divmod__", "__rdivmod__", "__pow__", "__rpow__",
  9. "__coerce__"]
  10. sequence_methods = ["__len__", "__iter__", "__contains__", "__getitem__",
  11. "__add__", "__mul__", "__rmul__"]
  12. class BuiltinInheritance(unittest.TestCase):
  13. def check_magic_methods(self, obj, isnum=False, isseq=False):
  14. def check_methods(methods):
  15. for method in methods:
  16. self.assertTrue(hasattr(obj, method),
  17. "Expected " + str(type(obj)) + " to have method '" + method + "'")
  18. self.assertIsInstance(obj, object)
  19. check_methods(object_methods)
  20. if (isnum):
  21. check_methods(numeric_methods)
  22. if (isseq):
  23. check_methods(sequence_methods)
  24. def test_object(self):
  25. self.check_magic_methods(object()) # object
  26. def test_none_notimplemented(self):
  27. self.check_magic_methods(None) # None
  28. self.check_magic_methods(NotImplemented) # NotImplemented
  29. def test_numeric_types(self):
  30. self.check_magic_methods(1, isnum=True) # int
  31. self.check_magic_methods(3L, isnum=True) # long
  32. self.check_magic_methods(2.5, isnum=True) # float
  33. self.check_magic_methods(3j, isnum=True) # complex
  34. self.check_magic_methods(True, isnum=True) # bool
  35. self.assertIsInstance(True, int)
  36. self.assertNotIsInstance(True, long)
  37. def test_sequence_types(self):
  38. self.check_magic_methods("hello world", isseq=True) # str
  39. self.check_magic_methods([1, 2, 3, 4], isseq=True) # list
  40. self.check_magic_methods((1, 2, 3, 4), isseq=True) # tuple
  41. def test_other_types(self):
  42. self.check_magic_methods({1:2, 3:4}) # dict
  43. self.check_magic_methods(enumerate([1, 2, 3, 4])) # enumerate
  44. self.check_magic_methods(open("skulpt.py")) # file
  45. self.check_magic_methods(set([1, 2, 3, 4])) # set
  46. self.check_magic_methods(slice(1, 2)) # slice
  47. if __name__ == '__main__':
  48. unittest.main()