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
@@ -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)")
|
||||
Reference in new issue
Block a user