diff --git a/pandas/conftest.py b/pandas/conftest.py index 30b24e00779a9..35a6b5df35ddc 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1,6 +1,5 @@ from datetime import date, time, timedelta from decimal import Decimal -import importlib import os from dateutil.tz import tzlocal, tzutc @@ -637,20 +636,6 @@ def any_skipna_inferred_dtype(request): return inferred_dtype, values -@pytest.fixture -def mock(): - """ - Fixture providing the 'mock' module. - - Uses 'unittest.mock' for Python 3. Attempts to import the 3rd party 'mock' - package for Python 2, skipping if not present. - """ - if PY3: - return importlib.import_module("unittest.mock") - else: - return pytest.importorskip("mock") - - @pytest.fixture(params=[getattr(pd.offsets, o) for o in pd.offsets.__all__ if issubclass(getattr(pd.offsets, o), pd.offsets.Tick)]) def tick_classes(request): diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index f58cb362cd6d2..89662b70a39ad 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -197,7 +197,7 @@ def __contains__(self, key): assert result is expected -def test_is_file_like(mock): +def test_is_file_like(): class MockFile(object): pass @@ -235,7 +235,6 @@ class MockFile(object): # Iterator but no read / write attributes data = [1, 2, 3] assert not is_file(data) - assert not is_file(mock.Mock()) @pytest.mark.parametrize( diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index c979894048127..d175f669703c7 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -305,16 +305,14 @@ def test_repr_non_interactive(self): assert not has_truncated_repr(df) assert not has_expanded_repr(df) - def test_repr_truncates_terminal_size(self, mock): - # https://github.com/pandas-dev/pandas/issues/21180 - # TODO: use mock fixutre. - # This is being backported, so doing it directly here. + def test_repr_truncates_terminal_size(self, monkeypatch): + # see gh-21180 terminal_size = (118, 96) - p1 = mock.patch('pandas.io.formats.console.get_terminal_size', - return_value=terminal_size) - p2 = mock.patch('pandas.io.formats.format.get_terminal_size', - return_value=terminal_size) + monkeypatch.setattr('pandas.io.formats.console.get_terminal_size', + lambda: terminal_size) + monkeypatch.setattr('pandas.io.formats.format.get_terminal_size', + lambda: terminal_size) index = range(5) columns = pd.MultiIndex.from_tuples([ @@ -323,8 +321,7 @@ def test_repr_truncates_terminal_size(self, mock): ]) df = pd.DataFrame(1, index=index, columns=columns) - with p1, p2: - result = repr(df) + result = repr(df) h1, h2 = result.split('\n')[:2] assert 'long' in h1 @@ -334,21 +331,19 @@ def test_repr_truncates_terminal_size(self, mock): # regular columns df2 = pd.DataFrame({"A" * 41: [1, 2], 'B' * 41: [1, 2]}) - with p1, p2: - result = repr(df2) + result = repr(df2) assert df2.columns[0] in result.split('\n')[0] - def test_repr_truncates_terminal_size_full(self, mock): + def test_repr_truncates_terminal_size_full(self, monkeypatch): # GH 22984 ensure entire window is filled terminal_size = (80, 24) df = pd.DataFrame(np.random.rand(1, 7)) - p1 = mock.patch('pandas.io.formats.console.get_terminal_size', - return_value=terminal_size) - p2 = mock.patch('pandas.io.formats.format.get_terminal_size', - return_value=terminal_size) - with p1, p2: - assert "..." not in str(df) + monkeypatch.setattr('pandas.io.formats.console.get_terminal_size', + lambda: terminal_size) + monkeypatch.setattr('pandas.io.formats.format.get_terminal_size', + lambda: terminal_size) + assert "..." not in str(df) def test_repr_max_columns_max_rows(self): term_width, term_height = get_terminal_size() diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index 2dc4c578102bb..b1547181350bc 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -1814,13 +1814,16 @@ class InvalidBuffer(object): parser.read_csv(InvalidBuffer()) -def test_invalid_file_buffer_mock(all_parsers, mock): +def test_invalid_file_buffer_mock(all_parsers): # see gh-15337 parser = all_parsers msg = "Invalid file path or buffer object type" + class Foo(): + pass + with pytest.raises(ValueError, match=msg): - parser.read_csv(mock.Mock()) + parser.read_csv(Foo()) def test_valid_file_buffer_seems_invalid(all_parsers): diff --git a/pandas/tests/io/test_gcs.py b/pandas/tests/io/test_gcs.py index 12b082c3d4099..ec0631e748dfc 100644 --- a/pandas/tests/io/test_gcs.py +++ b/pandas/tests/io/test_gcs.py @@ -17,43 +17,51 @@ def test_is_gcs_url(): @td.skip_if_no('gcsfs') -def test_read_csv_gcs(mock): +def test_read_csv_gcs(monkeypatch): df1 = DataFrame({'int': [1, 3], 'float': [2.0, np.nan], 'str': ['t', 's'], 'dt': date_range('2018-06-18', periods=2)}) - with mock.patch('gcsfs.GCSFileSystem') as MockFileSystem: - instance = MockFileSystem.return_value - instance.open.return_value = StringIO(df1.to_csv(index=False)) - df2 = read_csv('gs://test/test.csv', parse_dates=['dt']) + + class MockGCSFileSystem(): + def open(*args): + return StringIO(df1.to_csv(index=False)) + + monkeypatch.setattr('gcsfs.GCSFileSystem', MockGCSFileSystem) + df2 = read_csv('gs://test/test.csv', parse_dates=['dt']) assert_frame_equal(df1, df2) @td.skip_if_no('gcsfs') -def test_to_csv_gcs(mock): +def test_to_csv_gcs(monkeypatch): df1 = DataFrame({'int': [1, 3], 'float': [2.0, np.nan], 'str': ['t', 's'], 'dt': date_range('2018-06-18', periods=2)}) - with mock.patch('gcsfs.GCSFileSystem') as MockFileSystem: - s = StringIO() - instance = MockFileSystem.return_value - instance.open.return_value = s + s = StringIO() + + class MockGCSFileSystem(): + def open(*args): + return s - df1.to_csv('gs://test/test.csv', index=True) - df2 = read_csv(StringIO(s.getvalue()), parse_dates=['dt'], index_col=0) + monkeypatch.setattr('gcsfs.GCSFileSystem', MockGCSFileSystem) + df1.to_csv('gs://test/test.csv', index=True) + df2 = read_csv(StringIO(s.getvalue()), parse_dates=['dt'], index_col=0) assert_frame_equal(df1, df2) @td.skip_if_no('gcsfs') -def test_gcs_get_filepath_or_buffer(mock): +def test_gcs_get_filepath_or_buffer(monkeypatch): df1 = DataFrame({'int': [1, 3], 'float': [2.0, np.nan], 'str': ['t', 's'], 'dt': date_range('2018-06-18', periods=2)}) - with mock.patch('pandas.io.gcs.get_filepath_or_buffer') as MockGetFilepath: - MockGetFilepath.return_value = (StringIO(df1.to_csv(index=False)), - None, None, False) - df2 = read_csv('gs://test/test.csv', parse_dates=['dt']) + + def mock_get_filepath_or_buffer(*args, **kwargs): + return (StringIO(df1.to_csv(index=False)), + None, None, False) + + monkeypatch.setattr('pandas.io.gcs.get_filepath_or_buffer', + mock_get_filepath_or_buffer) + df2 = read_csv('gs://test/test.csv', parse_dates=['dt']) assert_frame_equal(df1, df2) - assert MockGetFilepath.called @pytest.mark.skipif(td.safe_import('gcsfs'), diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 436ccef48ae12..0e7672f4e2f9d 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -2988,21 +2988,21 @@ def test_secondary_axis_font_size(self, method): self._check_ticks_props(axes=ax.right_ax, ylabelsize=fontsize) - def test_misc_bindings(self, mock): + def test_misc_bindings(self, monkeypatch): df = pd.DataFrame(randn(10, 10), columns=list('abcdefghij')) - p1 = mock.patch('pandas.plotting._misc.scatter_matrix', - return_value=2) - p2 = mock.patch('pandas.plotting._misc.andrews_curves', - return_value=2) - p3 = mock.patch('pandas.plotting._misc.parallel_coordinates', - return_value=2) - p4 = mock.patch('pandas.plotting._misc.radviz', - return_value=2) - with p1, p2, p3, p4: - assert df.plot.scatter_matrix() == 2 - assert df.plot.andrews_curves('a') == 2 - assert df.plot.parallel_coordinates('a') == 2 - assert df.plot.radviz('a') == 2 + monkeypatch.setattr('pandas.plotting._misc.scatter_matrix', + lambda x: 2) + monkeypatch.setattr('pandas.plotting._misc.andrews_curves', + lambda x, y: 2) + monkeypatch.setattr('pandas.plotting._misc.parallel_coordinates', + lambda x, y: 2) + monkeypatch.setattr('pandas.plotting._misc.radviz', + lambda x, y: 2) + + assert df.plot.scatter_matrix() == 2 + assert df.plot.andrews_curves('a') == 2 + assert df.plot.parallel_coordinates('a') == 2 + assert df.plot.radviz('a') == 2 def _generate_4_axes_via_gridspec(): diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 39f8f2f44fda0..1e223c20f55b7 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -878,18 +878,18 @@ def test_custom_business_day_freq(self): _check_plot_works(s.plot) - def test_misc_bindings(self, mock): + def test_misc_bindings(self, monkeypatch): s = Series(randn(10)) - p1 = mock.patch('pandas.plotting._misc.lag_plot', - return_value=2) - p2 = mock.patch('pandas.plotting._misc.autocorrelation_plot', - return_value=2) - p3 = mock.patch('pandas.plotting._misc.bootstrap_plot', - return_value=2) - with p1, p2, p3: - assert s.plot.lag() == 2 - assert s.plot.autocorrelation() == 2 - assert s.plot.bootstrap() == 2 + monkeypatch.setattr('pandas.plotting._misc.lag_plot', + lambda x: 2) + monkeypatch.setattr('pandas.plotting._misc.autocorrelation_plot', + lambda x: 2) + monkeypatch.setattr('pandas.plotting._misc.bootstrap_plot', + lambda x: 2) + + assert s.plot.lag() == 2 + assert s.plot.autocorrelation() == 2 + assert s.plot.bootstrap() == 2 @pytest.mark.xfail def test_plot_accessor_updates_on_inplace(self):