1

I'm writing a test that asserts that a certain method is called with certain parameters.

I have a method that does some pandas.Timestamp() calls and some of them include pandas.Timestamp("now"). And this is where the problem arises.

class MyClass(object):
    def my_method(start, stop):
        start = start if pd.isna(start) else pd.Timestamp(0)
        stop = end if pd.isna(end) else pd.Timestamp("now")

        result = self.perform_calc(start, stop)
        return result

    def perform_calc():
        pass

When I patch pd.Timestamp I also patch it for the 0-case in addition to "now". How can I make a patch where pd.Timestamp acts normal for all other cases than pd.Timestamp("now")?

I have tried to make a side effect function:

def side_effect(t):
    if t == "now":
        return pd.Timestamp("2019-01-01")
    else:
        return pd.Timestamp(t)

But it seems that once pd.Timestamp is patched, this is also patched, so I get a recursion error.

    @patch("my_module.pd.Timestamp", side_effect=side_effect)
    @patch("my_module.MyClass.perform_calc")
    def test_my_method(self, mock_ts, mock_calc):
        start = pd.Timestamp("NaT")
        stop= pd.Timestamp("NaT")
        my_class = my_module.MyClass()
        my_class.my_method(start, stop)

        mock_calc.assert_called_once_with(
            pd.Timestamp(0), pd.Timestamp("2019-01-01")
        )

Basically, I want to fix the return value for pd.Timestamp("now") to a fixed date, while everything else is parsed normally.

Edits: Made changes to examples after questions.

Ivar Stange
  • 303
  • 2
  • 12
  • sorry this might be me but i do not understand what you are trying to do: "When I patch pd.Timestamp I also patch it for the 0-case in addition to "now". How can I make a patch where pd.Timestamp acts normal for all other cases than pd.Timestamp("now")?" what does this mean? – Bendik Knapstad Oct 03 '19 at 10:11
  • Can you please show the whole code where you patch `pd.Timestamp` not only `side_effect` function? – sanyassh Oct 03 '19 at 10:15
  • I've made some updates after your comment Bendik Knapstad. I want `pd.Timestamp(0)` to return `1970-01-01`, but I want `pd.Timestamp("now")` not to return actual now, but a fixed time, e.g. `2019-01-01`. – Ivar Stange Oct 03 '19 at 13:13

0 Answers0