Skip to content

REF/TST: use pytest builtin monkeypatch fixture and remove mock fixture #24624

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 5, 2019
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 0 additions & 15 deletions pandas/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from datetime import date, time, timedelta
from decimal import Decimal
import importlib
import os

from dateutil.tz import tzlocal, tzutc
Expand Down Expand Up @@ -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):
Expand Down
3 changes: 1 addition & 2 deletions pandas/tests/dtypes/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down
33 changes: 14 additions & 19 deletions pandas/tests/io/formats/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand All @@ -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
Expand All @@ -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()
Expand Down
7 changes: 5 additions & 2 deletions pandas/tests/io/parser/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 Mock():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally would rather just name this Foo so as not to cause confusion with the real Mock class

pass

with pytest.raises(ValueError, match=msg):
parser.read_csv(mock.Mock())
parser.read_csv(Mock())


def test_valid_file_buffer_seems_invalid(all_parsers):
Expand Down
44 changes: 26 additions & 18 deletions pandas/tests/io/test_gcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down
28 changes: 14 additions & 14 deletions pandas/tests/plotting/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
22 changes: 11 additions & 11 deletions pandas/tests/plotting/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down