feat: reorganize workbook into 3 tracks (core, engineering-2026, ecosystems)
This commit is contained in:
1 parent
82677455b2
commit
2e002b6176
64 files changed
+2295
-196
No files matched your search
@@ -0,0 +1,4 @@
|
||||
[package]
|
||||
name = "eng01-ai-code-audit"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
@@ -0,0 +1,19 @@
|
||||
# 01 — Audyt i Refaktoryzacja Kodu AI (AI-Era Drill)
|
||||
|
||||
W 2026 roku jedną z najważniejszych umiejętności inżyniera jest **krytyczne czytanie i naprawianie kodu wygenerowanego przez AI**.
|
||||
|
||||
W `src/lib.rs` znajdziesz kod, który "wygląda dobrze na pierwszy rzut oka", ale zawiera typowe błędy AI:
|
||||
* ukryte `.unwrap()` powodujące panikę na niepoprawnych danych,
|
||||
* niepotrzebne `.clone()` i przyjmowanie `String` zamiast `&str`,
|
||||
* błędną obsługę przypadków brzegowych (dzielenie przez zero, pusta kolekcja, niepoprawny format).
|
||||
|
||||
## Twoje zadanie
|
||||
Przeprowadź audyt i refaktoryzację funkcji w `src/lib.rs` tak, aby:
|
||||
1. Żadna funkcja **nie panikowała** (`unwrap` / `expect` / indeksowanie `[0]` bez sprawdzenia).
|
||||
2. Wszystkie testy (w tym testy negatywne i brzegowe) przechodziły.
|
||||
3. `make clippy` nie zgłaszał żadnych ostrzeżeń po usunięciu `#![allow(...)]`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=eng01-ai-code-audit
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
#![allow(unused_variables, dead_code, clippy::all)]
|
||||
|
||||
/// Celowo wadliwy kod w stylu "szybkiego draftu z AI".
|
||||
/// Audytuj i napraw poniższe funkcje tak, aby nie panikowały i przeszły testy!
|
||||
|
||||
pub fn parse_port(raw: &str) -> Result<u16, String> {
|
||||
// BUG: panikuje na złym wejściu i akceptuje port 0!
|
||||
let port: u16 = raw.trim().parse().unwrap();
|
||||
Ok(port)
|
||||
}
|
||||
|
||||
pub fn average(values: &[f64]) -> Option<f64> {
|
||||
// BUG: dzieli przez 0.0 (zwraca NaN zamiast None dla pustego wycinka)
|
||||
let sum: f64 = values.iter().sum();
|
||||
Some(sum / values.len() as f64)
|
||||
}
|
||||
|
||||
pub fn extract_bearer_token(auth_header: &str) -> Option<&str> {
|
||||
// BUG: panikuje gdy brak spacji, nie sprawdza prefiksu "Bearer ", przepuszcza pusty token!
|
||||
let parts: Vec<&str> = auth_header.split(' ').collect();
|
||||
Some(parts[1])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_and_zero_ports() {
|
||||
assert_eq!(parse_port("8080"), Ok(8080));
|
||||
assert_eq!(parse_port(" 443 "), Ok(443));
|
||||
assert!(parse_port("0").is_err());
|
||||
assert!(parse_port("99999").is_err());
|
||||
assert!(parse_port("not-a-port").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_empty_slice_without_nan() {
|
||||
assert_eq!(average(&[]), None);
|
||||
assert_eq!(average(&[10.0, 20.0]), Some(15.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safely_parses_bearer_header() {
|
||||
assert_eq!(extract_bearer_token("Bearer secret123"), Some("secret123"));
|
||||
assert_eq!(extract_bearer_token("Bearer "), None);
|
||||
assert_eq!(extract_bearer_token("Basic abc"), None);
|
||||
assert_eq!(extract_bearer_token("MalformedHeader"), None);
|
||||
assert_eq!(extract_bearer_token(""), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
[package]
|
||||
name = "eng02-type-driven-design"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
@@ -0,0 +1,12 @@
|
||||
# 02 — Type-Driven Design ("Make Illegal States Unrepresentable")
|
||||
|
||||
W erze AI **system typów Rusta jest Twoją najskuteczniejszą specyfikacją**. Zamiast pisać w komentarzu „email musi być poprawny” lub „nie dodawaj PLN do EUR”, wymuś to typami.
|
||||
|
||||
## Zadania (`src/lib.rs`)
|
||||
1. `Email::parse(raw: &str) -> Result<Email, ValidationError>` — konstrukcja możliwa wyłącznie przez walidujący konstruktor (pole wewnętrzne prywatne).
|
||||
2. `Money::checked_add(self, other: Money) -> Result<Money, CurrencyMismatch>` — bezpieczne dodawanie kwot w groszach/centach z kontrolą waluty.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=eng02-type-driven-design
|
||||
```
|
||||
@@ -0,0 +1,92 @@
|
||||
#![allow(unused_variables, dead_code)]
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ValidationError {
|
||||
InvalidEmail,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Email(String);
|
||||
|
||||
impl Email {
|
||||
pub fn parse(raw: &str) -> Result<Self, ValidationError> {
|
||||
todo!(
|
||||
"Odrzuć spacje, brak '@' lub pustą część przed/po '@'; zapisz znormalizowany lowercase"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Currency {
|
||||
Pln,
|
||||
Eur,
|
||||
Usd,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct CurrencyMismatch;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Money {
|
||||
pub cents: i64,
|
||||
pub currency: Currency,
|
||||
}
|
||||
|
||||
impl Money {
|
||||
pub fn checked_add(self, other: Money) -> Result<Money, CurrencyMismatch> {
|
||||
todo!("Dodaj kwoty tylko jeśli waluty są identyczne; użyj checked_add lub zwróć Err")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn validates_email_at_boundary() {
|
||||
let email = Email::parse("User@Example.COM").unwrap();
|
||||
assert_eq!(email.as_str(), "user@example.com");
|
||||
assert_eq!(
|
||||
Email::parse("no-at-sign"),
|
||||
Err(ValidationError::InvalidEmail)
|
||||
);
|
||||
assert_eq!(
|
||||
Email::parse("@example.com"),
|
||||
Err(ValidationError::InvalidEmail)
|
||||
);
|
||||
assert_eq!(Email::parse("user@"), Err(ValidationError::InvalidEmail));
|
||||
assert_eq!(
|
||||
Email::parse("a b@c.com"),
|
||||
Err(ValidationError::InvalidEmail)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prevents_mismatched_currency_addition() {
|
||||
let a = Money {
|
||||
cents: 500,
|
||||
currency: Currency::Pln,
|
||||
};
|
||||
let b = Money {
|
||||
cents: 250,
|
||||
currency: Currency::Pln,
|
||||
};
|
||||
let eur = Money {
|
||||
cents: 100,
|
||||
currency: Currency::Eur,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
a.checked_add(b),
|
||||
Ok(Money {
|
||||
cents: 750,
|
||||
currency: Currency::Pln
|
||||
})
|
||||
);
|
||||
assert_eq!(a.checked_add(eur), Err(CurrencyMismatch));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
[package]
|
||||
name = "eng03-cross-platform"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
@@ -0,0 +1,16 @@
|
||||
# 03 — Programowanie Cross-Platform (Linux, Windows, macOS)
|
||||
|
||||
## Zakres
|
||||
* Abstrakcje ścieżek `Path` i `PathBuf` (nigdy nie sklejaj ścieżek przez `format!("{}/{}", ...)`!)
|
||||
* Kompilacja warunkowa: `#[cfg(target_os = "linux")]`, `#[cfg(target_os = "macos")]`, `#[cfg(target_os = "windows")]`
|
||||
* Bezpieczna obsługa zmiennych środowiskowych (wstrzykiwanie źródła zamiast globalnego stanu w testach)
|
||||
|
||||
## Zadania (`src/lib.rs`)
|
||||
1. `config_file_path(base_dir: &Path, app_name: &str) -> PathBuf` — zbuduj przenośną ścieżkę `<base_dir>/<app_name>/config.toml` używając `Path::join`.
|
||||
2. `current_os_label() -> &'static str` — użyj `#[cfg(target_os = "...")]`, aby zwrócić `"linux"`, `"macos"`, `"windows"` lub `"other"`.
|
||||
3. `has_extension(path: &Path, expected: &str) -> bool` — porównaj rozszerzenie pliku bez uwzględniania wielkości liter (ważne na Windows/macOS).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=eng03-cross-platform
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
#![allow(unused_variables, dead_code)]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub fn config_file_path(base_dir: &Path, app_name: &str) -> PathBuf {
|
||||
todo!("Użyj base_dir.join(app_name).join(\"config.toml\")")
|
||||
}
|
||||
|
||||
pub fn current_os_label() -> &'static str {
|
||||
todo!("Użyj #[cfg(target_os = \"...\")] dla linux, macos, windows oraz fallback other")
|
||||
}
|
||||
|
||||
pub fn has_extension(path: &Path, expected: &str) -> bool {
|
||||
todo!("Porównaj path.extension() z expected bez wrażliwości na wielkość liter")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn builds_portable_config_path() {
|
||||
let base = Path::new("home").join("user");
|
||||
let expected = base.join("myapp").join("config.toml");
|
||||
assert_eq!(config_file_path(&base, "myapp"), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_known_os_label() {
|
||||
let label = current_os_label();
|
||||
assert!(matches!(label, "linux" | "macos" | "windows" | "other"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checks_extensions_case_insensitively() {
|
||||
assert!(has_extension(Path::new("notes.MD"), "md"));
|
||||
assert!(has_extension(Path::new("archive.tar.gz"), "gz"));
|
||||
assert!(!has_extension(Path::new("README"), "md"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
[package]
|
||||
name = "eng04-best-practices"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
@@ -0,0 +1,16 @@
|
||||
# 04 — Dobre Praktyki w Ruście (Errors, Display, From, Doctests)
|
||||
|
||||
## Zakres
|
||||
* Implementacja standardowych traitów `fmt::Display` i `std::error::Error` (fundament tego, co generuje `thiserror`)
|
||||
* Konwersja błędów przez `From<E>` dla czystego operatora `?`
|
||||
* Dokumentacja publicznego API i **doctesty** (testy wewnątrz komentarzy `///`)
|
||||
|
||||
## Zadania (`src/lib.rs`)
|
||||
1. Zaimplementuj `fmt::Display` i `std::error::Error` dla `ConfigError`.
|
||||
2. Zaimplementuj `From<ParseIntError>` dla `ConfigError`.
|
||||
3. Zaimplementuj `parse_timeout_secs(raw: &str) -> Result<u64, ConfigError>` (odrzuca puste wejście jako `Missing`, błędy parsowania przez `?`, a wartości `0` lub `> 300` jako `OutOfRange(u64)`).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=eng04-best-practices
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
#![allow(unused_variables, dead_code)]
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::num::ParseIntError;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ConfigError {
|
||||
Missing,
|
||||
InvalidNumber(String),
|
||||
OutOfRange(u64),
|
||||
}
|
||||
|
||||
impl fmt::Display for ConfigError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
todo!("Sformatuj czytelny komunikat błędu dla każdego wariantu ConfigError")
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ConfigError {}
|
||||
|
||||
impl From<ParseIntError> for ConfigError {
|
||||
fn from(err: ParseIntError) -> Self {
|
||||
todo!("Zamień ParseIntError na ConfigError::InvalidNumber(err.to_string())")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_timeout_secs(raw: &str) -> Result<u64, ConfigError> {
|
||||
todo!("Trim -> Missing jeśli pusty -> parse::<u64>()? -> OutOfRange jeśli 0 lub > 300")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn validates_timeout_range_and_formatting() {
|
||||
assert_eq!(parse_timeout_secs("30"), Ok(30));
|
||||
assert_eq!(parse_timeout_secs(" "), Err(ConfigError::Missing));
|
||||
assert_eq!(parse_timeout_secs("0"), Err(ConfigError::OutOfRange(0)));
|
||||
assert_eq!(parse_timeout_secs("301"), Err(ConfigError::OutOfRange(301)));
|
||||
assert!(matches!(
|
||||
parse_timeout_secs("abc"),
|
||||
Err(ConfigError::InvalidNumber(_))
|
||||
));
|
||||
|
||||
let msg = ConfigError::Missing.to_string();
|
||||
assert!(!msg.is_empty());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user