test_scalarinherit.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # -*- coding: utf-8 -*-
  2. """ Test printing of scalar types.
  3. """
  4. import pytest
  5. import numpy as np
  6. from numpy.testing import assert_, assert_raises
  7. class A:
  8. pass
  9. class B(A, np.float64):
  10. pass
  11. class C(B):
  12. pass
  13. class D(C, B):
  14. pass
  15. class B0(np.float64, A):
  16. pass
  17. class C0(B0):
  18. pass
  19. class HasNew:
  20. def __new__(cls, *args, **kwargs):
  21. return cls, args, kwargs
  22. class B1(np.float64, HasNew):
  23. pass
  24. class TestInherit:
  25. def test_init(self):
  26. x = B(1.0)
  27. assert_(str(x) == '1.0')
  28. y = C(2.0)
  29. assert_(str(y) == '2.0')
  30. z = D(3.0)
  31. assert_(str(z) == '3.0')
  32. def test_init2(self):
  33. x = B0(1.0)
  34. assert_(str(x) == '1.0')
  35. y = C0(2.0)
  36. assert_(str(y) == '2.0')
  37. def test_gh_15395(self):
  38. # HasNew is the second base, so `np.float64` should have priority
  39. x = B1(1.0)
  40. assert_(str(x) == '1.0')
  41. # previously caused RecursionError!?
  42. with pytest.raises(TypeError):
  43. B1(1.0, 2.0)
  44. class TestCharacter:
  45. def test_char_radd(self):
  46. # GH issue 9620, reached gentype_add and raise TypeError
  47. np_s = np.string_('abc')
  48. np_u = np.unicode_('abc')
  49. s = b'def'
  50. u = u'def'
  51. assert_(np_s.__radd__(np_s) is NotImplemented)
  52. assert_(np_s.__radd__(np_u) is NotImplemented)
  53. assert_(np_s.__radd__(s) is NotImplemented)
  54. assert_(np_s.__radd__(u) is NotImplemented)
  55. assert_(np_u.__radd__(np_s) is NotImplemented)
  56. assert_(np_u.__radd__(np_u) is NotImplemented)
  57. assert_(np_u.__radd__(s) is NotImplemented)
  58. assert_(np_u.__radd__(u) is NotImplemented)
  59. assert_(s + np_s == b'defabc')
  60. assert_(u + np_u == u'defabc')
  61. class MyStr(str, np.generic):
  62. # would segfault
  63. pass
  64. with assert_raises(TypeError):
  65. # Previously worked, but gave completely wrong result
  66. ret = s + MyStr('abc')
  67. class MyBytes(bytes, np.generic):
  68. # would segfault
  69. pass
  70. ret = s + MyBytes(b'abc')
  71. assert(type(ret) is type(s))
  72. assert ret == b"defabc"
  73. def test_char_repeat(self):
  74. np_s = np.string_('abc')
  75. np_u = np.unicode_('abc')
  76. res_s = b'abc' * 5
  77. res_u = u'abc' * 5
  78. assert_(np_s * 5 == res_s)
  79. assert_(np_u * 5 == res_u)