Skip to content

Commit 0b03a93

Browse files
committed
Use mock to test call_count
1 parent 2b204bd commit 0b03a93

File tree

1 file changed

+12
-21
lines changed

1 file changed

+12
-21
lines changed

pandas/tests/frame/test_apply.py

+12-21
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from datetime import datetime
33
from itertools import chain
44
import operator
5+
from unittest.mock import Mock
56
import warnings
67

78
import numpy as np
@@ -728,35 +729,25 @@ def test_apply_noreduction_tzaware_object(self):
728729

729730
def test_apply_function_runs_once(self):
730731
# https://github.com/pandas-dev/pandas/issues/30815
731-
def non_reducing_func_with_state(row):
732-
non_reducing_func_with_state.call_count = getattr(non_reducing_func_with_state, 'call_count', 0) + 1
733-
return row * non_reducing_func_with_state.call_count
732+
non_reducing_mock = Mock(side_effect=lambda x: x)
733+
reducing_mock = Mock(return_value=1)
734734

735-
def reducing_func_with_state(_):
736-
reducing_func_with_state.call_count = getattr(reducing_func_with_state, 'call_count', 0) + 1
737-
return reducing_func_with_state.call_count
738-
739-
df = pd.DataFrame({'a': [1, 2, 3]})
735+
df = pd.DataFrame({"a": [1, 2, 3]})
740736

741737
# no reduction
742-
res0 = df.apply(non_reducing_func_with_state)
743-
tm.assert_frame_equal(res0, df)
738+
df.apply(non_reducing_mock, axis=1)
739+
assert non_reducing_mock.call_count == 3
744740

745741
# reduction
746-
res1 = df.apply(reducing_func_with_state)
747-
tm.assert_series_equal(res1, Series(data=[1], index=['a']))
742+
df.apply(reducing_mock, axis=1)
743+
assert reducing_mock.call_count == 3
748744

749745
def test_applymap_function_runs_once(self):
746+
reducing_mock = Mock(return_value=1)
750747

751-
# This function will create the same values as in the DataFrame
752-
def func_with_state(_):
753-
func_with_state.call_count = getattr(func_with_state, 'call_count', 0) + 1
754-
return func_with_state.call_count
755-
756-
df = pd.DataFrame({'a': [1, 2, 3]})
757-
result = df.applymap(func_with_state)
758-
tm.assert_frame_equal(result, df)
759-
748+
df = pd.DataFrame({"a": [1, 2, 3]})
749+
df.applymap(reducing_mock)
750+
assert reducing_mock.call_count == 3
760751

761752

762753
class TestInferOutputShape:

0 commit comments

Comments
 (0)