mock.patch Fakes datetime.now In Tests

patch() swaps the module-level datetime name for a Mock whose now() returns an injected moment, so both greeting branches run without a real clock.

PythonData Integrity

Code

pythonsnippet
31 lines
import sys
from datetime import datetime
from unittest import TestCase, TestLoader, TextTestRunner
from unittest.mock import patch


def greeting() -> str:
    now = datetime.now()
    if now.hour < 12:
        return "good morning"
    return "good afternoon"


class GreetingTest(TestCase):
    def test_morning(self) -> None:
        fake_now = datetime(2026, 11, 22, 9, 0)
        # Replace the datetime name in this module, not a global object
        with patch("__main__.datetime") as fake_datetime:
            fake_datetime.now.return_value = fake_now
            self.assertEqual(greeting(), "good morning")

    def test_afternoon(self) -> None:
        fake_now = datetime(2026, 11, 22, 14, 30)
        with patch("__main__.datetime") as fake_datetime:
            fake_datetime.now.return_value = fake_now
            self.assertEqual(greeting(), "good afternoon")


suite = TestLoader().loadTestsFromTestCase(GreetingTest)
result = TextTestRunner(stream=sys.stdout, verbosity=1).run(suite)
print(f"{result.testsRun} tests, {len(result.failures)} failures")

Dissecting the snippet

One way to read it: the class GreetingTest and the functions greeting, test_morning and test_afternoon, doing all the work.

What to watch for

  • Built-in APIs only, so there is no supply chain to vet.

Putting it to use

Entry signature: def greeting() -> str

The surface worth importing is greeting; the helpers around it are private to the snippet.

Core lines

def test_afternoon(self) -> None:
    fake_now = datetime(2026, 11, 22, 14, 30)
    with patch("__main__.datetime") as fake_datetime:
        fake_datetime.now.return_value = fake_now
        self.assertEqual(greeting(), "good afternoon")
def test_morning(self) -> None:
    fake_now = datetime(2026, 11, 22, 9, 0)
    # Replace the datetime name in this module, not a global object
    with patch("__main__.datetime") as fake_datetime:
        fake_datetime.now.return_value = fake_now
        self.assertEqual(greeting(), "good morning")
def greeting() -> str:
    now = datetime.now()
    if now.hour < 12:
        return "good morning"
    return "good afternoon"

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `greeting`, `test_morning`, `test_afternoon` at load time.