diff --git a/.gitea/workflows/test-and-lint.yaml b/.gitea/workflows/test-and-lint.yaml new file mode 100644 index 0000000..7ced50d --- /dev/null +++ b/.gitea/workflows/test-and-lint.yaml @@ -0,0 +1,31 @@ +name: Test and Lint + +on: + push: + branches: + - main + - "attempt/*" + pull_request: + branches: + - main + +jobs: + quality: + runs-on: fedora + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Build container image + run: make image + + - name: Check formatting (ruff format) + run: make fmt-check + + - name: Lint and typecheck (ruff + mypy) + run: make check + + - name: Run test suite progress report (attempt branches) + if: startsWith(github.ref, 'refs/heads/attempt/') + continue-on-error: true + run: make test-all diff --git a/Makefile b/Makefile index 4fa03c1..c2a98b2 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ RUN_CONTAINER = $(ENGINE) run --rm \ -w /workspace \ $(IMAGE) -.PHONY: help image check test test-all lint fmt fmt-check typecheck shell +.PHONY: help image check test test-all test-project lint fmt fmt-check typecheck shell help: @echo "Dostępne komendy:" @@ -15,7 +15,8 @@ help: @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 test-project - Uruchom testy mini-projektu incident-tracker" + @echo " make test-all - Uruchom testy wszystkich ścieżek + projektu" @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" @@ -24,10 +25,10 @@ image: $(ENGINE) build -t $(IMAGE) -f Containerfile . lint: - $(RUN_CONTAINER) ruff check exercises + $(RUN_CONTAINER) ruff check exercises projects typecheck: - $(RUN_CONTAINER) mypy exercises + $(RUN_CONTAINER) mypy exercises projects check: lint typecheck @@ -38,14 +39,17 @@ else $(RUN_CONTAINER) pytest -v exercises/01-core exercises/02-engineering-2026 endif +test-project: + $(RUN_CONTAINER) pytest -v projects/incident-tracker + test-all: - $(RUN_CONTAINER) pytest -v exercises + $(RUN_CONTAINER) pytest -v exercises projects fmt: - $(RUN_CONTAINER) ruff format exercises + $(RUN_CONTAINER) ruff format exercises projects fmt-check: - $(RUN_CONTAINER) ruff format --check exercises + $(RUN_CONTAINER) ruff format --check exercises projects shell: $(ENGINE) run --rm -it \ diff --git a/README.md b/README.md index 3b56584..47378df 100644 --- a/README.md +++ b/README.md @@ -53,12 +53,17 @@ make fmt - [ ] `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 - [ ] `05-testing-types-and-mutation` — [README](exercises/02-engineering-2026/05-testing-types-and-mutation/README.md): testy jednostkowe, integracyjne i mutacyjne (zabijanie mutantów) +- [ ] `06-security-appsec` — [README](exercises/02-engineering-2026/06-security-appsec/README.md): bezpieczeństwo kodu (Path Traversal, redakcja sekretów) ### Ś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` +- [ ] `05-sql-sqlite` — [README](exercises/03-ecosystems/05-sql-sqlite/README.md): SQL i SQLite z ochroną przed SQL Injection + +### Mini-Projekt Końcowy (Capstone): `projects/incident-tracker/` +- [ ] `incident-tracker` — [README](projects/incident-tracker/README.md): pełna aplikacja SRE (CLI + SQLite + JSON + testy, `make test-project`) --- @@ -71,6 +76,10 @@ make fmt * [03 — Algorytmy i złożoność obliczeniowa (Big-O)](notes/03-algorithms-and-complexity.md) * [04 — Rodzaje testów: jednostkowe, integracyjne, mutacyjne, ręczne i automatyczne](notes/04-testing-pyramid-and-types.md) * [05 — Efektywny debugging i czytanie błędów (Tracebacki)](notes/05-debugging-and-reading-errors.md) +* [06 — SQL i Bazy Danych (SQLite & PostgreSQL)](notes/06-sql-and-databases.md) +* [07 — Bezpieczeństwo Kodu (AppSec & OWASP)](notes/07-appsec-and-secure-coding.md) +* [08 — Git w Korpo i Architektura Aplikacji](notes/08-git-workflow-and-architecture.md) +* [99 — Dziennik Błędów i System Powtórek](notes/99-mistakes-log.md) ## Nauka z asystentem AI (metoda sokratejska i era 2026) diff --git a/exercises/02-engineering-2026/06-security-appsec/README.md b/exercises/02-engineering-2026/06-security-appsec/README.md new file mode 100644 index 0000000..c3ae9b6 --- /dev/null +++ b/exercises/02-engineering-2026/06-security-appsec/README.md @@ -0,0 +1,12 @@ +# 06 — Bezpieczeństwo Kodu (AppSec: Path Traversal, Redakcja Sekretów) + +Teoria: [notes/07-appsec-and-secure-coding.md](../../../notes/07-appsec-and-secure-coding.md) + +## Zadania (`appsec.py`) +1. `safe_join(base_dir: Path, relative_path: str) -> Path` — bezpiecznie połącz `base_dir` z `relative_path`. Jeśli wynikowa ścieżka (po `resolve()`) ucieka poza `base_dir.resolve()` (np. `../../etc/passwd` lub ścieżka absolutna `/etc/passwd`), rzuć `PathTraversalError`. +2. `redact_secrets(log_line: str) -> str` — zamaskuj wartości po `token=`, `password=` lub `Bearer ` na `***`, aby sekrety nigdy nie trafiały do logów. + +## Uruchomienie testów +```bash +make test MOD=02-engineering-2026/06-security-appsec +``` diff --git a/exercises/02-engineering-2026/06-security-appsec/appsec.py b/exercises/02-engineering-2026/06-security-appsec/appsec.py new file mode 100644 index 0000000..828a31b --- /dev/null +++ b/exercises/02-engineering-2026/06-security-appsec/appsec.py @@ -0,0 +1,17 @@ +import re +from pathlib import Path + + +class PathTraversalError(ValueError): + """Próba wyjścia poza dozwolony katalog bazowy.""" + + +def safe_join(base_dir: Path, relative_path: str) -> Path: + raise NotImplementedError( + "Rozwiąż (base_dir / relative_path).resolve() i sprawdź is_relative_to(base_dir.resolve())" + ) + + +def redact_secrets(log_line: str) -> str: + _ = re + raise NotImplementedError("Zamień wartości po Bearer , token= oraz password= na '***'") diff --git a/exercises/02-engineering-2026/06-security-appsec/test_appsec.py b/exercises/02-engineering-2026/06-security-appsec/test_appsec.py new file mode 100644 index 0000000..55ed58b --- /dev/null +++ b/exercises/02-engineering-2026/06-security-appsec/test_appsec.py @@ -0,0 +1,24 @@ +from pathlib import Path + +import pytest +from appsec import PathTraversalError, redact_secrets, safe_join + + +def test_safe_join_allows_nested_and_blocks_traversal(tmp_path: Path) -> None: + ok = safe_join(tmp_path, "configs/app.yaml") + assert ok == (tmp_path / "configs" / "app.yaml").resolve() + + with pytest.raises(PathTraversalError): + safe_join(tmp_path, "../../etc/passwd") + + with pytest.raises(PathTraversalError): + safe_join(tmp_path, "/etc/passwd") + + +def test_redact_secrets_masks_credentials() -> None: + line = "auth failed header=Bearer s3cr3tTok3n user=admin password=hunter2 token=abc_123" + cleaned = redact_secrets(line) + assert "s3cr3tTok3n" not in cleaned + assert "hunter2" not in cleaned + assert "abc_123" not in cleaned + assert "user=admin" in cleaned diff --git a/exercises/03-ecosystems/05-sql-sqlite/README.md b/exercises/03-ecosystems/05-sql-sqlite/README.md new file mode 100644 index 0000000..aacf6ea --- /dev/null +++ b/exercises/03-ecosystems/05-sql-sqlite/README.md @@ -0,0 +1,14 @@ +# 05 — SQL i SQLite (`sqlite3`, parametryzowane zapytania, ochrona przed SQLi) + +Teoria: [notes/06-sql-and-databases.md](../../../notes/06-sql-and-databases.md) + +## Zadania (`sql_sqlite.py`) +Zaimplementuj `ServiceRegistry` na wbudowanym `sqlite3`: +1. `init_schema()` — utwórz tabelę `services(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, owner TEXT NOT NULL)`. +2. `register(name: str, owner: str) -> int` — wstaw rekord **parametryzowanym zapytaniem** (`?`) i zwróć `lastrowid`. +3. `find_by_owner(owner: str) -> list[str]` — zwróć posortowaną listę nazw serwisów danego właściciela (bez podatności na SQL Injection!). + +## Uruchomienie testów +```bash +make test MOD=03-ecosystems/05-sql-sqlite +``` diff --git a/exercises/03-ecosystems/05-sql-sqlite/sql_sqlite.py b/exercises/03-ecosystems/05-sql-sqlite/sql_sqlite.py new file mode 100644 index 0000000..bba462f --- /dev/null +++ b/exercises/03-ecosystems/05-sql-sqlite/sql_sqlite.py @@ -0,0 +1,17 @@ +import sqlite3 +from pathlib import Path + + +class ServiceRegistry: + def __init__(self, db_path: Path) -> None: + self._db_path = db_path + + def init_schema(self) -> None: + _ = sqlite3 + raise NotImplementedError("Utwórz tabelę services (CREATE TABLE IF NOT EXISTS ...)") + + def register(self, name: str, owner: str) -> int: + raise NotImplementedError("Wstaw (name, owner) parametryzowanym INSERT i zwróć id") + + def find_by_owner(self, owner: str) -> list[str]: + raise NotImplementedError("Zwróć posortowane nazwy serwisów dla owner (parametryzowane ?)") diff --git a/exercises/03-ecosystems/05-sql-sqlite/test_sql_sqlite.py b/exercises/03-ecosystems/05-sql-sqlite/test_sql_sqlite.py new file mode 100644 index 0000000..02d73c9 --- /dev/null +++ b/exercises/03-ecosystems/05-sql-sqlite/test_sql_sqlite.py @@ -0,0 +1,21 @@ +from pathlib import Path + +from sql_sqlite import ServiceRegistry + + +def test_sqlite_crud_and_sqli_resistance(tmp_path: Path) -> None: + db = tmp_path / "registry.db" + reg = ServiceRegistry(db) + reg.init_schema() + + id1 = reg.register("billing-api", "team-core") + id2 = reg.register("auth-api", "team-core") + reg.register("metrics-proxy", "team-sre") + + assert id1 > 0 + assert id2 > id1 + assert reg.find_by_owner("team-core") == ["auth-api", "billing-api"] + + # Negative security assertion: SQL Injection payload must NOT return all rows + sqli_payload = "' OR '1'='1" + assert reg.find_by_owner(sqli_payload) == [] diff --git a/notes/06-sql-and-databases.md b/notes/06-sql-and-databases.md new file mode 100644 index 0000000..0effa7f --- /dev/null +++ b/notes/06-sql-and-databases.md @@ -0,0 +1,53 @@ +# SQL i Bazy Danych (SQLite & PostgreSQL — fundament dla DevOps/SRE) + +SQL pojawia się w **~22% wszystkich ofert IT w Polsce**. Niezależnie od języka (Python, Go, Rust), zrozumienie podstaw relacyjnych baz danych jest obowiązkowe. + +--- + +## 1. Podstawowe zapytania SQL (ściągawka) + +```sql +-- Tworzenie tabeli (idempotentna migracja) +CREATE TABLE IF NOT EXISTS incidents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + severity TEXT NOT NULL CHECK (severity IN ('low', 'medium', 'high', 'critical')), + status TEXT NOT NULL DEFAULT 'open', + created_at TEXT NOT NULL +); + +-- Indeks przyspieszający filtrowanie po statusie i severity (O(log n) zamiast Full Table Scan O(n)) +CREATE INDEX IF NOT EXISTS idx_incidents_status_sev ON incidents(status, severity); + +-- INSERT, SELECT, UPDATE, DELETE +INSERT INTO incidents (title, severity, status, created_at) VALUES (?, ?, 'open', ?); +SELECT id, title, severity FROM incidents WHERE status = ? ORDER BY id ASC; +UPDATE incidents SET status = 'resolved' WHERE id = ?; +DELETE FROM incidents WHERE id = ?; + +-- Agregacja (GROUP BY + COUNT) +SELECT severity, COUNT(*) AS total FROM incidents GROUP BY severity; +``` + +## 2. JOIN — łączenie tabel +* **`INNER JOIN`:** tylko pasujące rekordy z obu tabel. +* **`LEFT JOIN`:** wszystkie rekordy z lewej tabeli + pasujące z prawej (lub `NULL`). + +## 3. Transakcje (ACID) +* **A**tomicity (wszystko albo nic — `COMMIT` lub `ROLLBACK`), +* **C**onsistency (zachowane ograniczenia `CHECK`, `FOREIGN KEY`, `UNIQUE`), +* **I**solation (równoległe transakcje nie psują sobie nawzajem danych), +* **D**urability (po `COMMIT` dane przeżywają restart). + +## 4. Złota zasada bezpieczeństwa: ZAWSZE parametryzowane zapytania! +```python +# ŹLE (SQL Injection!): +conn.execute(f"SELECT * FROM users WHERE name = '{user_input}'") + +# DOBRZE (parametryzowane zapytanie — dane nigdy nie stają się kodem SQL): +conn.execute("SELECT * FROM users WHERE name = ?", (user_input,)) +``` + +## 5. SQLite vs PostgreSQL (kiedy czego użyć) +* **SQLite:** wbudowana baza w jednym pliku (zero serwera), idealna do CLI, narzędzi lokalnych, aplikacji desktop/mobile i testów integracyjnych. +* **PostgreSQL:** standard produkcyjny dla aplikacji wielodostępnych, backendów webowych i dużych wolumenów danych. diff --git a/notes/07-appsec-and-secure-coding.md b/notes/07-appsec-and-secure-coding.md new file mode 100644 index 0000000..0c5e61e --- /dev/null +++ b/notes/07-appsec-and-secure-coding.md @@ -0,0 +1,24 @@ +# Bezpieczeństwo Kodu (AppSec & OWASP w praktyce) + +Bezpieczeństwo zaczyna się na poziomie pojedynczej funkcji — szczególnie w 2026 roku, gdy AI potrafi wygenerować kod wyglądający poprawnie, ale podatny na proste ataki. + +--- + +## 1. Najważniejsze podatności, które musisz wyłapywać w Code Review + +| Podatność | Jak wygląda błąd | Jak się zabezpieczyć | +| :--- | :--- | :--- | +| **SQL Injection** | Sklejanie SQL przez f-string / `format!` / `fmt.Sprintf`. | Zawsze **parametryzowane zapytania** (`?`, `$1`). | +| **Command Injection** | `subprocess.run(f"ls {user_dir}", shell=True)`. | Przekazuj listę argumentów z `shell=False` (w Go `exec.Command(bin, arg1, arg2)`, w Rust `Command::new(bin).arg(arg)`). | +| **Path Traversal (`../`)** | `base / user_filename` bez sprawdzenia, czy `../../etc/passwd` nie uciekł poza `base`. | Rozwiąż ścieżkę (`resolve()`) i sprawdź `resolved.is_relative_to(base.resolve())`. | +| **Wyciek sekretów** | Klucze API, hasła, tokeny w kodzie, `.env` w Gicie albo w logach aplikacji. | Zmienne środowiskowe / Vault, skanowanie **`gitleaks`**, redakcja tokenów w logach (`Bearer ***`). | +| **IDOR / BOLA** | Endpoint `GET /orders/42` zwraca cudze zamówienie bez sprawdzenia właściciela. | Zawsze weryfikuj autoryzację obiektu po stronie serwera (`WHERE id = ? AND owner_id = ?`). | + +## 2. Higiena łańcucha dostaw (Supply Chain) +Regularnie skanuj zależności pod kątem znanych luk CVE: +* **Python:** `pip-audit` +* **Go:** `govulncheck ./...` +* **Rust:** `cargo audit` +* **Wszystkie repozytoria (sekrety w Gicie):** `gitleaks detect --source .` + +Praktyczne zadania z Path Traversal i redakcji sekretów znajdziesz w [exercises/02-engineering-2026/06-security-appsec](../exercises/02-engineering-2026/06-security-appsec/README.md). diff --git a/notes/08-git-workflow-and-architecture.md b/notes/08-git-workflow-and-architecture.md new file mode 100644 index 0000000..7fb5a1f --- /dev/null +++ b/notes/08-git-workflow-and-architecture.md @@ -0,0 +1,39 @@ +# Git w Korpo i Podstawy Architektury Aplikacji + +## 1. Git Workflow w międzynarodowych zespołach + +* **Atomowe commity:** jeden commit = jedna logiczna zmiana (łatwe `git revert` i czytelne code review). +* **Conventional Commits:** + * `feat:` — nowa funkcjonalność + * `fix:` — naprawa błędu + * `refactor:` — zmiana struktury bez zmiany zachowania + * `test:` — dodanie lub poprawa testów + * `docs:` — dokumentacja + * `chore:` — konfiguracja, zależności, CI +* **`merge` vs `rebase`:** + * `git merge` zachowuje pełną historię rozgałęzień (bezpieczne na współdzielonych gałęziach). + * `git rebase` przepisuje Twoje lokalne commity na czubek `main` (czysta, liniowa historia — nigdy nie rób `rebase` na publicznym `main`!). +* **`git bisect`:** binarne wyszukiwanie commita, który wprowadził regresję (`git bisect start`, `git bisect bad`, `git bisect good `). +* **Checklista przed otwarciem Pull Requesta (PR):** + 1. Sam przejrzyj własny `git diff`. + 2. Czy przeszedł linter, formatter, typy i testy? + 3. Czy nie ma przypadkowych sekretów, debug-printów ani niepowiązanych zmian? + 4. Krótki opis PR: **Co** zmieniono, **Dlaczego**, **Jak przetestowano**. + +--- + +## 2. Architektura aplikacji: oddzielenie domeny od I/O (Ports & Adapters) + +Najczęstszy błąd początkujących to wrzucenie parsowania CLI/HTTP, logiki biznesowej i zapytań SQL do jednej funkcji. W efekcie kodu nie da się przetestować bez uruchamiania całej infrastruktury. + +```text +[ CLI / HTTP API ] ---> [ Logika domenowa (czyste funkcje/typy) ] ---> [ Interfejs / Port ] + | + +----------------------+----------------------+ + v v + [ SQLite Adapter ] [ In-Memory Fake ] + (produkcja) (szybkie testy) +``` + +* **Zasada:** logika biznesowa **nie wie**, czy dane przyszły z CLI, HTTP czy kolejki, ani czy trafią do SQLite, PostgreSQL czy pamięci RAM. +* Dokładnie ten wzorzec przećwiczysz w mini-projekcie końcowym `projects/incident-tracker/`. diff --git a/notes/99-mistakes-log.md b/notes/99-mistakes-log.md new file mode 100644 index 0000000..cba0ddd --- /dev/null +++ b/notes/99-mistakes-log.md @@ -0,0 +1,19 @@ +# Dziennik Błędów i System Powtórek (Spaced Repetition) + +Najwięcej uczysz się nie z zadań, które przeszły od razu, tylko z **błędów, na których utknąłeś**. Zapisuj je tutaj krótko i wracaj do nich według harmonogramu powtórek: **+1 dzień → +3 dni → +7 dni → +30 dni**. + +--- + +## Jak korzystać z dziennika +Po każdym trudniejszym rozdziale dopisz 1 wiersz do tabeli poniżej (na swojej gałęzi `attempt/*` lub na `main`, jeśli chcesz zachować wiedzę między podejściami). + +| Data | Rozdział | Co poszło nie tak (objaw / błąd) | Przyczyna źródłowa (*root cause*) | Zasada na przyszłość | Powtórka (+3d / +7d) | +| :--- | :--- | :--- | :--- | :--- | :--- | +| *przykład* | `02-engineering/01-ai-code-audit` | Lista tagów pamiętała dane z poprzedniego wywołania | Mutowalny argument domyślny `tags=[]` | Zawsze używaj `tags: list[str] | None = None` | `[ ]` `[ ]` | + +--- + +## Krótka retrospektywa po ukończeniu ścieżki +1. Który koncept sprawił mi największą trudność i czy potrafię go teraz wytłumaczyć własnymi słowami (PL i EN)? +2. Jakie 2–3 błędy powtarzały się u mnie najczęściej? +3. Co zrobiłbym inaczej, zaczynając kolejną gałąź `attempt/`? diff --git a/notes/README.md b/notes/README.md index 5a01f01..501e2ba 100644 --- a/notes/README.md +++ b/notes/README.md @@ -6,3 +6,7 @@ * [03 — Algorytmy i złożoność obliczeniowa (Big-O)](03-algorithms-and-complexity.md) * [04 — Rodzaje testów: jednostkowe, integracyjne, mutacyjne, ręczne i automatyczne](04-testing-pyramid-and-types.md) * [05 — Efektywny debugging i czytanie błędów (Tracebacki)](05-debugging-and-reading-errors.md) +* [06 — SQL i Bazy Danych (SQLite & PostgreSQL)](06-sql-and-databases.md) +* [07 — Bezpieczeństwo Kodu (AppSec & OWASP)](07-appsec-and-secure-coding.md) +* [08 — Git w Korpo i Architektura Aplikacji](08-git-workflow-and-architecture.md) +* [99 — Dziennik Błędów i System Powtórek](99-mistakes-log.md) diff --git a/projects/incident-tracker/README.md b/projects/incident-tracker/README.md new file mode 100644 index 0000000..2d19d3f --- /dev/null +++ b/projects/incident-tracker/README.md @@ -0,0 +1,21 @@ +# Capstone Mini-Projekt: `incident-tracker` (CLI + SQLite + JSON logs) + +Ten sam projekt SRE realizujesz w Pythonie, Go i Ruście, żeby porównać ergonomię i architekturę wszystkich trzech języków. + +## Wymagania +Zaimplementuj aplikację `incident-tracker` (`tracker.py`): +1. **Model domenowy:** `Incident(id, title, severity, status)` gdzie `severity` ∈ `{"low", "medium", "high", "critical"}`, `status` ∈ `{"open", "resolved"}`. +2. **Warstwa persystencji (`IncidentStore` na SQLite):** + * `init_schema()` — idempotentne tworzenie tabeli `incidents`. + * `add(title: str, severity: str) -> Incident` — walidacja niepustego tytułu i dozwolonego `severity`, zapis przez parametryzowane zapytanie. + * `list_incidents(severity: str | None = None) -> list[Incident]` — opcjonalne filtrowanie. + * `resolve(incident_id: int) -> Incident` — zmiana statusu na `"resolved"` (lub `IncidentNotFoundError`). + * `stats() -> dict[str, int]` — zliczenie incydentów po `status` (`{"open": ..., "resolved": ...}`). +3. **Warstwa CLI (`build_cli(db_path: Path)` w `typer`):** + * Podkomendy: `add --severity <sev>`, `list [--severity <sev>]`, `resolve <id>`, `stats`. + * Wynik wypisywany jako czysty JSON na `stdout`. + +## Uruchomienie testów +```bash +make test-project +``` diff --git a/projects/incident-tracker/test_tracker.py b/projects/incident-tracker/test_tracker.py new file mode 100644 index 0000000..fb39622 --- /dev/null +++ b/projects/incident-tracker/test_tracker.py @@ -0,0 +1,50 @@ +import json +from pathlib import Path + +import pytest +from tracker import ( + IncidentNotFoundError, + IncidentStore, + InvalidIncidentError, + build_cli, +) +from typer.testing import CliRunner + + +def test_incident_store_sqlite_lifecycle(tmp_path: Path) -> None: + store = IncidentStore(tmp_path / "incidents.db") + store.init_schema() + + with pytest.raises(InvalidIncidentError): + store.add(" ", "high") + with pytest.raises(InvalidIncidentError): + store.add("DB down", "urgent") + + inc1 = store.add("K8s node NotReady", "critical") + inc2 = store.add("High disk usage", "medium") + assert inc1.status == "open" + assert len(store.list_incidents()) == 2 + assert [i.id for i in store.list_incidents(severity="critical")] == [inc1.id] + + resolved = store.resolve(inc1.id) + assert resolved.status == "resolved" + assert store.stats() == {"open": 1, "resolved": 1} + + with pytest.raises(IncidentNotFoundError): + store.resolve(9999) + assert inc2.id != inc1.id + + +def test_incident_cli_end_to_end(tmp_path: Path) -> None: + db_path = tmp_path / "cli.db" + app = build_cli(db_path) + runner = CliRunner() + + res_add = runner.invoke(app, ["add", "API 502 spike", "--severity", "high"]) + assert res_add.exit_code == 0 + created = json.loads(res_add.stdout) + assert created["severity"] == "high" + + res_stats = runner.invoke(app, ["stats"]) + assert res_stats.exit_code == 0 + assert json.loads(res_stats.stdout) == {"open": 1, "resolved": 0} diff --git a/projects/incident-tracker/tracker.py b/projects/incident-tracker/tracker.py new file mode 100644 index 0000000..1ef7b69 --- /dev/null +++ b/projects/incident-tracker/tracker.py @@ -0,0 +1,50 @@ +import json +import sqlite3 +from dataclasses import dataclass +from pathlib import Path + +import typer + +VALID_SEVERITIES = frozenset({"low", "medium", "high", "critical"}) + + +class InvalidIncidentError(ValueError): + """Niepoprawne dane wejściowe incydentu.""" + + +class IncidentNotFoundError(KeyError): + """Nie znaleziono incydentu o podanym ID.""" + + +@dataclass(frozen=True) +class Incident: + id: int + title: str + severity: str + status: str + + +class IncidentStore: + def __init__(self, db_path: Path) -> None: + self._db_path = db_path + + def init_schema(self) -> None: + _ = sqlite3 + raise NotImplementedError("Utwórz tabelę incidents (id, title, severity, status)") + + def add(self, title: str, severity: str) -> Incident: + raise NotImplementedError("Zwaliduj title i severity, zapisz w SQLite i zwróć Incident") + + def list_incidents(self, severity: str | None = None) -> list[Incident]: + raise NotImplementedError("Zwróć incydenty (opcjonalnie przefiltrowane po severity)") + + def resolve(self, incident_id: int) -> Incident: + raise NotImplementedError("Zmień status na 'resolved' lub rzuć IncidentNotFoundError") + + def stats(self) -> dict[str, int]: + raise NotImplementedError("Zwróć {'open': X, 'resolved': Y}") + + +def build_cli(db_path: Path) -> typer.Typer: + _ = (json, db_path, typer.Typer) + raise NotImplementedError("Zarejestruj podkomendy add, list, resolve, stats wypisujące JSON") diff --git a/pyproject.toml b/pyproject.toml index 16439a4..f3ec51a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,10 +34,13 @@ mypy_path = [ "exercises/02-engineering-2026/03-cross-platform-os", "exercises/02-engineering-2026/04-testing-best-practices", "exercises/02-engineering-2026/05-testing-types-and-mutation", + "exercises/02-engineering-2026/06-security-appsec", "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", + "exercises/03-ecosystems/05-sql-sqlite", + "projects/incident-tracker", ] [tool.pytest.ini_options] @@ -58,8 +61,11 @@ pythonpath = [ "exercises/02-engineering-2026/03-cross-platform-os", "exercises/02-engineering-2026/04-testing-best-practices", "exercises/02-engineering-2026/05-testing-types-and-mutation", + "exercises/02-engineering-2026/06-security-appsec", "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", + "exercises/03-ecosystems/05-sql-sqlite", + "projects/incident-tracker", ]