PageRenderTime 47ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/pandas/tests/test_common.py

http://github.com/pydata/pandas
Python | 189 lines | 126 code | 46 blank | 17 comment | 10 complexity | 92e81226461caddb8ee7debfaa537c25 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. import collections
  2. from functools import partial
  3. import string
  4. import numpy as np
  5. import pytest
  6. import pandas as pd
  7. from pandas import Series
  8. import pandas._testing as tm
  9. from pandas.core import ops
  10. import pandas.core.common as com
  11. from pandas.util.version import Version
  12. def test_get_callable_name():
  13. getname = com.get_callable_name
  14. def fn(x):
  15. return x
  16. lambda_ = lambda x: x
  17. part1 = partial(fn)
  18. part2 = partial(part1)
  19. class somecall:
  20. def __call__(self):
  21. return x # noqa
  22. assert getname(fn) == "fn"
  23. assert getname(lambda_)
  24. assert getname(part1) == "fn"
  25. assert getname(part2) == "fn"
  26. assert getname(somecall()) == "somecall"
  27. assert getname(1) is None
  28. def test_any_none():
  29. assert com.any_none(1, 2, 3, None)
  30. assert not com.any_none(1, 2, 3, 4)
  31. def test_all_not_none():
  32. assert com.all_not_none(1, 2, 3, 4)
  33. assert not com.all_not_none(1, 2, 3, None)
  34. assert not com.all_not_none(None, None, None, None)
  35. def test_random_state():
  36. import numpy.random as npr
  37. # Check with seed
  38. state = com.random_state(5)
  39. assert state.uniform() == npr.RandomState(5).uniform()
  40. # Check with random state object
  41. state2 = npr.RandomState(10)
  42. assert com.random_state(state2).uniform() == npr.RandomState(10).uniform()
  43. # check with no arg random state
  44. assert com.random_state() is np.random
  45. # check array-like
  46. # GH32503
  47. state_arr_like = npr.randint(0, 2 ** 31, size=624, dtype="uint32")
  48. assert (
  49. com.random_state(state_arr_like).uniform()
  50. == npr.RandomState(state_arr_like).uniform()
  51. )
  52. # Check BitGenerators
  53. # GH32503
  54. assert (
  55. com.random_state(npr.MT19937(3)).uniform()
  56. == npr.RandomState(npr.MT19937(3)).uniform()
  57. )
  58. assert (
  59. com.random_state(npr.PCG64(11)).uniform()
  60. == npr.RandomState(npr.PCG64(11)).uniform()
  61. )
  62. # Error for floats or strings
  63. msg = (
  64. "random_state must be an integer, array-like, a BitGenerator, Generator, "
  65. "a numpy RandomState, or None"
  66. )
  67. with pytest.raises(ValueError, match=msg):
  68. com.random_state("test")
  69. with pytest.raises(ValueError, match=msg):
  70. com.random_state(5.5)
  71. @pytest.mark.parametrize(
  72. "left, right, expected",
  73. [
  74. (Series([1], name="x"), Series([2], name="x"), "x"),
  75. (Series([1], name="x"), Series([2], name="y"), None),
  76. (Series([1]), Series([2], name="x"), None),
  77. (Series([1], name="x"), Series([2]), None),
  78. (Series([1], name="x"), [2], "x"),
  79. ([1], Series([2], name="y"), "y"),
  80. ],
  81. )
  82. def test_maybe_match_name(left, right, expected):
  83. assert ops.common._maybe_match_name(left, right) == expected
  84. def test_standardize_mapping():
  85. # No uninitialized defaultdicts
  86. msg = r"to_dict\(\) only accepts initialized defaultdicts"
  87. with pytest.raises(TypeError, match=msg):
  88. com.standardize_mapping(collections.defaultdict)
  89. # No non-mapping subtypes, instance
  90. msg = "unsupported type: <class 'list'>"
  91. with pytest.raises(TypeError, match=msg):
  92. com.standardize_mapping([])
  93. # No non-mapping subtypes, class
  94. with pytest.raises(TypeError, match=msg):
  95. com.standardize_mapping(list)
  96. fill = {"bad": "data"}
  97. assert com.standardize_mapping(fill) == dict
  98. # Convert instance to type
  99. assert com.standardize_mapping({}) == dict
  100. dd = collections.defaultdict(list)
  101. assert isinstance(com.standardize_mapping(dd), partial)
  102. def test_git_version():
  103. # GH 21295
  104. git_version = pd.__git_version__
  105. assert len(git_version) == 40
  106. assert all(c in string.hexdigits for c in git_version)
  107. def test_version_tag():
  108. version = Version(pd.__version__)
  109. try:
  110. version > Version("0.0.1")
  111. except TypeError:
  112. raise ValueError(
  113. "No git tags exist, please sync tags between upstream and your repo"
  114. )
  115. @pytest.mark.parametrize(
  116. "obj", [(obj,) for obj in pd.__dict__.values() if callable(obj)]
  117. )
  118. def test_serializable(obj):
  119. # GH 35611
  120. unpickled = tm.round_trip_pickle(obj)
  121. assert type(obj) == type(unpickled)
  122. class TestIsBoolIndexer:
  123. def test_non_bool_array_with_na(self):
  124. # in particular, this should not raise
  125. arr = np.array(["A", "B", np.nan], dtype=object)
  126. assert not com.is_bool_indexer(arr)
  127. def test_list_subclass(self):
  128. # GH#42433
  129. class MyList(list):
  130. pass
  131. val = MyList(["a"])
  132. assert not com.is_bool_indexer(val)
  133. val = MyList([True])
  134. assert com.is_bool_indexer(val)
  135. def test_frozenlist(self):
  136. # GH#42461
  137. data = {"col1": [1, 2], "col2": [3, 4]}
  138. df = pd.DataFrame(data=data)
  139. frozen = df.index.names[1:]
  140. assert not com.is_bool_indexer(frozen)
  141. result = df[frozen]
  142. expected = df[[]]
  143. tm.assert_frame_equal(result, expected)