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