Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
5ece148
feat: Added first lab with hypothesis
Alvaro8317 Apr 12, 2026
c0be301
feat: Added first tests
Alvaro8317 Apr 12, 2026
7085036
feat: Added examples to explain coupling
Alvaro8317 Apr 12, 2026
963341f
feat: Added dummy code to explain the concept
Alvaro8317 Apr 13, 2026
0a84a8d
feat: Finished explanation about coupling
Alvaro8317 Apr 13, 2026
8312890
feat: Finished explanation of stubs
Alvaro8317 Apr 13, 2026
bdaa1e6
feat: Finished section about spy
Alvaro8317 Apr 14, 2026
9742cca
feat: Finished mocks and monkey patch section
Alvaro8317 Apr 14, 2026
07b909d
Merge branch 'feat/08-coupled-code-and-doubles' into feat/09-dependen…
Alvaro8317 Apr 14, 2026
c6185c7
feat: Finished section of DI with laboratory
Alvaro8317 Apr 28, 2026
cbd9702
Merge branch 'feat/09-dependency-injection-and-adapters' into feat/10…
Alvaro8317 Apr 28, 2026
974c705
Merge branch 'feat/10-hypothesis-and-property-based-testing' into fea…
Alvaro8317 Apr 28, 2026
2f95124
feat: Added patchverse code
Alvaro8317 Apr 28, 2026
ee890e5
feat: Finished explanation about singleton
Alvaro8317 May 3, 2026
8aa064a
feat: finished several mini-sections of extras sections
Alvaro8317 May 4, 2026
d2ae5c6
feat: Finished mini sections about TDD and django testing
Alvaro8317 May 4, 2026
491a4e6
feat: Finished mini section of testing with fastapi
Alvaro8317 May 4, 2026
81e126e
feat: Added pipeline of unit tests about django and fastapi apps
Alvaro8317 May 4, 2026
8f1cd01
fix: Requirements file fastapi
Alvaro8317 May 4, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions .github/workflows/python-unit-tests.yml
Original file line number Diff line number Diff line change
@@ -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
Empty file.
Original file line number Diff line number Diff line change
@@ -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
Empty file.
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions 11-extras/1-patchverse/pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[pytest]
markers =
enrollment: Unit tests about enrollment of a studen in udemy
10 changes: 10 additions & 0 deletions 11-extras/1-patchverse/requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -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
Empty file.
77 changes: 77 additions & 0 deletions 11-extras/1-patchverse/src/dependencies.py
Original file line number Diff line number Diff line change
@@ -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"]
Loading
Loading