diff --git a/.github/workflows/python-unit-tests.yml b/.github/workflows/python-unit-tests.yml
new file mode 100644
index 0000000..c62f6c1
--- /dev/null
+++ b/.github/workflows/python-unit-tests.yml
@@ -0,0 +1,56 @@
+name: Unit Tests
+
+on:
+ push:
+ branches: ["**"]
+ pull_request:
+ branches: ["**"]
+
+jobs:
+ django-tests:
+ name: Django Tests
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: 11-extras/8-testing-with-django
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ cache: "pip"
+ cache-dependency-path: 11-extras/8-testing-with-django/requirements.txt
+
+ - name: Install dependencies
+ run: pip install -r requirements.txt
+
+ - name: Run tests
+ run: pytest tests/
+
+ fastapi-tests:
+ name: FastAPI Tests
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: 11-extras/9-testing-with-fastapi
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ cache: "pip"
+ cache-dependency-path: 11-extras/9-testing-with-fastapi/requirements-dev.txt
+
+ - name: Install dependencies
+ run: pip install -r requirements-dev.txt
+
+ - name: Run tests
+ run: pytest tests/ -v
\ No newline at end of file
diff --git a/10-property-based-testing-labs/1-first-tests-using-pbt/src/__init__.py b/10-property-based-testing-labs/1-first-tests-using-pbt/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/10-property-based-testing-labs/1-first-tests-using-pbt/src/score_tracker.py b/10-property-based-testing-labs/1-first-tests-using-pbt/src/score_tracker.py
new file mode 100644
index 0000000..2ea5f14
--- /dev/null
+++ b/10-property-based-testing-labs/1-first-tests-using-pbt/src/score_tracker.py
@@ -0,0 +1,86 @@
+"""
+src/score_tracker.py
+=====================
+Sistema de puntajes para una competencia deportiva.
+Lleva el marcador de dos equipos y calcula estadísticas del partido.
+"""
+
+
+def add_points(current_score: int, points: int) -> int:
+ """Suma puntos al marcador actual de un equipo."""
+ if points < 0:
+ raise ValueError("Los puntos a agregar no pueden ser negativos")
+ return current_score + points
+
+
+def subtract_points(current_score: int, points: int) -> int:
+ """Resta puntos al marcador (penalización). El marcador mínimo es 0."""
+ if points < 0:
+ raise ValueError("Los puntos a restar no pueden ser negativos")
+ result = current_score - points
+ return result if result > 0 else 0
+
+
+def is_tied(score_a: int, score_b: int) -> bool:
+ """Retorna True si ambos equipos tienen el mismo puntaje."""
+ return score_a == score_b
+
+
+def winner(score_a: int, score_b: int) -> str:
+ """
+ Retorna 'A' si el equipo A va ganando, 'B' si va ganando B,
+ o 'tie' si están empatados.
+ """
+ if score_a > score_b:
+ return "A"
+ if score_b > score_a:
+ return "B"
+ return "tie"
+
+
+def goal_difference(score_a: int, score_b: int) -> int:
+ """Retorna la diferencia absoluta de goles entre los dos equipos."""
+ return abs(score_a - score_b)
+
+
+def average_score(scores: list[int]) -> float:
+ """
+ Calcula el promedio de una lista de puntajes.
+ Lanza ValueError si la lista está vacía.
+ """
+ if not scores:
+ raise ValueError("La lista de puntajes no puede estar vacía")
+ return sum(scores) / len(scores)
+
+
+def highest_score(scores: list[int]) -> int:
+ """
+ Retorna el puntaje más alto de la lista.
+ Lanza ValueError si la lista está vacía.
+ """
+ if not scores:
+ raise ValueError("La lista de puntajes no puede estar vacía")
+ return max(scores)
+
+
+def normalize_score(score: int, max_score: int) -> float:
+ """
+ Normaliza un puntaje al rango [0.0, 1.0] respecto al máximo posible.
+ Lanza ValueError si max_score es 0.
+ """
+ if max_score == 0:
+ raise ValueError("El puntaje máximo no puede ser 0")
+ return score / max_score
+
+
+def winning_percentage(wins: int, total_games: int) -> float:
+ """
+ Calcula el porcentaje de victorias como valor entre 0.0 y 100.0.
+ Lanza ValueError si total_games es 0 o negativo.
+ Lanza ValueError si wins es mayor que total_games.
+ """
+ if total_games <= 0:
+ raise ValueError("El total de partidos debe ser mayor a 0")
+ if wins > total_games:
+ raise ValueError("Las victorias no pueden superar el total de partidos")
+ return (wins / total_games) * 100
diff --git a/10-property-based-testing-labs/1-first-tests-using-pbt/tests/__init__.py b/10-property-based-testing-labs/1-first-tests-using-pbt/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/10-property-based-testing-labs/1-first-tests-using-pbt/tests/test_score_tracker.py b/10-property-based-testing-labs/1-first-tests-using-pbt/tests/test_score_tracker.py
new file mode 100644
index 0000000..95ab9b1
--- /dev/null
+++ b/10-property-based-testing-labs/1-first-tests-using-pbt/tests/test_score_tracker.py
@@ -0,0 +1,122 @@
+"""
+tests/test_score_tracker.py
+=============================
+Laboratorio: estrategias de prueba con enteros y flotantes.
+
+Escribe un test por cada comportamiento descrito en los comentarios.
+Importa lo que necesites desde src.score_tracker.
+"""
+
+import hypothesis
+from hypothesis import strategies as st
+from src import score_tracker
+
+# ---------------------------------------------------------------------------
+# add_points
+# ---------------------------------------------------------------------------
+
+# sumar 0 puntos no cambia el marcador
+# sumar puntos positivos incrementa el marcador correctamente
+# sumar puntos a un marcador de 0 retorna los puntos sumados
+# sumar puntos negativos lanza ValueError
+
+
+@hypothesis.given(current_score=st.integers(min_value=0, max_value=100), points_to_add=st.just(0))
+def test_add_points_add_zero_points_should_not_change_the_score_tracker(
+ current_score: int, points_to_add: int
+) -> None:
+ result = score_tracker.add_points(current_score=current_score, points=points_to_add)
+ assert result == current_score
+
+
+@hypothesis.given(
+ current_score=st.integers(min_value=0, max_value=100),
+ points_to_add=st.integers(min_value=1, max_value=10),
+)
+def test_add_points_should_update_the_current_score(current_score: int, points_to_add: int) -> None:
+ result = score_tracker.add_points(current_score=current_score, points=points_to_add)
+ assert result > current_score
+
+
+# ---------------------------------------------------------------------------
+# subtract_points
+# ---------------------------------------------------------------------------
+
+# restar menos puntos de los que hay reduce el marcador
+# restar exactamente los puntos disponibles deja el marcador en 0
+# restar más puntos de los que hay deja el marcador en 0 (no negativo)
+# restar 0 puntos no cambia el marcador
+# restar puntos negativos lanza ValueError
+
+
+# ---------------------------------------------------------------------------
+# is_tied
+# ---------------------------------------------------------------------------
+
+# dos marcadores iguales retorna True
+# dos marcadores distintos retorna False
+# dos marcadores en 0 retorna True
+
+
+# ---------------------------------------------------------------------------
+# winner
+# ---------------------------------------------------------------------------
+
+# cuando A tiene más puntos retorna 'A'
+# cuando B tiene más puntos retorna 'B'
+# cuando ambos tienen los mismos puntos retorna 'tie'
+# cuando ambos tienen 0 puntos retorna 'tie'
+
+
+# ---------------------------------------------------------------------------
+# goal_difference
+# ---------------------------------------------------------------------------
+
+# la diferencia entre 5 y 3 es 2
+# la diferencia entre 3 y 5 también es 2 (valor absoluto)
+# la diferencia entre marcadores iguales es 0
+
+
+# ---------------------------------------------------------------------------
+# average_score
+# ---------------------------------------------------------------------------
+
+# el promedio de una lista de enteros iguales es ese mismo entero como float
+# el promedio de [1, 2, 3] es 2.0
+# el promedio de un único elemento es ese elemento como float
+# el promedio de una lista vacía lanza ValueError
+# el resultado es de tipo float
+
+
+# ---------------------------------------------------------------------------
+# highest_score
+# ---------------------------------------------------------------------------
+
+# retorna el mayor puntaje de la lista
+# retorna el único elemento si la lista tiene uno solo
+# funciona cuando el mayor está al inicio de la lista
+# funciona cuando el mayor está al final de la lista
+# lanza ValueError si la lista está vacía
+
+
+# ---------------------------------------------------------------------------
+# normalize_score
+# ---------------------------------------------------------------------------
+
+# normalizar el puntaje máximo retorna exactamente 1.0
+# normalizar 0 retorna exactamente 0.0
+# normalizar la mitad del máximo retorna aproximadamente 0.5
+# el resultado es de tipo float
+# lanza ValueError si max_score es 0
+
+
+# ---------------------------------------------------------------------------
+# winning_percentage
+# ---------------------------------------------------------------------------
+
+# ganar todos los partidos retorna 100.0
+# no ganar ningún partido retorna 0.0
+# ganar la mitad retorna 50.0
+# el resultado es de tipo float
+# lanza ValueError si total_games es 0
+# lanza ValueError si wins supera total_games
diff --git a/11-extras/1-patchverse/pytest.ini b/11-extras/1-patchverse/pytest.ini
new file mode 100644
index 0000000..1b4cda0
--- /dev/null
+++ b/11-extras/1-patchverse/pytest.ini
@@ -0,0 +1,3 @@
+[pytest]
+markers =
+ enrollment: Unit tests about enrollment of a studen in udemy
\ No newline at end of file
diff --git a/11-extras/1-patchverse/requirements-dev.txt b/11-extras/1-patchverse/requirements-dev.txt
new file mode 100644
index 0000000..00d6d82
--- /dev/null
+++ b/11-extras/1-patchverse/requirements-dev.txt
@@ -0,0 +1,10 @@
+certifi==2026.4.22
+charset-normalizer==3.4.7
+idna==3.13
+iniconfig==2.3.0
+packaging==26.2
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
+requests==2.33.1
+urllib3==2.6.3
diff --git a/11-extras/1-patchverse/src/__init__.py b/11-extras/1-patchverse/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/1-patchverse/src/dependencies.py b/11-extras/1-patchverse/src/dependencies.py
new file mode 100644
index 0000000..7f45462
--- /dev/null
+++ b/11-extras/1-patchverse/src/dependencies.py
@@ -0,0 +1,77 @@
+import smtplib
+import sqlite3
+from datetime import datetime
+
+import requests
+
+
+class DatabaseService:
+ def __init__(self) -> None:
+ self.connection = sqlite3.connect("udemy_students.db")
+
+ def save_enrollment(self, student_email: str, course_id: str) -> int | None:
+ cursor = self.connection.cursor()
+ cursor.execute(
+ "INSERT INTO enrollments (email, course_id, enrolled_at) VALUES (?, ?, ?)",
+ (student_email, course_id, datetime.now().isoformat()),
+ )
+ self.connection.commit()
+ return cursor.lastrowid
+
+ def get_student(self, email: str) -> dict | None:
+ cursor = self.connection.cursor()
+ row = cursor.execute("SELECT * FROM students WHERE email = ?", (email,)).fetchone()
+ if row:
+ return {"email": row[0], "name": row[1], "plan": row[2]}
+ return None
+
+
+class EmailService:
+ def __init__(self) -> None:
+ self.smtp_client = smtplib.SMTP("smtp.udemy.com", 587)
+
+ def send_welcome_email(self, student_email: str, course_name: str) -> bool:
+ message = (
+ f"Subject: Bienvenido al curso {course_name}\n\n"
+ f"Hola, ya tienes acceso al curso {course_name}."
+ )
+ self.smtp_client.sendmail("no-reply@udemy.com", student_email, message)
+ return True
+
+
+class PaymentService:
+ def __init__(self) -> None:
+ self.api_url = "https://payments.udemy.com/api/v1"
+
+ def charge(self, student_email: str, amount: float, currency: str = "USD") -> dict:
+ response = requests.post(
+ f"{self.api_url}/charge",
+ json={"email": student_email, "amount": amount, "currency": currency},
+ timeout=10,
+ )
+ response.raise_for_status()
+ return response.json()
+
+ def refund(self, transaction_id: str) -> dict:
+ response = requests.post(
+ f"{self.api_url}/refund",
+ json={"transaction_id": transaction_id},
+ timeout=10,
+ )
+ response.raise_for_status()
+ return response.json()
+
+
+class CertificateService:
+ def __init__(self) -> None:
+ self.generator_url = "https://certificates.udemy.com/generate"
+
+ def generate(self, student_name: str, course_name: str) -> str:
+ response = requests.post(
+ self.generator_url,
+ json={"student": student_name, "course": course_name},
+ timeout=15,
+ )
+ response.raise_for_status()
+ data = response.json()
+ return data["certificate_url"]
diff --git a/11-extras/1-patchverse/src/enrollment_service.py b/11-extras/1-patchverse/src/enrollment_service.py
new file mode 100644
index 0000000..893824a
--- /dev/null
+++ b/11-extras/1-patchverse/src/enrollment_service.py
@@ -0,0 +1,39 @@
+from src import dependencies
+
+
+class EnrollmentService:
+ """
+ Orquesta la inscripción completa de un estudiante en un curso de Udemy.
+ Crea sus propias dependencias internamente (alto acoplamiento).
+ """
+
+ def enroll_student(
+ self,
+ student_email: str,
+ course_id: str,
+ course_name: str,
+ price: float,
+ ) -> dict:
+ db = dependencies.DatabaseService()
+ payment = dependencies.PaymentService()
+ email = dependencies.EmailService()
+ certificate = dependencies.CertificateService()
+
+ student = db.get_student(student_email)
+ if student is None:
+ raise ValueError(f"Estudiante {student_email} no encontrado")
+
+ charge_result = payment.charge(student_email, price)
+ if charge_result.get("status") != "approved":
+ raise RuntimeError("El pago fue rechazado")
+
+ enrollment_id = db.save_enrollment(student_email, course_id)
+ email.send_welcome_email(student_email, course_name)
+ cert_url = certificate.generate(student["name"], course_name)
+
+ return {
+ "enrollment_id": enrollment_id,
+ "transaction_id": charge_result["transaction_id"],
+ "certificate_url": cert_url,
+ "status": "enrolled",
+ }
diff --git a/11-extras/1-patchverse/tests/__init__.py b/11-extras/1-patchverse/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/1-patchverse/tests/test_enrollment_service.py b/11-extras/1-patchverse/tests/test_enrollment_service.py
new file mode 100644
index 0000000..89e3e29
--- /dev/null
+++ b/11-extras/1-patchverse/tests/test_enrollment_service.py
@@ -0,0 +1,50 @@
+import uuid
+from unittest import mock
+
+import pytest
+from src import enrollment_service
+
+_SRC = "src.enrollment_service.dependencies"
+
+
+@pytest.mark.enrollment
+@mock.patch(f"{_SRC}.DatabaseService") # A
+@mock.patch(f"{_SRC}.PaymentService") # B
+@mock.patch(f"{_SRC}.EmailService") # C
+@mock.patch(f"{_SRC}.CertificateService") # D
+def test_should_enroll_student(
+ mock_certificate_service: mock.MagicMock, # D
+ mock_email_service: mock.MagicMock, # C
+ mock_payment_service: mock.MagicMock, # B
+ mock_database_service: mock.MagicMock, # A
+) -> None:
+ # Arrange
+ mock_instance_database = mock_database_service.return_value
+ mock_instance_database.get_student.return_value = {
+ "email": "row[0]",
+ "name": "row[1]",
+ "plan": "row[2]",
+ }
+ mock_instance_database.save_enrollment.return_value = 1
+
+ mock_instance_payment = mock_payment_service.return_value
+ mock_instance_payment.charge.return_value = {
+ "status": "approved",
+ "transaction_id": str(uuid.uuid4()),
+ }
+
+ mock_instance_email = mock_email_service.return_value
+ mock_instance_email.send_welcome_email.return_value = True
+
+ mock_instance_certificate = mock_certificate_service.return_value
+ mock_instance_certificate.generate.return_value = "https://www.udemy-fake-url.com"
+
+ # Act
+ service = enrollment_service.EnrollmentService()
+ result = service.enroll_student(
+ student_email="fake@email.com", course_id="3", course_name="Testing with python", price=10
+ )
+
+ # Assert
+ assert result
+ assert result["enrollment_id"] == 1
diff --git a/11-extras/2-singleton-in-testing/commands.sh b/11-extras/2-singleton-in-testing/commands.sh
new file mode 100644
index 0000000..55dd6fe
--- /dev/null
+++ b/11-extras/2-singleton-in-testing/commands.sh
@@ -0,0 +1,2 @@
+pip install pytest-reverse
+pytest -v --reverse
\ No newline at end of file
diff --git a/11-extras/2-singleton-in-testing/requirements-dev.txt b/11-extras/2-singleton-in-testing/requirements-dev.txt
new file mode 100644
index 0000000..f681c91
--- /dev/null
+++ b/11-extras/2-singleton-in-testing/requirements-dev.txt
@@ -0,0 +1,6 @@
+iniconfig==2.3.0
+packaging==26.2
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
+pytest-reverse==1.9.0
diff --git a/11-extras/2-singleton-in-testing/src/__init__.py b/11-extras/2-singleton-in-testing/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/2-singleton-in-testing/src/hero_registry.py b/11-extras/2-singleton-in-testing/src/hero_registry.py
new file mode 100644
index 0000000..1b2d7a9
--- /dev/null
+++ b/11-extras/2-singleton-in-testing/src/hero_registry.py
@@ -0,0 +1,18 @@
+class HeroRegistry:
+ _instance = None
+ _heroes = {}
+
+ def __new__(cls) -> "HeroRegistry":
+ if cls._instance is None:
+ cls._instance = super().__new__(cls)
+ cls._instance._heroes = {}
+ return cls._instance
+
+ def add(self, name: str, power: int) -> None:
+ self._heroes[name] = power
+
+ def get(self, name: str) -> int | None:
+ return self._heroes.get(name)
+
+ def count(self) -> int:
+ return len(self._heroes)
diff --git a/11-extras/2-singleton-in-testing/tests/__init__.py b/11-extras/2-singleton-in-testing/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/2-singleton-in-testing/tests/test_hero_registry.py b/11-extras/2-singleton-in-testing/tests/test_hero_registry.py
new file mode 100644
index 0000000..3fe3ee5
--- /dev/null
+++ b/11-extras/2-singleton-in-testing/tests/test_hero_registry.py
@@ -0,0 +1,25 @@
+from src import hero_registry
+
+
+def test_should_registry_starts_empty() -> None:
+ registry = hero_registry.HeroRegistry()
+
+ # Pasa si corre primero
+ # Falla si corre después de test_should_add_hero
+ assert registry.count() == 0
+
+
+def test_should_add_hero() -> None:
+ registry = hero_registry.HeroRegistry()
+ registry.add("Spider-Man", 55)
+
+ assert registry.get("Spider-Man") == 55
+ assert registry.count() == 1 # Falla si ya había héroes de otro test
+
+
+def test_should_not_found_hero() -> None:
+ registry = hero_registry.HeroRegistry()
+
+ # Pasa si corre primero
+ # Falla si test_agregar_heroe corrió antes
+ assert registry.get("Spider-Man") is None
diff --git a/11-extras/2-singleton-in-testing/tests/test_hero_registry_2.py b/11-extras/2-singleton-in-testing/tests/test_hero_registry_2.py
new file mode 100644
index 0000000..0bdb68a
--- /dev/null
+++ b/11-extras/2-singleton-in-testing/tests/test_hero_registry_2.py
@@ -0,0 +1,33 @@
+from src import hero_registry
+
+
+def test_should_registry_starts_empty() -> None:
+ setup_hero_registry()
+ registry = hero_registry.HeroRegistry()
+
+ # Pasa si corre primero
+ # Falla si corre después de test_should_add_hero
+ assert registry.count() == 0
+
+
+def test_should_add_hero() -> None:
+ setup_hero_registry()
+ registry = hero_registry.HeroRegistry()
+ registry.add("Spider-Man", 55)
+
+ assert registry.get("Spider-Man") == 55
+ assert registry.count() == 1 # Falla si ya había héroes de otro test
+
+
+def test_should_not_found_hero() -> None:
+ setup_hero_registry()
+ registry = hero_registry.HeroRegistry()
+
+ # Pasa si corre primero
+ # Falla si test_agregar_heroe corrió antes
+ assert registry.get("Spider-Man") is None
+
+
+def setup_hero_registry() -> None:
+ hero_registry.HeroRegistry._instance = None
+ hero_registry.HeroRegistry._heroes = {}
diff --git a/11-extras/2-singleton-in-testing/tests/test_hero_registry_3.py b/11-extras/2-singleton-in-testing/tests/test_hero_registry_3.py
new file mode 100644
index 0000000..8e61684
--- /dev/null
+++ b/11-extras/2-singleton-in-testing/tests/test_hero_registry_3.py
@@ -0,0 +1,27 @@
+from collections.abc import Generator
+
+import pytest
+from src import hero_registry
+
+
+@pytest.fixture
+def fxt_hero_registry() -> Generator[hero_registry.HeroRegistry]:
+ registry = hero_registry.HeroRegistry()
+ yield registry
+ hero_registry.HeroRegistry._instance = None
+ hero_registry.HeroRegistry._heroes = {}
+
+
+def test_should_registry_starts_empty(fxt_hero_registry: hero_registry.HeroRegistry) -> None:
+ assert fxt_hero_registry.count() == 0
+
+
+def test_should_add_hero(fxt_hero_registry: hero_registry.HeroRegistry) -> None:
+ fxt_hero_registry.add("Spider-Man", 55)
+
+ assert fxt_hero_registry.get("Spider-Man") == 55
+ assert fxt_hero_registry.count() == 1
+
+
+def test_should_not_found_hero(fxt_hero_registry: hero_registry.HeroRegistry) -> None:
+ assert fxt_hero_registry.get("Spider-Man") is None
diff --git a/11-extras/2-singleton-in-testing/tests/test_hero_registry_4.py b/11-extras/2-singleton-in-testing/tests/test_hero_registry_4.py
new file mode 100644
index 0000000..7e6a7ff
--- /dev/null
+++ b/11-extras/2-singleton-in-testing/tests/test_hero_registry_4.py
@@ -0,0 +1,28 @@
+import pytest
+from src import hero_registry
+
+
+@pytest.fixture(autouse=True)
+def fxt_reset_singleton(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(hero_registry.HeroRegistry, "_instance", None)
+ monkeypatch.setattr(hero_registry.HeroRegistry, "_heroes", {})
+
+
+def test_should_registry_starts_empty() -> None:
+ registry = hero_registry.HeroRegistry()
+
+ assert registry.count() == 0
+
+
+def test_should_add_hero() -> None:
+ registry = hero_registry.HeroRegistry()
+ registry.add("Spider-Man", 55)
+
+ assert registry.get("Spider-Man") == 55
+ assert registry.count() == 1
+
+
+def test_should_not_found_hero() -> None:
+ registry = hero_registry.HeroRegistry()
+
+ assert registry.get("Spider-Man") is None
diff --git a/11-extras/3-moto/commands.sh b/11-extras/3-moto/commands.sh
new file mode 100644
index 0000000..6dd6fef
--- /dev/null
+++ b/11-extras/3-moto/commands.sh
@@ -0,0 +1,3 @@
+pip install boto3 moto
+# Opcional
+pip install 'boto3-stubs[essential]'
diff --git a/11-extras/3-moto/requirements-dev.txt b/11-extras/3-moto/requirements-dev.txt
new file mode 100644
index 0000000..c3fc416
--- /dev/null
+++ b/11-extras/3-moto/requirements-dev.txt
@@ -0,0 +1,5 @@
+iniconfig==2.3.0
+packaging==26.2
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
diff --git a/11-extras/3-moto/src/__init__.py b/11-extras/3-moto/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/3-moto/src/hero_vault.py b/11-extras/3-moto/src/hero_vault.py
new file mode 100644
index 0000000..749fb66
--- /dev/null
+++ b/11-extras/3-moto/src/hero_vault.py
@@ -0,0 +1,57 @@
+import json
+
+import boto3
+
+S3_BUCKET = "hero-files"
+DYNAMO_TABLE = "hero-powers"
+
+
+class HeroVault:
+ def __init__(self) -> None:
+ self.s3 = boto3.client("s3", region_name="us-east-1")
+ self.dynamo = boto3.resource("dynamodb", region_name="us-east-1")
+ self.table = self.dynamo.Table(DYNAMO_TABLE)
+
+ # ─── S3 ───────────────────────────────────────────────────────────────────
+
+ def upload_hero_profile(self, hero_name: str, profile: dict) -> str:
+ key = f"heroes/{hero_name.lower().replace(' ', '-')}.json"
+ self.s3.put_object(
+ Bucket=S3_BUCKET,
+ Key=key,
+ Body=json.dumps(profile),
+ ContentType="application/json",
+ )
+ return key
+
+ def get_hero_profile(self, hero_name: str) -> dict | None:
+ key = f"heroes/{hero_name.lower().replace(' ', '-')}.json"
+ try:
+ response = self.s3.get_object(Bucket=S3_BUCKET, Key=key)
+ return json.loads(response["Body"].read())
+ except self.s3.exceptions.NoSuchKey:
+ return None
+
+ def list_hero_profiles(self) -> list[str]:
+ response = self.s3.list_objects_v2(Bucket=S3_BUCKET, Prefix="heroes/")
+ contents = response.get("Contents", [])
+ return [obj["Key"] for obj in contents] # type: ignore
+
+ # ─── DynamoDB ─────────────────────────────────────────────────────────────
+
+ def save_powers(self, hero_name: str, powers: dict) -> None:
+ self.table.put_item(Item={"hero_name": hero_name, **powers})
+
+ def get_powers(self, hero_name: str) -> dict | None:
+ response = self.table.get_item(Key={"hero_name": hero_name})
+ return response.get("Item")
+
+ def update_power(self, hero_name: str, power_key: str, value: int) -> dict:
+ response = self.table.update_item(
+ Key={"hero_name": hero_name},
+ UpdateExpression="SET #pk = :val",
+ ExpressionAttributeNames={"#pk": power_key},
+ ExpressionAttributeValues={":val": value},
+ ReturnValues="ALL_NEW",
+ )
+ return response["Attributes"]
diff --git a/11-extras/3-moto/tests/__init__.py b/11-extras/3-moto/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/3-moto/tests/test_hero_vault.py b/11-extras/3-moto/tests/test_hero_vault.py
new file mode 100644
index 0000000..25c6ce4
--- /dev/null
+++ b/11-extras/3-moto/tests/test_hero_vault.py
@@ -0,0 +1,163 @@
+import json
+
+import boto3
+from moto import mock_aws
+from src import hero_vault
+
+
+@mock_aws
+def test_should_upload_hero_profile_to_s3() -> None:
+ conn = boto3.client("s3", region_name="us-east-1")
+ conn.create_bucket(Bucket=hero_vault.S3_BUCKET)
+
+ vault = hero_vault.HeroVault()
+ profile = {"alias": "Spider-Man", "city": "New York"}
+ key = vault.upload_hero_profile("Peter Parker", profile)
+
+ assert key == "heroes/peter-parker.json"
+ body = conn.get_object(Bucket=hero_vault.S3_BUCKET, Key=key)["Body"].read()
+ assert json.loads(body) == profile
+
+
+@mock_aws
+def test_should_get_existing_hero_profile_from_s3() -> None:
+ conn = boto3.client("s3", region_name="us-east-1")
+ conn.create_bucket(Bucket=hero_vault.S3_BUCKET)
+
+ vault = hero_vault.HeroVault()
+ profile = {"alias": "Iron Man", "city": "Malibu"}
+ vault.upload_hero_profile("Tony Stark", profile)
+
+ result = vault.get_hero_profile("Tony Stark")
+
+ assert result == profile
+
+
+@mock_aws
+def test_should_return_none_when_hero_profile_does_not_exist() -> None:
+ conn = boto3.client("s3", region_name="us-east-1")
+ conn.create_bucket(Bucket=hero_vault.S3_BUCKET)
+
+ vault = hero_vault.HeroVault()
+ result = vault.get_hero_profile("Unknown Hero")
+
+ assert result is None
+
+
+@mock_aws
+def test_should_list_all_hero_profiles_in_s3() -> None:
+ conn = boto3.client("s3", region_name="us-east-1")
+ conn.create_bucket(Bucket=hero_vault.S3_BUCKET)
+
+ vault = hero_vault.HeroVault()
+ vault.upload_hero_profile("Thor Odinson", {"alias": "Thor"})
+ vault.upload_hero_profile("Bruce Banner", {"alias": "Hulk"})
+
+ keys = vault.list_hero_profiles()
+
+ assert sorted(keys) == sorted(
+ [
+ "heroes/thor-odinson.json",
+ "heroes/bruce-banner.json",
+ ]
+ )
+
+
+@mock_aws
+def test_should_return_empty_list_when_no_hero_profiles_exist() -> None:
+ conn = boto3.client("s3", region_name="us-east-1")
+ conn.create_bucket(Bucket=hero_vault.S3_BUCKET)
+
+ vault = hero_vault.HeroVault()
+ result = vault.list_hero_profiles()
+
+ assert result == []
+
+
+@mock_aws
+def test_should_save_powers_to_dynamodb() -> None:
+ boto3.resource("dynamodb", region_name="us-east-1").create_table(
+ TableName=hero_vault.DYNAMO_TABLE,
+ KeySchema=[{"AttributeName": "hero_name", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "hero_name", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ vault = hero_vault.HeroVault()
+ vault.save_powers("Steve Rogers", {"strength": 95, "speed": 80})
+
+ table = boto3.resource("dynamodb", region_name="us-east-1").Table(hero_vault.DYNAMO_TABLE)
+ item = table.get_item(Key={"hero_name": "Steve Rogers"}).get("Item")
+ assert item
+ assert item["strength"] == 95
+ assert item["speed"] == 80
+
+
+@mock_aws
+def test_should_get_powers_from_dynamodb() -> None:
+ boto3.resource("dynamodb", region_name="us-east-1").create_table(
+ TableName=hero_vault.DYNAMO_TABLE,
+ KeySchema=[{"AttributeName": "hero_name", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "hero_name", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ vault = hero_vault.HeroVault()
+ vault.save_powers("Wanda Maximoff", {"magic": 100, "telepathy": 90})
+
+ result = vault.get_powers("Wanda Maximoff")
+ assert result
+ assert result["magic"] == 100
+ assert result["telepathy"] == 90
+
+
+@mock_aws
+def test_should_return_none_when_hero_powers_do_not_exist() -> None:
+ boto3.resource("dynamodb", region_name="us-east-1").create_table(
+ TableName=hero_vault.DYNAMO_TABLE,
+ KeySchema=[{"AttributeName": "hero_name", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "hero_name", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ vault = hero_vault.HeroVault()
+ result = vault.get_powers("Ghost Hero")
+
+ assert result is None
+
+
+@mock_aws
+def test_should_update_existing_power_in_dynamodb() -> None:
+ boto3.resource("dynamodb", region_name="us-east-1").create_table(
+ TableName=hero_vault.DYNAMO_TABLE,
+ KeySchema=[{"AttributeName": "hero_name", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "hero_name", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ vault = hero_vault.HeroVault()
+ vault.save_powers("Natasha Romanoff", {"agility": 85, "stealth": 90})
+
+ updated = vault.update_power("Natasha Romanoff", "agility", 95)
+
+ assert updated["agility"] == 95
+ assert updated["stealth"] == 90
+
+
+@mock_aws
+def test_should_return_all_attributes_after_updating_power() -> None:
+ boto3.resource("dynamodb", region_name="us-east-1").create_table(
+ TableName=hero_vault.DYNAMO_TABLE,
+ KeySchema=[{"AttributeName": "hero_name", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "hero_name", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ vault = hero_vault.HeroVault()
+ vault.save_powers("Clint Barton", {"aim": 99, "reflexes": 88})
+
+ updated = vault.update_power("Clint Barton", "reflexes", 95)
+
+ assert updated["hero_name"] == "Clint Barton"
+ assert updated["aim"] == 99
+ assert updated["reflexes"] == 95
diff --git a/11-extras/4-coverage/commands.sh b/11-extras/4-coverage/commands.sh
new file mode 100644
index 0000000..f05445a
--- /dev/null
+++ b/11-extras/4-coverage/commands.sh
@@ -0,0 +1 @@
+pip install pytest-cov
diff --git a/11-extras/5-object-mother/requirements-dev.txt b/11-extras/5-object-mother/requirements-dev.txt
new file mode 100644
index 0000000..c3fc416
--- /dev/null
+++ b/11-extras/5-object-mother/requirements-dev.txt
@@ -0,0 +1,5 @@
+iniconfig==2.3.0
+packaging==26.2
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
diff --git a/11-extras/5-object-mother/src/__init__.py b/11-extras/5-object-mother/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/5-object-mother/src/models.py b/11-extras/5-object-mother/src/models.py
new file mode 100644
index 0000000..7b83966
--- /dev/null
+++ b/11-extras/5-object-mother/src/models.py
@@ -0,0 +1,71 @@
+from dataclasses import dataclass, field
+from decimal import Decimal
+from enum import Enum
+
+
+class OrderStatus(Enum):
+ PENDING = "pending"
+ CONFIRMED = "confirmed"
+ SHIPPED = "shipped"
+ CANCELLED = "cancelled"
+
+
+@dataclass
+class Customer:
+ id: int
+ name: str
+ email: str
+ age: int
+ is_premium: bool = False
+
+ def can_place_order(self) -> bool:
+ return bool(self.name and self.email)
+
+
+@dataclass
+class Product:
+ id: int
+ name: str
+ price: Decimal
+ stock: int
+
+ def is_available(self) -> bool:
+ return self.stock > 0
+
+
+@dataclass
+class OrderItem:
+ product: Product
+ quantity: int
+
+ def subtotal(self) -> Decimal:
+ return self.product.price * self.quantity
+
+
+@dataclass
+class Order:
+ id: int
+ customer: Customer
+ items: list[OrderItem] = field(default_factory=list)
+ status: OrderStatus = OrderStatus.PENDING
+
+ def total(self) -> Decimal:
+ return sum(item.subtotal() for item in self.items) # type: ignore
+
+ def item_count(self) -> int:
+ return sum(item.quantity for item in self.items)
+
+ def confirm(self) -> None:
+ if not self.items:
+ raise ValueError("Cannot confirm an order with no items")
+ self.status = OrderStatus.CONFIRMED
+
+ def cancel(self) -> None:
+ if self.status == OrderStatus.SHIPPED:
+ raise ValueError("Cannot cancel a shipped order")
+ self.status = OrderStatus.CANCELLED
+
+ def apply_premium_discount(self) -> Decimal:
+ if not self.customer.is_premium:
+ return self.total()
+ return self.total() * Decimal("0.9")
diff --git a/11-extras/5-object-mother/tests/__init__.py b/11-extras/5-object-mother/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/5-object-mother/tests/mothers.py b/11-extras/5-object-mother/tests/mothers.py
new file mode 100644
index 0000000..9cca95f
--- /dev/null
+++ b/11-extras/5-object-mother/tests/mothers.py
@@ -0,0 +1,97 @@
+from decimal import Decimal
+
+from src.models import Customer, Order, OrderItem, OrderStatus, Product
+
+
+class CustomerMother:
+ @staticmethod
+ def default() -> Customer:
+ return Customer(
+ id=1, name="John Doe", email="john.doe@example.com", is_premium=False, age=28
+ )
+
+ @staticmethod
+ def create(
+ id: int = 1,
+ name: str = "John Doe",
+ age: int = 28,
+ email: str = "john.doe@example.com",
+ is_premium: bool = False,
+ ) -> Customer:
+ return Customer(id=id, name=name, email=email, is_premium=is_premium, age=age)
+
+ @staticmethod
+ def premium() -> Customer:
+ return CustomerMother.create(
+ id=2, name="Jane Smith", email="jane.smith@example.com", is_premium=True
+ )
+
+ @staticmethod
+ def without_email() -> Customer:
+ return CustomerMother.create(email="")
+
+
+class ProductMother:
+ @staticmethod
+ def default() -> Product:
+ return ProductMother.create()
+
+ @staticmethod
+ def create(
+ id: int = 1,
+ name: str = "Laptop",
+ price: Decimal = Decimal("999.99"),
+ stock: int = 10,
+ ) -> Product:
+ return Product(id=id, name=name, price=price, stock=stock)
+
+ @staticmethod
+ def out_of_stock() -> Product:
+ return ProductMother.create(id=99, name="Sold Out Item", stock=0)
+
+ @staticmethod
+ def cheap() -> Product:
+ return ProductMother.create(id=3, name="USB Cable", price=Decimal("9.99"), stock=100)
+
+
+class OrderMother:
+ @staticmethod
+ def default() -> Order:
+ customer = CustomerMother.default()
+ product = ProductMother.default()
+ return Order(
+ id=1,
+ customer=customer,
+ items=[OrderItem(product=product, quantity=1)],
+ status=OrderStatus.PENDING,
+ )
+
+ @staticmethod
+ def create(
+ id: int = 1,
+ customer: Customer | None = None,
+ items: list | None = None,
+ status: OrderStatus = OrderStatus.PENDING,
+ ) -> Order:
+ return Order(
+ id=id,
+ customer=customer or CustomerMother.default(),
+ items=items or [OrderItem(product=ProductMother.default(), quantity=1)],
+ status=status,
+ )
+
+ @staticmethod
+ def empty() -> Order:
+ return Order(id=2, customer=CustomerMother.default(), items=[], status=OrderStatus.PENDING)
+
+ @staticmethod
+ def confirmed() -> Order:
+ return OrderMother.create(id=3, status=OrderStatus.CONFIRMED)
+
+ @staticmethod
+ def shipped() -> Order:
+ return OrderMother.create(id=4, status=OrderStatus.SHIPPED)
+
+ @staticmethod
+ def for_premium_customer() -> Order:
+ return OrderMother.create(id=5, customer=CustomerMother.premium())
diff --git a/11-extras/5-object-mother/tests/test_customer.py b/11-extras/5-object-mother/tests/test_customer.py
new file mode 100644
index 0000000..8ac7fe6
--- /dev/null
+++ b/11-extras/5-object-mother/tests/test_customer.py
@@ -0,0 +1,31 @@
+from tests import mothers
+
+
+def test_should_allow_customer_to_place_order_when_data_is_complete() -> None:
+ customer = mothers.CustomerMother.default()
+
+ assert customer.can_place_order() is True
+
+
+def test_should_deny_customer_to_place_order_when_email_is_missing() -> None:
+ customer = mothers.CustomerMother.without_email()
+
+ assert customer.can_place_order() is False
+
+
+def test_should_create_premium_customer_with_discount_flag() -> None:
+ customer = mothers.CustomerMother.premium()
+
+ assert customer.is_premium is True
+
+
+def test_should_create_customer_with_custom_name() -> None:
+ customer = mothers.CustomerMother.create(name="Alice Wonder")
+
+ assert customer.name == "Alice Wonder"
+
+
+def test_should_create_customer_with_custom_email() -> None:
+ customer = mothers.CustomerMother.create(email="alice@example.com")
+
+ assert customer.email == "alice@example.com"
diff --git a/11-extras/5-object-mother/tests/test_order.py b/11-extras/5-object-mother/tests/test_order.py
new file mode 100644
index 0000000..e137fc2
--- /dev/null
+++ b/11-extras/5-object-mother/tests/test_order.py
@@ -0,0 +1,87 @@
+import pytest
+from decimal import Decimal
+from src.models import OrderStatus
+from tests.mothers import CustomerMother, OrderMother, ProductMother
+from src.models import OrderItem
+
+
+def test_should_calculate_correct_total_for_default_order():
+ order = OrderMother.default()
+
+ assert order.total() == Decimal("999.99")
+
+
+def test_should_confirm_order_when_it_has_items():
+ order = OrderMother.default()
+
+ order.confirm()
+
+ assert order.status == OrderStatus.CONFIRMED
+
+
+def test_should_raise_error_when_confirming_empty_order():
+ order = OrderMother.empty()
+
+ with pytest.raises(ValueError, match="no items"):
+ order.confirm()
+
+
+def test_should_cancel_pending_order():
+ order = OrderMother.default()
+
+ order.cancel()
+
+ assert order.status == OrderStatus.CANCELLED
+
+
+def test_should_cancel_confirmed_order():
+ order = OrderMother.confirmed()
+
+ order.cancel()
+
+ assert order.status == OrderStatus.CANCELLED
+
+
+def test_should_raise_error_when_cancelling_shipped_order():
+ order = OrderMother.shipped()
+
+ with pytest.raises(ValueError, match="shipped"):
+ order.cancel()
+
+
+def test_should_apply_10_percent_discount_for_premium_customer():
+ order = OrderMother.for_premium_customer()
+ expected = order.total() * Decimal("0.9")
+
+ discounted = order.apply_premium_discount()
+
+ assert discounted == expected
+
+
+def test_should_not_apply_discount_for_regular_customer():
+ order = OrderMother.default()
+
+ discounted = order.apply_premium_discount()
+
+ assert discounted == order.total()
+
+
+def test_should_count_total_items_in_order():
+ cheap_product = ProductMother.cheap()
+ expensive_product = ProductMother.default()
+ order = OrderMother.create(
+ items=[
+ OrderItem(product=cheap_product, quantity=3),
+ OrderItem(product=expensive_product, quantity=2),
+ ]
+ )
+
+ assert order.item_count() == 5
+
+
+def test_should_create_order_with_custom_customer():
+ vip_customer = CustomerMother.create(id=99, name="VIP Customer", is_premium=True)
+ order = OrderMother.create(customer=vip_customer)
+
+ assert order.customer.name == "VIP Customer"
+ assert order.customer.is_premium is True
diff --git a/11-extras/5-object-mother/tests/test_product.py b/11-extras/5-object-mother/tests/test_product.py
new file mode 100644
index 0000000..ff499d7
--- /dev/null
+++ b/11-extras/5-object-mother/tests/test_product.py
@@ -0,0 +1,32 @@
+from decimal import Decimal
+from tests.mothers import ProductMother
+
+
+def test_should_confirm_product_is_available_when_stock_is_positive():
+ product = ProductMother.default()
+
+ assert product.is_available() is True
+
+
+def test_should_confirm_product_is_unavailable_when_stock_is_zero():
+ product = ProductMother.out_of_stock()
+
+ assert product.is_available() is False
+
+
+def test_should_create_cheap_product_with_low_price():
+ product = ProductMother.cheap()
+
+ assert product.price < Decimal("50.00")
+
+
+def test_should_create_product_with_custom_price():
+ product = ProductMother.create(price=Decimal("249.99"))
+
+ assert product.price == Decimal("249.99")
+
+
+def test_should_create_product_with_custom_stock():
+ product = ProductMother.create(stock=5)
+
+ assert product.stock == 5
diff --git a/11-extras/6-prevents-assert/requirements-dev.txt b/11-extras/6-prevents-assert/requirements-dev.txt
new file mode 100644
index 0000000..c3fc416
--- /dev/null
+++ b/11-extras/6-prevents-assert/requirements-dev.txt
@@ -0,0 +1,5 @@
+iniconfig==2.3.0
+packaging==26.2
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
diff --git a/11-extras/6-prevents-assert/src/__init__.py b/11-extras/6-prevents-assert/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/6-prevents-assert/src/main.py b/11-extras/6-prevents-assert/src/main.py
new file mode 100644
index 0000000..293c0ac
--- /dev/null
+++ b/11-extras/6-prevents-assert/src/main.py
@@ -0,0 +1,20 @@
+def dividir(x: int, y: int) -> float:
+ assert y != 0, "Error: no se puede dividir entre cero"
+ return x / y
+
+
+def create_user(name: str, email: str, age: int) -> bool:
+ if "@" not in email:
+ raise ValueError("Email invalido")
+ if age < 18:
+ raise ValueError("Invalid age, you must be over 18")
+ return True
+
+
+if __name__ == "__main__":
+ create_user(name="Alvaro", email="exampleexample.com", age=12)
+ # try:
+ # result = dividir(x=10, y=0)
+ # print(result)
+ # except AssertionError as e:
+ # print("Error controlado exitosamente", e)
diff --git a/11-extras/6-prevents-assert/tests/__init__.py b/11-extras/6-prevents-assert/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/6-prevents-assert/tests/test_main.py b/11-extras/6-prevents-assert/tests/test_main.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/7-tdd/requirements-dev.txt b/11-extras/7-tdd/requirements-dev.txt
new file mode 100644
index 0000000..c3fc416
--- /dev/null
+++ b/11-extras/7-tdd/requirements-dev.txt
@@ -0,0 +1,5 @@
+iniconfig==2.3.0
+packaging==26.2
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
diff --git a/11-extras/7-tdd/src/__init__.py b/11-extras/7-tdd/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/7-tdd/src/pricing.py b/11-extras/7-tdd/src/pricing.py
new file mode 100644
index 0000000..27c84b2
--- /dev/null
+++ b/11-extras/7-tdd/src/pricing.py
@@ -0,0 +1,2 @@
+def calculate_final_price(price: float, discount_percent: float) -> float:
+ return price - (price * (discount_percent / 100))
diff --git a/11-extras/7-tdd/tests/__init__.py b/11-extras/7-tdd/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/7-tdd/tests/test_pricing.py b/11-extras/7-tdd/tests/test_pricing.py
new file mode 100644
index 0000000..5da2153
--- /dev/null
+++ b/11-extras/7-tdd/tests/test_pricing.py
@@ -0,0 +1,9 @@
+from src import pricing
+
+
+def test_should_calculate_price_without_discount() -> None:
+ assert pricing.calculate_final_price(price=100.0, discount_percent=0) == 100.0
+
+
+def test_should_calculate_price_with_ten_percent_discount() -> None:
+ assert pricing.calculate_final_price(price=100.0, discount_percent=10) == 90.0
diff --git a/11-extras/8-testing-with-django/manage.py b/11-extras/8-testing-with-django/manage.py
new file mode 100644
index 0000000..d5a135a
--- /dev/null
+++ b/11-extras/8-testing-with-django/manage.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+import os
+import sys
+from pathlib import Path
+
+
+def main() -> None:
+ sys.path.insert(0, str(Path(__file__).parent / "src"))
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
+ try:
+ from django.core.management import execute_from_command_line
+ except ImportError as exc:
+ raise ImportError(
+ "Couldn't import Django. Are you sure it's installed and "
+ "available on your PYTHONPATH environment variable? Did you "
+ "forget to activate a virtual environment?"
+ ) from exc
+ execute_from_command_line(sys.argv)
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/11-extras/8-testing-with-django/pytest.ini b/11-extras/8-testing-with-django/pytest.ini
new file mode 100644
index 0000000..cf4e3d4
--- /dev/null
+++ b/11-extras/8-testing-with-django/pytest.ini
@@ -0,0 +1,7 @@
+[pytest]
+DJANGO_SETTINGS_MODULE = src.config.settings
+pythonpath = src
+testpaths = tests
+python_files = test_*.py
+python_functions = test_*
+addopts = -v
diff --git a/11-extras/8-testing-with-django/requirements.txt b/11-extras/8-testing-with-django/requirements.txt
new file mode 100644
index 0000000..008fa4a
--- /dev/null
+++ b/11-extras/8-testing-with-django/requirements.txt
@@ -0,0 +1,3 @@
+django>=4.2
+pytest>=7.4
+pytest-django>=4.7
diff --git a/11-extras/8-testing-with-django/src/config/__init__.py b/11-extras/8-testing-with-django/src/config/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/8-testing-with-django/src/config/settings.py b/11-extras/8-testing-with-django/src/config/settings.py
new file mode 100644
index 0000000..f611186
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/config/settings.py
@@ -0,0 +1,46 @@
+from pathlib import Path
+
+BASE_DIR = Path(__file__).resolve().parent.parent.parent
+
+SECRET_KEY = "django-insecure-testing-secret-key-not-for-production"
+
+DEBUG = True
+
+ALLOWED_HOSTS: list[str] = ["*"]
+
+INSTALLED_APPS: list[str] = [
+ "django.contrib.contenttypes",
+ "django.contrib.auth",
+ "products",
+]
+
+MIDDLEWARE: list[str] = [
+ "django.middleware.security.SecurityMiddleware",
+ "django.middleware.common.CommonMiddleware",
+ "django.middleware.csrf.CsrfViewMiddleware",
+ "django.middleware.clickjacking.XFrameOptionsMiddleware",
+]
+
+ROOT_URLCONF = "config.urls"
+
+TEMPLATES = [
+ {
+ "BACKEND": "django.template.backends.django.DjangoTemplates",
+ "DIRS": [BASE_DIR / "templates"],
+ "APP_DIRS": True,
+ "OPTIONS": {
+ "context_processors": [
+ "django.template.context_processors.request",
+ ],
+ },
+ },
+]
+
+DATABASES = {
+ "default": {
+ "ENGINE": "django.db.backends.sqlite3",
+ "NAME": BASE_DIR / "db.sqlite3",
+ }
+}
+
+DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
diff --git a/11-extras/8-testing-with-django/src/config/urls.py b/11-extras/8-testing-with-django/src/config/urls.py
new file mode 100644
index 0000000..0aae63e
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/config/urls.py
@@ -0,0 +1,5 @@
+from django.urls import URLPattern, URLResolver, include, path
+
+urlpatterns: list[URLPattern | URLResolver] = [
+ path("products/", include("products.urls", namespace="products")),
+]
diff --git a/11-extras/8-testing-with-django/src/products/__init__.py b/11-extras/8-testing-with-django/src/products/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/8-testing-with-django/src/products/forms.py b/11-extras/8-testing-with-django/src/products/forms.py
new file mode 100644
index 0000000..2c418a7
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/products/forms.py
@@ -0,0 +1,27 @@
+from decimal import Decimal
+
+from django import forms
+
+from .models import Product
+
+
+class ProductForm(forms.ModelForm):
+ class Meta:
+ model = Product
+ fields = ["name", "price", "stock", "is_active"]
+
+ def clean_name(self) -> str:
+ name: str | None = self.cleaned_data.get("name")
+ if not name:
+ raise forms.ValidationError("Invalid name")
+ if len(name) < 3:
+ raise forms.ValidationError("Name must be at least 3 characters long")
+ return name
+
+ def clean_price(self) -> Decimal:
+ price: Decimal | None = self.cleaned_data.get("price")
+ if not price:
+ raise forms.ValidationError("Price must be valid")
+ if price is not None and price <= 0:
+ raise forms.ValidationError("Price must be greater than zero")
+ return price
diff --git a/11-extras/8-testing-with-django/src/products/migrations/0001_initial.py b/11-extras/8-testing-with-django/src/products/migrations/0001_initial.py
new file mode 100644
index 0000000..7888034
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/products/migrations/0001_initial.py
@@ -0,0 +1,43 @@
+import django.core.validators
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies: list[tuple[str, str]] = []
+
+ operations = [
+ migrations.CreateModel(
+ name="Product",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=200)),
+ (
+ "price",
+ models.DecimalField(
+ decimal_places=2,
+ max_digits=10,
+ validators=[django.core.validators.MinValueValidator(0)],
+ ),
+ ),
+ (
+ "stock",
+ models.IntegerField(
+ default=0,
+ validators=[django.core.validators.MinValueValidator(0)],
+ ),
+ ),
+ ("is_active", models.BooleanField(default=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ],
+ ),
+ ]
diff --git a/11-extras/8-testing-with-django/src/products/migrations/__init__.py b/11-extras/8-testing-with-django/src/products/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/8-testing-with-django/src/products/models.py b/11-extras/8-testing-with-django/src/products/models.py
new file mode 100644
index 0000000..8e1d212
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/products/models.py
@@ -0,0 +1,20 @@
+from django.core import validators
+from django.db import models
+
+
+class Product(models.Model):
+ name = models.CharField(max_length=200)
+ price = models.DecimalField(
+ max_digits=10,
+ decimal_places=2,
+ validators=[validators.MinValueValidator(0)],
+ )
+ stock = models.IntegerField(default=0, validators=[validators.MinValueValidator(0)])
+ is_active = models.BooleanField(default=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ def __str__(self) -> str:
+ return self.name
+
+ def is_available(self) -> bool:
+ return self.is_active and self.stock > 0
diff --git a/11-extras/8-testing-with-django/src/products/services.py b/11-extras/8-testing-with-django/src/products/services.py
new file mode 100644
index 0000000..1aa08f9
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/products/services.py
@@ -0,0 +1,33 @@
+from decimal import Decimal
+from typing import TypedDict
+
+from products import models
+
+
+class CartItem(TypedDict):
+ price: Decimal
+ quantity: int
+
+
+def calculate_discount(price: Decimal, discount_percentage: int | float) -> Decimal:
+ if discount_percentage < 0 or discount_percentage > 100:
+ raise ValueError("Discount percentage must be between 0 and 100")
+ discount = price * Decimal(str(discount_percentage)) / Decimal("100")
+ return price - discount
+
+
+def apply_tax(price: Decimal, tax_rate: int | float | Decimal) -> Decimal:
+ if tax_rate < 0:
+ raise ValueError("Tax rate cannot be negative")
+ return price * (Decimal("1") + Decimal(str(tax_rate)))
+
+
+def calculate_total(items: list[CartItem]) -> Decimal:
+ return sum(
+ (item["price"] * item["quantity"] for item in items),
+ Decimal("0"),
+ )
+
+
+def filter_available_products(products: list[models.Product]) -> list[models.Product]:
+ return [p for p in products if p.is_available()]
diff --git a/11-extras/8-testing-with-django/src/products/templates/base.html b/11-extras/8-testing-with-django/src/products/templates/base.html
new file mode 100644
index 0000000..ce6b932
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/products/templates/base.html
@@ -0,0 +1,266 @@
+
+
+
+
+
+ {% block title %}Products{% endblock %}
+
+
+
+
+
+ {% block content %}{% endblock %}
+
+
+
diff --git a/11-extras/8-testing-with-django/src/products/templates/products/product_detail.html b/11-extras/8-testing-with-django/src/products/templates/products/product_detail.html
new file mode 100644
index 0000000..6d2c95b
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/products/templates/products/product_detail.html
@@ -0,0 +1,37 @@
+{% extends "base.html" %}
+
+{% block title %}{{ product.name }}{% endblock %}
+
+{% block content %}
+
+
+
+
+
+ Price
+ ${{ product.price }}
+
+
+ Stock
+ {{ product.stock }} units
+
+
+ Status
+
+ {% if product.is_available %}
+ Available
+ {% else %}
+ Unavailable
+ {% endif %}
+
+
+
+ Active
+ {{ product.is_active|yesno:"Yes,No" }}
+
+
+
+{% endblock %}
diff --git a/11-extras/8-testing-with-django/src/products/templates/products/product_form.html b/11-extras/8-testing-with-django/src/products/templates/products/product_form.html
new file mode 100644
index 0000000..fe37d28
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/products/templates/products/product_form.html
@@ -0,0 +1,20 @@
+{% extends "base.html" %}
+
+{% block title %}Create Product{% endblock %}
+
+{% block content %}
+
+
+
+{% endblock %}
diff --git a/11-extras/8-testing-with-django/src/products/templates/products/product_list.html b/11-extras/8-testing-with-django/src/products/templates/products/product_list.html
new file mode 100644
index 0000000..346d063
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/products/templates/products/product_list.html
@@ -0,0 +1,21 @@
+{% extends "base.html" %}
+
+{% block title %}Products{% endblock %}
+
+{% block content %}
+
+
+
+ {% for product in products %}
+
+ {{ product.name }}
+ ${{ product.price }}
+
+ {% empty %}
+
No products available.
+ {% endfor %}
+
+{% endblock %}
diff --git a/11-extras/8-testing-with-django/src/products/urls.py b/11-extras/8-testing-with-django/src/products/urls.py
new file mode 100644
index 0000000..32259c5
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/products/urls.py
@@ -0,0 +1,11 @@
+from django.urls import URLPattern, path
+
+from . import views
+
+app_name = "products"
+
+urlpatterns: list[URLPattern] = [
+ path("", views.product_list, name="list"),
+ path("/", views.product_detail, name="detail"),
+ path("create/", views.product_create, name="create"),
+]
diff --git a/11-extras/8-testing-with-django/src/products/views.py b/11-extras/8-testing-with-django/src/products/views.py
new file mode 100644
index 0000000..3ab60c2
--- /dev/null
+++ b/11-extras/8-testing-with-django/src/products/views.py
@@ -0,0 +1,26 @@
+from django.http import HttpRequest, HttpResponse
+from django.shortcuts import get_object_or_404, redirect, render
+
+from .forms import ProductForm
+from .models import Product
+
+
+def product_list(request: HttpRequest) -> HttpResponse:
+ products = Product.objects.filter(is_active=True)
+ return render(request, "products/product_list.html", {"products": products})
+
+
+def product_detail(request: HttpRequest, pk: int) -> HttpResponse:
+ product = get_object_or_404(Product, pk=pk)
+ return render(request, "products/product_detail.html", {"product": product})
+
+
+def product_create(request: HttpRequest) -> HttpResponse:
+ if request.method == "POST":
+ form = ProductForm(request.POST)
+ if form.is_valid():
+ product = form.save()
+ return redirect("products:detail", pk=product.pk)
+ else:
+ form = ProductForm()
+ return render(request, "products/product_form.html", {"form": form})
diff --git a/11-extras/8-testing-with-django/tests/__init__.py b/11-extras/8-testing-with-django/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/8-testing-with-django/tests/products/__init__.py b/11-extras/8-testing-with-django/tests/products/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/8-testing-with-django/tests/products/conftest.py b/11-extras/8-testing-with-django/tests/products/conftest.py
new file mode 100644
index 0000000..4018b52
--- /dev/null
+++ b/11-extras/8-testing-with-django/tests/products/conftest.py
@@ -0,0 +1,34 @@
+from decimal import Decimal
+
+import pytest
+from products import models
+
+
+@pytest.fixture
+def product(db: None) -> models.Product:
+ return models.Product.objects.create(
+ name="Test Product",
+ price=Decimal("99.99"),
+ stock=10,
+ is_active=True,
+ )
+
+
+@pytest.fixture
+def inactive_product(db: None) -> models.Product:
+ return models.Product.objects.create(
+ name="Inactive Product",
+ price=Decimal("49.99"),
+ stock=0,
+ is_active=False,
+ )
+
+
+@pytest.fixture
+def out_of_stock_product(db: None) -> models.Product:
+ return models.Product.objects.create(
+ name="Out of Stock Product",
+ price=Decimal("29.99"),
+ stock=0,
+ is_active=True,
+ )
diff --git a/11-extras/8-testing-with-django/tests/products/test_forms.py b/11-extras/8-testing-with-django/tests/products/test_forms.py
new file mode 100644
index 0000000..72be36f
--- /dev/null
+++ b/11-extras/8-testing-with-django/tests/products/test_forms.py
@@ -0,0 +1,61 @@
+from products import forms
+
+
+def test_should_validate_form_with_valid_data() -> None:
+ data = {"name": "Laptop", "price": "999.99", "stock": 5, "is_active": True}
+ form = forms.ProductForm(data=data)
+ assert form.is_valid()
+
+
+def test_should_reject_name_shorter_than_three_characters() -> None:
+ data = {"name": "PC", "price": "999.99", "stock": 5, "is_active": True}
+ form = forms.ProductForm(data=data)
+ assert not form.is_valid()
+ assert "name" in form.errors
+
+
+def test_should_accept_name_with_exactly_three_characters() -> None:
+ data = {"name": "USB", "price": "9.99", "stock": 1, "is_active": True}
+ form = forms.ProductForm(data=data)
+ assert form.is_valid()
+
+
+def test_should_reject_price_equal_to_zero() -> None:
+ data = {"name": "Free Product", "price": "0.00", "stock": 5, "is_active": True}
+ form = forms.ProductForm(data=data)
+ assert not form.is_valid()
+ assert "price" in form.errors
+
+
+def test_should_reject_price_below_zero() -> None:
+ data = {"name": "Negative Product", "price": "-10.00", "stock": 5, "is_active": True}
+ form = forms.ProductForm(data=data)
+ assert not form.is_valid()
+ assert "price" in form.errors
+
+
+def test_should_reject_missing_name() -> None:
+ data = {"price": "99.99", "stock": 5, "is_active": True}
+ form = forms.ProductForm(data=data)
+ assert not form.is_valid()
+ assert "name" in form.errors
+
+
+def test_should_reject_missing_price() -> None:
+ data = {"name": "Laptop", "stock": 5, "is_active": True}
+ form = forms.ProductForm(data=data)
+ assert not form.is_valid()
+ assert "price" in form.errors
+
+
+def test_should_default_stock_to_zero_when_not_provided() -> None:
+ data = {"name": "Laptop", "price": "999.99", "is_active": True}
+ form = forms.ProductForm(data=data)
+ assert not form.is_valid()
+
+
+def test_should_accept_product_without_is_active_field() -> None:
+ data = {"name": "Laptop", "price": "999.99", "stock": 0}
+ form = forms.ProductForm(data=data)
+ assert form.is_valid()
+ assert form.cleaned_data["is_active"] is False
diff --git a/11-extras/8-testing-with-django/tests/products/test_models.py b/11-extras/8-testing-with-django/tests/products/test_models.py
new file mode 100644
index 0000000..397895e
--- /dev/null
+++ b/11-extras/8-testing-with-django/tests/products/test_models.py
@@ -0,0 +1,76 @@
+from decimal import Decimal
+
+import pytest
+from products import models
+
+
+@pytest.mark.django_db
+def test_should_create_product_with_valid_data() -> None:
+ product = models.Product.objects.create(
+ name="Laptop",
+ price=Decimal("999.99"),
+ stock=5,
+ )
+ assert product.pk is not None
+ assert product.name == "Laptop"
+ assert product.price == Decimal("999.99")
+ assert product.stock == 5
+ assert product.is_active is True
+
+
+@pytest.mark.django_db
+def test_should_set_is_active_true_by_default() -> None:
+ product = models.Product.objects.create(name="Mouse", price=Decimal("29.99"), stock=1)
+ assert product.is_active is True
+
+
+@pytest.mark.django_db
+def test_should_set_stock_zero_by_default() -> None:
+ product = models.Product.objects.create(name="Keyboard", price=Decimal("49.99"))
+ assert product.stock == 0
+
+
+@pytest.mark.django_db
+def test_should_mark_product_as_available_when_stock_is_positive(product: models.Product) -> None:
+ assert product.is_available() is True
+
+
+@pytest.mark.django_db
+def test_should_mark_product_as_unavailable_when_stock_is_zero(
+ out_of_stock_product: models.Product,
+) -> None:
+ assert out_of_stock_product.is_available() is False
+
+
+@pytest.mark.django_db
+def test_should_mark_product_as_unavailable_when_inactive(inactive_product: models.Product) -> None:
+ assert inactive_product.is_available() is False
+
+
+@pytest.mark.django_db
+def test_should_mark_product_as_unavailable_when_inactive_and_out_of_stock() -> None:
+ product = models.Product.objects.create(
+ name="Ghost Product",
+ price=Decimal("9.99"),
+ stock=0,
+ is_active=False,
+ )
+ assert product.is_available() is False
+
+
+@pytest.mark.django_db
+def test_should_return_product_name_as_string_representation(product: models.Product) -> None:
+ assert str(product) == "Test Product"
+
+
+@pytest.mark.django_db
+def test_should_persist_product_in_database() -> None:
+ models.Product.objects.create(name="Monitor", price=Decimal("299.99"), stock=3)
+ assert models.Product.objects.filter(name="Monitor").exists()
+
+
+@pytest.mark.django_db
+def test_should_retrieve_product_by_name() -> None:
+ models.Product.objects.create(name="Webcam", price=Decimal("79.99"), stock=2)
+ result = models.Product.objects.get(name="Webcam")
+ assert result.price == Decimal("79.99")
diff --git a/11-extras/8-testing-with-django/tests/products/test_services.py b/11-extras/8-testing-with-django/tests/products/test_services.py
new file mode 100644
index 0000000..d406b3c
--- /dev/null
+++ b/11-extras/8-testing-with-django/tests/products/test_services.py
@@ -0,0 +1,86 @@
+from decimal import Decimal
+
+import pytest
+from products import models, services
+
+
+def test_should_calculate_discount_correctly() -> None:
+ price = Decimal("100.00")
+ result = services.calculate_discount(price, 20)
+ assert result == Decimal("80.00")
+
+
+def test_should_return_original_price_when_discount_is_zero() -> None:
+ price = Decimal("100.00")
+ result = services.calculate_discount(price, 0)
+ assert result == price
+
+
+def test_should_apply_full_discount_when_percentage_is_100() -> None:
+ price = Decimal("100.00")
+ result = services.calculate_discount(price, 100)
+ assert result == Decimal("0.00")
+
+
+def test_should_raise_error_when_discount_exceeds_100() -> None:
+ with pytest.raises(ValueError):
+ services.calculate_discount(Decimal("100.00"), 150)
+
+
+def test_should_raise_error_when_discount_is_negative() -> None:
+ with pytest.raises(ValueError):
+ services.calculate_discount(Decimal("100.00"), -10)
+
+
+def test_should_apply_tax_correctly() -> None:
+ price = Decimal("100.00")
+ result = services.apply_tax(price, Decimal("0.19"))
+ assert result == Decimal("119.00")
+
+
+def test_should_not_modify_price_when_tax_rate_is_zero() -> None:
+ price = Decimal("100.00")
+ result = services.apply_tax(price, 0)
+ assert result == price
+
+
+def test_should_raise_error_when_tax_rate_is_negative() -> None:
+ with pytest.raises(ValueError):
+ services.apply_tax(Decimal("100.00"), -0.05)
+
+
+def test_should_calculate_total_for_multiple_items() -> None:
+ items: list[services.CartItem] = [
+ {"price": Decimal("10.00"), "quantity": 2},
+ {"price": Decimal("5.00"), "quantity": 3},
+ ]
+ result = services.calculate_total(items)
+ assert result == Decimal("35.00")
+
+
+def test_should_return_zero_for_empty_cart() -> None:
+ result = services.calculate_total([])
+ assert result == Decimal("0")
+
+
+def test_should_calculate_total_for_single_item() -> None:
+ items: list[services.CartItem] = [{"price": Decimal("25.50"), "quantity": 4}]
+ result = services.calculate_total(items)
+ assert result == Decimal("102.00")
+
+
+def test_should_filter_available_products(
+ product: models.Product, out_of_stock_product: models.Product, inactive_product: models.Product
+) -> None:
+ all_products: list[models.Product] = [product, out_of_stock_product, inactive_product]
+ result = services.filter_available_products(all_products)
+ assert len(result) == 1
+ assert result[0].name == "Test Product"
+
+
+def test_should_return_empty_list_when_no_products_are_available(
+ out_of_stock_product: models.Product, inactive_product: models.Product
+) -> None:
+ all_products: list[models.Product] = [out_of_stock_product, inactive_product]
+ result = services.filter_available_products(all_products)
+ assert result == []
diff --git a/11-extras/8-testing-with-django/tests/products/test_views.py b/11-extras/8-testing-with-django/tests/products/test_views.py
new file mode 100644
index 0000000..52ea51c
--- /dev/null
+++ b/11-extras/8-testing-with-django/tests/products/test_views.py
@@ -0,0 +1,85 @@
+import pytest
+from django.test import Client
+from django.urls import reverse
+from products.models import Product
+
+
+@pytest.mark.django_db
+def test_should_return_200_on_product_list(client: Client) -> None:
+ response = client.get(reverse("products:list"))
+ assert response.status_code == 200
+
+
+@pytest.mark.django_db
+def test_should_list_only_active_products(
+ client: Client, product: Product, inactive_product: Product
+) -> None:
+ response = client.get(reverse("products:list"))
+ assert response.status_code == 200
+ assert "Test Product" in response.content.decode()
+ assert "Inactive Product" not in response.content.decode()
+
+
+@pytest.mark.django_db
+def test_should_return_empty_list_when_no_active_products_exist(
+ client: Client, inactive_product: Product
+) -> None:
+ response = client.get(reverse("products:list"))
+ assert response.status_code == 200
+ assert "No products available" in response.content.decode()
+
+
+@pytest.mark.django_db
+def test_should_return_200_on_product_detail(client: Client, product: Product) -> None:
+ response = client.get(reverse("products:detail", kwargs={"pk": product.pk}))
+ assert response.status_code == 200
+
+
+@pytest.mark.django_db
+def test_should_display_product_name_on_detail_page(client: Client, product: Product) -> None:
+ response = client.get(reverse("products:detail", kwargs={"pk": product.pk}))
+ assert "Test Product" in response.content.decode()
+
+
+@pytest.mark.django_db
+def test_should_return_404_when_product_does_not_exist(client: Client) -> None:
+ response = client.get(reverse("products:detail", kwargs={"pk": 99999}))
+ assert response.status_code == 404
+
+
+@pytest.mark.django_db
+def test_should_return_200_on_product_create_get(client: Client) -> None:
+ response = client.get(reverse("products:create"))
+ assert response.status_code == 200
+
+
+@pytest.mark.django_db
+def test_should_create_product_and_redirect_on_valid_post(client: Client) -> None:
+ data = {"name": "New Laptop", "price": "1299.99", "stock": 5, "is_active": True}
+ response = client.post(reverse("products:create"), data)
+ assert response.status_code == 302
+ assert Product.objects.filter(name="New Laptop").exists()
+
+
+@pytest.mark.django_db
+def test_should_redirect_to_product_detail_after_create(client: Client) -> None:
+ data = {"name": "New Monitor", "price": "299.99", "stock": 3, "is_active": True}
+ response = client.post(reverse("products:create"), data)
+ created_product = Product.objects.get(name="New Monitor")
+ assert response["Location"] == reverse("products:detail", kwargs={"pk": created_product.pk})
+
+
+@pytest.mark.django_db
+def test_should_not_create_product_on_invalid_post(client: Client) -> None:
+ data = {"name": "AB", "price": "0.00", "stock": 0, "is_active": True}
+ response = client.post(reverse("products:create"), data)
+ assert response.status_code == 200
+ assert not Product.objects.filter(name="AB").exists()
+
+
+@pytest.mark.django_db
+def test_should_not_create_product_when_name_is_missing(client: Client) -> None:
+ initial_count: int = Product.objects.count()
+ data = {"price": "99.99", "stock": 5, "is_active": True}
+ client.post(reverse("products:create"), data)
+ assert Product.objects.count() == initial_count
diff --git a/11-extras/9-testing-with-fastapi/pytest.ini b/11-extras/9-testing-with-fastapi/pytest.ini
new file mode 100644
index 0000000..21ed400
--- /dev/null
+++ b/11-extras/9-testing-with-fastapi/pytest.ini
@@ -0,0 +1,4 @@
+[pytest]
+addopts="-v"
+markers=
+ fastapi: Marker about fastapi unit tests
\ No newline at end of file
diff --git a/11-extras/9-testing-with-fastapi/requirements-dev.txt b/11-extras/9-testing-with-fastapi/requirements-dev.txt
new file mode 100644
index 0000000..ca7b1ec
--- /dev/null
+++ b/11-extras/9-testing-with-fastapi/requirements-dev.txt
@@ -0,0 +1,46 @@
+annotated-doc==0.0.4
+annotated-types==0.7.0
+anyio==4.13.0
+certifi==2026.4.22
+click==8.3.3
+dnspython==2.8.0
+email-validator==2.3.0
+fastapi==0.136.1
+fastapi-cli==0.0.24
+fastapi-cloud-cli==0.17.1
+fastar==0.11.0
+h11==0.16.0
+httpcore==1.0.9
+httptools==0.7.1
+httpx==0.28.1
+idna==3.13
+iniconfig==2.3.0
+Jinja2==3.1.6
+markdown-it-py==4.0.0
+MarkupSafe==3.0.3
+mdurl==0.1.2
+packaging==26.2
+pluggy==1.6.0
+pydantic==2.13.3
+pydantic-extra-types==2.11.1
+pydantic-settings==2.14.0
+pydantic_core==2.46.3
+Pygments==2.20.0
+pytest==9.0.3
+python-dotenv==1.2.2
+python-multipart==0.0.27
+PyYAML==6.0.3
+rich==15.0.0
+rich-toolkit==0.19.7
+rignore==0.7.6
+sentry-sdk==2.58.0
+shellingham==1.5.4
+starlette==1.0.0
+typer==0.25.1
+typing-inspection==0.4.2
+typing_extensions==4.15.0
+urllib3==2.6.3
+uvicorn==0.46.0
+uvloop==0.22.1
+watchfiles==1.1.1
+websockets==16.0
diff --git a/11-extras/9-testing-with-fastapi/src/__init__.py b/11-extras/9-testing-with-fastapi/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/9-testing-with-fastapi/src/database.py b/11-extras/9-testing-with-fastapi/src/database.py
new file mode 100644
index 0000000..a989375
--- /dev/null
+++ b/11-extras/9-testing-with-fastapi/src/database.py
@@ -0,0 +1,46 @@
+from src import models
+
+_costs: dict[int, models.Cost] = {}
+_next_id: int = 1
+
+
+def get_all() -> list[models.Cost]:
+ return list(_costs.values())
+
+
+def get_by_id(cost_id: int) -> models.Cost | None:
+ return _costs.get(cost_id)
+
+
+def create(cost: models.Cost) -> models.Cost:
+ _costs[cost.id] = cost
+ return cost
+
+
+def update(cost_id: int, data: dict[str, object]) -> models.Cost | None:
+ existing: models.Cost | None = _costs.get(cost_id)
+ if existing is None:
+ return None
+ updated: models.Cost = existing.model_copy(update=data)
+ _costs[cost_id] = updated
+ return updated
+
+
+def delete(cost_id: int) -> bool:
+ if cost_id not in _costs:
+ return False
+ del _costs[cost_id]
+ return True
+
+
+def next_id() -> int:
+ global _next_id
+ result: int = _next_id
+ _next_id += 1
+ return result
+
+
+def reset() -> None:
+ global _costs, _next_id
+ _costs = {}
+ _next_id = 1
diff --git a/11-extras/9-testing-with-fastapi/src/main.py b/11-extras/9-testing-with-fastapi/src/main.py
new file mode 100644
index 0000000..0db3670
--- /dev/null
+++ b/11-extras/9-testing-with-fastapi/src/main.py
@@ -0,0 +1,11 @@
+from fastapi import FastAPI
+
+from src import router as cost_router
+
+app = FastAPI(title="Cost Tracker API", version="1.0.0")
+app.include_router(cost_router.router)
+
+
+@app.get("/health")
+def health() -> dict[str, str]:
+ return {"status": "ok"}
diff --git a/11-extras/9-testing-with-fastapi/src/models.py b/11-extras/9-testing-with-fastapi/src/models.py
new file mode 100644
index 0000000..6a85d03
--- /dev/null
+++ b/11-extras/9-testing-with-fastapi/src/models.py
@@ -0,0 +1,21 @@
+import datetime
+
+from pydantic import BaseModel, Field
+
+
+class CostCreate(BaseModel):
+ description: str = Field(..., min_length=1, max_length=200)
+ amount: float = Field(..., gt=0)
+ category: str = Field(..., min_length=1, max_length=100)
+ date: datetime.date = Field(default_factory=datetime.date.today)
+
+
+class CostUpdate(BaseModel):
+ description: str | None = Field(None, min_length=1, max_length=200)
+ amount: float | None = Field(None, gt=0)
+ category: str | None = Field(None, min_length=1, max_length=100)
+ date: datetime.date | None = None
+
+
+class Cost(CostCreate):
+ id: int
diff --git a/11-extras/9-testing-with-fastapi/src/router.py b/11-extras/9-testing-with-fastapi/src/router.py
new file mode 100644
index 0000000..3c49c41
--- /dev/null
+++ b/11-extras/9-testing-with-fastapi/src/router.py
@@ -0,0 +1,39 @@
+import fastapi
+
+from src import database, models
+
+router = fastapi.APIRouter(prefix="/costs", tags=["costs"])
+
+
+@router.get("/", response_model=list[models.Cost])
+def list_costs() -> list[models.Cost]:
+ return database.get_all()
+
+
+@router.get("/{cost_id}", response_model=models.Cost)
+def get_cost(cost_id: int) -> models.Cost:
+ cost: models.Cost | None = database.get_by_id(cost_id)
+ if cost is None:
+ raise fastapi.HTTPException(status_code=404, detail="Cost not found")
+ return cost
+
+
+@router.post("/", response_model=models.Cost, status_code=201)
+def create_cost(payload: models.CostCreate) -> models.Cost:
+ cost: models.Cost = models.Cost(id=database.next_id(), **payload.model_dump())
+ return database.create(cost)
+
+
+@router.put("/{cost_id}", response_model=models.Cost)
+def update_cost(cost_id: int, payload: models.CostUpdate) -> models.Cost:
+ data: dict[str, object] = {k: v for k, v in payload.model_dump().items() if v is not None}
+ cost: models.Cost | None = database.update(cost_id, data)
+ if cost is None:
+ raise fastapi.HTTPException(status_code=404, detail="Cost not found")
+ return cost
+
+
+@router.delete("/{cost_id}", status_code=204)
+def delete_cost(cost_id: int) -> None:
+ if not database.delete(cost_id):
+ raise fastapi.HTTPException(status_code=404, detail="Cost not found")
diff --git a/11-extras/9-testing-with-fastapi/tests/__init__.py b/11-extras/9-testing-with-fastapi/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/11-extras/9-testing-with-fastapi/tests/conftest.py b/11-extras/9-testing-with-fastapi/tests/conftest.py
new file mode 100644
index 0000000..4f79934
--- /dev/null
+++ b/11-extras/9-testing-with-fastapi/tests/conftest.py
@@ -0,0 +1,27 @@
+from collections.abc import Generator
+
+import pytest
+from fastapi.testclient import TestClient
+from src import database, main
+
+
+@pytest.fixture(autouse=True)
+def fxt_reset_db() -> Generator[None, None, None]:
+ database.reset()
+ yield
+ database.reset()
+
+
+@pytest.fixture
+def fxt_client() -> TestClient:
+ return TestClient(main.app)
+
+
+@pytest.fixture
+def fxt_sample_cost() -> dict[str, str | float]:
+ return {
+ "description": "Internet bill",
+ "amount": 50.0,
+ "category": "Services",
+ "date": "2026-05-01",
+ }
diff --git a/11-extras/9-testing-with-fastapi/tests/test_costs.py b/11-extras/9-testing-with-fastapi/tests/test_costs.py
new file mode 100644
index 0000000..837c95c
--- /dev/null
+++ b/11-extras/9-testing-with-fastapi/tests/test_costs.py
@@ -0,0 +1,151 @@
+import datetime
+
+import pytest
+from fastapi import testclient
+
+
+@pytest.mark.fastapi
+class TestCreateCost:
+ def test_creates_cost_and_returns_201(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ response = fxt_client.post("/costs/", json=fxt_sample_cost)
+ assert response.status_code == 201
+ body: dict[str, object] = response.json()
+ assert body["id"] == 1
+ assert body["description"] == fxt_sample_cost["description"]
+ assert body["amount"] == fxt_sample_cost["amount"]
+ assert body["category"] == fxt_sample_cost["category"]
+
+ def test_ids_auto_increment(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ first: dict[str, object] = fxt_client.post("/costs/", json=fxt_sample_cost).json()
+ second: dict[str, object] = fxt_client.post("/costs/", json=fxt_sample_cost).json()
+ assert second["id"] == first["id"] + 1 # type: ignore[operator]
+
+ def test_returns_422_when_amount_is_zero(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ fxt_sample_cost["amount"] = 0
+ response = fxt_client.post("/costs/", json=fxt_sample_cost)
+ assert response.status_code == 422
+
+ def test_returns_422_when_amount_is_negative(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ fxt_sample_cost["amount"] = -10
+ response = fxt_client.post("/costs/", json=fxt_sample_cost)
+ assert response.status_code == 422
+
+ def test_returns_422_when_description_is_empty(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ fxt_sample_cost["description"] = ""
+ response = fxt_client.post("/costs/", json=fxt_sample_cost)
+ assert response.status_code == 422
+
+ def test_uses_today_as_default_date(self, fxt_client: testclient.TestClient) -> None:
+ payload: dict[str, str | float] = {
+ "description": "Coffee",
+ "amount": 3.5,
+ "category": "Food",
+ }
+ response = fxt_client.post("/costs/", json=payload)
+ assert response.status_code == 201
+ assert response.json()["date"] == str(datetime.date.today())
+
+
+@pytest.mark.fastapi
+class TestListCosts:
+ def test_returns_empty_list_initially(self, fxt_client: testclient.TestClient) -> None:
+ response = fxt_client.get("/costs/")
+ assert response.status_code == 200
+ assert response.json() == []
+
+ def test_returns_all_created_costs(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ fxt_client.post("/costs/", json=fxt_sample_cost)
+ fxt_client.post("/costs/", json=fxt_sample_cost)
+ response = fxt_client.get("/costs/")
+ assert response.status_code == 200
+ assert len(response.json()) == 2
+
+
+@pytest.mark.fastapi
+class TestGetCost:
+ def test_returns_cost_by_id(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ created: dict[str, object] = fxt_client.post("/costs/", json=fxt_sample_cost).json()
+ response = fxt_client.get(f"/costs/{created['id']}")
+ assert response.status_code == 200
+ assert response.json()["id"] == created["id"]
+
+ def test_returns_404_for_unknown_id(self, fxt_client: testclient.TestClient) -> None:
+ response = fxt_client.get("/costs/999")
+ assert response.status_code == 404
+ assert response.json()["detail"] == "Cost not found"
+
+
+@pytest.mark.fastapi
+class TestUpdateCost:
+ def test_updates_amount(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ created: dict[str, object] = fxt_client.post("/costs/", json=fxt_sample_cost).json()
+ response = fxt_client.put(f"/costs/{created['id']}", json={"amount": 99.9})
+ assert response.status_code == 200
+ assert response.json()["amount"] == 99.9
+
+ def test_partial_update_keeps_other_fields(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ created: dict[str, object] = fxt_client.post("/costs/", json=fxt_sample_cost).json()
+ fxt_client.put(f"/costs/{created['id']}", json={"amount": 75.0})
+ body: dict[str, object] = fxt_client.get(f"/costs/{created['id']}").json()
+ assert body["description"] == fxt_sample_cost["description"]
+ assert body["category"] == fxt_sample_cost["category"]
+ assert body["amount"] == 75.0
+
+ def test_returns_404_when_updating_unknown_id(self, fxt_client: testclient.TestClient) -> None:
+ response = fxt_client.put("/costs/999", json={"amount": 10.0})
+ assert response.status_code == 404
+
+ def test_returns_422_when_updating_with_invalid_amount(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ created: dict[str, object] = fxt_client.post("/costs/", json=fxt_sample_cost).json()
+ response = fxt_client.put(f"/costs/{created['id']}", json={"amount": -5})
+ assert response.status_code == 422
+
+
+@pytest.mark.fastapi
+class TestDeleteCost:
+ def test_deletes_existing_cost(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ created: dict[str, object] = fxt_client.post("/costs/", json=fxt_sample_cost).json()
+ response = fxt_client.delete(f"/costs/{created['id']}")
+ assert response.status_code == 204
+
+ def test_cost_no_longer_accessible_after_deletion(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ created: dict[str, object] = fxt_client.post("/costs/", json=fxt_sample_cost).json()
+ fxt_client.delete(f"/costs/{created['id']}")
+ response = fxt_client.get(f"/costs/{created['id']}")
+ assert response.status_code == 404
+
+ def test_returns_404_when_deleting_unknown_id(self, fxt_client: testclient.TestClient) -> None:
+ response = fxt_client.delete("/costs/999")
+ assert response.status_code == 404
+
+ def test_list_shrinks_after_deletion(
+ self, fxt_client: testclient.TestClient, fxt_sample_cost: dict[str, str | float]
+ ) -> None:
+ c1: dict[str, object] = fxt_client.post("/costs/", json=fxt_sample_cost).json()
+ fxt_client.post("/costs/", json=fxt_sample_cost)
+ fxt_client.delete(f"/costs/{c1['id']}")
+ assert len(fxt_client.get("/costs/").json()) == 1
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/prod_database.db b/7-coupled-code-and-doubles/1-meaning-coupling/prod_database.db
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/src/__init__.py b/7-coupled-code-and-doubles/1-meaning-coupling/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/src/example.py b/7-coupled-code-and-doubles/1-meaning-coupling/src/example.py
new file mode 100644
index 0000000..f189323
--- /dev/null
+++ b/7-coupled-code-and-doubles/1-meaning-coupling/src/example.py
@@ -0,0 +1,19 @@
+class Class1:
+ x = True
+
+
+class Class2:
+ def my_method(self, valor: str) -> None:
+ if Class1.x: # If True
+ self.value = valor
+
+
+# my_class = Class2()
+# my_class.my_method("Hola")
+# print(my_class.value)
+
+# Class1.x = False # Cambio en clase 1, de la cuál está fuertemente acoplada la clase 2
+
+# # Otro proceso
+# my_class.my_method("Hola de nuevo")
+# print(my_class.value) # Debería de ser "hola de nuevo"
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/src/example_2.py b/7-coupled-code-and-doubles/1-meaning-coupling/src/example_2.py
new file mode 100644
index 0000000..2f8a97f
--- /dev/null
+++ b/7-coupled-code-and-doubles/1-meaning-coupling/src/example_2.py
@@ -0,0 +1,19 @@
+class Configuration:
+ debug_mode = True
+ max_retries = 3
+
+
+class PaymentProcessor:
+ def process(self, monto: float) -> str:
+ if Configuration.debug_mode:
+ print(f"[DEBUG] Procesando ${monto}")
+
+ for _ in range(Configuration.max_retries):
+ if monto > 0:
+ return "aprobado"
+
+ return "rechazado"
+
+
+# Configuration.debug_mode = False
+# Configuration.max_retries = 0
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/src/users/__init__.py b/7-coupled-code-and-doubles/1-meaning-coupling/src/users/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/src/users/db.py b/7-coupled-code-and-doubles/1-meaning-coupling/src/users/db.py
new file mode 100644
index 0000000..b240ed3
--- /dev/null
+++ b/7-coupled-code-and-doubles/1-meaning-coupling/src/users/db.py
@@ -0,0 +1,24 @@
+import sqlite3
+
+
+class DatabaseConnection:
+ """Realiza una conexión real a una base de datos."""
+
+ def __init__(self) -> None:
+ # En producción, esto abriría una conexión real
+ self.connection = sqlite3.connect("prod_database.db")
+ print("[DB] Conexión establecida con prod_database.db")
+
+ def find_by_email(self, email: str) -> dict | None:
+ cursor = self.connection.cursor()
+ cursor.execute("SELECT * FROM users WHERE email = ?", (email,))
+ row = cursor.fetchone()
+ return {"email": row[0], "name": row[1]} if row else None
+
+ def save(self, user: dict) -> None:
+ cursor = self.connection.cursor()
+ cursor.execute(
+ "INSERT INTO users (email, name) VALUES (?, ?)", (user["email"], user["name"])
+ )
+ self.connection.commit()
+ print(f"[DB] Usuario guardado: {user['email']}")
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/src/users/service.py b/7-coupled-code-and-doubles/1-meaning-coupling/src/users/service.py
new file mode 100644
index 0000000..8f287eb
--- /dev/null
+++ b/7-coupled-code-and-doubles/1-meaning-coupling/src/users/service.py
@@ -0,0 +1,34 @@
+from src.users import db
+
+
+class UserService:
+ """
+ Servicio de usuarios con acoplamiento fuerte a la base de datos.
+
+ El problema está en el __init__:
+ UserService instancia DatabaseConnection directamente.
+ No hay forma de reemplazarla desde afuera.
+ """
+
+ def __init__(self) -> None:
+ # Acoplamiento fuerte — instancia la dependencia directamente
+ # Para testear UserService, DatabaseConnection también se ejecuta
+ # lo que significa que necesitas una base de datos real disponible
+ self.db_connection = db.DatabaseConnection()
+ # self.email_sender = SMTPClient() # ← acoplamiento fuerte
+ # self.report_gen = FileWriter() # ← acoplamiento fuerte
+
+ def register(self, name: str, email: str) -> dict:
+ existing = self.db_connection.find_by_email(email)
+ if existing:
+ raise ValueError(f"Email already registered: {email}")
+
+ user = {"name": name, "email": email}
+ self.db_connection.save(user)
+ return user
+
+ def find_user(self, email: str) -> dict:
+ user = self.db_connection.find_by_email(email)
+ if not user:
+ raise KeyError(f"User not found: {email}")
+ return user
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/tests/__init__.py b/7-coupled-code-and-doubles/1-meaning-coupling/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/tests/test_example.py b/7-coupled-code-and-doubles/1-meaning-coupling/tests/test_example.py
new file mode 100644
index 0000000..e005792
--- /dev/null
+++ b/7-coupled-code-and-doubles/1-meaning-coupling/tests/test_example.py
@@ -0,0 +1,14 @@
+from src import example
+
+
+def test_should_invoke_my_method() -> None:
+ my_class = example.Class2()
+ my_class.my_method("Hola")
+ assert my_class.value == "Hola"
+
+
+def test_should_invoke_my_method_modifying_class_1() -> None:
+ my_class = example.Class2()
+ example.Class1.x = False
+ my_class.my_method("Hola")
+ assert my_class.value == "Hola"
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/tests/test_example_2.py b/7-coupled-code-and-doubles/1-meaning-coupling/tests/test_example_2.py
new file mode 100644
index 0000000..9427bec
--- /dev/null
+++ b/7-coupled-code-and-doubles/1-meaning-coupling/tests/test_example_2.py
@@ -0,0 +1,22 @@
+import pytest
+from src import example_2
+
+
+@pytest.fixture(autouse=True)
+def fxt_configuration_testing() -> None:
+ example_2.Configuration.debug_mode = False
+ example_2.Configuration.max_retries = 0
+
+
+def test_should_approve_payment() -> None:
+ processor = example_2.PaymentProcessor()
+ result_processing = processor.process(10.0)
+ assert result_processing == "aprobado"
+
+
+# def test_should_approve_payment_modifying_config() -> None:
+# processor = example_2.PaymentProcessor()
+# example_2.Configuration.debug_mode = False
+# example_2.Configuration.max_retries = 0
+# result_processing = processor.process(10.0)
+# assert result_processing == "aprobado"
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/tests/users/__init__.py b/7-coupled-code-and-doubles/1-meaning-coupling/tests/users/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/tests/users/test_db.py b/7-coupled-code-and-doubles/1-meaning-coupling/tests/users/test_db.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/1-meaning-coupling/tests/users/test_service.py b/7-coupled-code-and-doubles/1-meaning-coupling/tests/users/test_service.py
new file mode 100644
index 0000000..ed8ddb6
--- /dev/null
+++ b/7-coupled-code-and-doubles/1-meaning-coupling/tests/users/test_service.py
@@ -0,0 +1,14 @@
+import pytest
+from src.users import service
+
+
+def test_should_throw_error_because_email_is_duplicated() -> None:
+ user_service = service.UserService()
+ # ^ esta línea ya ejecuta DatabaseConnection.__init__()
+ # que intenta conectarse a prod_database.db
+ # Si el archivo no existe de la base de datos, puede que cree esta misma base de datos
+ # o si la tabla no está creada el test explota aquí, antes de llegar a la lógica
+ user_service.register("Ana", "ana@empresa.com")
+
+ with pytest.raises(ValueError):
+ user_service.register("Otro", "ana@empresa.com")
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/requirements.txt b/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/requirements.txt
new file mode 100644
index 0000000..473bc4f
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/requirements.txt
@@ -0,0 +1,10 @@
+certifi==2026.2.25
+charset-normalizer==3.4.7
+idna==3.11
+iniconfig==2.3.0
+packaging==26.0
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
+requests==2.33.1
+urllib3==2.6.3
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/src/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/src/order_service.py b/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/src/order_service.py
new file mode 100644
index 0000000..547b79c
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/src/order_service.py
@@ -0,0 +1,37 @@
+# Un Dummy es un objeto que se pasa como argumento pero nunca se usa realmente.
+# Su único propósito es satisfacer la firma del método cuando el parámetro
+# no es relevante para el comportamiento que estamos probando.
+
+import requests
+
+
+class Logger:
+ def log(self, message: str) -> None:
+ print(f"[LOG] {message}")
+
+
+class Order:
+ def __init__(self, product: str, quantity: int):
+ self.product = product
+ self.quantity = quantity
+
+
+CACHE_ORDERS = {1: Order(product="A nice product", quantity=210)}
+
+
+class OrderService:
+ def __init__(self, logger: Logger) -> None:
+ # El logger es una dependencia real, pero en ciertos tests no importa
+ self._logger = logger
+
+ def calculate_total(self, order: Order, price_per_unit: float) -> float:
+ # El logger existe pero no afecta el cálculo
+ self._logger.log(f"Calculando total para {order.product}")
+ return order.quantity * price_per_unit
+
+ def get_order(self, id_order: int, http_response: requests.Response) -> Order:
+ order = CACHE_ORDERS.get(id_order)
+ if order:
+ return order
+ # Código que solo se necesitará si no lo encuentra en caché
+ return http_response.json().get(id_order)
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/tests/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/tests/test_order_service.py b/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/tests/test_order_service.py
new file mode 100644
index 0000000..17d9bb6
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/1-dummy/tests/test_order_service.py
@@ -0,0 +1,37 @@
+from unittest import mock
+
+from src import order_service
+
+
+# DummyLogger satisface la firma del constructor de OrderService,
+# pero no hace nada. No nos importa el logging en este test.
+class DummyLogger(order_service.Logger):
+ def log(self, message: str) -> None:
+ pass # No hace nada — es un dummy
+
+
+class TestOrderService:
+ def test_calculate_total_returns_correct_value(self) -> None:
+ dummy_logger = DummyLogger() # Solo existe para pasar el argumento
+ service = order_service.OrderService(logger=dummy_logger)
+ order = order_service.Order(product="Laptop", quantity=3)
+
+ total = service.calculate_total(order, price_per_unit=1000.0)
+
+ assert total == 3000.0
+
+ def test_calculate_total_with_zero_quantity(self) -> None:
+ dummy_logger = DummyLogger()
+ service = order_service.OrderService(logger=dummy_logger)
+ order = order_service.Order(product="Mouse", quantity=0)
+
+ total = service.calculate_total(order, price_per_unit=25.0)
+
+ assert total == 0.0
+
+
+def test_should_get_order_from_cache() -> None:
+ service = order_service.OrderService(logger=DummyLogger())
+ response_dummy = mock.MagicMock()
+ result = service.get_order(id_order=1, http_response=response_dummy)
+ assert result.quantity == 210
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/requirements.txt b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/requirements.txt
new file mode 100644
index 0000000..88a7c6d
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/requirements.txt
@@ -0,0 +1,5 @@
+iniconfig==2.3.0
+packaging==26.0
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/src/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/src/weather_service.py b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/src/weather_service.py
new file mode 100644
index 0000000..923aa88
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/src/weather_service.py
@@ -0,0 +1,29 @@
+# Un Stub reemplaza una dependencia y devuelve respuestas predefinidas (hardcodeadas).
+# Se usa cuando necesitamos controlar los datos que recibe nuestro código,
+# sin depender de sistemas externos (APIs, bases de datos, etc.).
+
+
+class WeatherApiClient:
+ """Cliente real que consulta una API externa (lenta, costosa, impredecible)."""
+
+ def get_temperature(self, city: str) -> float:
+ # En producción haría una llamada HTTP real
+ raise NotImplementedError("Llama a una API real")
+
+
+class WeatherService:
+ def __init__(self, api_client: WeatherApiClient) -> None:
+ self._client = api_client
+
+ def is_hot_weather(self, city: str) -> bool:
+ temperature = self._client.get_temperature(city)
+ return temperature > 30.0
+
+ def get_weather_advice(self, city: str) -> str:
+ temperature = self._client.get_temperature(city)
+ if temperature > 30.0:
+ return "Lleva agua y protector solar"
+ elif temperature > 15.0:
+ return "El clima es agradable"
+ else:
+ return "Abrígate bien"
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/src/weather_service_coupled.py b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/src/weather_service_coupled.py
new file mode 100644
index 0000000..165109a
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/src/weather_service_coupled.py
@@ -0,0 +1,29 @@
+# Un Stub reemplaza una dependencia y devuelve respuestas predefinidas (hardcodeadas).
+# Se usa cuando necesitamos controlar los datos que recibe nuestro código,
+# sin depender de sistemas externos (APIs, bases de datos, etc.).
+
+
+class WeatherApiClient:
+ """Cliente real que consulta una API externa (lenta, costosa, impredecible)."""
+
+ def get_temperature(self, city: str) -> float:
+ # En producción haría una llamada HTTP real
+ raise NotImplementedError("Llama a una API real")
+
+
+class WeatherService:
+ def __init__(self) -> None:
+ self._client = WeatherApiClient()
+
+ def is_hot_weather(self, city: str) -> bool:
+ temperature = self._client.get_temperature(city)
+ return temperature > 30.0
+
+ def get_weather_advice(self, city: str) -> str:
+ temperature = self._client.get_temperature(city)
+ if temperature > 30.0:
+ return "Lleva agua y protector solar"
+ elif temperature > 15.0:
+ return "El clima es agradable"
+ else:
+ return "Abrígate bien"
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/tests/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/tests/test_weather_service.py b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/tests/test_weather_service.py
new file mode 100644
index 0000000..514ce2e
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/tests/test_weather_service.py
@@ -0,0 +1,115 @@
+from unittest import mock
+
+import pytest
+from src import weather_service
+
+
+class HotWeatherApiStub(weather_service.WeatherApiClient):
+ """Simula una API que reporta clima caluroso (35°C)."""
+
+ def get_temperature(self, city: str) -> float:
+ return 35.0
+
+
+class MildWeatherApiStub(weather_service.WeatherApiClient):
+ """Simula una API que reporta clima templado (22°C)."""
+
+ def get_temperature(self, city: str) -> float:
+ return 22.0
+
+
+class ColdWeatherApiStub(weather_service.WeatherApiClient):
+ """Simula una API que reporta clima frío (5°C)."""
+
+ def get_temperature(self, city: str) -> float:
+ return 5.0
+
+
+class TestWeatherService:
+ def test_is_hot_weather_returns_true_when_above_30(self) -> None:
+ service = weather_service.WeatherService(api_client=HotWeatherApiStub())
+
+ result = service.is_hot_weather("Bogotá")
+
+ assert result
+
+ def test_is_hot_weather_returns_false_when_below_30(self) -> None:
+ service = weather_service.WeatherService(api_client=ColdWeatherApiStub())
+
+ result = service.is_hot_weather("Bogotá")
+
+ assert not result
+
+ def test_advice_for_hot_weather(self) -> None:
+ service = weather_service.WeatherService(api_client=HotWeatherApiStub())
+
+ advice = service.get_weather_advice("Medellín")
+
+ assert advice == "Lleva agua y protector solar"
+
+ def test_advice_for_mild_weather(self) -> None:
+ service = weather_service.WeatherService(api_client=MildWeatherApiStub())
+
+ advice = service.get_weather_advice("Medellín")
+
+ assert advice == "El clima es agradable"
+
+ def test_advice_for_cold_weather(self) -> None:
+ service = weather_service.WeatherService(api_client=ColdWeatherApiStub())
+
+ advice = service.get_weather_advice("Medellín")
+
+ assert advice == "Abrígate bien"
+
+
+def test_should_validate_advice_for_mild_weather() -> None:
+ # Act
+ stub_cold_weather = mock.MagicMock()
+ stub_cold_weather.get_temperature.return_value = 28
+ service = weather_service.WeatherService(api_client=stub_cold_weather)
+
+ # Arrange
+ result = service.get_weather_advice(city="Mosquera")
+
+ # Assert
+ assert result == "El clima es agradable"
+
+
+def test_should_validate_advice_for_hot_weather() -> None:
+ # Act
+ stub_cold_weather = mock.MagicMock()
+ stub_cold_weather.get_temperature.return_value = 35
+ service = weather_service.WeatherService(api_client=stub_cold_weather)
+
+ # Arrange
+ result = service.get_weather_advice(city="Mosquera")
+
+ # Assert
+ assert result == "Lleva agua y protector solar"
+
+
+@pytest.fixture(scope="function")
+def fxt_stub_weather(request: pytest.FixtureRequest) -> mock.MagicMock:
+ value_temperature = request.param
+ stub_cold_weather = mock.MagicMock()
+ stub_cold_weather.get_temperature.return_value = value_temperature
+ return stub_cold_weather
+
+
+@pytest.mark.parametrize(
+ "fxt_stub_weather, expected_advice",
+ [
+ (pytest.param(8, "Abrígate bien", id="A cold weather")),
+ (pytest.param(28, "El clima es agradable", id="Mild weather")),
+ (pytest.param(35, "Lleva agua y protector solar", id="Hot weather")),
+ ],
+ indirect=["fxt_stub_weather"],
+)
+def test_should_validate_advice(fxt_stub_weather: mock.MagicMock, expected_advice: str) -> None:
+ service = weather_service.WeatherService(api_client=fxt_stub_weather)
+
+ # Arrange
+ result = service.get_weather_advice(city="Mosquera")
+
+ # Assert
+ assert result == expected_advice
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/tests/test_weather_service_coupled.py b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/tests/test_weather_service_coupled.py
new file mode 100644
index 0000000..93b6e14
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/2-stubs/tests/test_weather_service_coupled.py
@@ -0,0 +1,17 @@
+from unittest import mock
+
+from src import weather_service_coupled
+
+
+@mock.patch("src.weather_service_coupled.WeatherApiClient")
+def test_validate_if_it_is_hot_weather(stub_weather_api_client_class: mock.MagicMock) -> None:
+ # Act
+ stub_weather_api_client_instance: mock.MagicMock = stub_weather_api_client_class.return_value
+ stub_weather_api_client_instance.get_temperature.return_value = 40
+
+ service = weather_service_coupled.WeatherService()
+ # Arrange
+ result = service.is_hot_weather("Medellin")
+
+ # Assert
+ assert result
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/pytest.ini b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/pytest.ini
new file mode 100644
index 0000000..c011857
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/pytest.ini
@@ -0,0 +1,3 @@
+[pytest]
+markers=
+ spy: Marks tests that use a spy test double
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/requirements-dev.txt b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/requirements-dev.txt
new file mode 100644
index 0000000..88a7c6d
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/requirements-dev.txt
@@ -0,0 +1,5 @@
+iniconfig==2.3.0
+packaging==26.0
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/email_sender.py b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/email_sender.py
new file mode 100644
index 0000000..6b1cd95
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/email_sender.py
@@ -0,0 +1,5 @@
+class EmailSender:
+ def send(self, to: str, subject: str, body: str) -> dict:
+ # En producción aquí iría el cliente SMTP real
+ print(f"[EMAIL] To: {to} | Subject: {subject}")
+ return {"status": "sent", "to": to, "channel": "email"}
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/notification_service.py b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/notification_service.py
new file mode 100644
index 0000000..9a3f0a9
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/notification_service.py
@@ -0,0 +1,36 @@
+from src import email_sender, push_sender, sms_sender
+
+
+class NotificationService:
+ def __init__(
+ self, email_sender: email_sender.EmailSender, sms_sender: sms_sender.SmsSender
+ ) -> None:
+ self.email_sender = email_sender
+ self.sms_sender = sms_sender
+
+ def notify_user(self, user: dict[str, str], message: str) -> list[dict]:
+ """Notifica al usuario por todos sus canales disponibles."""
+ results = []
+
+ if email := user.get("email"):
+ result = self.email_sender.send(
+ to=email,
+ subject="Notificación",
+ body=message,
+ )
+ results.append(result)
+
+ if phone := user.get("phone"):
+ result = self.sms_sender.send(phone=phone, message=message)
+ results.append(result)
+
+ return results
+
+ def notify_by_sms_only(self, email: str, message: str) -> list[dict[str, str]]:
+ result = self.email_sender.send(to=email, subject="Welcome to this class", body=message)
+ return [result]
+
+ def notify_by_push_all_available(
+ self, push_sender: push_sender.PushSender, message: str
+ ) -> None:
+ push_sender.send_push_notification_to_all_available_receivers(message=message)
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/push_sender.py b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/push_sender.py
new file mode 100644
index 0000000..e55579c
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/push_sender.py
@@ -0,0 +1,6 @@
+class PushSender:
+ def send_push_notification_to_single_receiver(self, message: str, receiver_id: str) -> None:
+ print(f"Sent push notification to {receiver_id} with message {message}")
+
+ def send_push_notification_to_all_available_receivers(self, message: str) -> None:
+ print(f"Send massive message to all receivers with message {message}")
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/sms_sender.py b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/sms_sender.py
new file mode 100644
index 0000000..4fa8c78
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/src/sms_sender.py
@@ -0,0 +1,4 @@
+class SmsSender:
+ def send(self, phone: str, message: str) -> dict:
+ print(f"[SMS] To: {phone} | Message: {message}")
+ return {"status": "sent", "to": phone, "channel": "sms"}
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/conftest.py b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/conftest.py
new file mode 100644
index 0000000..b473dee
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/conftest.py
@@ -0,0 +1,39 @@
+from unittest import mock
+
+import pytest
+from src import email_sender, notification_service, sms_sender
+
+
+@pytest.fixture
+def fxt_email_sender_instance() -> email_sender.EmailSender:
+ return email_sender.EmailSender()
+
+
+@pytest.fixture
+def fxt_sms_sender_instance() -> sms_sender.SmsSender:
+ return sms_sender.SmsSender()
+
+
+@pytest.fixture
+def fxt_email_spy(fxt_email_sender_instance: email_sender.EmailSender) -> mock.MagicMock:
+ spy = mock.MagicMock(wraps=fxt_email_sender_instance.send)
+ fxt_email_sender_instance.send = spy
+ return spy
+
+
+@pytest.fixture
+def fxt_sms_spy(fxt_sms_sender_instance: sms_sender.SmsSender) -> mock.MagicMock:
+ spy = mock.MagicMock(wraps=fxt_sms_sender_instance.send)
+ fxt_sms_sender_instance.send = spy
+ return spy
+
+
+@pytest.fixture
+def fxt_subject(
+ fxt_email_sender_instance: email_sender.EmailSender,
+ fxt_sms_sender_instance: sms_sender.SmsSender,
+) -> notification_service.NotificationService:
+ return notification_service.NotificationService(
+ email_sender=fxt_email_sender_instance,
+ sms_sender=fxt_sms_sender_instance,
+ )
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/test_notification_service.py b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/test_notification_service.py
new file mode 100644
index 0000000..a420230
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/test_notification_service.py
@@ -0,0 +1,130 @@
+from unittest import mock
+
+import pytest
+from src import notification_service
+
+
+@pytest.mark.spy
+def test_sends_email_notification_when_email_is_present(
+ fxt_subject: notification_service.NotificationService,
+ fxt_email_spy: mock.MagicMock,
+ fxt_sms_spy: mock.MagicMock,
+) -> None:
+ user = {"email": "ana@test.com"}
+
+ fxt_subject.notify_user(user=user, message="Bienvenida!")
+
+ fxt_email_spy.assert_called_once_with(
+ to="ana@test.com",
+ subject="Notificación",
+ body="Bienvenida!",
+ )
+ fxt_sms_spy.assert_not_called()
+
+
+@pytest.mark.spy
+def test_sends_sms_notification_when_phone_is_present(
+ fxt_subject: notification_service.NotificationService,
+ fxt_email_spy: mock.MagicMock,
+ fxt_sms_spy: mock.MagicMock,
+) -> None:
+ user = {"phone": "+57300000000"}
+
+ fxt_subject.notify_user(user, "Tu pedido llegó")
+
+ fxt_sms_spy.assert_called_once_with(
+ phone="+57300000000",
+ message="Tu pedido llegó",
+ )
+ fxt_email_spy.assert_not_called()
+
+
+@pytest.mark.spy
+def test_sends_notifications_through_both_channels(
+ fxt_subject: notification_service.NotificationService,
+ fxt_email_spy: mock.MagicMock,
+ fxt_sms_spy: mock.MagicMock,
+) -> None:
+ user = {"email": "carlos@test.com", "phone": "+57311111111"}
+
+ fxt_subject.notify_user(user, "Alerta importante")
+
+ assert fxt_email_spy.call_count == 1
+ fxt_email_spy.assert_called_once_with(
+ to="carlos@test.com",
+ subject="Notificación",
+ body="Alerta importante",
+ )
+
+ assert fxt_sms_spy.call_count == 1
+ fxt_sms_spy.assert_called_once_with(
+ phone="+57311111111",
+ message="Alerta importante",
+ )
+
+
+@pytest.mark.spy
+def test_does_not_send_notifications_when_no_channels_available(
+ fxt_subject: notification_service.NotificationService,
+ fxt_email_spy: mock.MagicMock,
+ fxt_sms_spy: mock.MagicMock,
+) -> None:
+ user = {"name": "Fantasma"}
+
+ results = fxt_subject.notify_user(user, "Hola?")
+
+ fxt_email_spy.assert_not_called()
+ fxt_sms_spy.assert_not_called()
+ assert results == []
+
+
+@pytest.mark.spy
+def test_returns_actual_email_result(
+ fxt_subject: notification_service.NotificationService,
+) -> None:
+ user = {"email": "sofia@test.com"}
+
+ results = fxt_subject.notify_user(user, "Prueba")
+
+ assert results[0]["status"] == "sent"
+ assert results[0]["channel"] == "email"
+
+
+@pytest.mark.spy
+def test_call_order_when_both_channels_are_used(
+ fxt_subject: notification_service.NotificationService,
+ fxt_email_spy: mock.MagicMock,
+ fxt_sms_spy: mock.MagicMock,
+) -> None:
+ user = {"email": "luis@test.com", "phone": "+57322222222"}
+
+ fxt_subject.notify_user(user, "Mensaje")
+
+ fxt_email_spy.assert_called_with(
+ to="luis@test.com",
+ subject="Notificación",
+ body="Mensaje",
+ )
+ fxt_sms_spy.assert_called_with(
+ phone="+57322222222",
+ message="Mensaje",
+ )
+
+
+@pytest.mark.spy
+def test_multiple_users_accumulate_calls(
+ fxt_subject: notification_service.NotificationService,
+ fxt_email_spy: mock.MagicMock,
+) -> None:
+ users = [
+ {"email": "a@test.com"},
+ {"email": "b@test.com"},
+ {"email": "c@test.com"},
+ ]
+
+ for user in users:
+ fxt_subject.notify_user(user, "Promo")
+
+ assert fxt_email_spy.call_count == 3
+ recipients = [call.kwargs["to"] for call in fxt_email_spy.call_args_list]
+ assert recipients == ["a@test.com", "b@test.com", "c@test.com"]
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/test_notification_service_2.py b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/test_notification_service_2.py
new file mode 100644
index 0000000..6a299d8
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/3-spy/tests/test_notification_service_2.py
@@ -0,0 +1,20 @@
+from unittest import mock
+
+import pytest
+from src import notification_service, push_sender
+
+
+@pytest.fixture
+def fxt_push_sender() -> mock.MagicMock:
+ instance_push_sender = push_sender.PushSender()
+ spy_push = mock.MagicMock(wraps=instance_push_sender)
+ return spy_push
+
+
+def test_notify_by_push_all_available(
+ fxt_subject: notification_service.NotificationService, fxt_push_sender: mock.MagicMock
+) -> None:
+ fxt_subject.notify_by_push_all_available(push_sender=fxt_push_sender, message="Hola mundo")
+ fxt_push_sender.send_push_notification_to_all_available_receivers.assert_called_once_with(
+ message="Hola mundo"
+ )
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/requirements-dev.txt b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/requirements-dev.txt
new file mode 100644
index 0000000..88a7c6d
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/requirements-dev.txt
@@ -0,0 +1,5 @@
+iniconfig==2.3.0
+packaging==26.0
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/src/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/src/payment_gateway.py b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/src/payment_gateway.py
new file mode 100644
index 0000000..4cbbbe1
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/src/payment_gateway.py
@@ -0,0 +1,8 @@
+class PaymentGateway:
+ """Pasarela de pago real (nunca llamar en tests — cobra dinero real)."""
+
+ def charge(self, card_token: str, amount: float, currency: str) -> dict:
+ raise NotImplementedError("Procesa pago real")
+
+ def refund(self, transaction_id: str, amount: float) -> dict:
+ raise NotImplementedError("Procesa reembolso real")
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/src/payment_service.py b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/src/payment_service.py
new file mode 100644
index 0000000..caa4cad
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/src/payment_service.py
@@ -0,0 +1,26 @@
+# Un Mock es un doble que tiene expectativas preconfiguradas sobre cómo debe ser usado.
+# El mock verifica automáticamente que se llamaron los métodos correctos con los
+# argumentos correctos. Si las expectativas no se cumplen, el test falla.
+from src import payment_gateway
+
+
+class PaymentService:
+ def __init__(self) -> None:
+ self._gateway = payment_gateway.PaymentGateway()
+
+ def process_order_payment(self, card_token: str, amount: float) -> dict:
+ if amount <= 0:
+ raise ValueError("El monto debe ser mayor a cero")
+
+ result = self._gateway.charge(
+ card_token=card_token,
+ amount=amount,
+ currency="USD",
+ )
+ return result
+
+ def cancel_order(self, transaction_id: str, amount: float) -> dict:
+ return self._gateway.refund(
+ transaction_id=transaction_id,
+ amount=amount,
+ )
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/tests/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/tests/test_payment_service.py b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/tests/test_payment_service.py
new file mode 100644
index 0000000..1be4db7
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/4-mocks/tests/test_payment_service.py
@@ -0,0 +1,34 @@
+from unittest import mock
+
+from src import payment_service
+
+# --- MOCKS con unittest.mock ---
+# MagicMock crea un objeto que registra llamadas Y permite definir expectativas.
+# Usamos assert_called_once_with, assert_called_with, etc.
+# para verificar que la interacción fue exactamente la esperada.
+
+
+@mock.patch("src.payment_service.payment_gateway.PaymentGateway")
+def test_process_order_payment(mock_payment_gateway: mock.MagicMock) -> None:
+ # Setup
+ mock_payment_gateway_instance = mock_payment_gateway.return_value
+ mock_payment_gateway_instance.charge.return_value = {"status": "Finished", "code": 201}
+
+ service = payment_service.PaymentService()
+ result = service.process_order_payment(card_token="fake-card-token", amount=20.0)
+ assert result.get("status") == "Finished"
+ mock_payment_gateway_instance.charge.assert_called_once_with(
+ card_token="fake-card-token", amount=20.0, currency="USD"
+ )
+
+
+@mock.patch("src.payment_service.payment_gateway.PaymentGateway")
+def test_process_cancel_order(mock_payment_gateway: mock.MagicMock) -> None:
+ # Setup
+ mock_payment_gateway_instance: mock.MagicMock = mock_payment_gateway.return_value
+ mock_payment_gateway_instance.refund.return_value = {"status": "OK", "code": 201}
+
+ service = payment_service.PaymentService()
+ result = service.cancel_order(transaction_id="fake-transaction-id", amount=20.0)
+ assert result.get("status") == "OK"
+ mock_payment_gateway_instance.refund.assert_called_once()
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/requirements-dev.txt b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/requirements-dev.txt
new file mode 100644
index 0000000..473bc4f
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/requirements-dev.txt
@@ -0,0 +1,10 @@
+certifi==2026.2.25
+charset-normalizer==3.4.7
+idna==3.11
+iniconfig==2.3.0
+packaging==26.0
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
+requests==2.33.1
+urllib3==2.6.3
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/spiderman_client.py b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/spiderman_client.py
new file mode 100644
index 0000000..b603137
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/spiderman_client.py
@@ -0,0 +1,24 @@
+import requests
+
+BASE_URL = "https://superheroapi2.com/api/TOKEN"
+
+
+def get_character(character_id: int) -> dict:
+ response = requests.get(f"{BASE_URL}/{character_id}")
+ response.raise_for_status()
+ return response.json()
+
+
+def get_power_stats(character_id: int) -> dict:
+ data = get_character(character_id)
+ return {
+ "name": data["name"],
+ "intelligence": int(data["powerstats"]["intelligence"]),
+ "strength": int(data["powerstats"]["strength"]),
+ "speed": int(data["powerstats"]["speed"]),
+ }
+
+
+def is_stronger_than(character_id: int, strength_threshold: int) -> bool:
+ stats = get_power_stats(character_id)
+ return stats["strength"] > strength_threshold
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/order.py b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/order.py
new file mode 100644
index 0000000..94952d1
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/order.py
@@ -0,0 +1,11 @@
+import dataclasses
+
+
+@dataclasses.dataclass
+class Order:
+ order_name: str
+ order_id: str
+
+
+def get_order() -> Order:
+ raise ConnectionError()
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/user.py b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/user.py
new file mode 100644
index 0000000..b572e9a
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/user.py
@@ -0,0 +1,11 @@
+import dataclasses
+
+
+@dataclasses.dataclass
+class User:
+ name: str
+ last_name: str
+
+
+def get_user() -> User:
+ raise ConnectionError()
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/user_service.py b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/user_service.py
new file mode 100644
index 0000000..9e6cbcc
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/src/users_and_orders/user_service.py
@@ -0,0 +1,5 @@
+from src.users_and_orders import order, user
+
+
+def get_user_and_orders_related_to_user() -> tuple:
+ return (order.get_order(), user.get_user())
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/tests/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/tests/test_spiderman_client.py b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/tests/test_spiderman_client.py
new file mode 100644
index 0000000..2f354f6
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/tests/test_spiderman_client.py
@@ -0,0 +1,21 @@
+import pytest
+import requests
+from src import spiderman_client
+
+
+class FakeResponse:
+ def raise_for_status(self) -> None:
+ pass
+
+ def json(self) -> dict:
+ return {"data": 123}
+
+
+def fake_get(url: str) -> FakeResponse:
+ return FakeResponse()
+
+
+def test_should_get_character(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(requests, "get", fake_get)
+ result = spiderman_client.get_character(123456)
+ assert result.get("data") == 123
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/tests/users_and_orders/__init__.py b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/tests/users_and_orders/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/tests/users_and_orders/test_user_service.py b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/tests/users_and_orders/test_user_service.py
new file mode 100644
index 0000000..c3938f5
--- /dev/null
+++ b/7-coupled-code-and-doubles/2-types-of-doubles/5-monkeypatch/tests/users_and_orders/test_user_service.py
@@ -0,0 +1,22 @@
+import pytest
+from src.users_and_orders import order, user, user_service
+
+
+def get_fake_order() -> order.Order:
+ return order.Order(order_name="fake", order_id="fake")
+
+
+@pytest.fixture
+def fxt_setup_user_and_order(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr("src.users_and_orders.user_service.order.get_order", get_fake_order)
+ monkeypatch.setattr(
+ "src.users_and_orders.user_service.user.get_user",
+ lambda: user.User(name="fake", last_name="fake"),
+ )
+
+
+def test_should_get_user_and_orders_related_to_user(fxt_setup_user_and_order: None) -> None:
+ result = user_service.get_user_and_orders_related_to_user()
+ assert isinstance(result, tuple)
diff --git a/8-dependency-injection-and-fake-object/1-explanation/__init__.py b/8-dependency-injection-and-fake-object/1-explanation/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/1-explanation/requirements-dev.txt b/8-dependency-injection-and-fake-object/1-explanation/requirements-dev.txt
new file mode 100644
index 0000000..88a7c6d
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/1-explanation/requirements-dev.txt
@@ -0,0 +1,5 @@
+iniconfig==2.3.0
+packaging==26.0
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
diff --git a/8-dependency-injection-and-fake-object/1-explanation/src/__init__.py b/8-dependency-injection-and-fake-object/1-explanation/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/1-explanation/src/notification_sender.py b/8-dependency-injection-and-fake-object/1-explanation/src/notification_sender.py
new file mode 100644
index 0000000..72992c7
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/1-explanation/src/notification_sender.py
@@ -0,0 +1,4 @@
+class NotificationSender:
+ def send_message(self, message: str, user_id: str) -> dict[str, str]:
+ print("Acá se realiza una implementación real de enviar notificaciones con SNS")
+ return {"status": "sent", "user_id": user_id, "message": message}
diff --git a/8-dependency-injection-and-fake-object/1-explanation/src/notification_service.py b/8-dependency-injection-and-fake-object/1-explanation/src/notification_service.py
new file mode 100644
index 0000000..482b86d
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/1-explanation/src/notification_service.py
@@ -0,0 +1,9 @@
+from src import notification_sender
+
+
+class NotificationService:
+ def __init__(self, notification_sender: notification_sender.NotificationSender) -> None:
+ self.sender = notification_sender
+
+ def notify(self, user_id: str) -> dict[str, str]:
+ return self.sender.send_message("Hello world", user_id)
diff --git a/8-dependency-injection-and-fake-object/1-explanation/tests/__init__.py b/8-dependency-injection-and-fake-object/1-explanation/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/1-explanation/tests/fakes.py b/8-dependency-injection-and-fake-object/1-explanation/tests/fakes.py
new file mode 100644
index 0000000..9b6f120
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/1-explanation/tests/fakes.py
@@ -0,0 +1,10 @@
+from src import notification_sender
+
+
+class FakeNotificationSender(notification_sender.NotificationSender):
+ def send_message(self, message: str, user_id: str) -> dict[str, str]:
+ print(
+ "Acá se realiza una implementación fake de enviar "
+ "notificaciones con SNS, solo en memoria se hace"
+ )
+ return {"status": "sent", "user_id": user_id, "message": message}
diff --git a/8-dependency-injection-and-fake-object/1-explanation/tests/test_notification_service.py b/8-dependency-injection-and-fake-object/1-explanation/tests/test_notification_service.py
new file mode 100644
index 0000000..342aa96
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/1-explanation/tests/test_notification_service.py
@@ -0,0 +1,10 @@
+from src import notification_service
+from tests import fakes
+
+
+def test_should_notify() -> None:
+ service = notification_service.NotificationService(
+ notification_sender=fakes.FakeNotificationSender()
+ )
+ result = service.notify("123")
+ assert result == {"status": "sent", "user_id": "123", "message": "Hello world"}
diff --git a/8-dependency-injection-and-fake-object/2-repository/__init_.py b/8-dependency-injection-and-fake-object/2-repository/__init_.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/2-repository/requirements-dev.txt b/8-dependency-injection-and-fake-object/2-repository/requirements-dev.txt
new file mode 100644
index 0000000..88a7c6d
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/2-repository/requirements-dev.txt
@@ -0,0 +1,5 @@
+iniconfig==2.3.0
+packaging==26.0
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
diff --git a/8-dependency-injection-and-fake-object/2-repository/src/__init__.py b/8-dependency-injection-and-fake-object/2-repository/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/2-repository/src/hero_repository.py b/8-dependency-injection-and-fake-object/2-repository/src/hero_repository.py
new file mode 100644
index 0000000..d9444ba
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/2-repository/src/hero_repository.py
@@ -0,0 +1,63 @@
+import sqlite3
+
+
+class HeroRepository:
+ def __init__(self, db_path: str = "heroes.db"):
+ self.db_path = db_path
+ self._init_db()
+
+ def _connect(self) -> sqlite3.Connection:
+ return sqlite3.connect(self.db_path)
+
+ def _init_db(self) -> None:
+ with self._connect() as conn:
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS heroes (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL UNIQUE,
+ strength INTEGER NOT NULL,
+ city TEXT NOT NULL
+ )
+ """)
+
+ def save(self, name: str, strength: int, city: str) -> dict:
+ with self._connect() as conn:
+ cursor = conn.execute(
+ "INSERT INTO heroes (name, strength, city) VALUES (?, ?, ?)",
+ (name, strength, city),
+ )
+ return {"id": cursor.lastrowid, "name": name, "strength": strength, "city": city}
+
+ def get_by_id(self, hero_id: int) -> dict | None:
+ with self._connect() as conn:
+ row = conn.execute(
+ "SELECT id, name, strength, city FROM heroes WHERE id = ?",
+ (hero_id,),
+ ).fetchone()
+ if row is None:
+ return None
+ return {"id": row[0], "name": row[1], "strength": row[2], "city": row[3]}
+
+ def get_by_city(self, city: str) -> list[dict]:
+ with self._connect() as conn:
+ rows = conn.execute(
+ "SELECT id, name, strength, city FROM heroes WHERE city = ?",
+ (city,),
+ ).fetchall()
+ return [{"id": r[0], "name": r[1], "strength": r[2], "city": r[3]} for r in rows]
+
+ def delete(self, hero_id: int) -> bool:
+ with self._connect() as conn:
+ cursor = conn.execute(
+ "DELETE FROM heroes WHERE id = ?",
+ (hero_id,),
+ )
+ return cursor.rowcount > 0
+
+ def update_strength(self, hero_id: int, strength: int) -> dict | None:
+ with self._connect() as conn:
+ conn.execute(
+ "UPDATE heroes SET strength = ? WHERE id = ?",
+ (strength, hero_id),
+ )
+ return self.get_by_id(hero_id)
diff --git a/8-dependency-injection-and-fake-object/2-repository/src/hero_service.py b/8-dependency-injection-and-fake-object/2-repository/src/hero_service.py
new file mode 100644
index 0000000..d58cea6
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/2-repository/src/hero_service.py
@@ -0,0 +1,26 @@
+from src import hero_repository
+
+
+class HeroService:
+ def __init__(self, repo: hero_repository.HeroRepository):
+ self.repo = repo
+
+ def recruit_hero(self, name: str, strength: int, city: str) -> dict:
+ if strength < 0 or strength > 100:
+ raise ValueError(f"La fuerza debe estar entre 0 y 100, se recibió {strength}")
+ if not name.strip():
+ raise ValueError("El nombre no puede estar vacío")
+ return self.repo.save(name, strength, city)
+
+ def get_strongest_in_city(self, city: str) -> dict | None:
+ heroes = self.repo.get_by_city(city)
+ if not heroes:
+ return None
+ return max(heroes, key=lambda h: h["strength"])
+
+ def power_up(self, hero_id: int, bonus: int) -> dict | None:
+ hero = self.repo.get_by_id(hero_id)
+ if hero is None:
+ return None
+ new_strength = min(hero["strength"] + bonus, 100)
+ return self.repo.update_strength(hero_id, new_strength)
diff --git a/8-dependency-injection-and-fake-object/2-repository/tests/__init__.py b/8-dependency-injection-and-fake-object/2-repository/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/2-repository/tests/fakes.py b/8-dependency-injection-and-fake-object/2-repository/tests/fakes.py
new file mode 100644
index 0000000..cc2e559
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/2-repository/tests/fakes.py
@@ -0,0 +1,32 @@
+from src import hero_repository
+
+
+class FakeHeroRepository(hero_repository.HeroRepository):
+ def __init__(self, db_path: str = "heroes.db") -> None:
+ self._store: dict[int, dict] = {}
+ self._next_id: int = 1
+
+ def save(self, name: str, strength: int, city: str) -> dict:
+ hero = {"id": self._next_id, "name": name, "strength": strength, "city": city}
+ self._store[self._next_id] = hero
+ self._next_id += 1
+ return hero
+
+ def get_by_id(self, hero_id: int) -> dict | None:
+ return self._store.get(hero_id)
+
+ def get_by_city(self, city: str) -> list[dict]:
+ heroes_by_city = [hero for hero in self._store.values() if hero["city"] == city]
+ return heroes_by_city
+
+ def delete(self, hero_id: int) -> bool:
+ if hero_id in self._store:
+ del self._store[hero_id]
+ return True
+ return False
+
+ def update_strength(self, hero_id: int, strength: int) -> dict | None:
+ if hero_id in self._store:
+ self._store[hero_id] = {**self._store[hero_id], "strength": strength}
+ return self._store[hero_id]
+ return None
diff --git a/8-dependency-injection-and-fake-object/2-repository/tests/test_hero_service.py b/8-dependency-injection-and-fake-object/2-repository/tests/test_hero_service.py
new file mode 100644
index 0000000..ef1c1b8
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/2-repository/tests/test_hero_service.py
@@ -0,0 +1,32 @@
+import pytest
+from src import hero_service
+
+from tests import fakes
+
+
+@pytest.fixture
+def fxt_hero_service() -> hero_service.HeroService:
+ return hero_service.HeroService(repo=fakes.FakeHeroRepository())
+
+
+def test_should_recruit_hero(fxt_hero_service: hero_service.HeroService) -> None:
+ result = fxt_hero_service.recruit_hero(name="Spiderman", strength=8, city="California")
+ assert result.get("id") == 1
+ result = fxt_hero_service.recruit_hero(name="Batman", strength=9, city="Gotham city")
+ assert result.get("id") == 2
+
+
+def test_should_get_strongest_in_city(fxt_hero_service: hero_service.HeroService) -> None:
+ fxt_hero_service.recruit_hero(name="Batman", strength=9, city="Gotham city")
+ fxt_hero_service.recruit_hero(name="Joker", strength=7, city="Gotham city")
+ fxt_hero_service.recruit_hero(name="Superman", strength=10, city="Gotham city")
+ result = fxt_hero_service.get_strongest_in_city("Gotham city")
+ assert result
+ assert result.get("id") == 3
+
+
+def test_should_power_up(fxt_hero_service: hero_service.HeroService) -> None:
+ result_creation = fxt_hero_service.recruit_hero(name="Bakugo", strength=6, city="Japan")
+ result_power_up = fxt_hero_service.power_up(hero_id=result_creation["id"], bonus=2)
+ assert result_power_up
+ assert result_power_up.get("strength") == 8
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/requirements-dev.txt b/8-dependency-injection-and-fake-object/3-ports-and-adapters/requirements-dev.txt
new file mode 100644
index 0000000..473bc4f
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/3-ports-and-adapters/requirements-dev.txt
@@ -0,0 +1,10 @@
+certifi==2026.2.25
+charset-normalizer==3.4.7
+idna==3.11
+iniconfig==2.3.0
+packaging==26.0
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
+requests==2.33.1
+urllib3==2.6.3
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/__init__.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/adapters/__init__.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/adapters/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/adapters/rick_and_morty.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/adapters/rick_and_morty.py
new file mode 100644
index 0000000..ad8a37b
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/adapters/rick_and_morty.py
@@ -0,0 +1,67 @@
+import requests
+
+from src.domain import entities, ports
+
+
+class CharacterNotFoundException(Exception): ...
+
+
+class RickAndMortyApiAdapter(ports.CharacterPort):
+ BASE_URL = "https://rickandmortyapi.com/api"
+
+ def get_by_id(self, character_id: int) -> entities.Character:
+ response = requests.get(
+ f"{self.BASE_URL}/character/{character_id}",
+ timeout=10,
+ )
+ data = response.json()
+ if not data:
+ raise CharacterNotFoundException(character_id)
+ response.raise_for_status()
+
+ return entities.Character(
+ id=data["id"],
+ name=data["name"],
+ status=data["status"],
+ species=data["species"],
+ gender=data["gender"],
+ origin_name=data["origin"]["name"],
+ )
+
+ def create_character(self) -> None:
+ pass
+
+
+class FakeRickAndMortyApiAdapter(ports.CharacterPort):
+ _FAKE_STORAGE = {
+ 1: entities.Character(
+ id=1,
+ name="Rick Sanchez",
+ status="Alive",
+ species="Human",
+ gender="Male",
+ origin_name="Earth (C-137)",
+ ),
+ 2: entities.Character(
+ id=2,
+ name="Morty Smith",
+ status="Alive",
+ species="Human",
+ gender="Male",
+ origin_name="unknown",
+ ),
+ 3: entities.Character(
+ id=3,
+ name="Summer Smith",
+ status="Alive",
+ species="Human",
+ gender="Female",
+ origin_name="Earth (Replacement Dimension)",
+ ),
+ }
+
+ def get_by_id(self, character_id: int) -> entities.Character:
+ character_to_return = self._FAKE_STORAGE.get(character_id)
+ if not character_to_return:
+ raise CharacterNotFoundException(character_id)
+ return character_to_return
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/domain/__init__.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/domain/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/domain/entities.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/domain/entities.py
new file mode 100644
index 0000000..7b08ce2
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/domain/entities.py
@@ -0,0 +1,11 @@
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class Character:
+ id: int
+ name: str
+ status: str
+ species: str
+ gender: str
+ origin_name: str
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/domain/ports.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/domain/ports.py
new file mode 100644
index 0000000..20502ca
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/domain/ports.py
@@ -0,0 +1,9 @@
+import abc
+
+from src.domain import entities
+
+
+class CharacterPort(abc.ABC):
+ @abc.abstractmethod
+ def get_by_id(self, character_id: int) -> entities.Character:
+ raise NotImplementedError
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/main.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/main.py
new file mode 100644
index 0000000..3b1add3
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/main.py
@@ -0,0 +1,13 @@
+from src.adapters import rick_and_morty
+from src.services import character_service
+
+
+def main() -> None:
+ adapter = rick_and_morty.RickAndMortyApiAdapter()
+ character = character_service.get_character(adapter_character=adapter, character_id=3)
+
+ print(character)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/services/__init__.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/services/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/services/character_service.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/services/character_service.py
new file mode 100644
index 0000000..afee59e
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/3-ports-and-adapters/src/services/character_service.py
@@ -0,0 +1,5 @@
+from src.domain import entities, ports
+
+
+def get_character(adapter_character: ports.CharacterPort, character_id: int) -> entities.Character:
+ return adapter_character.get_by_id(character_id=character_id)
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/tests/__init__.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/tests/services/__init__.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/tests/services/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/3-ports-and-adapters/tests/services/test_character_service.py b/8-dependency-injection-and-fake-object/3-ports-and-adapters/tests/services/test_character_service.py
new file mode 100644
index 0000000..9eee601
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/3-ports-and-adapters/tests/services/test_character_service.py
@@ -0,0 +1,18 @@
+import pytest
+from src.adapters import rick_and_morty
+from src.services import character_service
+
+
+def test_should_get_character() -> None:
+ result = character_service.get_character(
+ adapter_character=rick_and_morty.FakeRickAndMortyApiAdapter(), character_id=1
+ )
+ assert result.id == 1
+
+
+def test_should_raise_exception_character_not_found() -> None:
+ with pytest.raises(rick_and_morty.CharacterNotFoundException) as exception_info:
+ character_service.get_character(
+ adapter_character=rick_and_morty.FakeRickAndMortyApiAdapter(), character_id=100
+ )
+ assert exception_info.type is rick_and_morty.CharacterNotFoundException
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/pytest.ini b/8-dependency-injection-and-fake-object/4-laboratory/pytest.ini
new file mode 100644
index 0000000..1ceccf5
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/4-laboratory/pytest.ini
@@ -0,0 +1,5 @@
+[pytest]
+testpaths = tests
+pythonpath = .
+markers =
+ payments: mark a test as a unit test of payments.
\ No newline at end of file
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/requirements-dev.txt b/8-dependency-injection-and-fake-object/4-laboratory/requirements-dev.txt
new file mode 100644
index 0000000..c3fc416
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/4-laboratory/requirements-dev.txt
@@ -0,0 +1,5 @@
+iniconfig==2.3.0
+packaging==26.2
+pluggy==1.6.0
+Pygments==2.20.0
+pytest==9.0.3
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/src/__init__.py b/8-dependency-injection-and-fake-object/4-laboratory/src/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/src/adapters/__init__.py b/8-dependency-injection-and-fake-object/4-laboratory/src/adapters/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/src/adapters/stripe_payment_adapter.py b/8-dependency-injection-and-fake-object/4-laboratory/src/adapters/stripe_payment_adapter.py
new file mode 100644
index 0000000..a2a6154
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/4-laboratory/src/adapters/stripe_payment_adapter.py
@@ -0,0 +1,27 @@
+from src.domain import models, payment_gateway
+
+
+class StripePaymentAdapter(payment_gateway.PaymentGatewayPort):
+ """Real Stripe adapter — requires a live API key and network access.
+
+ Cannot be used in unit tests: instantiating it with a valid key and
+ hitting the Stripe sandbox costs money and introduces network flakiness.
+ Use FakePaymentGateway in tests instead.
+ """
+
+ def __init__(self, api_key: str) -> None:
+ self._api_key = api_key
+
+ def charge(self, amount: float, currency: str, card_token: str) -> models.PaymentResult:
+ # Real implementation would call: stripe.PaymentIntent.create(...)
+ raise NotImplementedError(
+ "StripePaymentAdapter requires a live Stripe connection. "
+ "Use FakePaymentGateway in unit tests."
+ )
+
+ def refund(self, transaction_id: str, amount: float) -> models.PaymentResult:
+ # Real implementation would call: stripe.Refund.create(...)
+ raise NotImplementedError(
+ "StripePaymentAdapter requires a live Stripe connection. "
+ "Use FakePaymentGateway in unit tests."
+ )
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/src/domain/__init__.py b/8-dependency-injection-and-fake-object/4-laboratory/src/domain/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/src/domain/models.py b/8-dependency-injection-and-fake-object/4-laboratory/src/domain/models.py
new file mode 100644
index 0000000..33f4409
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/4-laboratory/src/domain/models.py
@@ -0,0 +1,16 @@
+from dataclasses import dataclass
+
+
+@dataclass
+class Order:
+ order_id: str
+ amount: float
+ currency: str
+ card_token: str
+
+
+@dataclass
+class PaymentResult:
+ success: bool
+ transaction_id: str
+ message: str
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/src/domain/payment_gateway.py b/8-dependency-injection-and-fake-object/4-laboratory/src/domain/payment_gateway.py
new file mode 100644
index 0000000..83d4a2c
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/4-laboratory/src/domain/payment_gateway.py
@@ -0,0 +1,17 @@
+import abc
+
+from src.domain import models
+
+
+class PaymentGatewayPort(abc.ABC):
+ """Port: contract that every payment gateway adapter must satisfy."""
+
+ @abc.abstractmethod
+ def charge(self, amount: float, currency: str, card_token: str) -> models.PaymentResult:
+ """Charge *amount* to the card identified by *card_token*."""
+ ...
+
+ @abc.abstractmethod
+ def refund(self, transaction_id: str, amount: float) -> models.PaymentResult:
+ """Refund *amount* for the given *transaction_id*."""
+ ...
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/src/services/__init__.py b/8-dependency-injection-and-fake-object/4-laboratory/src/services/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/src/services/order_service.py b/8-dependency-injection-and-fake-object/4-laboratory/src/services/order_service.py
new file mode 100644
index 0000000..f9a8d42
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/4-laboratory/src/services/order_service.py
@@ -0,0 +1,16 @@
+from src.domain import models, payment_gateway
+
+
+class OrderService:
+ def __init__(self, payment_gateway: payment_gateway.PaymentGatewayPort) -> None:
+ self._gateway = payment_gateway
+
+ def process_order(self, order: models.Order) -> models.PaymentResult:
+ if order.amount <= 0:
+ raise ValueError("Order amount must be positive")
+ return self._gateway.charge(order.amount, order.currency, order.card_token)
+
+ def cancel_order(self, transaction_id: str, amount: float) -> models.PaymentResult:
+ if amount <= 0:
+ raise ValueError("Refund amount must be positive")
+ return self._gateway.refund(transaction_id, amount)
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/tests/__init__.py b/8-dependency-injection-and-fake-object/4-laboratory/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/tests/fakes/__init__.py b/8-dependency-injection-and-fake-object/4-laboratory/tests/fakes/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/tests/fakes/fake_payment_gateway.py b/8-dependency-injection-and-fake-object/4-laboratory/tests/fakes/fake_payment_gateway.py
new file mode 100644
index 0000000..bcc191b
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/4-laboratory/tests/fakes/fake_payment_gateway.py
@@ -0,0 +1,73 @@
+import uuid
+
+from src.domain import models, payment_gateway
+
+
+class FakePaymentGateway(payment_gateway.PaymentGatewayPort):
+ """Fake implementation of PaymentGateway for use in unit tests.
+
+ A *fake* is a simplified but working implementation that is not suitable
+ for production. Unlike a mock (which only records calls), a fake has
+ real — though minimal — logic.
+
+ ─────────────────────────────────────────────────────────────────────────
+ YOUR TASKS
+ ─────────────────────────────────────────────────────────────────────────
+ 1. Add the attributes you need to track state (e.g. charged_payments,
+ should_fail). Initialize them in __init__.
+
+ 2. Implement `charge` so that:
+ a. It records every call in self.charged_payments (list of dicts with
+ keys "amount", "currency" and "card_token").
+ b. When self.should_fail is True it returns a failure PaymentResult.
+ c. Otherwise it returns a successful PaymentResult with a deterministic
+ transaction_id such as "fake-txn-1", "fake-txn-2", … (use a counter) uuid.
+
+ 3. Implement `refund` so that it always returns a successful PaymentResult.
+
+ Hints
+ ─────
+ • PaymentResult(success, transaction_id, message) is a plain dataclass.
+ • You do NOT need to import anything beyond what is already imported here.
+ ─────────────────────────────────────────────────────────────────────────
+ """
+
+ def __init__(self) -> None:
+ # TODO: initialize your state here
+ # Example attributes you may want:
+ self.charged_payments: list[dict] = []
+ # self.should_fail: bool = False
+ # self._charge_counter: int = 0
+ pass
+
+ def charge(self, amount: float, currency: str, card_token: str) -> models.PaymentResult:
+ transaction_id = str(uuid.uuid4())
+ self.charged_payments.append(
+ {
+ "amount": amount,
+ "currency": currency,
+ "card_token": card_token,
+ "transaction_id": transaction_id,
+ }
+ )
+ return models.PaymentResult(
+ success=True, transaction_id=transaction_id, message="Charge successful"
+ )
+
+ def refund(self, transaction_id: str, amount: float) -> models.PaymentResult:
+ payment = next(
+ (txn for txn in self.charged_payments if txn["transaction_id"] == transaction_id), None
+ )
+ if not payment:
+ return models.PaymentResult(
+ success=False, transaction_id=transaction_id, message="Transaction not found"
+ )
+ if amount > payment["amount"]:
+ return models.PaymentResult(
+ success=False,
+ transaction_id=transaction_id,
+ message="Refund amount exceeds original charge",
+ )
+ return models.PaymentResult(
+ success=True, transaction_id=transaction_id, message="Refund successful"
+ )
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/tests/services/__init__.py b/8-dependency-injection-and-fake-object/4-laboratory/tests/services/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/8-dependency-injection-and-fake-object/4-laboratory/tests/services/test_order_service.py b/8-dependency-injection-and-fake-object/4-laboratory/tests/services/test_order_service.py
new file mode 100644
index 0000000..3c4b4d4
--- /dev/null
+++ b/8-dependency-injection-and-fake-object/4-laboratory/tests/services/test_order_service.py
@@ -0,0 +1,94 @@
+"""Unit tests for OrderService.
+
+─────────────────────────────────────────────────────────────────────────────
+YOUR TASKS
+─────────────────────────────────────────────────────────────────────────────
+1. Finish implementing FakePaymentGateway in tests/fakes/fake_payment_gateway.py.
+2. Import it below (replace the TODO comment).
+3. Complete every test method so that each one has at least one assertion.
+4. Run the suite with: pytest tests/ -v
+
+Rules
+─────
+• Use FakePaymentGateway — never StripePaymentAdapter — in these tests.
+• Do not patch or monkeypatch anything. Inject the fake through __init__.
+─────────────────────────────────────────────────────────────────────────────
+"""
+
+import uuid
+
+import pytest
+from src.domain import models
+from src.services import order_service
+
+from tests.fakes import fake_payment_gateway
+
+
+@pytest.mark.payments
+class TestProcessOrder:
+ def test_successful_charge_returns_success_result(self) -> None:
+ fake_adapter = fake_payment_gateway.FakePaymentGateway()
+ order_srv = order_service.OrderService(payment_gateway=fake_adapter)
+ order = models.Order(
+ order_id=str(uuid.uuid4()), amount=100.0, currency="USD", card_token="fake-card-token"
+ )
+ result = order_srv.process_order(order=order)
+ assert result.success is True
+
+ def test_charge_is_recorded_in_fake(self) -> None:
+ # TODO: after calling process_order, inspect fake.charged_payments
+ # TODO: assert that exactly one payment was recorded
+ # TODO: assert the recorded amount matches the order amount
+ pass
+
+ def test_currency_is_forwarded_to_gateway(self) -> None:
+ # TODO: create an Order with currency="EUR"
+ # TODO: assert the recorded payment has currency "EUR"
+ pass
+
+ def test_process_order_raises_when_amount_is_zero(self) -> None:
+ # TODO: create an Order with amount=0
+ # TODO: use pytest.raises to assert that process_order raises ValueError
+ pass
+
+ def test_process_order_raises_when_amount_is_negative(self) -> None:
+ # TODO: create an Order with a negative amount
+ # TODO: use pytest.raises to assert that process_order raises ValueError
+ pass
+
+ def test_gateway_failure_is_returned_to_caller(self) -> None:
+ # TODO: set fake.should_fail = True before calling process_order
+ # TODO: assert that result.success is False
+ pass
+
+ def test_multiple_orders_are_all_recorded(self) -> None:
+ # TODO: call process_order twice with different orders
+ # TODO: assert that fake.charged_payments has exactly two entries
+ pass
+
+
+@pytest.mark.payments
+class TestCancelOrder:
+ def test_successful_refund_returns_success_result(self) -> None:
+ # TODO: call cancel_order with a valid transaction_id and positive amount
+ # TODO: assert result.success is True
+ fake_adapter = fake_payment_gateway.FakePaymentGateway()
+ order_srv = order_service.OrderService(payment_gateway=fake_adapter)
+ order = models.Order(
+ order_id=str(uuid.uuid4()), amount=100.0, currency="USD", card_token="fake-card-token"
+ )
+ result_charge = order_srv.process_order(order=order)
+ result_refund = order_srv.cancel_order(
+ transaction_id=result_charge.transaction_id, amount=100.0
+ )
+ assert result_refund.message == "Refund successful"
+ assert result_refund.success is True
+ assert result_refund.transaction_id == result_charge.transaction_id
+
+ def test_cancel_order_raises_when_amount_is_zero(self) -> None:
+ # TODO: assert that cancel_order raises ValueError when amount=0
+ pass
+
+ def test_cancel_order_raises_when_amount_is_negative(self) -> None:
+ # TODO: assert that cancel_order raises ValueError when amount is negative
+ pass