Skip to content

Commit 9a05458

Browse files
authored
TST: Scope pytest.raises closer to failing line (#56746)
1 parent a311f77 commit 9a05458

File tree

22 files changed

+65
-69
lines changed

22 files changed

+65
-69
lines changed

pandas/tests/computation/test_eval.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,8 @@ class TestEval:
141141
def test_complex_cmp_ops(self, cmp1, cmp2, binop, lhs, rhs, engine, parser):
142142
if parser == "python" and binop in ["and", "or"]:
143143
msg = "'BoolOp' nodes are not implemented"
144+
ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)"
144145
with pytest.raises(NotImplementedError, match=msg):
145-
ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)"
146146
pd.eval(ex, engine=engine, parser=parser)
147147
return
148148

@@ -161,9 +161,8 @@ def test_simple_cmp_ops(self, cmp_op, lhs, rhs, engine, parser):
161161

162162
if parser == "python" and cmp_op in ["in", "not in"]:
163163
msg = "'(In|NotIn)' nodes are not implemented"
164-
164+
ex = f"lhs {cmp_op} rhs"
165165
with pytest.raises(NotImplementedError, match=msg):
166-
ex = f"lhs {cmp_op} rhs"
167166
pd.eval(ex, engine=engine, parser=parser)
168167
return
169168

@@ -193,8 +192,8 @@ def test_simple_cmp_ops(self, cmp_op, lhs, rhs, engine, parser):
193192
def test_compound_invert_op(self, op, lhs, rhs, request, engine, parser):
194193
if parser == "python" and op in ["in", "not in"]:
195194
msg = "'(In|NotIn)' nodes are not implemented"
195+
ex = f"~(lhs {op} rhs)"
196196
with pytest.raises(NotImplementedError, match=msg):
197-
ex = f"~(lhs {op} rhs)"
198197
pd.eval(ex, engine=engine, parser=parser)
199198
return
200199

pandas/tests/frame/methods/test_compare.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -168,25 +168,25 @@ def test_compare_multi_index(align_axis):
168168
tm.assert_frame_equal(result, expected)
169169

170170

171-
def test_compare_unaligned_objects():
172-
# test DataFrames with different indices
171+
def test_compare_different_indices():
173172
msg = (
174173
r"Can only compare identically-labeled \(both index and columns\) DataFrame "
175174
"objects"
176175
)
176+
df1 = pd.DataFrame([1, 2, 3], index=["a", "b", "c"])
177+
df2 = pd.DataFrame([1, 2, 3], index=["a", "b", "d"])
177178
with pytest.raises(ValueError, match=msg):
178-
df1 = pd.DataFrame([1, 2, 3], index=["a", "b", "c"])
179-
df2 = pd.DataFrame([1, 2, 3], index=["a", "b", "d"])
180179
df1.compare(df2)
181180

182-
# test DataFrames with different shapes
181+
182+
def test_compare_different_shapes():
183183
msg = (
184184
r"Can only compare identically-labeled \(both index and columns\) DataFrame "
185185
"objects"
186186
)
187+
df1 = pd.DataFrame(np.ones((3, 3)))
188+
df2 = pd.DataFrame(np.zeros((2, 1)))
187189
with pytest.raises(ValueError, match=msg):
188-
df1 = pd.DataFrame(np.ones((3, 3)))
189-
df2 = pd.DataFrame(np.zeros((2, 1)))
190190
df1.compare(df2)
191191

192192

pandas/tests/frame/methods/test_sample.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,12 +111,10 @@ def test_sample_invalid_weight_lengths(self, obj):
111111
obj.sample(n=3, weights=[0, 1])
112112

113113
with pytest.raises(ValueError, match=msg):
114-
bad_weights = [0.5] * 11
115-
obj.sample(n=3, weights=bad_weights)
114+
obj.sample(n=3, weights=[0.5] * 11)
116115

117116
with pytest.raises(ValueError, match="Fewer non-zero entries in p than size"):
118-
bad_weight_series = Series([0, 0, 0.2])
119-
obj.sample(n=4, weights=bad_weight_series)
117+
obj.sample(n=4, weights=Series([0, 0, 0.2]))
120118

121119
def test_sample_negative_weights(self, obj):
122120
# Check won't accept negative weights

pandas/tests/frame/methods/test_tz_convert.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,21 +98,23 @@ def test_tz_convert_and_localize(self, fn):
9898
tm.assert_index_equal(df3.index.levels[1], l1_expected)
9999
assert not df3.index.levels[1].equals(l1)
100100

101-
# Bad Inputs
102-
101+
@pytest.mark.parametrize("fn", ["tz_localize", "tz_convert"])
102+
def test_tz_convert_and_localize_bad_input(self, fn):
103+
int_idx = Index(range(5))
104+
l0 = date_range("20140701", periods=5, freq="D")
103105
# Not DatetimeIndex / PeriodIndex
106+
df = DataFrame(index=int_idx)
104107
with pytest.raises(TypeError, match="DatetimeIndex"):
105-
df = DataFrame(index=int_idx)
106108
getattr(df, fn)("US/Pacific")
107109

108110
# Not DatetimeIndex / PeriodIndex
111+
df = DataFrame(np.ones(5), MultiIndex.from_arrays([int_idx, l0]))
109112
with pytest.raises(TypeError, match="DatetimeIndex"):
110-
df = DataFrame(np.ones(5), MultiIndex.from_arrays([int_idx, l0]))
111113
getattr(df, fn)("US/Pacific", level=0)
112114

113115
# Invalid level
116+
df = DataFrame(index=l0)
114117
with pytest.raises(ValueError, match="not valid"):
115-
df = DataFrame(index=l0)
116118
getattr(df, fn)("US/Pacific", level=1)
117119

118120
@pytest.mark.parametrize("copy", [True, False])

pandas/tests/groupby/aggregate/test_aggregate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -466,8 +466,8 @@ def numpystd(x):
466466

467467
# this uses column selection & renaming
468468
msg = r"nested renamer is not supported"
469+
d = {"C": "mean", "D": {"foo": "mean", "bar": "std"}}
469470
with pytest.raises(SpecificationError, match=msg):
470-
d = {"C": "mean", "D": {"foo": "mean", "bar": "std"}}
471471
grouped.aggregate(d)
472472

473473
# But without renaming, these functions are OK

pandas/tests/indexes/datetimes/test_partial_slicing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,8 +450,8 @@ def test_getitem_with_datestring_with_UTC_offset(self, start, end):
450450
with pytest.raises(ValueError, match="Both dates must"):
451451
df[start : end[:-4] + "1:00"]
452452

453+
df = df.tz_localize(None)
453454
with pytest.raises(ValueError, match="The index must be timezone"):
454-
df = df.tz_localize(None)
455455
df[start:end]
456456

457457
def test_slice_reduce_to_series(self):

pandas/tests/indexing/test_na_indexing.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ def test_series_mask_boolean(values, dtype, mask, indexer_class, frame):
5454
msg = "iLocation based boolean indexing cannot use an indexable as a mask"
5555
with pytest.raises(ValueError, match=msg):
5656
result = obj.iloc[mask]
57-
tm.assert_equal(result, expected)
5857
else:
5958
result = obj.iloc[mask]
6059
tm.assert_equal(result, expected)

pandas/tests/indexing/test_scalar.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ def test_iat_set_ints(self, dtype, frame_or_series):
5353
def test_iat_set_other(self, index, frame_or_series):
5454
f = frame_or_series(range(len(index)), index=index)
5555
msg = "iAt based indexing can only have integer indexers"
56+
idx = next(generate_indices(f, False))
5657
with pytest.raises(ValueError, match=msg):
57-
idx = next(generate_indices(f, False))
5858
f.iat[idx] = 1
5959

6060
@pytest.mark.parametrize(

pandas/tests/internals/test_internals.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -381,8 +381,8 @@ def test_duplicate_ref_loc_failure(self):
381381

382382
msg = "Gaps in blk ref_locs"
383383

384+
mgr = BlockManager(blocks, axes)
384385
with pytest.raises(AssertionError, match=msg):
385-
mgr = BlockManager(blocks, axes)
386386
mgr._rebuild_blknos_and_blklocs()
387387

388388
blocks[0].mgr_locs = BlockPlacement(np.array([0]))

pandas/tests/io/excel/test_openpyxl.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,8 +269,8 @@ def test_if_sheet_exists_raises(ext, if_sheet_exists, msg):
269269
# GH 40230
270270
df = DataFrame({"fruit": ["pear"]})
271271
with tm.ensure_clean(ext) as f:
272+
df.to_excel(f, sheet_name="foo", engine="openpyxl")
272273
with pytest.raises(ValueError, match=re.escape(msg)):
273-
df.to_excel(f, sheet_name="foo", engine="openpyxl")
274274
with ExcelWriter(
275275
f, engine="openpyxl", mode="a", if_sheet_exists=if_sheet_exists
276276
) as writer:

0 commit comments

Comments
 (0)