Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
Generate Fake User Data with Faker in Python
Use the Faker library to generate realistic fake user profiles with names, emails, phone numbers, and addresses for tests or demos.
from faker import Faker
fake = Faker()
def generate_user():
return {
"name": fake.name(),
"email": fake.email(),
"phone": fake.phone_number(),
"address": fake.address().replace("\n", ", "),
}
if __name__ == "__main__":
user = generate_user()
for key, value in user.ite…
How to Use Union Type Hints in Python
This code demonstrates how to use Union type hints to specify that a parameter can accept multiple types (int, float, str) and handle them accordingly.
from typing import Union
def process_value(value: Union[int, float, str]) -> str:
if isinstance(value, (int, float)):
return f"Number: {value * 2}"
return f"String: {value.upper()}"
if __name__ == "__main__":
print(process_value(10))
print(process_value(3.14))
print(process_value("hello"))
How to Use setUp and tearDown in Python unittest TestCase
Demonstrates how to structure unit tests with setUp and tearDown methods in Python's unittest framework for reusable test fixtures.
import unittest
class ExampleTest(unittest.TestCase):
def setUp(self):
self.data = [1, 2, 3]
def tearDown(self):
self.data = None
def test_length(self):
self.assertEqual(len(self.data), 3)
def test_contains(self):
self.assertIn(2, self.data)
if __name__ == "__main…
How to use unittest mock side_effect with a sequence in Python
Demonstrates using Mock.side_effect with a list to return different values per call and raise an exception at a specific call in unittest.
import unittest
from unittest.mock import Mock
class TestMockSideEffectSequence(unittest.TestCase):
def test_side_effect_sequence(self):
mock = Mock()
mock.side_effect = [1, 2, 3, Exception("boom")]
self.assertEqual(mock(), 1)
self.assertEqual(mock(), 2)
self.asser…
Browse by section
Each section groups closely related Python snippets.
Testing & modern typing — Python code examples
What you will find here
This page collects testing & modern typing snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.