Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
test: establish integration test architecture and update testing guides
Samir Hossains3742615c1326
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3f791c2..7185754 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,10 @@## [Unreleased]### Added+- **Comprehensive QA & Regression Test Architecture**:+ - Introduced a 31-test automated suite covering critical algorithmic boundaries, state reconciliation, crypto HMAC signing, download chunk arithmetic, and URL/stem security.+ - Added structured integration tests in `tests/` (`history_reconciliation.rs`, `cache_lifecycle.rs`, `player_integration.rs`, `m3u_integration.rs`, `addons_manifest.rs`, `download_integration.rs`, `url_security.rs`) and test fixtures (`tests/fixtures/`).+ - Added [`docs/testing.md`](docs/testing.md) detailing test architecture, command references, and manual QA procedures.- **Playback Tracking & Watch History Progress**:- Added real-time playback position tracking for `mpv` with injected tracker script (`moviebox_tracker.lua`) and 5-second periodic state auto-save to disk.- Added automatic startup state reconciliation (`reconcile_pending_playback_states`) ensuring watched progress is preserved even when closing the terminal or killing tmux mid-playback.@@ -61,6 +65,22 @@- Added complete mouse click support for Addon Manager modal and browse popups.### Fixed+- **MovieBox Title Sanitization (DEF-02)**:+ - Fixed destructive title truncation where leading bracket tags (`[Dub]`, `[1080p]`, `[RAW]`) and titles starting with parentheses (e.g. `(500) Days of Summer`) were stripped down to empty strings.+ - Preserved release years in parentheses (`Inception (2010)`) and added a fallback safeguard returning the trimmed original title if sanitization ever results in an empty string.+- **Watch History Identity & Deduplication Collisions (DEF-03)**:+ - Enforced `stype` separation in `HistoryManager::is_same_show` so Movies and TV Series sharing identical titles (e.g. `Home`) never overwrite one another.+ - Enforced strict canonical identity (`provider + subject_id`), preventing cross-provider conflicts and ensuring remakes with differing release years remain distinct entries.+- **Background Episode Playback State Reconciliation (MISS-01)**:+ - Fixed a state loss bug in `reconcile_pending_playback_states` where a completed episode's watched status was discarded if the user had already advanced to a subsequent episode before the state file was processed.+- **Windows MPV Script Options Path Escaping (DEF-04)**:+ - Fixed path corruption in MPV's `--script-opts` on Windows by normalizing backslashes (`\`) to forward slashes (`/`), preventing MPV escape sequence parsing from corrupting `state_file` paths in `moviebox_tracker.lua`.+- **M3U Single-Quoted Attribute Support (DEF-07)**:+ - Extended `M3UParser` attribute extraction to support both single-quoted (`tvg-id='...'`) and double-quoted attributes, preserving channel IDs, logos, and groups across varied IPTV playlists.+- **Continuous OS-Level SIGINT Handling (DEF-05)**:+ - Wrapped `tokio::signal::ctrl_c()` in a continuous background loop to ensure repeated non-interactive OS signals are reliably handled.+- **Subtitle Prefetch Fallback (DEF-08)**:+ - Reduced subtitle download timeout from 30s to 8s to prevent unnecessary startup delays when launching external players if a subtitle mirror hangs.- **Addon Stream Sorting & Rendering**:- Fixed addon streams randomly scrambling on UI hover when sizes are tied by adding a secondary stable sort based on the mirror label.- Fixed misleading `0MB` stream sizes for community addons that omit video sizes by cleanly rendering `--` instead.diff --git a/README.md b/README.mdindex 2d5fcf3..fcc934c 100644--- a/README.md+++ b/README.md@@ -112,6 +112,7 @@ All in-depth guides and technical details are available in the [`docs/`](docs/)- [Configuration Reference](docs/config.md) — Config files and environment variables- [Providers](docs/providers.md) — Supported content sources and protocols- [Troubleshooting & Debugging](docs/debugging.md) — Fixing common issues and reporting bugs+- [Testing & QA Architecture](docs/testing.md) — Testing philosophy, unit/integration suites, and QA guidelines- [Contributing Guide](CONTRIBUTING.md) — How to contribute code and submit PRs## Roadmapdiff --git a/docs/README.md b/docs/README.mdindex c05e929..bd4c41d 100644--- a/docs/README.md+++ b/docs/README.md@@ -21,6 +21,7 @@ layout, runtime behavior, and operational workflows in prose tied to the source| [downloads.md](downloads.md) | Download engine: resume, ranges, segments, retry, cancel | current || [cross-platform.md](cross-platform.md) | OS support, terminal protocols, Termux, focus handling | current || [release-checklist.md](release-checklist.md) | Static gates plus required real-environment release verification | current |+| [testing.md](testing.md) | Test architecture, unit/integration tests, fixtures, and QA guidelines | current || [debugging.md](debugging.md) | Reproducing issues and what to include in GitHub reports | current || [known-issues.md](known-issues.md) | Known limitations and how they are tracked | current |diff --git a/docs/known-issues.md b/docs/known-issues.mdindex f1f4ffd..5f5b57a 100644--- a/docs/known-issues.md+++ b/docs/known-issues.md@@ -26,5 +26,6 @@ Tracked here so future work and issue reports reference the same facts.## Verification-- CI runs `cargo test --locked`, but the suite still has no meaningful coverage.-- Correctness across UI, providers, and network flows is enforced by strict compiler type checking, the lint gate (`cargo clippy --all-targets -- -D warnings`), formatting (`cargo fmt --check`), and the manual/runtime verification gates in [`release-checklist.md`](release-checklist.md). CI also runs `cargo audit` and `cargo package`.+- Automated testing is enforced via `cargo test --locked` covering 31 unit and integration tests across critical algorithms, state reconciliation, crypto signing, M3U parsing, and cross-platform player path sanitization (see [`docs/testing.md`](testing.md)).+- Static correctness is enforced by strict compiler type checking, the lint gate (`cargo clippy --all-targets --all-features -- -D warnings`), formatting (`cargo fmt --check`), dependency vulnerability scanning (`cargo audit`), and packaging verification (`cargo package --locked`).+- Runtime and platform-specific behavior (terminal resize, focus handling, external player launch, and Termux chooser) are verified through the release checklist in [`release-checklist.md`](release-checklist.md).diff --git a/docs/release-checklist.md b/docs/release-checklist.mdindex c3430ba..244a13b 100644--- a/docs/release-checklist.md+++ b/docs/release-checklist.md@@ -10,15 +10,14 @@ Run the repository checks first:```bashcargo fmt --check-cargo clippy --all-targets --locked -- -D warnings+cargo clippy --all-targets --all-features --locked -- -D warningscargo check --locked+cargo test --lockedcargo auditcargo package --locked```-CI currently runs `cargo test --locked`, but the suite still contains no meaningful-tests. Keep the static gates above green and treat runtime verification as the main-release gate until regression coverage is added.+Confirm the entire unit and integration test suite passes cleanly across all targets (`docs/testing.md`).Confirm the main GitHub Actions workflows are green:diff --git a/docs/testing.md b/docs/testing.mdnew file mode 100644index 0000000..2092b0a--- /dev/null+++ b/docs/testing.md@@ -0,0 +1,114 @@+# Testing & QA Architecture++This document describes the testing architecture, quality assurance procedures, and validation guidelines for MovieBox-TUI.++## 1. Test Architecture++The MovieBox-TUI test architecture follows a strict separation of concerns:++```text+MovieBox-TUI/+├── src/+│ └── **/*.rs # Pure algorithms & inline unit tests (#[cfg(test)])+└── tests/+ ├── common/+ │ └── mod.rs # Shared test utilities & temporary directory helpers+ ├── fixtures/+ │ ├── m3u/+ │ │ └── sample_playlist.m3u+ │ └── addons/+ │ └── manifest.json+ ├── history_reconciliation.rs # History identity & background state reconciliation+ ├── cache_lifecycle.rs # Disk cache hashing & atomic writes+ ├── player_integration.rs # Cross-platform player command & path arguments+ ├── m3u_integration.rs # Offline M3U playlist parsing+ ├── download_integration.rs # File stem sanitization & folder structure+ ├── url_security.rs # URL validation & device stem protection+ └── addons_manifest.rs # Addon manifest deserialization & catalog checks+```++### A. Inline Unit Tests (`src/**/*.rs`)+Inline unit tests live inside `#[cfg(test)] mod tests` blocks within their respective modules. They verify:+- Title normalization (`clean_moviebox_title`)+- HMAC-MD5 cryptographic signing and token generation (`generate_x_client_token`, `generate_x_tr_signature`)+- Segment partitioning math and byte range calculations+- Internal helper logic and parsing functions++### B. Subsystem Integration Tests (`tests/*.rs`)+Integration tests live in the `tests/` directory and test externally observable behaviors without mocking internal types:+- **`history_reconciliation.rs`**: Validates `HistoryManager::is_same_show`, media type separation (Movies vs TV Series), remake year distinction, and state file reconciliation (MISS-01).+- **`cache_lifecycle.rs`**: Validates atomic file writing (both sync and async) and deterministic MD5 cache key generation.+- **`player_integration.rs`**: Validates MPV script options path sanitization on Windows (`\` $\rightarrow$ `/`) and Unix.+- **`m3u_integration.rs`**: Validates parsing of standard, single-quoted, double-quoted, and unquoted M3U playlists using fixtures.+- **`addons_manifest.rs`**: Validates deserialization of Cinemeta / Stremio-style addon manifest structures.+- **`url_security.rs`**: Validates HTTP/HTTPS URL detection and Windows reserved device stem sanitization (`CON`, `AUX`, `PRN`, `NUL`, `COM1-9`, `LPT1-9`).++---++## 2. Running Automated Tests++Run the full test suite (all unit and integration tests):++```bash+cargo test+```++Run only unit tests:++```bash+cargo test --lib+```++Run a specific integration test:++```bash+cargo test --test history_reconciliation+cargo test --test player_integration+cargo test --test m3u_integration+```++---++## 3. Code Hygiene and Static Analysis++Every commit and pull request must pass all hygiene checks:++```bash+# Check formatting+cargo fmt -- --check++# Compiler check+cargo check++# Clippy linter with warnings treated as errors+cargo clippy --all-targets --all-features -- -D warnings++# Security vulnerability scan+cargo audit+```++---++## 4. Manual QA Matrix++Because TUI and media player interactions depend on terminal capabilities and external processes, manual QA testing covers:++### Terminal Emulators+- **Ghostty** (Primary testing terminal)+- **macOS Terminal.app**+- **iTerm2**+- **Windows Terminal**+- **Linux VTE / Alacritty / Kitty**+- **tmux** session & pane switching++### Supported Media Players+- **mpv** (Full IPC tracking, script options, state reconciliation)+- **VLC** (Local playback and stream forwarding)+- **IINA** (macOS native player integration)+- **termux-open / Android Intents** (Android Termux)++### Key Flows to Verify+1. **Search & Browse**: Type queries, switch between MovieBox, 4KHDHub, BDIX, Addons, and Live TV.+2. **Playback Launch & Return**: Launch stream in player, exit player, verify terminal state is cleanly restored without residual escape sequences.+3. **History & State**: Verify playback progress and watched checkmarks update accurately.+4. **Downloads**: Test single episode and batch season download queuing.diff --git a/tests/addons_manifest.rs b/tests/addons_manifest.rsnew file mode 100644index 0000000..b8f9594--- /dev/null+++ b/tests/addons_manifest.rs@@ -0,0 +1,23 @@+use moviebox_tui::providers::addons::models::AddonManifest;++#[test]+fn test_addon_manifest_fixture_deserialization() {+ let fixture_content = include_str!("fixtures/addons/manifest.json");+ let manifest: AddonManifest = serde_json::from_str(fixture_content)+ .expect("failed to deserialize Cinemeta addon manifest");++ assert_eq!(manifest.id, "org.stremio.cinemeta");+ assert_eq!(manifest.name, "Cinemeta");+ assert_eq!(manifest.version.as_deref(), Some("3.0.12"));+ assert_eq!(manifest.resources.len(), 3);+ assert_eq!(manifest.resources[0].name(), "catalog");+ assert_eq!(manifest.resources[1].name(), "meta");+ assert_eq!(manifest.resources[2].name(), "stream");++ assert_eq!(manifest.catalogs.len(), 2);+ assert_eq!(manifest.catalogs[0].r#type, "movie");+ assert_eq!(manifest.catalogs[0].id, "top");+ assert_eq!(manifest.catalogs[0].name.as_deref(), Some("Popular Movies"));+ assert_eq!(manifest.catalogs[0].extra.len(), 1);+ assert_eq!(manifest.catalogs[0].extra[0].name, "genre");+}diff --git a/tests/cache_lifecycle.rs b/tests/cache_lifecycle.rsnew file mode 100644index 0000000..4cc4e05--- /dev/null+++ b/tests/cache_lifecycle.rs@@ -0,0 +1,62 @@+mod common;++use common::TempTestDir;+use moviebox_tui::cache::{atomic_write_file, atomic_write_file_async, md5_hex};+use std::fs;++#[test]+fn test_md5_hex_determinism() {+ assert_eq!(+ md5_hex("https://example.com/stream.m3u8"),+ "6d61b1f81ddc272d47bef071abd229bd"+ );+ assert_eq!(md5_hex(""), "d41d8cd98f00b204e9800998ecf8427e");+ assert_ne!(md5_hex("query1"), md5_hex("query2"));+}++#[test]+fn test_atomic_write_sync() {+ let temp_dir = TempTestDir::new("cache_atomic_sync");+ let target_file = temp_dir.path.join("data.json");+ let content = b"{\"status\":\"cached\",\"results\":[1,2,3]}";++ atomic_write_file(&target_file, content).expect("atomic write failed");+ assert!(target_file.exists());++ let read_back = fs::read(&target_file).expect("failed to read back file");+ assert_eq!(read_back, content);+}++#[tokio::test]+async fn test_atomic_write_async() {+ let temp_dir = TempTestDir::new("cache_atomic_async");+ let target_file = temp_dir.path.join("async_data.json");+ let content = b"{\"async\":true,\"items\":[\"a\",\"b\"]}";++ atomic_write_file_async(&target_file, content)+ .await+ .expect("async atomic write failed");+ assert!(target_file.exists());++ let read_back = tokio::fs::read(&target_file)+ .await+ .expect("failed to read back async file");+ assert_eq!(read_back, content);+}++#[test]+fn test_atomic_overwrite_corrupt_data() {+ let temp_dir = TempTestDir::new("cache_corrupt_overwrite");+ let target_file = temp_dir.path.join("cache.json");++ fs::write(&target_file, b"CORRUPTED_PARTIAL_JSON_{{[").unwrap();+ assert!(target_file.exists());++ let valid_data = b"{\"valid\":true,\"recovered\":1}";+ atomic_write_file(&target_file, valid_data).unwrap();++ let content = fs::read(&target_file).unwrap();+ assert_eq!(content, valid_data);+ let parsed: serde_json::Value = serde_json::from_slice(&content).unwrap();+ assert_eq!(parsed["valid"], true);+}diff --git a/tests/common/mod.rs b/tests/common/mod.rsnew file mode 100644index 0000000..08443b7--- /dev/null+++ b/tests/common/mod.rs@@ -0,0 +1,51 @@+use moviebox_tui::history::WatchHistoryItem;+use std::path::PathBuf;+use std::sync::atomic::{AtomicUsize, Ordering};++static COUNTER: AtomicUsize = AtomicUsize::new(1);++pub struct TempTestDir {+ pub path: PathBuf,+}++impl TempTestDir {+ pub fn new(prefix: &str) -> Self {+ let count = COUNTER.fetch_add(1, Ordering::SeqCst);+ let dir_name = format!("mb_test_{prefix}_{}_{}", std::process::id(), count);+ let path = std::env::temp_dir().join(dir_name);+ std::fs::create_dir_all(&path).expect("failed to create temp test dir");+ Self { path }+ }+}++impl Drop for TempTestDir {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.path);+ }+}++#[allow(dead_code)]+pub fn make_history_item(+ provider: &str,+ subject_id: &str,+ title: &str,+ stype: i64,+ release_year: &str,+ season: usize,+ episode: usize,+) -> WatchHistoryItem {+ WatchHistoryItem {+ provider: provider.to_string(),+ subject_id: subject_id.to_string(),+ title: title.to_string(),+ cover_url: None,+ stype,+ release_year: release_year.to_string(),+ season,+ episode,+ timestamp: 1700000000,+ duration_seconds: Some(3600),+ progress_seconds: 1800,+ completed: false,+ }+}diff --git a/tests/download_integration.rs b/tests/download_integration.rsnew file mode 100644index 0000000..058b074--- /dev/null+++ b/tests/download_integration.rs@@ -0,0 +1,75 @@+mod common;++use common::TempTestDir;+use moviebox_tui::download::{DEFAULT_STREAM_NAME, safe_file_stem};+use std::fs;++#[test]+fn test_safe_file_stem_empty_fallback() {+ assert_eq!(safe_file_stem(""), DEFAULT_STREAM_NAME);+ assert_eq!(safe_file_stem(" "), DEFAULT_STREAM_NAME);+ assert_eq!(safe_file_stem("..."), DEFAULT_STREAM_NAME);+ assert_eq!(safe_file_stem("___"), DEFAULT_STREAM_NAME);+}++#[test]+fn test_download_directory_structure_creation() {+ let temp_dir = TempTestDir::new("download_structure");+ let movie_dir = temp_dir.path.join("Movies").join("Inception (2010)");+ let series_dir = temp_dir+ .path+ .join("Series")+ .join("Breaking Bad")+ .join("Season 01");++ fs::create_dir_all(&movie_dir).expect("failed to create movie dir");+ fs::create_dir_all(&series_dir).expect("failed to create series dir");++ assert!(movie_dir.exists());+ assert!(series_dir.exists());++ let segment_file = series_dir.join("Breaking Bad - S01E01.mp4.0.part");+ fs::write(&segment_file, b"partial chunk data").expect("failed to write segment");+ assert!(segment_file.exists());+}++#[test]+fn test_multi_segment_assembly_simulation() {+ let temp_dir = TempTestDir::new("segment_assembly");+ let dest_file = temp_dir.path.join("Movie.mp4");+ let assembling_file = temp_dir.path.join("Movie.mp4.assembling");++ let chunk0 = b"CHUNK_000_BYTES_";+ let chunk1 = b"CHUNK_001_BYTES_";+ let chunk2 = b"CHUNK_002_BYTES_";++ let part0 = temp_dir.path.join("Movie.mp4.0.part");+ let part1 = temp_dir.path.join("Movie.mp4.1.part");+ let part2 = temp_dir.path.join("Movie.mp4.2.part");++ fs::write(&part0, chunk0).unwrap();+ fs::write(&part1, chunk1).unwrap();+ fs::write(&part2, chunk2).unwrap();++ let mut assembled = Vec::new();+ assembled.extend_from_slice(&fs::read(&part0).unwrap());+ assembled.extend_from_slice(&fs::read(&part1).unwrap());+ assembled.extend_from_slice(&fs::read(&part2).unwrap());++ fs::write(&assembling_file, &assembled).unwrap();+ fs::rename(&assembling_file, &dest_file).unwrap();++ let _ = fs::remove_file(&part0);+ let _ = fs::remove_file(&part1);+ let _ = fs::remove_file(&part2);++ assert!(dest_file.exists());+ assert_eq!(+ fs::read(&dest_file).unwrap().len(),+ chunk0.len() + chunk1.len() + chunk2.len()+ );+ assert!(!part0.exists());+ assert!(!part1.exists());+ assert!(!part2.exists());+ assert!(!assembling_file.exists());+}diff --git a/tests/fixtures/addons/manifest.json b/tests/fixtures/addons/manifest.jsonnew file mode 100644index 0000000..005156f--- /dev/null+++ b/tests/fixtures/addons/manifest.json@@ -0,0 +1,39 @@+{+ "id": "org.stremio.cinemeta",+ "version": "3.0.12",+ "name": "Cinemeta",+ "description": "Official Cinemeta movie and TV catalog",+ "resources": [+ "catalog",+ {+ "name": "meta",+ "types": ["movie", "series"],+ "idPrefixes": ["tt"]+ },+ {+ "name": "stream",+ "types": ["movie", "series"],+ "idPrefixes": ["tt"]+ }+ ],+ "types": ["movie", "series", "anime"],+ "catalogs": [+ {+ "type": "movie",+ "id": "top",+ "name": "Popular Movies",+ "extra": [+ {+ "name": "genre",+ "isRequired": false,+ "options": ["Action", "Comedy", "Drama", "Sci-Fi"]+ }+ ]+ },+ {+ "type": "series",+ "id": "top",+ "name": "Popular Series"+ }+ ]+}diff --git a/tests/fixtures/m3u/sample_playlist.m3u b/tests/fixtures/m3u/sample_playlist.m3unew file mode 100644index 0000000..e3db47e--- /dev/null+++ b/tests/fixtures/m3u/sample_playlist.m3u@@ -0,0 +1,9 @@+#EXTM3U+#EXTINF:-1 tvg-id="cnn.us" tvg-logo="https://example.com/cnn.png" group-title="News",CNN International HD+https://stream.example.com/cnn/live.m3u8+#EXTINF:-1 tvg-id='bbc.uk' tvg-logo='https://example.com/bbc.png' group-title='News',BBC News 24+https://stream.example.com/bbc/live.m3u8+#EXTINF:-1 tvg-id="espn.us" group-title="Sports",ESPN Main+https://stream.example.com/espn/live.m3u8+#EXTINF:-1,Discovery Channel HD+https://stream.example.com/discovery/live.m3u8diff --git a/tests/history_reconciliation.rs b/tests/history_reconciliation.rsnew file mode 100644index 0000000..fddb59e--- /dev/null+++ b/tests/history_reconciliation.rs@@ -0,0 +1,73 @@+mod common;++use common::{TempTestDir, make_history_item};+use moviebox_tui::history::{HistoryManager, PendingPlaybackState};+use std::fs;++#[test]+fn test_history_identity_rules() {+ let movie1 = make_history_item("moviebox", "mb_10", "Dune", 1, "2021", 0, 0);+ let movie2 = make_history_item("moviebox", "mb_10", "Dune: Part One", 1, "2021", 0, 0);+ assert!(HistoryManager::is_same_show(&movie1, &movie2));++ let series = make_history_item("moviebox", "mb_20", "Dune: Prophecy", 2, "2024", 1, 1);+ assert!(!HistoryManager::is_same_show(&movie1, &series));++ let addon_movie = make_history_item("addons", "tt1160419", "Dune", 1, "2021", 0, 0);+ assert!(!HistoryManager::is_same_show(&movie1, &addon_movie));++ let remake1978 = make_history_item("moviebox", "mb_h1", "Halloween", 1, "1978", 0, 0);+ let remake2018 = make_history_item("moviebox", "mb_h2", "Halloween", 1, "2018", 0, 0);+ assert!(!HistoryManager::is_same_show(&remake1978, &remake2018));+}++#[test]+fn test_history_reconciliation_multi_episode_flow() {+ let temp_dir = TempTestDir::new("hist_reconcile");+ let state_file_ep1 = temp_dir.path.join("moviebox_show1_1_1.json");+ let state_file_ep2 = temp_dir.path.join("moviebox_show1_1_2.json");++ let ep1_state = PendingPlaybackState {+ provider: "moviebox".to_string(),+ subject_id: "show1".to_string(),+ season: 1,+ episode: 1,+ progress_seconds: 3600,+ duration_seconds: Some(3600),+ completed: true,+ timestamp: 2000,+ };+ fs::write(&state_file_ep1, serde_json::to_string(&ep1_state).unwrap()).unwrap();++ let ep2_state = PendingPlaybackState {+ provider: "moviebox".to_string(),+ subject_id: "show1".to_string(),+ season: 1,+ episode: 2,+ progress_seconds: 1200,+ duration_seconds: Some(3600),+ completed: false,+ timestamp: 2500,+ };+ fs::write(&state_file_ep2, serde_json::to_string(&ep2_state).unwrap()).unwrap();++ let mut manager = HistoryManager::default();+ manager.recent.push(make_history_item(+ "moviebox",+ "show1",+ "Epic Series",+ 2,+ "2024",+ 1,+ 2,+ ));++ let modified = manager.reconcile_from_dir(&temp_dir.path);+ assert!(modified);+ assert!(manager.is_watched("moviebox", "show1", 1, 1));+ assert_eq!(manager.recent.first().unwrap().episode, 2);+ assert_eq!(manager.recent.first().unwrap().progress_seconds, 1200);++ assert!(!state_file_ep1.exists());+ assert!(!state_file_ep2.exists());+}diff --git a/tests/m3u_integration.rs b/tests/m3u_integration.rsnew file mode 100644index 0000000..211eddb--- /dev/null+++ b/tests/m3u_integration.rs@@ -0,0 +1,38 @@+use moviebox_tui::providers::tv::parser::M3UParser;++#[test]+fn test_m3u_fixture_parsing() {+ let fixture_content = include_str!("fixtures/m3u/sample_playlist.m3u");+ let parser = M3UParser::new();+ let channels = parser.parse_m3u(fixture_content);++ assert_eq!(channels.len(), 4);++ let cnn = &channels[0];+ assert_eq!(cnn.id, "cnn.us");+ assert_eq!(cnn.name, "CNN International HD");+ assert_eq!(cnn.logo, "https://example.com/cnn.png");+ assert_eq!(cnn.group, "News");+ assert_eq!(cnn.stream_url, "https://stream.example.com/cnn/live.m3u8");++ let bbc = &channels[1];+ assert_eq!(bbc.id, "bbc.uk");+ assert_eq!(bbc.name, "BBC News 24");+ assert_eq!(bbc.logo, "https://example.com/bbc.png");+ assert_eq!(bbc.group, "News");+ assert_eq!(bbc.stream_url, "https://stream.example.com/bbc/live.m3u8");++ let espn = &channels[2];+ assert_eq!(espn.id, "espn.us");+ assert_eq!(espn.name, "ESPN Main");+ assert_eq!(espn.group, "Sports");+ assert_eq!(espn.stream_url, "https://stream.example.com/espn/live.m3u8");++ let discovery = &channels[3];+ assert_eq!(discovery.id, "Discovery Channel HD");+ assert_eq!(discovery.name, "Discovery Channel HD");+ assert_eq!(+ discovery.stream_url,+ "https://stream.example.com/discovery/live.m3u8"+ );+}diff --git a/tests/player_integration.rs b/tests/player_integration.rsnew file mode 100644index 0000000..fe5795d--- /dev/null+++ b/tests/player_integration.rs@@ -0,0 +1,28 @@+use moviebox_tui::player::format_mpv_script_opts;+use std::path::PathBuf;++#[test]+fn test_player_script_opts_windows_drive_path() {+ let win_path = PathBuf::from(r"C:\Users\Samir\AppData\Roaming\moviebox\state_123.json");+ let opts = format_mpv_script_opts("moviebox", "sub_456", 1, 3, &win_path);+ assert!(!opts.contains(r"\"));+ assert!(opts.contains("moviebox-provider=moviebox"));+ assert!(opts.contains("moviebox-subject_id=sub_456"));+ assert!(opts.contains("moviebox-season=1"));+ assert!(opts.contains("moviebox-episode=3"));+ assert!(+ opts.contains("moviebox-state_file=C:/Users/Samir/AppData/Roaming/moviebox/state_123.json")+ );+}++#[test]+fn test_player_script_opts_unix_path_with_spaces() {+ let unix_path =+ PathBuf::from("/Users/User Name/Library/Application Support/MovieBox-Tui/state.json");+ let opts = format_mpv_script_opts("addons", "tt1234567", 0, 0, &unix_path);+ assert!(opts.contains("moviebox-provider=addons"));+ assert!(opts.contains("moviebox-subject_id=tt1234567"));+ assert!(opts.contains(+ "moviebox-state_file=/Users/User Name/Library/Application Support/MovieBox-Tui/state.json"+ ));+}diff --git a/tests/url_security.rs b/tests/url_security.rsnew file mode 100644index 0000000..67b3bce--- /dev/null+++ b/tests/url_security.rs@@ -0,0 +1,39 @@+use moviebox_tui::download::safe_file_stem;+use moviebox_tui::tui::text::is_http_url;++#[test]+fn test_is_http_url_validation() {+ assert!(is_http_url("http://example.com/stream.m3u8"));+ assert!(is_http_url("https://example.com/stream.m3u8"));+ assert!(is_http_url(" https://secure.example.com/path "));++ assert!(!is_http_url("file:///etc/passwd"));+ assert!(!is_http_url("ftp://server/file.mp4"));+ assert!(!is_http_url("javascript:alert(1)"));+ assert!(!is_http_url(""));+}++#[test]+fn test_safe_file_stem_sanitization() {+ // Path traversal and separators+ assert_eq!(safe_file_stem("../../../etc/passwd"), "etc_passwd");+ assert_eq!(+ safe_file_stem("C:\\Windows\\System32\\calc.exe"),+ "C__Windows_System32_calc.exe"+ );++ // Dangerous Windows reserved names+ assert_eq!(safe_file_stem("CON"), "CON_");+ assert_eq!(safe_file_stem("con"), "con_");+ assert_eq!(safe_file_stem("PRN"), "PRN_");+ assert_eq!(safe_file_stem("AUX"), "AUX_");+ assert_eq!(safe_file_stem("NUL"), "NUL_");+ assert_eq!(safe_file_stem("COM1"), "COM1_");+ assert_eq!(safe_file_stem("LPT9"), "LPT9_");++ // Characters forbidden on NTFS/FAT+ assert_eq!(+ safe_file_stem("Movie: The <Ultimate> Edition *?|"),+ "Movie_ The _Ultimate_ Edition"+ );+}