Skip to content

Commit 87f6f16

Browse files
simonjayhawkinsPingviinituutti
authored andcommitted
REF/TST: use pytest builtin monkeypatch fixture and remove mock fixture (pandas-dev#24624)
* use monkeypatch * remove mock fixture * rename class
1 parent 4516e97 commit 87f6f16

File tree

7 files changed

+71
-81
lines changed

7 files changed

+71
-81
lines changed

pandas/conftest.py

-15
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from datetime import date, time, timedelta
22
from decimal import Decimal
3-
import importlib
43
import os
54

65
from dateutil.tz import tzlocal, tzutc
@@ -637,20 +636,6 @@ def any_skipna_inferred_dtype(request):
637636
return inferred_dtype, values
638637

639638

640-
@pytest.fixture
641-
def mock():
642-
"""
643-
Fixture providing the 'mock' module.
644-
645-
Uses 'unittest.mock' for Python 3. Attempts to import the 3rd party 'mock'
646-
package for Python 2, skipping if not present.
647-
"""
648-
if PY3:
649-
return importlib.import_module("unittest.mock")
650-
else:
651-
return pytest.importorskip("mock")
652-
653-
654639
@pytest.fixture(params=[getattr(pd.offsets, o) for o in pd.offsets.__all__ if
655640
issubclass(getattr(pd.offsets, o), pd.offsets.Tick)])
656641
def tick_classes(request):

pandas/tests/dtypes/test_inference.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ def __contains__(self, key):
197197
assert result is expected
198198

199199

200-
def test_is_file_like(mock):
200+
def test_is_file_like():
201201
class MockFile(object):
202202
pass
203203

@@ -235,7 +235,6 @@ class MockFile(object):
235235
# Iterator but no read / write attributes
236236
data = [1, 2, 3]
237237
assert not is_file(data)
238-
assert not is_file(mock.Mock())
239238

240239

241240
@pytest.mark.parametrize(

pandas/tests/io/formats/test_format.py

+14-19
Original file line numberDiff line numberDiff line change
@@ -305,16 +305,14 @@ def test_repr_non_interactive(self):
305305
assert not has_truncated_repr(df)
306306
assert not has_expanded_repr(df)
307307

308-
def test_repr_truncates_terminal_size(self, mock):
309-
# https://github.com/pandas-dev/pandas/issues/21180
310-
# TODO: use mock fixutre.
311-
# This is being backported, so doing it directly here.
308+
def test_repr_truncates_terminal_size(self, monkeypatch):
309+
# see gh-21180
312310

313311
terminal_size = (118, 96)
314-
p1 = mock.patch('pandas.io.formats.console.get_terminal_size',
315-
return_value=terminal_size)
316-
p2 = mock.patch('pandas.io.formats.format.get_terminal_size',
317-
return_value=terminal_size)
312+
monkeypatch.setattr('pandas.io.formats.console.get_terminal_size',
313+
lambda: terminal_size)
314+
monkeypatch.setattr('pandas.io.formats.format.get_terminal_size',
315+
lambda: terminal_size)
318316

319317
index = range(5)
320318
columns = pd.MultiIndex.from_tuples([
@@ -323,8 +321,7 @@ def test_repr_truncates_terminal_size(self, mock):
323321
])
324322
df = pd.DataFrame(1, index=index, columns=columns)
325323

326-
with p1, p2:
327-
result = repr(df)
324+
result = repr(df)
328325

329326
h1, h2 = result.split('\n')[:2]
330327
assert 'long' in h1
@@ -334,21 +331,19 @@ def test_repr_truncates_terminal_size(self, mock):
334331

335332
# regular columns
336333
df2 = pd.DataFrame({"A" * 41: [1, 2], 'B' * 41: [1, 2]})
337-
with p1, p2:
338-
result = repr(df2)
334+
result = repr(df2)
339335

340336
assert df2.columns[0] in result.split('\n')[0]
341337

342-
def test_repr_truncates_terminal_size_full(self, mock):
338+
def test_repr_truncates_terminal_size_full(self, monkeypatch):
343339
# GH 22984 ensure entire window is filled
344340
terminal_size = (80, 24)
345341
df = pd.DataFrame(np.random.rand(1, 7))
346-
p1 = mock.patch('pandas.io.formats.console.get_terminal_size',
347-
return_value=terminal_size)
348-
p2 = mock.patch('pandas.io.formats.format.get_terminal_size',
349-
return_value=terminal_size)
350-
with p1, p2:
351-
assert "..." not in str(df)
342+
monkeypatch.setattr('pandas.io.formats.console.get_terminal_size',
343+
lambda: terminal_size)
344+
monkeypatch.setattr('pandas.io.formats.format.get_terminal_size',
345+
lambda: terminal_size)
346+
assert "..." not in str(df)
352347

353348
def test_repr_max_columns_max_rows(self):
354349
term_width, term_height = get_terminal_size()

pandas/tests/io/parser/test_common.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -1814,13 +1814,16 @@ class InvalidBuffer(object):
18141814
parser.read_csv(InvalidBuffer())
18151815

18161816

1817-
def test_invalid_file_buffer_mock(all_parsers, mock):
1817+
def test_invalid_file_buffer_mock(all_parsers):
18181818
# see gh-15337
18191819
parser = all_parsers
18201820
msg = "Invalid file path or buffer object type"
18211821

1822+
class Foo():
1823+
pass
1824+
18221825
with pytest.raises(ValueError, match=msg):
1823-
parser.read_csv(mock.Mock())
1826+
parser.read_csv(Foo())
18241827

18251828

18261829
def test_valid_file_buffer_seems_invalid(all_parsers):

pandas/tests/io/test_gcs.py

+26-18
Original file line numberDiff line numberDiff line change
@@ -17,43 +17,51 @@ def test_is_gcs_url():
1717

1818

1919
@td.skip_if_no('gcsfs')
20-
def test_read_csv_gcs(mock):
20+
def test_read_csv_gcs(monkeypatch):
2121
df1 = DataFrame({'int': [1, 3], 'float': [2.0, np.nan], 'str': ['t', 's'],
2222
'dt': date_range('2018-06-18', periods=2)})
23-
with mock.patch('gcsfs.GCSFileSystem') as MockFileSystem:
24-
instance = MockFileSystem.return_value
25-
instance.open.return_value = StringIO(df1.to_csv(index=False))
26-
df2 = read_csv('gs://test/test.csv', parse_dates=['dt'])
23+
24+
class MockGCSFileSystem():
25+
def open(*args):
26+
return StringIO(df1.to_csv(index=False))
27+
28+
monkeypatch.setattr('gcsfs.GCSFileSystem', MockGCSFileSystem)
29+
df2 = read_csv('gs://test/test.csv', parse_dates=['dt'])
2730

2831
assert_frame_equal(df1, df2)
2932

3033

3134
@td.skip_if_no('gcsfs')
32-
def test_to_csv_gcs(mock):
35+
def test_to_csv_gcs(monkeypatch):
3336
df1 = DataFrame({'int': [1, 3], 'float': [2.0, np.nan], 'str': ['t', 's'],
3437
'dt': date_range('2018-06-18', periods=2)})
35-
with mock.patch('gcsfs.GCSFileSystem') as MockFileSystem:
36-
s = StringIO()
37-
instance = MockFileSystem.return_value
38-
instance.open.return_value = s
38+
s = StringIO()
39+
40+
class MockGCSFileSystem():
41+
def open(*args):
42+
return s
3943

40-
df1.to_csv('gs://test/test.csv', index=True)
41-
df2 = read_csv(StringIO(s.getvalue()), parse_dates=['dt'], index_col=0)
44+
monkeypatch.setattr('gcsfs.GCSFileSystem', MockGCSFileSystem)
45+
df1.to_csv('gs://test/test.csv', index=True)
46+
df2 = read_csv(StringIO(s.getvalue()), parse_dates=['dt'], index_col=0)
4247

4348
assert_frame_equal(df1, df2)
4449

4550

4651
@td.skip_if_no('gcsfs')
47-
def test_gcs_get_filepath_or_buffer(mock):
52+
def test_gcs_get_filepath_or_buffer(monkeypatch):
4853
df1 = DataFrame({'int': [1, 3], 'float': [2.0, np.nan], 'str': ['t', 's'],
4954
'dt': date_range('2018-06-18', periods=2)})
50-
with mock.patch('pandas.io.gcs.get_filepath_or_buffer') as MockGetFilepath:
51-
MockGetFilepath.return_value = (StringIO(df1.to_csv(index=False)),
52-
None, None, False)
53-
df2 = read_csv('gs://test/test.csv', parse_dates=['dt'])
55+
56+
def mock_get_filepath_or_buffer(*args, **kwargs):
57+
return (StringIO(df1.to_csv(index=False)),
58+
None, None, False)
59+
60+
monkeypatch.setattr('pandas.io.gcs.get_filepath_or_buffer',
61+
mock_get_filepath_or_buffer)
62+
df2 = read_csv('gs://test/test.csv', parse_dates=['dt'])
5463

5564
assert_frame_equal(df1, df2)
56-
assert MockGetFilepath.called
5765

5866

5967
@pytest.mark.skipif(td.safe_import('gcsfs'),

pandas/tests/plotting/test_frame.py

+14-14
Original file line numberDiff line numberDiff line change
@@ -2988,21 +2988,21 @@ def test_secondary_axis_font_size(self, method):
29882988
self._check_ticks_props(axes=ax.right_ax,
29892989
ylabelsize=fontsize)
29902990

2991-
def test_misc_bindings(self, mock):
2991+
def test_misc_bindings(self, monkeypatch):
29922992
df = pd.DataFrame(randn(10, 10), columns=list('abcdefghij'))
2993-
p1 = mock.patch('pandas.plotting._misc.scatter_matrix',
2994-
return_value=2)
2995-
p2 = mock.patch('pandas.plotting._misc.andrews_curves',
2996-
return_value=2)
2997-
p3 = mock.patch('pandas.plotting._misc.parallel_coordinates',
2998-
return_value=2)
2999-
p4 = mock.patch('pandas.plotting._misc.radviz',
3000-
return_value=2)
3001-
with p1, p2, p3, p4:
3002-
assert df.plot.scatter_matrix() == 2
3003-
assert df.plot.andrews_curves('a') == 2
3004-
assert df.plot.parallel_coordinates('a') == 2
3005-
assert df.plot.radviz('a') == 2
2993+
monkeypatch.setattr('pandas.plotting._misc.scatter_matrix',
2994+
lambda x: 2)
2995+
monkeypatch.setattr('pandas.plotting._misc.andrews_curves',
2996+
lambda x, y: 2)
2997+
monkeypatch.setattr('pandas.plotting._misc.parallel_coordinates',
2998+
lambda x, y: 2)
2999+
monkeypatch.setattr('pandas.plotting._misc.radviz',
3000+
lambda x, y: 2)
3001+
3002+
assert df.plot.scatter_matrix() == 2
3003+
assert df.plot.andrews_curves('a') == 2
3004+
assert df.plot.parallel_coordinates('a') == 2
3005+
assert df.plot.radviz('a') == 2
30063006

30073007

30083008
def _generate_4_axes_via_gridspec():

pandas/tests/plotting/test_series.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -878,18 +878,18 @@ def test_custom_business_day_freq(self):
878878

879879
_check_plot_works(s.plot)
880880

881-
def test_misc_bindings(self, mock):
881+
def test_misc_bindings(self, monkeypatch):
882882
s = Series(randn(10))
883-
p1 = mock.patch('pandas.plotting._misc.lag_plot',
884-
return_value=2)
885-
p2 = mock.patch('pandas.plotting._misc.autocorrelation_plot',
886-
return_value=2)
887-
p3 = mock.patch('pandas.plotting._misc.bootstrap_plot',
888-
return_value=2)
889-
with p1, p2, p3:
890-
assert s.plot.lag() == 2
891-
assert s.plot.autocorrelation() == 2
892-
assert s.plot.bootstrap() == 2
883+
monkeypatch.setattr('pandas.plotting._misc.lag_plot',
884+
lambda x: 2)
885+
monkeypatch.setattr('pandas.plotting._misc.autocorrelation_plot',
886+
lambda x: 2)
887+
monkeypatch.setattr('pandas.plotting._misc.bootstrap_plot',
888+
lambda x: 2)
889+
890+
assert s.plot.lag() == 2
891+
assert s.plot.autocorrelation() == 2
892+
assert s.plot.bootstrap() == 2
893893

894894
@pytest.mark.xfail
895895
def test_plot_accessor_updates_on_inplace(self):

0 commit comments

Comments
 (0)