Skip to content

Commit 13f45e7

Browse files
TST/BUG (string dtype): Fix and adjust indexes string tests (#59544)
Co-authored-by: Joris Van den Bossche <[email protected]>
1 parent 80b6850 commit 13f45e7

File tree

5 files changed

+24
-30
lines changed

5 files changed

+24
-30
lines changed

pandas/core/construction.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -611,7 +611,10 @@ def sanitize_array(
611611
dtype = StringDtype(na_value=np.nan)
612612
subarr = dtype.construct_array_type()._from_sequence(data, dtype=dtype)
613613

614-
if subarr is data and copy:
614+
if (
615+
subarr is data
616+
or (subarr.dtype == "str" and subarr.dtype.storage == "python") # type: ignore[union-attr]
617+
) and copy:
615618
subarr = subarr.copy()
616619

617620
else:

pandas/core/indexes/base.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,8 @@ def __new__(
504504

505505
elif is_ea_or_datetimelike_dtype(dtype):
506506
# non-EA dtype indexes have special casting logic, so we punt here
507-
pass
507+
if isinstance(data, (set, frozenset)):
508+
data = list(data)
508509

509510
elif is_ea_or_datetimelike_dtype(data_dtype):
510511
pass
@@ -6877,6 +6878,9 @@ def insert(self, loc: int, item) -> Index:
68776878
# We cannot keep the same dtype, so cast to the (often object)
68786879
# minimal shared dtype before doing the insert.
68796880
dtype = self._find_common_type_compat(item)
6881+
if dtype == self.dtype:
6882+
# EA's might run into recursion errors if loc is invalid
6883+
raise
68806884
return self.astype(dtype).insert(loc, item)
68816885

68826886
if arr.dtype != object or not isinstance(

pandas/tests/indexes/base_class/test_setops.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
import numpy as np
44
import pytest
55

6-
from pandas._config import using_string_dtype
7-
86
import pandas as pd
97
from pandas import (
108
Index,
@@ -233,7 +231,6 @@ def test_tuple_union_bug(self, method, expected, sort):
233231
expected = Index(expected)
234232
tm.assert_index_equal(result, expected)
235233

236-
@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)", strict=False)
237234
@pytest.mark.parametrize("first_list", [["b", "a"], []])
238235
@pytest.mark.parametrize("second_list", [["a", "b"], []])
239236
@pytest.mark.parametrize(
@@ -243,6 +240,7 @@ def test_tuple_union_bug(self, method, expected, sort):
243240
def test_union_name_preservation(
244241
self, first_list, second_list, first_name, second_name, expected_name, sort
245242
):
243+
expected_dtype = object if not first_list or not second_list else "str"
246244
first = Index(first_list, name=first_name)
247245
second = Index(second_list, name=second_name)
248246
union = first.union(second, sort=sort)
@@ -253,7 +251,7 @@ def test_union_name_preservation(
253251
expected = Index(sorted(vals), name=expected_name)
254252
tm.assert_index_equal(union, expected)
255253
else:
256-
expected = Index(vals, name=expected_name)
254+
expected = Index(vals, name=expected_name, dtype=expected_dtype)
257255
tm.assert_index_equal(union.sort_values(), expected.sort_values())
258256

259257
@pytest.mark.parametrize(

pandas/tests/indexes/test_base.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,6 @@ def test_constructor_casting(self, index):
7676
tm.assert_contains_all(arr, new_index)
7777
tm.assert_index_equal(index, new_index)
7878

79-
@pytest.mark.xfail(
80-
using_string_dtype() and not HAS_PYARROW, reason="TODO(infer_string)"
81-
)
8279
def test_constructor_copy(self, using_infer_string):
8380
index = Index(list("abc"), name="name")
8481
arr = np.array(index)
@@ -343,11 +340,6 @@ def test_constructor_empty_special(self, empty, klass):
343340
def test_view_with_args(self, index):
344341
index.view("i8")
345342

346-
@pytest.mark.xfail(
347-
using_string_dtype() and not HAS_PYARROW,
348-
reason="TODO(infer_string)",
349-
strict=False,
350-
)
351343
@pytest.mark.parametrize(
352344
"index",
353345
[
@@ -364,7 +356,8 @@ def test_view_with_args_object_array_raises(self, index):
364356
msg = "When changing to a larger dtype"
365357
with pytest.raises(ValueError, match=msg):
366358
index.view("i8")
367-
elif index.dtype == "string":
359+
elif index.dtype == "str" and not index.dtype.storage == "python":
360+
# TODO(infer_string): Make the errors consistent
368361
with pytest.raises(NotImplementedError, match="i8"):
369362
index.view("i8")
370363
else:

pandas/tests/indexes/test_old_base.py

+11-15
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,7 @@
66
import numpy as np
77
import pytest
88

9-
from pandas._config import using_string_dtype
10-
119
from pandas._libs.tslibs import Timestamp
12-
from pandas.compat import HAS_PYARROW
1310

1411
from pandas.core.dtypes.common import (
1512
is_integer_dtype,
@@ -28,6 +25,7 @@
2825
PeriodIndex,
2926
RangeIndex,
3027
Series,
28+
StringDtype,
3129
TimedeltaIndex,
3230
isna,
3331
period_range,
@@ -229,7 +227,6 @@ def test_logical_compat(self, simple_index):
229227
with pytest.raises(TypeError, match=msg):
230228
idx.any()
231229

232-
@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)", strict=False)
233230
def test_repr_roundtrip(self, simple_index):
234231
if isinstance(simple_index, IntervalIndex):
235232
pytest.skip(f"Not a valid repr for {type(simple_index).__name__}")
@@ -246,11 +243,6 @@ def test_repr_max_seq_item_setting(self, simple_index):
246243
repr(idx)
247244
assert "..." not in str(idx)
248245

249-
@pytest.mark.xfail(
250-
using_string_dtype() and not HAS_PYARROW,
251-
reason="TODO(infer_string)",
252-
strict=False,
253-
)
254246
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
255247
def test_ensure_copied_data(self, index):
256248
# Check the "copy" argument of each Index.__new__ is honoured
@@ -296,7 +288,9 @@ def test_ensure_copied_data(self, index):
296288
tm.assert_numpy_array_equal(
297289
index._values._mask, result._values._mask, check_same="same"
298290
)
299-
elif index.dtype == "string[python]":
291+
elif (
292+
isinstance(index.dtype, StringDtype) and index.dtype.storage == "python"
293+
):
300294
assert np.shares_memory(index._values._ndarray, result._values._ndarray)
301295
tm.assert_numpy_array_equal(
302296
index._values._ndarray, result._values._ndarray, check_same="same"
@@ -444,11 +438,7 @@ def test_insert_base(self, index):
444438
result = trimmed.insert(0, index[0])
445439
assert index[0:4].equals(result)
446440

447-
@pytest.mark.skipif(
448-
using_string_dtype(),
449-
reason="completely different behavior, tested elsewher",
450-
)
451-
def test_insert_out_of_bounds(self, index):
441+
def test_insert_out_of_bounds(self, index, using_infer_string):
452442
# TypeError/IndexError matches what np.insert raises in these cases
453443

454444
if len(index) > 0:
@@ -460,6 +450,12 @@ def test_insert_out_of_bounds(self, index):
460450
msg = "index (0|0.5) is out of bounds for axis 0 with size 0"
461451
else:
462452
msg = "slice indices must be integers or None or have an __index__ method"
453+
454+
if using_infer_string and (
455+
index.dtype == "string" or index.dtype == "category" # noqa: PLR1714
456+
):
457+
msg = "loc must be an integer between"
458+
463459
with pytest.raises(err, match=msg):
464460
index.insert(0.5, "foo")
465461

0 commit comments

Comments
 (0)