| 1 |
# This file is part of Hypothesis, which may be found at |
| 2 |
# https://github.com/HypothesisWorks/hypothesis/ |
| 3 |
# |
| 4 |
# Copyright the Hypothesis Authors. |
| 5 |
# Individual contributors are listed in AUTHORS.rst and the git log. |
| 6 |
# |
| 7 |
# This Source Code Form is subject to the terms of the Mozilla Public License, |
| 8 |
# v. 2.0. If a copy of the MPL was not distributed with this file, You can |
| 9 |
# obtain one at https://mozilla.org/MPL/2.0/. |
| 10 |
|
| 11 |
import numpy as np |
| 12 |
import pandas as pd |
| 13 |
import pytest |
| 14 |
|
| 15 |
from hypothesis import HealthCheck, given, reject, settings, strategies as st |
| 16 |
from hypothesis.errors import InvalidArgument |
| 17 |
from hypothesis.extra import numpy as npst, pandas as pdst |
| 18 |
from hypothesis.extra.pandas.impl import IntegerDtype |
| 19 |
|
| 20 |
from tests.common.debug import ( |
| 21 |
assert_all_examples, |
| 22 |
check_can_generate_examples, |
| 23 |
find_any, |
| 24 |
) |
| 25 |
from tests.pandas.helpers import supported_by_pandas |
| 26 |
|
| 27 |
|
| 28 |
@given(pdst.data_frames([pdst.column("a", dtype=int), pdst.column("b", dtype=float)])) |
| 29 |
def test_can_have_columns_of_distinct_types(df): |
| 30 |
assert df["a"].dtype == np.dtype(int) |
| 31 |
assert df["b"].dtype == np.dtype(float) |
| 32 |
|
| 33 |
|
| 34 |
@given( |
| 35 |
pdst.data_frames( |
| 36 |
[pdst.column(dtype=int)], index=pdst.range_indexes(min_size=1, max_size=5) |
| 37 |
) |
| 38 |
) |
| 39 |
def test_respects_size_bounds(df): |
| 40 |
assert 1 <= len(df) <= 5 |
| 41 |
|
| 42 |
|
| 43 |
@given(pdst.data_frames(pdst.columns(["A", "B"], dtype=float))) |
| 44 |
def test_can_specify_just_column_names(df): |
| 45 |
df["A"] |
| 46 |
df["B"] |
| 47 |
|
| 48 |
|
| 49 |
@given(pdst.data_frames(pdst.columns(2, dtype=float))) |
| 50 |
def test_can_specify_just_column_count(df): |
| 51 |
df[0] |
| 52 |
df[1] |
| 53 |
|
| 54 |
|
| 55 |
@given( |
| 56 |
pdst.data_frames( |
| 57 |
rows=st.fixed_dictionaries({"A": st.integers(1, 10), "B": st.floats()}) |
| 58 |
) |
| 59 |
) |
| 60 |
def test_gets_the_correct_data_shape_for_just_rows(table): |
| 61 |
assert table["A"].dtype == np.dtype("int64") |
| 62 |
assert table["B"].dtype == np.dtype(float) |
| 63 |
|
| 64 |
|
| 65 |
@given( |
| 66 |
pdst.data_frames( |
| 67 |
columns=pdst.columns(["A", "B"], dtype=int), |
| 68 |
rows=st.lists(st.integers(0, 1000), min_size=2, max_size=2).map(sorted), |
| 69 |
) |
| 70 |
) |
| 71 |
def test_can_specify_both_rows_and_columns_list(d): |
| 72 |
assert d["A"].dtype == np.dtype(int) |
| 73 |
assert d["B"].dtype == np.dtype(int) |
| 74 |
for _, r in d.iterrows(): |
| 75 |
assert r["A"] <= r["B"] |
| 76 |
|
| 77 |
|
| 78 |
@given( |
| 79 |
pdst.data_frames( |
| 80 |
columns=pdst.columns(["A", "B"], dtype=int), |
| 81 |
rows=st.lists(st.integers(0, 1000), min_size=2, max_size=2) |
| 82 |
.map(sorted) |
| 83 |
.map(tuple), |
| 84 |
) |
| 85 |
) |
| 86 |
def test_can_specify_both_rows_and_columns_tuple(d): |
| 87 |
assert d["A"].dtype == np.dtype(int) |
| 88 |
assert d["B"].dtype == np.dtype(int) |
| 89 |
for _, r in d.iterrows(): |
| 90 |
assert r["A"] <= r["B"] |
| 91 |
|
| 92 |
|
| 93 |
@given( |
| 94 |
pdst.data_frames( |
| 95 |
columns=pdst.columns(["A", "B"], dtype=int), |
| 96 |
rows=st.lists(st.integers(0, 1000), min_size=2, max_size=2).map( |
| 97 |
lambda x: {"A": min(x), "B": max(x)} |
| 98 |
), |
| 99 |
) |
| 100 |
) |
| 101 |
def test_can_specify_both_rows_and_columns_dict(d): |
| 102 |
assert d["A"].dtype == np.dtype(int) |
| 103 |
assert d["B"].dtype == np.dtype(int) |
| 104 |
for _, r in d.iterrows(): |
| 105 |
assert r["A"] <= r["B"] |
| 106 |
|
| 107 |
|
| 108 |
@given( |
| 109 |
pdst.data_frames( |
| 110 |
[ |
| 111 |
pdst.column( |
| 112 |
"A", |
| 113 |
fill=st.just(np.nan), |
| 114 |
dtype=float, |
| 115 |
elements=st.floats(allow_nan=False), |
| 116 |
) |
| 117 |
], |
| 118 |
rows=st.builds(dict), |
| 119 |
) |
| 120 |
) |
| 121 |
def test_can_fill_in_missing_elements_from_dict(df): |
| 122 |
assert np.isnan(df["A"]).all() |
| 123 |
|
| 124 |
|
| 125 |
@st.composite |
| 126 |
def column_strategy(draw): |
| 127 |
name = draw(st.none() | st.text()) |
| 128 |
dtype = draw(npst.scalar_dtypes().filter(supported_by_pandas)) |
| 129 |
pass_dtype = not draw(st.booleans()) |
| 130 |
if pass_dtype: |
| 131 |
pass_elements = not draw(st.booleans()) |
| 132 |
else: |
| 133 |
pass_elements = True |
| 134 |
if pass_elements: |
| 135 |
elements = npst.from_dtype(dtype) |
| 136 |
else: |
| 137 |
elements = None |
| 138 |
|
| 139 |
unique = draw(st.booleans()) |
| 140 |
fill = st.nothing() if draw(st.booleans()) else None |
| 141 |
|
| 142 |
return pdst.column( |
| 143 |
name=name, dtype=dtype, unique=unique, fill=fill, elements=elements |
| 144 |
) |
| 145 |
|
| 146 |
|
| 147 |
@given(pdst.data_frames(pdst.columns(1, dtype=np.dtype("M8[ns]")))) |
| 148 |
def test_data_frames_with_timestamp_columns(df): |
| 149 |
pass |
| 150 |
|
| 151 |
|
| 152 |
@given( |
| 153 |
pdst.data_frames( |
| 154 |
pdst.columns(["A"], dtype=float, fill=st.just(np.nan), unique=True) |
| 155 |
) |
| 156 |
) |
| 157 |
def test_unique_column_with_fill(df): |
| 158 |
assert len(set(df["A"])) == len(df["A"]) |
| 159 |
|
| 160 |
|
| 161 |
@settings(suppress_health_check=[HealthCheck.too_slow, HealthCheck.filter_too_much]) |
| 162 |
@given(st.data()) |
| 163 |
def test_arbitrary_data_frames(data): |
| 164 |
columns = data.draw( |
| 165 |
st.lists( |
| 166 |
column_strategy(), |
| 167 |
unique_by=lambda c: c.name if c.name is not None else np.nan, |
| 168 |
) |
| 169 |
) |
| 170 |
|
| 171 |
try: |
| 172 |
# Use raw data to work around pandas bug in repr. See |
| 173 |
# https://github.com/pandas-dev/pandas/issues/27484 |
| 174 |
df = data.conjecture_data.draw(pdst.data_frames(columns)) |
| 175 |
except Exception as e: |
| 176 |
if type(e).__name__ == "OutOfBoundsDatetime": |
| 177 |
# See https://github.com/HypothesisWorks/hypothesis-python/pull/826 |
| 178 |
reject() |
| 179 |
else: |
| 180 |
raise |
| 181 |
data_frame_columns = list(df) |
| 182 |
|
| 183 |
assert len(data_frame_columns) == len(columns) |
| 184 |
|
| 185 |
for i, (c, n) in enumerate(zip(columns, df, strict=True)): |
| 186 |
if c.name is None: |
| 187 |
assert n == i |
| 188 |
else: |
| 189 |
assert c.name == n |
| 190 |
|
| 191 |
for i, c in enumerate(columns): |
| 192 |
column_name = data_frame_columns[i] |
| 193 |
values = df[column_name] |
| 194 |
if c.unique: |
| 195 |
# NA values should always be treated as unique to each other, so we |
| 196 |
# just ignore them here. Note NA values in the ecosystem can have |
| 197 |
# different identity behaviours, e.g. |
| 198 |
# |
| 199 |
# >>> set([float("nan"), float("nan")]) |
| 200 |
# {nan, nan} |
| 201 |
# >>> set([pd.NaT, pd.NaT]) |
| 202 |
# {NaT} |
| 203 |
# |
| 204 |
non_na_values = values.dropna() |
| 205 |
assert len(set(non_na_values)) == len(non_na_values) |
| 206 |
|
| 207 |
|
| 208 |
@given( |
| 209 |
pdst.data_frames( |
| 210 |
pdst.columns(["A"], unique=True, dtype=int), rows=st.tuples(st.integers(0, 10)) |
| 211 |
) |
| 212 |
) |
| 213 |
def test_can_specify_unique_with_rows(df): |
| 214 |
column = df["A"] |
| 215 |
assert len(set(column)) == len(column) |
| 216 |
|
| 217 |
|
| 218 |
def test_uniqueness_does_not_affect_other_rows_1(): |
| 219 |
data_frames = pdst.data_frames( |
| 220 |
[ |
| 221 |
pdst.column("A", dtype=int, unique=True), |
| 222 |
pdst.column("B", dtype=int, unique=False), |
| 223 |
], |
| 224 |
rows=st.tuples(st.integers(0, 10), st.integers(0, 10)), |
| 225 |
index=pdst.range_indexes(2, 2), |
| 226 |
) |
| 227 |
find_any(data_frames, lambda x: x["B"][0] == x["B"][1]) |
| 228 |
|
| 229 |
|
| 230 |
def test_uniqueness_does_not_affect_other_rows_2(): |
| 231 |
data_frames = pdst.data_frames( |
| 232 |
[ |
| 233 |
pdst.column("A", dtype=bool, unique=False), |
| 234 |
pdst.column("B", dtype=int, unique=True), |
| 235 |
], |
| 236 |
rows=st.tuples(st.booleans(), st.integers(0, 10)), |
| 237 |
index=pdst.range_indexes(2, 2), |
| 238 |
) |
| 239 |
find_any(data_frames, lambda x: x["A"][0] == x["A"][1]) |
| 240 |
|
| 241 |
|
| 242 |
@given( |
| 243 |
pdst.data_frames(pdst.columns(["A"], dtype=int, fill=st.just(7)), rows=st.tuples()) |
| 244 |
) |
| 245 |
def test_will_fill_missing_columns_in_tuple_row(df): |
| 246 |
for d in df["A"]: |
| 247 |
assert d == 7 |
| 248 |
|
| 249 |
|
| 250 |
@settings(suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow]) |
| 251 |
@given( |
| 252 |
pdst.data_frames( |
| 253 |
index=pdst.range_indexes(10, 10), |
| 254 |
columns=[pdst.column(elements=st.integers(0, 9), fill=None, unique=True)], |
| 255 |
) |
| 256 |
) |
| 257 |
def test_can_generate_unique_columns(df): |
| 258 |
assert set(df[0]) == set(range(10)) |
| 259 |
|
| 260 |
|
| 261 |
@pytest.mark.skip(reason="Just works on Pandas 1.4, though the changelog is silent") |
| 262 |
@pytest.mark.parametrize("dtype", [None, object]) |
| 263 |
def test_expected_failure_from_omitted_object_dtype(dtype): |
| 264 |
# See https://github.com/HypothesisWorks/hypothesis/issues/3133 |
| 265 |
col = pdst.column(elements=st.sets(st.text(), min_size=1), dtype=dtype) |
| 266 |
|
| 267 |
@given(pdst.data_frames(columns=[col])) |
| 268 |
def works_with_object_dtype(df): |
| 269 |
pass |
| 270 |
|
| 271 |
if dtype is object: |
| 272 |
works_with_object_dtype() |
| 273 |
else: |
| 274 |
assert dtype is None |
| 275 |
with pytest.raises(ValueError, match="Maybe passing dtype=object would help"): |
| 276 |
works_with_object_dtype() |
| 277 |
|
| 278 |
|
| 279 |
@pytest.mark.skipif( |
| 280 |
not IntegerDtype, reason="Nullable types not available in this version of Pandas" |
| 281 |
) |
| 282 |
def test_pandas_nullable_types(): |
| 283 |
st = pdst.data_frames(pdst.columns(2, dtype=pd.core.arrays.integer.Int8Dtype())) |
| 284 |
df = find_any(st, lambda s: s.isna().any().any()) |
| 285 |
for s in df.columns: |
| 286 |
assert type(df[s].dtype) == pd.core.arrays.integer.Int8Dtype |
| 287 |
|
| 288 |
|
| 289 |
@given(pdst.data_frames(columns=[pdst.column("col", dtype=object)])) |
| 290 |
def test_object_columns_are_of_type_object(df): |
| 291 |
assert df["col"].dtype == np.dtype("O") |
| 292 |
|
| 293 |
|
| 294 |
def test_class_instances_not_allowed_in_scalar_columns(): |
| 295 |
class A: |
| 296 |
pass |
| 297 |
|
| 298 |
s = pdst.data_frames( |
| 299 |
columns=[ |
| 300 |
pdst.column( |
| 301 |
"col", |
| 302 |
elements=st.just(A()), |
| 303 |
dtype=npst.scalar_dtypes(), |
| 304 |
) |
| 305 |
] |
| 306 |
) |
| 307 |
|
| 308 |
with pytest.raises(InvalidArgument): |
| 309 |
check_can_generate_examples(s) |
| 310 |
|
| 311 |
|
| 312 |
def test_can_generate_object_arrays_with_mixed_dtype_elements(): |
| 313 |
class A: |
| 314 |
pass |
| 315 |
|
| 316 |
s = pdst.data_frames( |
| 317 |
columns=[pdst.column("col", st.just(A()) | st.integers(), dtype=object)], |
| 318 |
index=pdst.range_indexes(1), |
| 319 |
) |
| 320 |
assert_all_examples(s, lambda df: df["col"].dtype == np.dtype("O")) |
| 321 |
find_any(s, lambda df: len({type(x) for x in df["col"].values}) > 1) |
| 322 |
|
| 323 |
|
| 324 |
@given(st.data()) |
| 325 |
@pytest.mark.xfail( |
| 326 |
strict=False, |
| 327 |
reason="not actually true due to pandas conversion. see " |
| 328 |
"https://github.com/HypothesisWorks/hypothesis/pull/4444#issuecomment-3413951478", |
| 329 |
) |
| 330 |
def test_object_dataframe_can_hold_arbitrary_class_instances(data): |
| 331 |
instance = data.draw(st.from_type(type).flatmap(st.from_type)) |
| 332 |
s = pdst.data_frames( |
| 333 |
columns=[pdst.column("col", elements=st.just(instance), dtype=object)] |
| 334 |
) |
| 335 |
df = data.draw(s) |
| 336 |
|
| 337 |
assert all(v is instance for v in df["col"].values) |