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.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.