[PYTHON] I want to mock datetime.datetime.now () even with pytest!

TL; DR

If you mock like this, you can mock datetime.datetime.now (). This way you can use the other functions of datetime.datetime as they are.

from unittest.mock import MagicMock

def test_mocking_datetime_now(monkeypatch):
    datetime_mock = MagicMock(wrap=datetime.datetime)
    datetime_mock.now.return_value = datetime.datetime(2020, 3, 11, 0, 0, 0)
    monkeypatch.setattr(datetime, "datetime", datetime_mock)

background

When testing the process of getting the current time, you may want to mock datetime.datetime.now (). At this time, even if you simply try to mock with monkeypatch.setattr, you cannot mock becausedatetime.datetime.now ()is built-in.

import datetime
from unittest.mock import MagicMock

FAKE_NOW = datetime.datetime(2020, 3, 11, 0, 0, 0)

def test_mocking_datetime_now_incorrect(monkeypatch):
    monkeypatch.setattr(datetime.datetime, "now", MagicMock(return_value=FAKE_NOW)
>       monkeypatch.setattr(datetime.datetime, "now", MagicMock(return_value="hoge"))
E       TypeError: can't set attributes of built-in/extension type 'datetime.datetime'

So MagicMock (wrap = datetime.datetime)

Therefore, use MagicMock (wrap = ...). You can specify the object to mock in the wrap argument and mock the required method while flowing the normal method to the wrapped object.

from unittest.mock import MagicMock

def test_mocking_datetime_now(monkeypatch):
    # now()Only mocked datetime_Create mock
    datetime_mock = MagicMock(wrap=datetime.datetime)
    datetime_mock.now.return_value = datetime.datetime(2020, 3, 11, 0, 0, 0)  #Now now()Mock

    # datetime.datetime to datetime_Replaced with mock
    monkeypatch.setattr(datetime, "datetime", datetime_mock)

    #Below, datetime.datetime.now()Test using

Extra

Top answer of stackoverflow wasn't cool, so I was messed up [(answered) I did it](https://stackoverflow.com/a/ 60629703/7449523). I haven't reflected on it.

With the top answer method, you can't call other methods of datetime.datetime. With this method, you can call datetime.datetime.fromisoformat () or other methods as usual.

By the way, another solution is to use pytest-freezegun, which is more like a major. Reference: Pytest current time test (fixed date and time) -Qiita

Recommended Posts

I want to mock datetime.datetime.now () even with pytest!
I want to do ○○ with Pandas
I want to debug with Python
I want to detect objects with OpenCV
I want to blog with Jupyter Notebook
I want to pip install with PythonAnywhere
I want to analyze logs with Python
I want to play with aws with python
I want to run Rails with rails s even in vagrant environment
Use Mock with pytest
I want to use MATLAB feval with python
I want to analyze songs with Spotify API 2
I want to display multiple images with matplotlib.
I want to knock 100 data sciences with Colaboratory
I want to make a game with Python
I want to be an OREMO with setParam!
I want to analyze songs with Spotify API 1
I want to use Temporary Directory with Python2
I don't want to use -inf with np.log
#Unresolved I want to compile gobject-introspection with Python3
I want to use ip vrf with SONiC
I want to solve APG4b with Python (Chapter 2)
I want to start over with Django's Migrate
I want to write to a file with Python
I want to convert an image to WebP with lollipop
Even beginners want to say "I fully understand Python"
I want to handle optimization with python and cplex
I want to climb a mountain with reinforcement learning
Even in JavaScript, I want to see Python `range ()`!
I want to inherit to the back with python dataclass
I want to work with a robot in python.
I want to split a character string with hiragana
I want to write in Python! (3) Utilize the mock
I want to AWS Lambda with Python on Mac!
I want to manually create a legend with matplotlib
[TensorFlow] I want to process windows with Ragged Tensor
[ML Ops] I want to do multi-project with Python
I want to run a quantum computer with Python
I want to bind a local variable with lambda
I want to solve Sudoku (Sudoku)
I want to be able to analyze data with Python (Part 3)
I want to remove Python's Unresolved Import Warning with vsCode
I want to use R functions easily with ipython notebook
I want to specify another version of Python with pyvenv
I want to exchange gifts even for myself! [Christmas hackathon]
I want to be able to analyze data with Python (Part 1)
I want to make a blog editor with django admin
I want to start a jupyter environment with one command
[NetworkX] I want to search for nodes with specific attributes
I want to make a click macro with pyautogui (desire)
I want to change the Japanese flag to the Palau flag with Numpy
I want to be able to analyze data with Python (Part 4)
I want to color black-and-white photos of memories with GAN
I want to be able to analyze data with Python (Part 2)
I want to automatically attend online classes with Python + Selenium!
I want to make a click macro with pyautogui (outlook)
[Python] I want to use the -h option with argparse
I want to use a virtual environment with jupyter notebook!
I want to install a package from requirements.txt with poetry
[Visualization] I want to draw a beautiful graph with Plotly
I want to improve efficiency with Python even in an experimental system (2) RS232C and pySerial