test_unpack.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # Unpack tests from CPython converted from doctest to unittest
  2. import unittest
  3. class UnpackTest(unittest.TestCase):
  4. def test_basic(self):
  5. t = (1, 2, 3)
  6. a, b, c = t
  7. self.assertEqual(a, 1)
  8. self.assertEqual(b, 2)
  9. self.assertEqual(c, 3)
  10. l = [4, 5, 6]
  11. a, b, c = l
  12. self.assertEqual(a, 4)
  13. self.assertEqual(b, 5)
  14. self.assertEqual(c, 6)
  15. a, b, c = 7, 8, 9
  16. self.assertEqual(a, 7)
  17. self.assertEqual(b, 8)
  18. self.assertEqual(c, 9)
  19. s = 'one'
  20. a, b, c = s
  21. self.assertEqual(a, 'o')
  22. self.assertEqual(b, 'n')
  23. self.assertEqual(c, 'e')
  24. def test_single(self):
  25. st = (99,)
  26. sl = [100]
  27. a, = st
  28. self.assertEqual(a, 99)
  29. b, = sl
  30. self.assertEqual(b, 100)
  31. def test_non_sequence(self):
  32. def unpack():
  33. a, b, c = 7
  34. # Currently has incorrect message
  35. self.assertRaises(TypeError, unpack)
  36. def test_wrong_size(self):
  37. def tup_too_big():
  38. t = (1, 2, 3)
  39. a, b = t
  40. def list_too_big():
  41. l = [4, 5, 6]
  42. a, b = l
  43. def tup_too_small():
  44. t = (1, 2, 3)
  45. a, b, c, d = t
  46. def list_too_small():
  47. l = [4, 5, 6]
  48. a, b, c, d = l
  49. self.assertRaises(ValueError, tup_too_big)
  50. self.assertRaises(ValueError, list_too_big)
  51. self.assertRaises(ValueError, tup_too_small)
  52. self.assertRaises(ValueError, list_too_small)
  53. def test_class(self):
  54. class Seq:
  55. def __getitem__(self, i):
  56. if i >= 0 and i < 3: return i
  57. raise IndexError
  58. a, b, c = Seq()
  59. self.assertEqual(a, 0)
  60. self.assertEqual(b, 1)
  61. self.assertEqual(c, 2)
  62. def test_class_fail(self):
  63. class Seq:
  64. def __getitem__(self, i):
  65. if i >= 0 and i < 3: return i
  66. raise IndexError
  67. def too_small():
  68. a, b, c, d = Seq()
  69. def too_big():
  70. a, b = Seq()
  71. self.assertRaises(ValueError, too_small)
  72. self.assertRaises(ValueError, too_big)
  73. def test_bad_class(self):
  74. class BadSeq:
  75. def __getitem__(self, i):
  76. if i >=0 and i < 3:
  77. return i
  78. elif i ==3:
  79. raise NameError
  80. else:
  81. raise IndexError
  82. def raise_bad_error1():
  83. a, b, c, d, e = BadSeq()
  84. def raise_bad_error2():
  85. a, b, c = BadSeq()
  86. self.assertRaises(NameError, raise_bad_error1)
  87. self.assertRaises(NameError, raise_bad_error2)
  88. if __name__ == "__main__":
  89. unittest.main()