Home > Net >  Mocking a formatted datetime.datetime.now()
Mocking a formatted datetime.datetime.now()

Time:10-22

I have this below function and tried pytesting it using mock as per the examples I found here. But unfortunately I am getting an AssertionError.

def get_print_date():
    now = datetime.datetime.now()
    return now.strftime("%d/%m/%Y %H:%M:%S")

This is my pytest code:

import datetime
from unittest.mock import MagicMock

FAKE_NOW = datetime.datetime(2022, 10, 21, 22, 22, 22)
#fake_now = FAKE_NOW.strftime("%d/%m/%Y %H:%M:%S")

@pytest.fixture()
def mock_print_date(monkeypatch):
    print_date_mock = MagicMock(wraps = datetime.datetime)
    print_date_mock.now.return_value = FAKE_NOW
    monkeypatch.setattr(datetime, "datetime", print_date_mock)

def test_get_print_date(mock_print_date):
    assert get_print_date == FAKE_NOW

I also tried using strftime to the constant (to match with the exact format of the return value of my function) which I commented too because it also output for an AssertionError. Any idea what's wrong with it?

CodePudding user response:

From a quick look, you're asserting a function to a datetime object, i.e. assert get_print_date == FAKE_NOW, without calling the function. Doing the latter, in addition to changing the return type of the function from string to datetime, passes the test:

import datetime
from unittest.mock import MagicMock
import pytest

def get_print_date():
    now = datetime.datetime.now()
    return now

FAKE_NOW = datetime.datetime(2022, 10, 21, 22, 22, 22)

@pytest.fixture()
def mock_print_date(monkeypatch):
    print_date_mock = MagicMock(wraps = datetime.datetime)
    print_date_mock.now.return_value = FAKE_NOW
    monkeypatch.setattr(datetime, "datetime", print_date_mock)

def test_get_print_date(mock_print_date):
    assert get_print_date() == FAKE_NOW
  • Related