test_print.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import sys
  2. import pytest
  3. import numpy as np
  4. from numpy.testing import assert_, assert_equal
  5. from numpy.core.tests._locales import CommaDecimalPointLocale
  6. from io import StringIO
  7. _REF = {np.inf: 'inf', -np.inf: '-inf', np.nan: 'nan'}
  8. @pytest.mark.parametrize('tp', [np.float32, np.double, np.longdouble])
  9. def test_float_types(tp):
  10. """ Check formatting.
  11. This is only for the str function, and only for simple types.
  12. The precision of np.float32 and np.longdouble aren't the same as the
  13. python float precision.
  14. """
  15. for x in [0, 1, -1, 1e20]:
  16. assert_equal(str(tp(x)), str(float(x)),
  17. err_msg='Failed str formatting for type %s' % tp)
  18. if tp(1e16).itemsize > 4:
  19. assert_equal(str(tp(1e16)), str(float('1e16')),
  20. err_msg='Failed str formatting for type %s' % tp)
  21. else:
  22. ref = '1e+16'
  23. assert_equal(str(tp(1e16)), ref,
  24. err_msg='Failed str formatting for type %s' % tp)
  25. @pytest.mark.parametrize('tp', [np.float32, np.double, np.longdouble])
  26. def test_nan_inf_float(tp):
  27. """ Check formatting of nan & inf.
  28. This is only for the str function, and only for simple types.
  29. The precision of np.float32 and np.longdouble aren't the same as the
  30. python float precision.
  31. """
  32. for x in [np.inf, -np.inf, np.nan]:
  33. assert_equal(str(tp(x)), _REF[x],
  34. err_msg='Failed str formatting for type %s' % tp)
  35. @pytest.mark.parametrize('tp', [np.complex64, np.cdouble, np.clongdouble])
  36. def test_complex_types(tp):
  37. """Check formatting of complex types.
  38. This is only for the str function, and only for simple types.
  39. The precision of np.float32 and np.longdouble aren't the same as the
  40. python float precision.
  41. """
  42. for x in [0, 1, -1, 1e20]:
  43. assert_equal(str(tp(x)), str(complex(x)),
  44. err_msg='Failed str formatting for type %s' % tp)
  45. assert_equal(str(tp(x*1j)), str(complex(x*1j)),
  46. err_msg='Failed str formatting for type %s' % tp)
  47. assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j)),
  48. err_msg='Failed str formatting for type %s' % tp)
  49. if tp(1e16).itemsize > 8:
  50. assert_equal(str(tp(1e16)), str(complex(1e16)),
  51. err_msg='Failed str formatting for type %s' % tp)
  52. else:
  53. ref = '(1e+16+0j)'
  54. assert_equal(str(tp(1e16)), ref,
  55. err_msg='Failed str formatting for type %s' % tp)
  56. @pytest.mark.parametrize('dtype', [np.complex64, np.cdouble, np.clongdouble])
  57. def test_complex_inf_nan(dtype):
  58. """Check inf/nan formatting of complex types."""
  59. TESTS = {
  60. complex(np.inf, 0): "(inf+0j)",
  61. complex(0, np.inf): "infj",
  62. complex(-np.inf, 0): "(-inf+0j)",
  63. complex(0, -np.inf): "-infj",
  64. complex(np.inf, 1): "(inf+1j)",
  65. complex(1, np.inf): "(1+infj)",
  66. complex(-np.inf, 1): "(-inf+1j)",
  67. complex(1, -np.inf): "(1-infj)",
  68. complex(np.nan, 0): "(nan+0j)",
  69. complex(0, np.nan): "nanj",
  70. complex(-np.nan, 0): "(nan+0j)",
  71. complex(0, -np.nan): "nanj",
  72. complex(np.nan, 1): "(nan+1j)",
  73. complex(1, np.nan): "(1+nanj)",
  74. complex(-np.nan, 1): "(nan+1j)",
  75. complex(1, -np.nan): "(1+nanj)",
  76. }
  77. for c, s in TESTS.items():
  78. assert_equal(str(dtype(c)), s)
  79. # print tests
  80. def _test_redirected_print(x, tp, ref=None):
  81. file = StringIO()
  82. file_tp = StringIO()
  83. stdout = sys.stdout
  84. try:
  85. sys.stdout = file_tp
  86. print(tp(x))
  87. sys.stdout = file
  88. if ref:
  89. print(ref)
  90. else:
  91. print(x)
  92. finally:
  93. sys.stdout = stdout
  94. assert_equal(file.getvalue(), file_tp.getvalue(),
  95. err_msg='print failed for type%s' % tp)
  96. @pytest.mark.parametrize('tp', [np.float32, np.double, np.longdouble])
  97. def test_float_type_print(tp):
  98. """Check formatting when using print """
  99. for x in [0, 1, -1, 1e20]:
  100. _test_redirected_print(float(x), tp)
  101. for x in [np.inf, -np.inf, np.nan]:
  102. _test_redirected_print(float(x), tp, _REF[x])
  103. if tp(1e16).itemsize > 4:
  104. _test_redirected_print(float(1e16), tp)
  105. else:
  106. ref = '1e+16'
  107. _test_redirected_print(float(1e16), tp, ref)
  108. @pytest.mark.parametrize('tp', [np.complex64, np.cdouble, np.clongdouble])
  109. def test_complex_type_print(tp):
  110. """Check formatting when using print """
  111. # We do not create complex with inf/nan directly because the feature is
  112. # missing in python < 2.6
  113. for x in [0, 1, -1, 1e20]:
  114. _test_redirected_print(complex(x), tp)
  115. if tp(1e16).itemsize > 8:
  116. _test_redirected_print(complex(1e16), tp)
  117. else:
  118. ref = '(1e+16+0j)'
  119. _test_redirected_print(complex(1e16), tp, ref)
  120. _test_redirected_print(complex(np.inf, 1), tp, '(inf+1j)')
  121. _test_redirected_print(complex(-np.inf, 1), tp, '(-inf+1j)')
  122. _test_redirected_print(complex(-np.nan, 1), tp, '(nan+1j)')
  123. def test_scalar_format():
  124. """Test the str.format method with NumPy scalar types"""
  125. tests = [('{0}', True, np.bool_),
  126. ('{0}', False, np.bool_),
  127. ('{0:d}', 130, np.uint8),
  128. ('{0:d}', 50000, np.uint16),
  129. ('{0:d}', 3000000000, np.uint32),
  130. ('{0:d}', 15000000000000000000, np.uint64),
  131. ('{0:d}', -120, np.int8),
  132. ('{0:d}', -30000, np.int16),
  133. ('{0:d}', -2000000000, np.int32),
  134. ('{0:d}', -7000000000000000000, np.int64),
  135. ('{0:g}', 1.5, np.float16),
  136. ('{0:g}', 1.5, np.float32),
  137. ('{0:g}', 1.5, np.float64),
  138. ('{0:g}', 1.5, np.longdouble),
  139. ('{0:g}', 1.5+0.5j, np.complex64),
  140. ('{0:g}', 1.5+0.5j, np.complex128),
  141. ('{0:g}', 1.5+0.5j, np.clongdouble)]
  142. for (fmat, val, valtype) in tests:
  143. try:
  144. assert_equal(fmat.format(val), fmat.format(valtype(val)),
  145. "failed with val %s, type %s" % (val, valtype))
  146. except ValueError as e:
  147. assert_(False,
  148. "format raised exception (fmt='%s', val=%s, type=%s, exc='%s')" %
  149. (fmat, repr(val), repr(valtype), str(e)))
  150. #
  151. # Locale tests: scalar types formatting should be independent of the locale
  152. #
  153. class TestCommaDecimalPointLocale(CommaDecimalPointLocale):
  154. def test_locale_single(self):
  155. assert_equal(str(np.float32(1.2)), str(float(1.2)))
  156. def test_locale_double(self):
  157. assert_equal(str(np.double(1.2)), str(float(1.2)))
  158. def test_locale_longdouble(self):
  159. assert_equal(str(np.longdouble('1.2')), str(float(1.2)))