You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.6 KiB

  1. import pytest
  2. def isclose(a, b, rel_tol=1e-05, abs_tol=0.0):
  3. """Like math.isclose() from Python 3.5"""
  4. return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
  5. def allclose(a_list, b_list, rel_tol=1e-05, abs_tol=0.0):
  6. return all(isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol) for a, b in zip(a_list, b_list))
  7. def test_generalized_iterators():
  8. from pybind11_tests import IntPairs
  9. assert list(IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero()) == [(1, 2), (3, 4)]
  10. assert list(IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero()) == [(1, 2)]
  11. assert list(IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero()) == []
  12. assert list(IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero_keys()) == [1, 3]
  13. assert list(IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero_keys()) == [1]
  14. assert list(IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero_keys()) == []
  15. def test_sequence():
  16. from pybind11_tests import Sequence, ConstructorStats
  17. cstats = ConstructorStats.get(Sequence)
  18. s = Sequence(5)
  19. assert cstats.values() == ['of size', '5']
  20. assert "Sequence" in repr(s)
  21. assert len(s) == 5
  22. assert s[0] == 0 and s[3] == 0
  23. assert 12.34 not in s
  24. s[0], s[3] = 12.34, 56.78
  25. assert 12.34 in s
  26. assert isclose(s[0], 12.34) and isclose(s[3], 56.78)
  27. rev = reversed(s)
  28. assert cstats.values() == ['of size', '5']
  29. rev2 = s[::-1]
  30. assert cstats.values() == ['of size', '5']
  31. expected = [0, 56.78, 0, 0, 12.34]
  32. assert allclose(rev, expected)
  33. assert allclose(rev2, expected)
  34. assert rev == rev2
  35. rev[0::2] = Sequence([2.0, 2.0, 2.0])
  36. assert cstats.values() == ['of size', '3', 'from std::vector']
  37. assert allclose(rev, [2, 56.78, 2, 0, 2])
  38. assert cstats.alive() == 3
  39. del s
  40. assert cstats.alive() == 2
  41. del rev
  42. assert cstats.alive() == 1
  43. del rev2
  44. assert cstats.alive() == 0
  45. assert cstats.values() == []
  46. assert cstats.default_constructions == 0
  47. assert cstats.copy_constructions == 0
  48. assert cstats.move_constructions >= 1
  49. assert cstats.copy_assignments == 0
  50. assert cstats.move_assignments == 0
  51. def test_map_iterator():
  52. from pybind11_tests import StringMap
  53. m = StringMap({'hi': 'bye', 'black': 'white'})
  54. assert m['hi'] == 'bye'
  55. assert len(m) == 2
  56. assert m['black'] == 'white'
  57. with pytest.raises(KeyError):
  58. assert m['orange']
  59. m['orange'] = 'banana'
  60. assert m['orange'] == 'banana'
  61. expected = {'hi': 'bye', 'black': 'white', 'orange': 'banana'}
  62. for k in m:
  63. assert m[k] == expected[k]
  64. for k, v in m.items():
  65. assert v == expected[k]