chore: initialize containerized Python learning workbook (2026 DevOps/SRE)
This commit is contained in:
commit
ae4c421815
63 files changed
+1273
No files matched your search
+10
@@ -0,0 +1,10 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
.venv/
|
||||
.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
@@ -0,0 +1,39 @@
|
||||
# AGENTS.md — Instrukcje dla agentów AI (Python Learning Workbook — Era 2026)
|
||||
|
||||
Ten projekt to **zeszyt ćwiczeń do nauki Pythona od zera dla inżyniera DevOps / SRE w 2026 roku**.
|
||||
Kluczowe cele nauki: **solidne podstawy logiki i struktur danych**, **nowoczesne typowanie (`mypy`)**, **audyt kodu generowanego przez AI** oraz **praktyka DevOps/SRE/AIOps**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Trzy tryby pracy agenta
|
||||
|
||||
### A. `exercises/01-core/` — Tryb Sokratejski (Rdzeń języka od zera)
|
||||
* **Nie rozwiązuj zadań za użytkownika domyślnie.** Tutaj budowane są fundamenty programowania.
|
||||
* Stosuj stopniowane podpowiedzi:
|
||||
1. **Naprowadzenie:** wyjaśnij błąd (`Traceback`, `AssertionError`, `mypy`), wskaż koncepcję lub metodę z `stdlib`.
|
||||
2. **Analogiczny przykład:** pokaż krótki przykład na *innym* problemie.
|
||||
3. **Pełne rozwiązanie:** wyłącznie na wyraźną prośbę użytkownika.
|
||||
* Po przejściu testów zaproponuj krótkie **code review** (czytelność, Pythonic idioms, `ruff`, `mypy`).
|
||||
|
||||
### B. `exercises/02-engineering-2026/` — Tryb Specyfikacja → Audyt / Review (Era AI)
|
||||
* W `01-ai-code-audit` pomagaj wyłapywać klasyczne pułapki Pythona i AI (mutable defaults, gołe `except:`, `shell=True`, brak walidacji).
|
||||
* W `02-type-driven-design` nacisk na kontrakty typowe i niezmienniki.
|
||||
* W `03-cross-platform-os` i `04-testing-best-practices` pilnuj `pathlib.Path`, braku `shell=True` i In-Memory Fakes zamiast nadużywania mocków.
|
||||
|
||||
### C. `exercises/03-ecosystems/` — Tryb Architekta DevOps/SRE
|
||||
* Tłumacz *dlaczego i kiedy* używać `typer`, `fastapi`, `pydantic`, `pyyaml`, `httpx` oraz jak unikać typowych błędów w produkcji (brak timeoutów, brak walidacji danych zewnętrznych).
|
||||
|
||||
---
|
||||
|
||||
## 2. Model A — Architektura gałęzi Git (Zasada krytyczna)
|
||||
|
||||
* **`main`:** czysty szablon (nierozwiązane zadania + `notes/` + `AGENTS.md`). **Nigdy nie commituj rozwiązań na `main`.**
|
||||
* **`attempt/<YYYY-MM>`:** gałąź robocza na rozwiązania. Przed edycją zadań sprawdź `git branch --show-current` i ostrzeż użytkownika, jeśli jest na `main`.
|
||||
* Nowe rozdziały i wspólne notatki w `notes/` trafiają na `main`, a potem `git merge main` do `attempt/*`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Zero Host Pollution (Wyłącznie kontener Podman)
|
||||
|
||||
* Nie instaluj pakietów Pythona na hoście i nie uruchamiaj lokalnego `pytest`/`python`.
|
||||
* Używaj wyłącznie `Makefile`: `make check`, `make test MOD=01-core/01-basics`, `make test`, `make test-all`, `make fmt`, `make fmt-check`.
|
||||
@@ -0,0 +1,19 @@
|
||||
FROM docker.io/library/python:3.12-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
UV_SYSTEM_PYTHON=1
|
||||
|
||||
RUN pip install --no-cache-dir uv && \
|
||||
uv pip install --system --no-cache \
|
||||
pytest \
|
||||
ruff \
|
||||
mypy \
|
||||
pydantic \
|
||||
fastapi \
|
||||
httpx \
|
||||
typer \
|
||||
pyyaml \
|
||||
types-PyYAML
|
||||
|
||||
WORKDIR /workspace
|
||||
@@ -0,0 +1,54 @@
|
||||
IMAGE ?= python-learning:latest
|
||||
ENGINE ?= podman
|
||||
MOD ?=
|
||||
|
||||
RUN_CONTAINER = $(ENGINE) run --rm \
|
||||
-v "$(CURDIR):/workspace:Z" \
|
||||
-w /workspace \
|
||||
$(IMAGE)
|
||||
|
||||
.PHONY: help image check test test-all lint fmt fmt-check typecheck shell
|
||||
|
||||
help:
|
||||
@echo "Dostępne komendy:"
|
||||
@echo " make image - Zbuduj obraz kontenera Python (jednorazowo)"
|
||||
@echo " make check - Sprawdź lint (ruff) + typy (mypy)"
|
||||
@echo " make test MOD=01-core/01-basics - Uruchom testy wybranego rozdziału"
|
||||
@echo " make test - Uruchom testy 01-core + 02-engineering-2026"
|
||||
@echo " make test-all - Uruchom testy wszystkich 3 ścieżek"
|
||||
@echo " make fmt - Sformatuj kod (ruff format)"
|
||||
@echo " make fmt-check - Sprawdź formatowanie kodu"
|
||||
@echo " make shell - Otwórz powłokę bash wewnątrz kontenera"
|
||||
|
||||
image:
|
||||
$(ENGINE) build -t $(IMAGE) -f Containerfile .
|
||||
|
||||
lint:
|
||||
$(RUN_CONTAINER) ruff check exercises
|
||||
|
||||
typecheck:
|
||||
$(RUN_CONTAINER) mypy exercises
|
||||
|
||||
check: lint typecheck
|
||||
|
||||
test:
|
||||
ifdef MOD
|
||||
$(RUN_CONTAINER) pytest -v exercises/$(MOD)
|
||||
else
|
||||
$(RUN_CONTAINER) pytest -v exercises/01-core exercises/02-engineering-2026
|
||||
endif
|
||||
|
||||
test-all:
|
||||
$(RUN_CONTAINER) pytest -v exercises
|
||||
|
||||
fmt:
|
||||
$(RUN_CONTAINER) ruff format exercises
|
||||
|
||||
fmt-check:
|
||||
$(RUN_CONTAINER) ruff format --check exercises
|
||||
|
||||
shell:
|
||||
$(ENGINE) run --rm -it \
|
||||
-v "$(CURDIR):/workspace:Z" \
|
||||
-w /workspace \
|
||||
$(IMAGE) bash
|
||||
@@ -0,0 +1,74 @@
|
||||
# Python Learning Workbook (2026 DevOps/SRE Edition)
|
||||
|
||||
Zeszyt ćwiczeń do nauki języka Python od zera, zaprojektowany pod **DevOps / SRE w 2026 roku** — izolowane środowisko **Podman** (Zero Host Pollution), nowoczesny toolchain (`uv`, `pytest`, `ruff`, `mypy`) oraz podejście dopasowane do ery AI.
|
||||
|
||||
## Architektura pracy (Model A — podział na gałęzie)
|
||||
|
||||
* **`main`** — czysty szablon: nierozwiązane zadania (`exercises/`), wspólne notatki (`notes/`), `AGENTS.md`. **Nie commituj tutaj rozwiązań zadań.**
|
||||
* **`attempt/<YYYY-MM>`** — gałąź robocza dla konkretnego podejścia (np. `attempt/2026-11`).
|
||||
* **Powrót po czasie / start od nowa:**
|
||||
```bash
|
||||
git checkout main
|
||||
git checkout -b attempt/2027-01
|
||||
```
|
||||
|
||||
## Szybki start (Podman)
|
||||
|
||||
```bash
|
||||
# 1. Zbuduj lokalny obraz z Python 3.12, uv, pytest, ruff, mypy (raz)
|
||||
make image
|
||||
|
||||
# 2. Sprawdź lint (ruff) i typy (mypy)
|
||||
make check
|
||||
|
||||
# 3. Uruchom testy wybranego rozdziału
|
||||
make test MOD=01-core/01-basics
|
||||
make test MOD=02-engineering-2026/01-ai-code-audit
|
||||
make test MOD=03-ecosystems/01-cli-typer
|
||||
|
||||
# 4. Sformatuj kod
|
||||
make fmt
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ścieżki i checklista postępów
|
||||
|
||||
### Ścieżka 1: `01-core/` — Rdzeń języka od zera (czyste `stdlib`)
|
||||
- [ ] `01-basics` — [README](exercises/01-core/01-basics/README.md): zmienne, typy, warunki, pętle, funkcje
|
||||
- [ ] `02-collections` — [README](exercises/01-core/02-collections/README.md): `list`, `tuple`, `dict`, `set`, slicing
|
||||
- [ ] `03-strings-files` — [README](exercises/01-core/03-strings-files/README.md): f-stringi, parsowanie tekstu, `pathlib.Path`
|
||||
- [ ] `04-errors-exceptions` — [README](exercises/01-core/04-errors-exceptions/README.md): `try`/`except`, własne wyjątki, walidacja
|
||||
- [ ] `05-comprehensions-functional` — [README](exercises/01-core/05-comprehensions-functional/README.md): comprehensions, generatory (`yield`), lambdy
|
||||
- [ ] `06-oop-dataclasses` — [README](exercises/01-core/06-oop-dataclasses/README.md): klasy, `@dataclass`, kompozycja, `Protocol`
|
||||
- [ ] `07-typing-contracts` — [README](exercises/01-core/07-typing-contracts/README.md): nowoczesne typowanie, `Enum`, `TypedDict`, `mypy`
|
||||
- [ ] `08-data-structures` — [README](exercises/01-core/08-data-structures/README.md): `Stack`, `Queue` (`deque`), `Counter`, `defaultdict`
|
||||
- [ ] `09-design-patterns` — [README](exercises/01-core/09-design-patterns/README.md): Strategy, Factory, Context Manager (`with`), DI
|
||||
- [ ] `10-crud-repository` — [README](exercises/01-core/10-crud-repository/README.md): pełny CRUD w pamięci (`TaskStore`)
|
||||
|
||||
### Ścieżka 2: `02-engineering-2026/` — Dobre praktyki i umiejętności ery AI
|
||||
- [ ] `01-ai-code-audit` — [README](exercises/02-engineering-2026/01-ai-code-audit/README.md): audyt wadliwego „kodu z AI”
|
||||
- [ ] `02-type-driven-design` — [README](exercises/02-engineering-2026/02-type-driven-design/README.md): walidowane typy domenowe (`Email`, `Money`, `Port`)
|
||||
- [ ] `03-cross-platform-os` — [README](exercises/02-engineering-2026/03-cross-platform-os/README.md): `pathlib`, env vars, bezpieczny `subprocess`, logi JSON
|
||||
- [ ] `04-testing-best-practices` — [README](exercises/02-engineering-2026/04-testing-best-practices/README.md): `pytest` fixtures, parametryzacja, In-Memory Fakes
|
||||
|
||||
### Ścieżka 3: `03-ecosystems/` — DevOps, SRE, Web i AIOps
|
||||
- [ ] `01-cli-typer` — [README](exercises/03-ecosystems/01-cli-typer/README.md): parsowanie argumentów CLI z `typer`
|
||||
- [ ] `02-web-api-fastapi` — [README](exercises/03-ecosystems/02-web-api-fastapi/README.md): REST API w `FastAPI` + `Pydantic`
|
||||
- [ ] `03-devops-automation` — [README](exercises/03-ecosystems/03-devops-automation/README.md): YAML/JSON, analiza logów, retry z backoffem
|
||||
- [ ] `04-aiops-structured-io` — [README](exercises/03-ecosystems/04-aiops-structured-io/README.md): walidacja JSON z API LLM przez `Pydantic`
|
||||
|
||||
---
|
||||
|
||||
## Notatki i Mapa Ekosystemu
|
||||
|
||||
* [Indeks notatek](notes/README.md)
|
||||
* [00 — Ściągawka Python 3.12](notes/00-cheatsheet.md)
|
||||
* [01 — Ekosystem Pythona i najważniejsze biblioteki (2026)](notes/01-python-ecosystem-2026.md)
|
||||
|
||||
## Nauka z asystentem AI (metoda sokratejska i era 2026)
|
||||
|
||||
Repozytorium zawiera plik [AGENTS.md](AGENTS.md), który konfiguruje agentów AI do pracy w **3 trybach**:
|
||||
* **Tryb Sokratejski (`01-core/`)** — stopniowane podpowiedzi zamiast gotowców + code review po przejściu testów.
|
||||
* **Tryb Specyfikacja → Audyt (`02-engineering-2026/`)** — nacisk na krytyczny przegląd kodu AI, typowanie i bezpieczeństwo.
|
||||
* **Tryb Architekta (`03-ecosystems/`)** — praktyka DevOps/SRE, FastAPI, CLI i AIOps.
|
||||
@@ -0,0 +1,12 @@
|
||||
# 01 — Podstawy (zmienne, warunki, pętle, funkcje)
|
||||
|
||||
## Zadania (`basics.py`)
|
||||
1. `celsius_to_fahrenheit(c: float) -> float` — przelicz temperaturę ($F = C \cdot 1.8 + 32$).
|
||||
2. `classify_score(score: int) -> str` — `0..49` -> `"fail"`, `50..74` -> `"pass"`, `75..89` -> `"good"`, `90..100` -> `"excellent"`, inaczej `"invalid"`.
|
||||
3. `sum_up_to(n: int) -> int` — suma liczb od `1` do `n` włącznie (dla `<= 0` zwróć `0`).
|
||||
4. `fizzbuzz_label(n: int) -> str` — `"Fizz"`, `"Buzz"`, `"FizzBuzz"` lub `str(n)`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=01-core/01-basics
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
def celsius_to_fahrenheit(c: float) -> float:
|
||||
raise NotImplementedError("Przelicz Celsjusze na Fahrenheity: c * 1.8 + 32.0")
|
||||
|
||||
|
||||
def classify_score(score: int) -> str:
|
||||
raise NotImplementedError("Sklasyfikuj wynik 0..100 lub zwróć 'invalid'")
|
||||
|
||||
|
||||
def sum_up_to(n: int) -> int:
|
||||
raise NotImplementedError("Zsumuj liczby od 1 do n włącznie")
|
||||
|
||||
|
||||
def fizzbuzz_label(n: int) -> str:
|
||||
raise NotImplementedError("Zwróć Fizz / Buzz / FizzBuzz lub str(n)")
|
||||
@@ -0,0 +1,30 @@
|
||||
import pytest
|
||||
from basics import celsius_to_fahrenheit, classify_score, fizzbuzz_label, sum_up_to
|
||||
|
||||
|
||||
def test_celsius_to_fahrenheit() -> None:
|
||||
assert celsius_to_fahrenheit(0.0) == pytest.approx(32.0)
|
||||
assert celsius_to_fahrenheit(100.0) == pytest.approx(212.0)
|
||||
assert celsius_to_fahrenheit(-40.0) == pytest.approx(-40.0)
|
||||
|
||||
|
||||
def test_classify_score() -> None:
|
||||
assert classify_score(0) == "fail"
|
||||
assert classify_score(50) == "pass"
|
||||
assert classify_score(80) == "good"
|
||||
assert classify_score(95) == "excellent"
|
||||
assert classify_score(101) == "invalid"
|
||||
assert classify_score(-1) == "invalid"
|
||||
|
||||
|
||||
def test_sum_up_to() -> None:
|
||||
assert sum_up_to(0) == 0
|
||||
assert sum_up_to(-5) == 0
|
||||
assert sum_up_to(10) == 55
|
||||
|
||||
|
||||
def test_fizzbuzz_label() -> None:
|
||||
assert fizzbuzz_label(1) == "1"
|
||||
assert fizzbuzz_label(3) == "Fizz"
|
||||
assert fizzbuzz_label(5) == "Buzz"
|
||||
assert fizzbuzz_label(15) == "FizzBuzz"
|
||||
@@ -0,0 +1,11 @@
|
||||
# 02 — Kolekcje (`list`, `tuple`, `dict`, `set`, slicing)
|
||||
|
||||
## Zadania (`collections_ex.py`)
|
||||
1. `unique_sorted(items: list[int]) -> list[int]` — usuń duplikaty i posortuj rosnąco.
|
||||
2. `word_counts(text: str) -> dict[str, int]` — policz wystąpienia słów (lowercase).
|
||||
3. `first_and_last(items: list[str]) -> tuple[str, str] | None` — zwróć pierwszy i ostatni element lub `None` dla pustej listy.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=01-core/02-collections
|
||||
```
|
||||
@@ -0,0 +1,10 @@
|
||||
def unique_sorted(items: list[int]) -> list[int]:
|
||||
raise NotImplementedError("Zwróć posortowaną listę unikalnych elementów")
|
||||
|
||||
|
||||
def word_counts(text: str) -> dict[str, int]:
|
||||
raise NotImplementedError("Policz wystąpienia słów (case-insensitive)")
|
||||
|
||||
|
||||
def first_and_last(items: list[str]) -> tuple[str, str] | None:
|
||||
raise NotImplementedError("Zwróć (pierwszy, ostatni) lub None dla pustej listy")
|
||||
@@ -0,0 +1,18 @@
|
||||
from collections_ex import first_and_last, unique_sorted, word_counts
|
||||
|
||||
|
||||
def test_unique_sorted() -> None:
|
||||
assert unique_sorted([3, 1, 2, 3, 1]) == [1, 2, 3]
|
||||
assert unique_sorted([]) == []
|
||||
|
||||
|
||||
def test_word_counts() -> None:
|
||||
counts = word_counts("Python python is great and PYTHON works")
|
||||
assert counts["python"] == 3
|
||||
assert counts["is"] == 1
|
||||
|
||||
|
||||
def test_first_and_last() -> None:
|
||||
assert first_and_last([]) is None
|
||||
assert first_and_last(["only"]) == ("only", "only")
|
||||
assert first_and_last(["a", "b", "c"]) == ("a", "c")
|
||||
@@ -0,0 +1,10 @@
|
||||
# 03 — Napisy i pliki (`f-string`, `pathlib.Path`, `with open`)
|
||||
|
||||
## Zadania (`strings_files.py`)
|
||||
1. `parse_key_value_lines(raw: str) -> dict[str, str]` — sparsuj linie `KEY=VALUE`, ignorując puste linie i komentarze `#`.
|
||||
2. `count_non_empty_lines(path: Path) -> int` — policz niepuste linie w pliku tekstowym (użyj `with path.open(...)` lub `read_text`).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=01-core/03-strings-files
|
||||
```
|
||||
@@ -0,0 +1,9 @@
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def parse_key_value_lines(raw: str) -> dict[str, str]:
|
||||
raise NotImplementedError("Sparsuj linie KEY=VALUE, pomiń puste i zaczynające się od '#'")
|
||||
|
||||
|
||||
def count_non_empty_lines(path: Path) -> int:
|
||||
raise NotImplementedError("Policz niepuste (po strip) linie w pliku")
|
||||
@@ -0,0 +1,24 @@
|
||||
from pathlib import Path
|
||||
|
||||
from strings_files import count_non_empty_lines, parse_key_value_lines
|
||||
|
||||
|
||||
def test_parse_key_value_lines() -> None:
|
||||
raw = """
|
||||
# konfiguracja
|
||||
HOST=127.0.0.1
|
||||
PORT = 8080
|
||||
|
||||
DEBUG=true
|
||||
"""
|
||||
assert parse_key_value_lines(raw) == {
|
||||
"HOST": "127.0.0.1",
|
||||
"PORT": "8080",
|
||||
"DEBUG": "true",
|
||||
}
|
||||
|
||||
|
||||
def test_count_non_empty_lines(tmp_path: Path) -> None:
|
||||
sample = tmp_path / "sample.txt"
|
||||
sample.write_text("line1\n\n \nline2\nline3\n", encoding="utf-8")
|
||||
assert count_non_empty_lines(sample) == 3
|
||||
@@ -0,0 +1,10 @@
|
||||
# 04 — Błędy i Wyjątki (`try`/`except`, własne wyjątki)
|
||||
|
||||
## Zadania (`errors_ex.py`)
|
||||
1. `parse_positive_int(raw: str) -> int` — rzuć `InvalidNumberError`, gdy nie da się sparsować do `int`, lub `NotPositiveError`, gdy `<= 0`.
|
||||
2. `safe_divide(a: float, b: float) -> float | None` — zwróć `None` zamiast `ZeroDivisionError`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=01-core/04-errors-exceptions
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
class InvalidNumberError(ValueError):
|
||||
"""Błąd parsowania liczby."""
|
||||
|
||||
|
||||
class NotPositiveError(ValueError):
|
||||
"""Liczba nie jest dodatnia."""
|
||||
|
||||
|
||||
def parse_positive_int(raw: str) -> int:
|
||||
raise NotImplementedError("Sparsuj raw do int lub rzuć InvalidNumberError / NotPositiveError")
|
||||
|
||||
|
||||
def safe_divide(a: float, b: float) -> float | None:
|
||||
raise NotImplementedError("Podziel a / b, zwracając None dla b == 0")
|
||||
@@ -0,0 +1,17 @@
|
||||
import pytest
|
||||
from errors_ex import InvalidNumberError, NotPositiveError, parse_positive_int, safe_divide
|
||||
|
||||
|
||||
def test_parse_positive_int() -> None:
|
||||
assert parse_positive_int("42") == 42
|
||||
with pytest.raises(NotPositiveError):
|
||||
parse_positive_int("0")
|
||||
with pytest.raises(NotPositiveError):
|
||||
parse_positive_int("-3")
|
||||
with pytest.raises(InvalidNumberError):
|
||||
parse_positive_int("abc")
|
||||
|
||||
|
||||
def test_safe_divide() -> None:
|
||||
assert safe_divide(10.0, 2.0) == 5.0
|
||||
assert safe_divide(10.0, 0.0) is None
|
||||
@@ -0,0 +1,11 @@
|
||||
# 05 — Comprehensions, Generatory i Styl Funkcyjny
|
||||
|
||||
## Zadania (`functional_ex.py`)
|
||||
1. `even_squares(nums: list[int]) -> list[int]` — kwadraty liczb parzystych przez list comprehension.
|
||||
2. `invert_dict(mapping: dict[str, int]) -> dict[int, str]` — odwrócenie słownika przez dict comprehension.
|
||||
3. `fibonacci_gen(limit: int) -> Iterator[int]` — generator zwracający `limit` pierwszych liczb Fibonacciego (`0, 1, 1, 2, 3, ...`).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=01-core/05-comprehensions-functional
|
||||
```
|
||||
@@ -0,0 +1,13 @@
|
||||
from collections.abc import Iterator
|
||||
|
||||
|
||||
def even_squares(nums: list[int]) -> list[int]:
|
||||
raise NotImplementedError("Zwróć listę kwadratów liczb parzystych")
|
||||
|
||||
|
||||
def invert_dict(mapping: dict[str, int]) -> dict[int, str]:
|
||||
raise NotImplementedError("Zamień klucze z wartościami w słowniku")
|
||||
|
||||
|
||||
def fibonacci_gen(limit: int) -> Iterator[int]:
|
||||
raise NotImplementedError("Wygeneruj limit liczb Fibonacciego używając yield")
|
||||
@@ -0,0 +1,14 @@
|
||||
from functional_ex import even_squares, fibonacci_gen, invert_dict
|
||||
|
||||
|
||||
def test_even_squares() -> None:
|
||||
assert even_squares([1, 2, 3, 4, 5]) == [4, 16]
|
||||
|
||||
|
||||
def test_invert_dict() -> None:
|
||||
assert invert_dict({"a": 1, "b": 2}) == {1: "a", 2: "b"}
|
||||
|
||||
|
||||
def test_fibonacci_gen() -> None:
|
||||
assert list(fibonacci_gen(0)) == []
|
||||
assert list(fibonacci_gen(6)) == [0, 1, 1, 2, 3, 5]
|
||||
@@ -0,0 +1,10 @@
|
||||
# 06 — Obiektowość, `@dataclass` i `Protocol`
|
||||
|
||||
## Zadania (`oop_ex.py`)
|
||||
1. `BankAccount` — enkapsulacja salda (`_balance`), metody `deposit`, `withdraw -> bool`, właściwość `balance`.
|
||||
2. `Notifier` (`Protocol`) + `EmailNotifier`, `SmsNotifier` + `AlertService` (kompozycja).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=01-core/06-oop-dataclasses
|
||||
```
|
||||
@@ -0,0 +1,45 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
class BankAccount:
|
||||
def __init__(self, initial_balance: int = 0) -> None:
|
||||
self._balance = initial_balance
|
||||
|
||||
@property
|
||||
def balance(self) -> int:
|
||||
return self._balance
|
||||
|
||||
def deposit(self, amount: int) -> None:
|
||||
raise NotImplementedError("Dodaj amount do _balance (odrzuć <= 0 przez ValueError)")
|
||||
|
||||
def withdraw(self, amount: int) -> bool:
|
||||
raise NotImplementedError("Wypłać jeśli _balance >= amount i zwróć True, inaczej False")
|
||||
|
||||
|
||||
class Notifier(Protocol):
|
||||
def format_message(self, msg: str) -> str: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EmailNotifier:
|
||||
address: str
|
||||
|
||||
def format_message(self, msg: str) -> str:
|
||||
raise NotImplementedError("Zwróć '[email] <msg>'")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SmsNotifier:
|
||||
phone: str
|
||||
|
||||
def format_message(self, msg: str) -> str:
|
||||
raise NotImplementedError("Zwróć '[sms] <msg>'")
|
||||
|
||||
|
||||
class AlertService:
|
||||
def __init__(self, notifiers: list[Notifier]) -> None:
|
||||
self._notifiers = notifiers
|
||||
|
||||
def broadcast(self, msg: str) -> list[str]:
|
||||
raise NotImplementedError("Wywołaj format_message(msg) dla każdego notifiera")
|
||||
@@ -0,0 +1,16 @@
|
||||
from oop_ex import AlertService, BankAccount, EmailNotifier, SmsNotifier
|
||||
|
||||
|
||||
def test_bank_account() -> None:
|
||||
acc = BankAccount(100)
|
||||
acc.deposit(50)
|
||||
assert acc.balance == 150
|
||||
assert acc.withdraw(40) is True
|
||||
assert acc.balance == 110
|
||||
assert acc.withdraw(500) is False
|
||||
assert acc.balance == 110
|
||||
|
||||
|
||||
def test_alert_service_protocol_composition() -> None:
|
||||
svc = AlertService([EmailNotifier("ops@example.com"), SmsNotifier("+48123456789")])
|
||||
assert svc.broadcast("CPU 95%") == ["[email] CPU 95%", "[sms] CPU 95%"]
|
||||
@@ -0,0 +1,10 @@
|
||||
# 07 — Nowoczesne Typowanie (`Enum`, `TypedDict`, `mypy`)
|
||||
|
||||
## Zadania (`typing_ex.py`)
|
||||
1. `parse_severity(raw: str) -> Severity` — zamień tekst (`"info"`, `"warn"`, `"error"`, case-insensitive) na `Severity` Enum (lub rzuć `ValueError`).
|
||||
2. `summarize_incident(incident: IncidentRecord) -> str` — sformatuj `"[<SEVERITY>] <service>: <message>"`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=01-core/07-typing-contracts
|
||||
```
|
||||
@@ -0,0 +1,18 @@
|
||||
import pytest
|
||||
from typing_ex import IncidentRecord, Severity, parse_severity, summarize_incident
|
||||
|
||||
|
||||
def test_parse_severity() -> None:
|
||||
assert parse_severity("warn") is Severity.WARN
|
||||
assert parse_severity("ERROR") is Severity.ERROR
|
||||
with pytest.raises(ValueError):
|
||||
parse_severity("fatal")
|
||||
|
||||
|
||||
def test_summarize_incident() -> None:
|
||||
rec: IncidentRecord = {
|
||||
"service": "ingress",
|
||||
"severity": Severity.ERROR,
|
||||
"message": "502 Bad Gateway",
|
||||
}
|
||||
assert summarize_incident(rec) == "[ERROR] ingress: 502 Bad Gateway"
|
||||
@@ -0,0 +1,22 @@
|
||||
from enum import Enum
|
||||
from typing import TypedDict
|
||||
|
||||
|
||||
class Severity(Enum):
|
||||
INFO = "INFO"
|
||||
WARN = "WARN"
|
||||
ERROR = "ERROR"
|
||||
|
||||
|
||||
class IncidentRecord(TypedDict):
|
||||
service: str
|
||||
severity: Severity
|
||||
message: str
|
||||
|
||||
|
||||
def parse_severity(raw: str) -> Severity:
|
||||
raise NotImplementedError("Zmapuj tekst case-insensitive na Severity lub rzuć ValueError")
|
||||
|
||||
|
||||
def summarize_incident(incident: IncidentRecord) -> str:
|
||||
raise NotImplementedError("Zwróć '[<SEVERITY>] <service>: <message>'")
|
||||
@@ -0,0 +1,11 @@
|
||||
# 08 — Struktury Danych (`Stack`, `Queue`, `Counter`, `defaultdict`)
|
||||
|
||||
## Zadania (`ds_ex.py`)
|
||||
1. `Stack[T]` — generyczny stos (`push`, `pop`, `peek`, `is_empty`).
|
||||
2. `Queue[T]` — generyczna kolejka na `collections.deque` (`enqueue`, `dequeue`, `__len__`).
|
||||
3. `top_k_frequent(items: list[str], k: int) -> list[str]` — zwróć `k` najczęstszych elementów używając `Counter`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=01-core/08-data-structures
|
||||
```
|
||||
@@ -0,0 +1,37 @@
|
||||
from collections import Counter, deque
|
||||
|
||||
|
||||
class Stack[T]:
|
||||
def __init__(self) -> None:
|
||||
self._items: list[T] = []
|
||||
|
||||
def push(self, value: T) -> None:
|
||||
raise NotImplementedError("Dodaj element na wierzch stosu")
|
||||
|
||||
def pop(self) -> T | None:
|
||||
raise NotImplementedError("Zdejmij element lub zwróć None gdy pusty")
|
||||
|
||||
def peek(self) -> T | None:
|
||||
raise NotImplementedError("Podgląd wierzchu stosu bez zdejmowania")
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
raise NotImplementedError("Zwróć True jeśli stos jest pusty")
|
||||
|
||||
|
||||
class Queue[T]:
|
||||
def __init__(self) -> None:
|
||||
self._items: deque[T] = deque()
|
||||
|
||||
def enqueue(self, value: T) -> None:
|
||||
raise NotImplementedError("Dodaj na koniec kolejki")
|
||||
|
||||
def dequeue(self) -> T | None:
|
||||
raise NotImplementedError("Zdejmij z początku kolejki lub zwróć None")
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self._items)
|
||||
|
||||
|
||||
def top_k_frequent(items: list[str], k: int) -> list[str]:
|
||||
_ = Counter
|
||||
raise NotImplementedError("Zwróć k najczęstszych elementów używając Counter.most_common(k)")
|
||||
@@ -0,0 +1,26 @@
|
||||
from ds_ex import Queue, Stack, top_k_frequent
|
||||
|
||||
|
||||
def test_stack() -> None:
|
||||
s: Stack[int] = Stack()
|
||||
assert s.is_empty()
|
||||
s.push(1)
|
||||
s.push(2)
|
||||
assert s.peek() == 2
|
||||
assert s.pop() == 2
|
||||
assert s.pop() == 1
|
||||
assert s.pop() is None
|
||||
|
||||
|
||||
def test_queue() -> None:
|
||||
q: Queue[str] = Queue()
|
||||
q.enqueue("a")
|
||||
q.enqueue("b")
|
||||
assert len(q) == 2
|
||||
assert q.dequeue() == "a"
|
||||
assert q.dequeue() == "b"
|
||||
assert q.dequeue() is None
|
||||
|
||||
|
||||
def test_top_k_frequent() -> None:
|
||||
assert top_k_frequent(["pod", "svc", "pod", "ing", "pod", "svc"], 2) == ["pod", "svc"]
|
||||
@@ -0,0 +1,10 @@
|
||||
# 09 — Wzorce Projektowe w Pythonie (Strategy, Context Manager, DI)
|
||||
|
||||
## Zadania (`patterns_ex.py`)
|
||||
1. `apply_discount(price_cents: int, strategy: Callable[[int], int]) -> int` — wzorzec Strategy (w Pythonie funkcje są obiektami pierwszej klasy).
|
||||
2. `ManagedFlag` — Context Manager (`__enter__` ustawia `active = True`, `__exit__` zawsze przywraca `active = False`, nawet przy wyjątku).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=01-core/09-design-patterns
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
from collections.abc import Callable
|
||||
from types import TracebackType
|
||||
|
||||
|
||||
def percentage_discount(percent: int) -> Callable[[int], int]:
|
||||
raise NotImplementedError("Zwróć funkcję obliczającą cenę po rabacie percent%")
|
||||
|
||||
|
||||
def apply_discount(price_cents: int, strategy: Callable[[int], int]) -> int:
|
||||
raise NotImplementedError("Zastosuj strategy do price_cents (nie zwracaj wartości < 0)")
|
||||
|
||||
|
||||
class ManagedFlag:
|
||||
def __init__(self) -> None:
|
||||
self.active: bool = False
|
||||
|
||||
def __enter__(self) -> "ManagedFlag":
|
||||
raise NotImplementedError("Ustaw self.active = True i zwróć self")
|
||||
|
||||
def __exit__(
|
||||
self,
|
||||
exc_type: type[BaseException] | None,
|
||||
exc_val: BaseException | None,
|
||||
exc_tb: TracebackType | None,
|
||||
) -> None:
|
||||
raise NotImplementedError("Ustaw self.active = False")
|
||||
@@ -0,0 +1,16 @@
|
||||
import pytest
|
||||
from patterns_ex import ManagedFlag, apply_discount, percentage_discount
|
||||
|
||||
|
||||
def test_strategy_discount() -> None:
|
||||
discount_20 = percentage_discount(20)
|
||||
assert apply_discount(1000, discount_20) == 800
|
||||
|
||||
|
||||
def test_context_manager_cleans_up_even_on_error() -> None:
|
||||
flag = ManagedFlag()
|
||||
assert flag.active is False
|
||||
with pytest.raises(RuntimeError), flag as entered:
|
||||
assert entered.active is True
|
||||
raise RuntimeError("boom")
|
||||
assert flag.active is False
|
||||
@@ -0,0 +1,9 @@
|
||||
# 10 — CRUD w pamięci (`TaskStore`)
|
||||
|
||||
## Zadania (`crud_ex.py`)
|
||||
Zaimplementuj pełny CRUD w `TaskStore`: `create`, `get`, `list_all`, `update_title`, `mark_done`, `delete` z wyjątkami `InvalidTitleError` i `TaskNotFoundError`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=01-core/10-crud-repository
|
||||
```
|
||||
@@ -0,0 +1,42 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
class InvalidTitleError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class TaskNotFoundError(KeyError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Task:
|
||||
id: int
|
||||
title: str
|
||||
done: bool = False
|
||||
|
||||
|
||||
class TaskStore:
|
||||
def __init__(self) -> None:
|
||||
self._next_id = 1
|
||||
self._tasks: dict[int, Task] = {}
|
||||
|
||||
def create(self, title: str) -> Task:
|
||||
raise NotImplementedError("Zwaliduj tytuł, utwórz Task z auto-ID i zapisz")
|
||||
|
||||
def get(self, task_id: int) -> Task | None:
|
||||
raise NotImplementedError("Zwróć Task lub None")
|
||||
|
||||
def list_all(self) -> list[Task]:
|
||||
raise NotImplementedError("Zwróć wszystkie zadania posortowane po id")
|
||||
|
||||
def update_title(self, task_id: int, title: str) -> Task:
|
||||
raise NotImplementedError(
|
||||
"Zaktualizuj tytuł lub rzuć InvalidTitleError / TaskNotFoundError"
|
||||
)
|
||||
|
||||
def mark_done(self, task_id: int) -> Task:
|
||||
raise NotImplementedError("Ustaw done=True lub rzuć TaskNotFoundError")
|
||||
|
||||
def delete(self, task_id: int) -> Task:
|
||||
raise NotImplementedError("Usuń i zwróć zadanie lub rzuć TaskNotFoundError")
|
||||
@@ -0,0 +1,23 @@
|
||||
import pytest
|
||||
from crud_ex import InvalidTitleError, TaskNotFoundError, TaskStore
|
||||
|
||||
|
||||
def test_crud_lifecycle() -> None:
|
||||
store = TaskStore()
|
||||
with pytest.raises(InvalidTitleError):
|
||||
store.create(" ")
|
||||
|
||||
t1 = store.create("Learn Python")
|
||||
t2 = store.create("Automate K8s")
|
||||
assert t1.id == 1
|
||||
assert t2.id == 2
|
||||
assert len(store.list_all()) == 2
|
||||
|
||||
updated = store.update_title(1, "Master Python")
|
||||
assert updated.title == "Master Python"
|
||||
assert store.mark_done(1).done is True
|
||||
|
||||
deleted = store.delete(2)
|
||||
assert deleted.id == 2
|
||||
with pytest.raises(TaskNotFoundError):
|
||||
store.delete(2)
|
||||
@@ -0,0 +1,14 @@
|
||||
# 01 — Audyt i Refaktoryzacja Kodu AI (AI-Era Drill)
|
||||
|
||||
W `ai_audit.py` znajdziesz typowe pułapki Pythona często generowane przez AI:
|
||||
* mutowalny argument domyślny (`def add_tag(tag, tags=[])`),
|
||||
* dzielenie przez zero w średniej dla pustej listy,
|
||||
* brak walidacji nagłówka `Authorization: Bearer <token>`.
|
||||
|
||||
## Twoje zadanie
|
||||
Znajdź i napraw błędy w `ai_audit.py`, aż wszystkie testy przejdą, a `make check` nie zgłosi uwag.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=02-engineering-2026/01-ai-code-audit
|
||||
```
|
||||
@@ -0,0 +1,18 @@
|
||||
# ruff: noqa: B006
|
||||
"""Celowo wadliwy kod w stylu 'szybkiego draftu z AI'. Audytuj i napraw!"""
|
||||
|
||||
|
||||
def add_tag(tag: str, tags: list[str] = []) -> list[str]:
|
||||
# BUG: mutowalny argument domyślny współdzielony między wywołaniami!
|
||||
tags.append(tag)
|
||||
return tags
|
||||
|
||||
|
||||
def average(values: list[float]) -> float | None:
|
||||
# BUG: ZeroDivisionError dla pustej listy
|
||||
return sum(values) / len(values)
|
||||
|
||||
|
||||
def extract_bearer_token(auth_header: str) -> str | None:
|
||||
# BUG: IndexError bez spacji, nie sprawdza prefiksu "Bearer ", przepuszcza pusty token
|
||||
return auth_header.split(" ")[1]
|
||||
@@ -0,0 +1,21 @@
|
||||
from ai_audit import add_tag, average, extract_bearer_token
|
||||
|
||||
|
||||
def test_add_tag_does_not_leak_state_across_calls() -> None:
|
||||
first = add_tag("prod")
|
||||
second = add_tag("staging")
|
||||
assert first == ["prod"]
|
||||
assert second == ["staging"]
|
||||
|
||||
|
||||
def test_average_handles_empty_list() -> None:
|
||||
assert average([]) is None
|
||||
assert average([10.0, 20.0]) == 15.0
|
||||
|
||||
|
||||
def test_extract_bearer_token() -> None:
|
||||
assert extract_bearer_token("Bearer secret123") == "secret123"
|
||||
assert extract_bearer_token("Bearer ") is None
|
||||
assert extract_bearer_token("Basic abc") is None
|
||||
assert extract_bearer_token("Malformed") is None
|
||||
assert extract_bearer_token("") is None
|
||||
@@ -0,0 +1,10 @@
|
||||
# 02 — Type-Driven Design (`dataclass(frozen=True)`, walidacja w konstruktorze)
|
||||
|
||||
## Zadania (`tdd_types.py`)
|
||||
1. `Email.parse(raw: str) -> Email` — niemutowalny obiekt walidujący format i normalizujący do lowercase.
|
||||
2. `Money.add(other: Money) -> Money` — dodawanie kwot w groszach/centach z kontrolą zgodności waluty (`CurrencyMismatchError`).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=02-engineering-2026/02-type-driven-design
|
||||
```
|
||||
@@ -0,0 +1,30 @@
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Currency(Enum):
|
||||
PLN = "PLN"
|
||||
EUR = "EUR"
|
||||
USD = "USD"
|
||||
|
||||
|
||||
class CurrencyMismatchError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Email:
|
||||
value: str
|
||||
|
||||
@classmethod
|
||||
def parse(cls, raw: str) -> "Email":
|
||||
raise NotImplementedError("Zwaliduj email (brak spacji, jedna '@', niepuste części)")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Money:
|
||||
cents: int
|
||||
currency: Currency
|
||||
|
||||
def add(self, other: "Money") -> "Money":
|
||||
raise NotImplementedError("Dodaj kwoty dla tej samej waluty lub rzuć CurrencyMismatchError")
|
||||
@@ -0,0 +1,18 @@
|
||||
import pytest
|
||||
from tdd_types import Currency, CurrencyMismatchError, Email, Money
|
||||
|
||||
|
||||
def test_email_parse() -> None:
|
||||
email = Email.parse("Ops@Example.COM")
|
||||
assert email.value == "ops@example.com"
|
||||
for bad in ["no-at", "@example.com", "user@", "a b@c.com"]:
|
||||
with pytest.raises(ValueError):
|
||||
Email.parse(bad)
|
||||
|
||||
|
||||
def test_money_add() -> None:
|
||||
a = Money(500, Currency.PLN)
|
||||
b = Money(250, Currency.PLN)
|
||||
assert a.add(b) == Money(750, Currency.PLN)
|
||||
with pytest.raises(CurrencyMismatchError):
|
||||
a.add(Money(100, Currency.EUR))
|
||||
@@ -0,0 +1,11 @@
|
||||
# 03 — Cross-Platform OS (`pathlib`, bezpieczny `subprocess`, JSON logi)
|
||||
|
||||
## Zadania (`cross_os.py`)
|
||||
1. `config_path(base_dir: Path, app_name: str) -> Path` — przenośna ścieżka `<base_dir>/<app_name>/config.yaml`.
|
||||
2. `run_echo_safely(message: str) -> str` — uruchom komendę `[sys.executable, "-c", "import sys; print(sys.argv[1])", message]` używając `subprocess.run(..., shell=False, capture_output=True, text=True, check=True, timeout=5)`.
|
||||
3. `format_json_log(level: str, event: str, **fields: object) -> str` — zwróć jedną linię JSON z kluczami `level`, `event` oraz dodatkowymi polami.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=02-engineering-2026/03-cross-platform-os
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def config_path(base_dir: Path, app_name: str) -> Path:
|
||||
raise NotImplementedError("Zwróć base_dir / app_name / 'config.yaml'")
|
||||
|
||||
|
||||
def run_echo_safely(message: str) -> str:
|
||||
_ = (subprocess, sys)
|
||||
raise NotImplementedError(
|
||||
"Uruchom bezpieczny subprocess (shell=False, timeout=5) i zwróć stdout.strip()"
|
||||
)
|
||||
|
||||
|
||||
def format_json_log(level: str, event: str, **fields: object) -> str:
|
||||
_ = json
|
||||
raise NotImplementedError("Zwróć JSON zawierający level, event oraz **fields")
|
||||
@@ -0,0 +1,20 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from cross_os import config_path, format_json_log, run_echo_safely
|
||||
|
||||
|
||||
def test_config_path() -> None:
|
||||
base = Path("home") / "ops"
|
||||
assert config_path(base, "monitor") == base / "monitor" / "config.yaml"
|
||||
|
||||
|
||||
def test_run_echo_safely_blocks_shell_metacharacters() -> None:
|
||||
payload = "hello; echo INJECTED"
|
||||
assert run_echo_safely(payload) == payload
|
||||
|
||||
|
||||
def test_format_json_log() -> None:
|
||||
line = format_json_log("INFO", "deploy_done", env="prod", replicas=3)
|
||||
parsed = json.loads(line)
|
||||
assert parsed == {"level": "INFO", "event": "deploy_done", "env": "prod", "replicas": 3}
|
||||
@@ -0,0 +1,12 @@
|
||||
# 04 — Dobre Praktyki Testowania (`pytest`, In-Memory Fakes)
|
||||
|
||||
Zamiast kruchych mocków (`MagicMock`), w testach jednostkowych stosuj czyste **In-Memory Fakes** implementujące ten sam kontrakt (`Protocol`).
|
||||
|
||||
## Zadania (`testing_ex.py`)
|
||||
1. Zaimplementuj `InMemoryKvStore` spełniający `KvStore`.
|
||||
2. Zaimplementuj `FeatureFlagService.is_enabled(flag: str) -> bool` (zwraca `True`, jeśli wartość w store to `"true"` lub `"1"`, case-insensitive).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=02-engineering-2026/04-testing-best-practices
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
import pytest
|
||||
from testing_ex import FeatureFlagService, InMemoryKvStore
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("raw_value", "expected"),
|
||||
[("true", True), ("TRUE", True), ("1", True), ("false", False), ("0", False), (None, False)],
|
||||
)
|
||||
def test_feature_flag_service_with_in_memory_fake(raw_value: str | None, expected: bool) -> None:
|
||||
store = InMemoryKvStore()
|
||||
if raw_value is not None:
|
||||
store.set("new_ui", raw_value)
|
||||
svc = FeatureFlagService(store)
|
||||
assert svc.is_enabled("new_ui") is expected
|
||||
@@ -0,0 +1,25 @@
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
class KvStore(Protocol):
|
||||
def get(self, key: str) -> str | None: ...
|
||||
def set(self, key: str, value: str) -> None: ...
|
||||
|
||||
|
||||
class InMemoryKvStore:
|
||||
def __init__(self) -> None:
|
||||
self._data: dict[str, str] = {}
|
||||
|
||||
def get(self, key: str) -> str | None:
|
||||
raise NotImplementedError("Pobierz wartość lub None")
|
||||
|
||||
def set(self, key: str, value: str) -> None:
|
||||
raise NotImplementedError("Zapisz wartość w słowniku")
|
||||
|
||||
|
||||
class FeatureFlagService:
|
||||
def __init__(self, store: KvStore) -> None:
|
||||
self._store = store
|
||||
|
||||
def is_enabled(self, flag: str) -> bool:
|
||||
raise NotImplementedError("Zwróć True jeśli wartość flagi to 'true' lub '1' (lowercase)")
|
||||
@@ -0,0 +1,13 @@
|
||||
# 01 — Parsowanie argumentów CLI z `typer`
|
||||
|
||||
`typer` buduje narzędzia CLI na podstawie zwykłych adnotacji typów Pythona (automatyczny `--help`, walidacja, podkomendy, kody wyjścia).
|
||||
|
||||
## Zadania (`cli_typer.py`)
|
||||
Zaimplementuj podkomendy aplikacji `app`:
|
||||
1. `add(title: str, priority: int = 3)` — wypisz `add:<title>:p<priority>`.
|
||||
2. `done(task_id: int)` — wypisz `done:<task_id>`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=03-ecosystems/01-cli-typer
|
||||
```
|
||||
@@ -0,0 +1,13 @@
|
||||
import typer
|
||||
|
||||
app = typer.Typer(help="Mini CLI do nauki Typer")
|
||||
|
||||
|
||||
@app.command()
|
||||
def add(title: str, priority: int = typer.Option(3, "--priority", "-p")) -> None:
|
||||
raise NotImplementedError("Wypisz przez typer.echo(f'add:{title}:p{priority}')")
|
||||
|
||||
|
||||
@app.command()
|
||||
def done(task_id: int) -> None:
|
||||
raise NotImplementedError("Wypisz przez typer.echo(f'done:{task_id}')")
|
||||
@@ -0,0 +1,19 @@
|
||||
from cli_typer import app
|
||||
from typer.testing import CliRunner
|
||||
|
||||
runner = CliRunner()
|
||||
|
||||
|
||||
def test_cli_add_and_done() -> None:
|
||||
res = runner.invoke(app, ["add", "Check pods", "-p", "1"])
|
||||
assert res.exit_code == 0
|
||||
assert res.stdout.strip() == "add:Check pods:p1"
|
||||
|
||||
res_done = runner.invoke(app, ["done", "42"])
|
||||
assert res_done.exit_code == 0
|
||||
assert res_done.stdout.strip() == "done:42"
|
||||
|
||||
|
||||
def test_cli_rejects_bad_int() -> None:
|
||||
res = runner.invoke(app, ["done", "not-an-int"])
|
||||
assert res.exit_code != 0
|
||||
@@ -0,0 +1,10 @@
|
||||
# 02 — Web API z `FastAPI` + `Pydantic`
|
||||
|
||||
## Zadania (`api_fastapi.py`)
|
||||
1. `GET /health` -> `{"status": "ok"}`.
|
||||
2. `POST /echo` -> przyjmuje `EchoRequest(message: str)`; odrzuca pusty napis (po `strip()`) kodem `400`, w przeciwnym razie zwraca `EchoResponse(echoed=..., length=...)`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=03-ecosystems/02-web-api-fastapi
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI(title="Python Learning API")
|
||||
|
||||
|
||||
class EchoRequest(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
class EchoResponse(BaseModel):
|
||||
echoed: str
|
||||
length: int
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health() -> dict[str, str]:
|
||||
raise NotImplementedError("Zwróć {'status': 'ok'}")
|
||||
|
||||
|
||||
@app.post("/echo", response_model=EchoResponse)
|
||||
def echo(payload: EchoRequest) -> EchoResponse:
|
||||
_ = HTTPException
|
||||
raise NotImplementedError(
|
||||
"Odrzuć pusty payload.message przez HTTPException(400), inaczej zwróć EchoResponse"
|
||||
)
|
||||
@@ -0,0 +1,19 @@
|
||||
from api_fastapi import app
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_health() -> None:
|
||||
resp = client.get("/health")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == {"status": "ok"}
|
||||
|
||||
|
||||
def test_echo_validation() -> None:
|
||||
ok = client.post("/echo", json={"message": "devops"})
|
||||
assert ok.status_code == 200
|
||||
assert ok.json() == {"echoed": "devops", "length": 6}
|
||||
|
||||
bad = client.post("/echo", json={"message": " "})
|
||||
assert bad.status_code == 400
|
||||
@@ -0,0 +1,11 @@
|
||||
# 03 — Automatyzacja DevOps/SRE (YAML, analiza logów, retry)
|
||||
|
||||
## Zadania (`devops_ops.py`)
|
||||
1. `extract_k8s_images(manifest_yaml: str) -> list[str]` — wyciągnij nazwy obrazów (`image`) z kontenerów w manifeście Deployment YAML (`yaml.safe_load`).
|
||||
2. `count_error_lines(log_text: str) -> int` — policz linie zawierające poziom `ERROR` lub `CRITICAL`.
|
||||
3. `retry_call(fn: Callable[[], T], attempts: int) -> T` — ponawiaj wywołanie do `attempts` razy przy wyjątku `RuntimeError`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=03-ecosystems/03-devops-automation
|
||||
```
|
||||
@@ -0,0 +1,18 @@
|
||||
from collections.abc import Callable
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
def extract_k8s_images(manifest_yaml: str) -> list[str]:
|
||||
_ = yaml
|
||||
raise NotImplementedError(
|
||||
"Użyj yaml.safe_load i wyciągnij image z spec.template.spec.containers"
|
||||
)
|
||||
|
||||
|
||||
def count_error_lines(log_text: str) -> int:
|
||||
raise NotImplementedError("Policz linie zawierające 'ERROR' lub 'CRITICAL'")
|
||||
|
||||
|
||||
def retry_call[T](fn: Callable[[], T], attempts: int) -> T:
|
||||
raise NotImplementedError("Wywołuj fn() do attempts razy przy RuntimeError")
|
||||
@@ -0,0 +1,46 @@
|
||||
import pytest
|
||||
from devops_ops import count_error_lines, extract_k8s_images, retry_call
|
||||
|
||||
SAMPLE_DEPLOYMENT = """
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: web
|
||||
spec:
|
||||
template:
|
||||
spec:
|
||||
containers:
|
||||
- name: app
|
||||
image: ghcr.io/org/web:1.2.0
|
||||
- name: sidecar
|
||||
image: envoyproxy/envoy:v1.31
|
||||
"""
|
||||
|
||||
|
||||
def test_extract_k8s_images() -> None:
|
||||
assert extract_k8s_images(SAMPLE_DEPLOYMENT) == [
|
||||
"ghcr.io/org/web:1.2.0",
|
||||
"envoyproxy/envoy:v1.31",
|
||||
]
|
||||
|
||||
|
||||
def test_count_error_lines() -> None:
|
||||
logs = "INFO start\nWARN retry\nERROR db timeout\nCRITICAL oom\n"
|
||||
assert count_error_lines(logs) == 2
|
||||
|
||||
|
||||
def test_retry_call() -> None:
|
||||
calls = 0
|
||||
|
||||
def flaky() -> str:
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls < 3:
|
||||
raise RuntimeError("transient")
|
||||
return "ok"
|
||||
|
||||
assert retry_call(flaky, attempts=3) == "ok"
|
||||
assert calls == 3
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
retry_call(lambda: (_ for _ in ()).throw(RuntimeError("always")), attempts=2)
|
||||
@@ -0,0 +1,11 @@
|
||||
# 04 — AIOps & Structured Output (`Pydantic` walidacja odpowiedzi LLM)
|
||||
|
||||
W produkcyjnym AIOps nigdy nie ufasz surowemu tekstowi z modelu AI — wymuszasz **ustrukturyzowany JSON** i walidujesz go schematem `Pydantic` przed podjęciem jakiejkolwiek akcji operacyjnej.
|
||||
|
||||
## Zadania (`aiops_io.py`)
|
||||
1. `parse_triage_result(raw_json: str) -> TriageResult` — sparsuj i zwaliduj JSON modelem `TriageResult` (odrzuć nieznane `severity` lub `confidence` spoza `0.0..1.0`).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test MOD=03-ecosystems/04-aiops-structured-io
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class TriageResult(BaseModel):
|
||||
service: str = Field(min_length=1)
|
||||
severity: Literal["low", "medium", "high", "critical"]
|
||||
confidence: float = Field(ge=0.0, le=1.0)
|
||||
recommended_action: str = Field(min_length=1)
|
||||
|
||||
|
||||
def parse_triage_result(raw_json: str) -> TriageResult:
|
||||
raise NotImplementedError("Użyj TriageResult.model_validate_json(raw_json)")
|
||||
@@ -0,0 +1,28 @@
|
||||
import pytest
|
||||
from aiops_io import TriageResult, parse_triage_result
|
||||
from pydantic import ValidationError
|
||||
|
||||
|
||||
def test_parse_valid_triage_json() -> None:
|
||||
raw = (
|
||||
'{"service":"payments","severity":"high",'
|
||||
'"confidence":0.92,"recommended_action":"scale replicas to 4"}'
|
||||
)
|
||||
res = parse_triage_result(raw)
|
||||
assert isinstance(res, TriageResult)
|
||||
assert res.service == "payments"
|
||||
assert res.severity == "high"
|
||||
|
||||
|
||||
def test_rejects_invalid_llm_output() -> None:
|
||||
bad_confidence = (
|
||||
'{"service":"payments","severity":"high","confidence":1.5,"recommended_action":"restart"}'
|
||||
)
|
||||
with pytest.raises(ValidationError):
|
||||
parse_triage_result(bad_confidence)
|
||||
|
||||
bad_severity = (
|
||||
'{"service":"payments","severity":"urgent","confidence":0.5,"recommended_action":"restart"}'
|
||||
)
|
||||
with pytest.raises(ValidationError):
|
||||
parse_triage_result(bad_severity)
|
||||
@@ -0,0 +1,19 @@
|
||||
# Ściągawka Python 3.12
|
||||
|
||||
## Podstawowe struktury danych
|
||||
* `list`: `[1, 2, 3]` — mutowalna sekwencja
|
||||
* `tuple`: `(1, 2)` — niemutowalna krotka
|
||||
* `dict`: `{"key": "val"}` — słownik klucz → wartość (`d.get("k", default)`)
|
||||
* `set`: `{"a", "b"}` — zbiór unikalnych elementów
|
||||
|
||||
## Złote zasady w nowoczesnym Pythonie (2026)
|
||||
* Zawsze pisz adnotacje typów (`def parse(raw: str) -> int | None:`).
|
||||
* Nigdy nie używaj mutowalnych wartości domyślnych (`def f(items: list[str] | None = None):`).
|
||||
* Do ścieżek plików zawsze używaj `pathlib.Path`, nigdy sklejania stringów z `/`.
|
||||
* Do zasobów (pliki, połączenia) zawsze używaj `with` (context manager).
|
||||
* Nigdy nie łap gołego `except:` — łap konkretne wyjątki (`except ValueError:`).
|
||||
|
||||
## Komendy `make`
|
||||
* `make check` — `ruff check` + `mypy`
|
||||
* `make test MOD=01-core/01-basics` — testy jednego rozdziału
|
||||
* `make fmt` — formatowanie `ruff format`
|
||||
@@ -0,0 +1,14 @@
|
||||
# Ekosystem Pythona i najważniejsze biblioteki (2026)
|
||||
|
||||
| Obszar | Standard (2026) | Do czego służy |
|
||||
| :--- | :--- | :--- |
|
||||
| **Pakiety i środowiska** | `uv` | Błyskawiczny menedżer środowisk i zależności (napisany w Ruście, zastąpił `pip`/`poetry`). |
|
||||
| **Linting i formatowanie** | `ruff` | Jedno narzędzie zamiast `flake8` + `black` + `isort`. |
|
||||
| **Kontrola typów** | `mypy` / `pyright` | Statyczna weryfikacja adnotacji typów przed uruchomieniem. |
|
||||
| **Testy** | `pytest` | Standard testowania jednostkowego i integracyjnego. |
|
||||
| **Walidacja danych / schematy** | `pydantic` v2 | Walidacja JSON, konfiguracji (`pydantic-settings`) i odpowiedzi z API / LLM. |
|
||||
| **Web API (Backend)** | `FastAPI` + `uvicorn` | Nowoczesne REST API z automatycznym OpenAPI i walidacją Pydantic. |
|
||||
| **CLI** | `typer` / `click` / `argparse` | Budowa narzędzi wiersza poleceń z podkomendami i `--help`. |
|
||||
| **Klient HTTP** | `httpx` | Nowoczesny następca `requests` (obsługuje sync i `async`, HTTP/2, timeouty). |
|
||||
| **DevOps / Cloud** | `boto3`, `kubernetes`, `pyyaml`, `ansible` | Automatyzacja AWS, K8s, konfiguracji YAML i serwerów. |
|
||||
| **Dane i AIOps** | `polars`, `google-genai`, `openai` | Szybka analiza danych/logów i integracja z modelami AI. |
|
||||
@@ -0,0 +1,4 @@
|
||||
# Notatki z nauki Pythona
|
||||
|
||||
* [00 — Ściągawka Python 3.12](00-cheatsheet.md)
|
||||
* [01 — Ekosystem Pythona i najważniejsze biblioteki (2026)](01-python-ecosystem-2026.md)
|
||||
@@ -0,0 +1,61 @@
|
||||
[project]
|
||||
name = "python-learning"
|
||||
version = "0.1.0"
|
||||
description = "Containerized Python learning workbook for DevOps/SRE (2026 Edition)"
|
||||
requires-python = ">=3.12"
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.12"
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
disallow_untyped_defs = true
|
||||
explicit_package_bases = true
|
||||
mypy_path = [
|
||||
"exercises/01-core/01-basics",
|
||||
"exercises/01-core/02-collections",
|
||||
"exercises/01-core/03-strings-files",
|
||||
"exercises/01-core/04-errors-exceptions",
|
||||
"exercises/01-core/05-comprehensions-functional",
|
||||
"exercises/01-core/06-oop-dataclasses",
|
||||
"exercises/01-core/07-typing-contracts",
|
||||
"exercises/01-core/08-data-structures",
|
||||
"exercises/01-core/09-design-patterns",
|
||||
"exercises/01-core/10-crud-repository",
|
||||
"exercises/02-engineering-2026/01-ai-code-audit",
|
||||
"exercises/02-engineering-2026/02-type-driven-design",
|
||||
"exercises/02-engineering-2026/03-cross-platform-os",
|
||||
"exercises/02-engineering-2026/04-testing-best-practices",
|
||||
"exercises/03-ecosystems/01-cli-typer",
|
||||
"exercises/03-ecosystems/02-web-api-fastapi",
|
||||
"exercises/03-ecosystems/03-devops-automation",
|
||||
"exercises/03-ecosystems/04-aiops-structured-io",
|
||||
]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = [
|
||||
"exercises/01-core/01-basics",
|
||||
"exercises/01-core/02-collections",
|
||||
"exercises/01-core/03-strings-files",
|
||||
"exercises/01-core/04-errors-exceptions",
|
||||
"exercises/01-core/05-comprehensions-functional",
|
||||
"exercises/01-core/06-oop-dataclasses",
|
||||
"exercises/01-core/07-typing-contracts",
|
||||
"exercises/01-core/08-data-structures",
|
||||
"exercises/01-core/09-design-patterns",
|
||||
"exercises/01-core/10-crud-repository",
|
||||
"exercises/02-engineering-2026/01-ai-code-audit",
|
||||
"exercises/02-engineering-2026/02-type-driven-design",
|
||||
"exercises/02-engineering-2026/03-cross-platform-os",
|
||||
"exercises/02-engineering-2026/04-testing-best-practices",
|
||||
"exercises/03-ecosystems/01-cli-typer",
|
||||
"exercises/03-ecosystems/02-web-api-fastapi",
|
||||
"exercises/03-ecosystems/03-devops-automation",
|
||||
"exercises/03-ecosystems/04-aiops-structured-io",
|
||||
]
|
||||
Reference in new issue
Block a user