Patch __call__ of a function

后端 未结 3 1777
离开以前
离开以前 2020-12-11 00:44

I need to patch current datetime in tests. I am using this solution:

def _utcnow():
    return datetime.datetime.utcnow()


def utcnow():
    \"\"\"A proxy w         


        
3条回答
  •  误落风尘
    2020-12-11 01:01

    As commented on the question, since datetime.datetime is written in C, Mock can't replace attributes on the class (see Mocking datetime.today by Ned Batchelder). Instead you can use freezegun.

    $ pip install freezegun
    

    Here's an example:

    import datetime
    
    from freezegun import freeze_time
    
    def my_now():
        return datetime.datetime.utcnow()
    
    
    @freeze_time('2000-01-01 12:00:01')
    def test_freezegun():
        assert my_now() == datetime.datetime(2000, 1, 1, 12, 00, 1)
    

    As you mention, an alternative is to track each module importing datetime and patch them. This is in essence what freezegun does. It takes an object mocking datetime, iterates through sys.modules to find where datetime has been imported and replaces every instance. I guess it's arguable whether you can do this elegantly in one function.

提交回复
热议问题