80_array2d.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. from array2d import array2d
  2. # test error args for __init__
  3. try:
  4. a = array2d(0, 0)
  5. exit(0)
  6. except ValueError:
  7. pass
  8. # test callable constructor
  9. a = array2d(2, 4, default=lambda: 0)
  10. assert a.width == a.n_cols == 2
  11. assert a.height == a.n_rows == 4
  12. assert a.numel == 8
  13. # test is_valid
  14. assert a.is_valid(0, 0)
  15. assert a.is_valid(1, 3)
  16. assert not a.is_valid(2, 0)
  17. assert not a.is_valid(0, 4)
  18. assert not a.is_valid(-1, 0)
  19. assert not a.is_valid(0, -1)
  20. # test get
  21. assert a.get(0, 0) == 0
  22. assert a.get(1, 3) == 0
  23. assert a.get(2, 0) is None
  24. assert a.get(0, 4, default='S') == 'S'
  25. # test __getitem__
  26. assert a[0, 0] == 0
  27. assert a[1, 3] == 0
  28. try:
  29. a[2, 0]
  30. exit(1)
  31. except IndexError:
  32. pass
  33. # test __setitem__
  34. a[0, 0] = 5
  35. assert a[0, 0] == 5
  36. a[1, 3] = 6
  37. assert a[1, 3] == 6
  38. try:
  39. a[0, -1] = 7
  40. exit(1)
  41. except IndexError:
  42. pass
  43. # test __iter__
  44. a_list = [[5, 0], [0, 0], [0, 0], [0, 6]]
  45. assert a_list == list(a)
  46. # test __len__
  47. assert len(a) == 4
  48. # test __eq__
  49. x = array2d(2, 4, default=0)
  50. b = array2d(2, 4, default=0)
  51. assert x == b
  52. b[0, 0] = 1
  53. assert x != b
  54. # test __repr__
  55. assert repr(a) == f'array2d(2, 4)'
  56. # test map
  57. c = a.map(lambda x: x + 1)
  58. assert list(c) == [[6, 1], [1, 1], [1, 1], [1, 7]]
  59. assert list(a) == [[5, 0], [0, 0], [0, 0], [0, 6]]
  60. assert c.width == c.n_cols == 2
  61. assert c.height == c.n_rows == 4
  62. assert c.numel == 8
  63. # test copy
  64. d = c.copy()
  65. assert d == c and d is not c
  66. # test fill_
  67. d.fill_(-3)
  68. assert d == array2d(2, 4, default=-3)
  69. # test apply_
  70. d.apply_(lambda x: x + 3)
  71. assert d == array2d(2, 4, default=0)
  72. # test copy_
  73. a.copy_(d)
  74. assert a == d and a is not d
  75. # test subclass array2d
  76. class A(array2d):
  77. def __init__(self):
  78. super().__init__(2, 4, default=0)
  79. assert A().width == 2
  80. assert A().height == 4
  81. assert A().numel == 8
  82. assert A().get(0, 0, default=2) == 0