Skip to content

Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.

test: isolate test sandbox, prune duplicate tests, and expand provider/player coverage

Samir Hossains862a343a2e74
diff --git a/CHANGELOG.md b/CHANGELOG.md
index facf4c1..e327f72 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -48,6 +48,8 @@
- Optimized typed cache serialization in `src/cache.rs` using direct in-place encoding (`rmp_serde::encode::write`) into pre-seeded magic header buffers, eliminating intermediate vector allocations and duplicate memory copies.
- Pre-allocated file buffer capacity from file metadata in `get_typed_cache` in `src/cache.rs`, eliminating repetitive vector reallocations during cache reads.
- Offloaded `atomic_write_file_async` in `src/cache.rs` to `tokio::task::spawn_blocking`, switched `src/logging.rs` to `WriteMode::BufferAndFlush` with a `LazyLock` cached home directory path, centralized corrupt JSON file rotation (`rotate_corrupt_file`) in `src/config.rs`, and enabled cross-platform stale update artifact cleanup in `src/updater/apply.rs`.
+ - Isolated all unit and integration test runs into a per-process temporary sandbox (`TEST_SANDBOX_DIR` in `src/config.rs`) and guarded external browser launches (`open_external_url` in `src/net.rs`), preventing tests from modifying real user configuration, watch history, favorites, or disk cache files.
+ - Added unit and mock-server test coverage for `4KHDHub` HTTP 206 seekable mirror prioritization, `CircleFTP` catalog mapping, `DhakaFlix` stream extraction, `Addons` concurrent stream aggregation and torrent filtering, `TV` UTF-8 BOM / HLS M3U parsing, `IINA` command construction, `StreamRelay` DASH sidecar warmup, non-`mpv` watch progress retention, and `Action::SetStatus` warning/modal toast routing.
### Changed
- **TUI & Ergonomics**:
- Remapped `q` / `Q` on `Screen::Details` in `src/tui/app/keyboard.rs` from application exit to `Action::GoBack`, preserving active search results and returning to the home screen without unexpected process termination.
diff --git a/docs/architecture.md b/docs/architecture.md
index 19092b5..f728cd3 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -148,9 +148,9 @@ interval, forwarding them into the action channel (capacity 128).
1. User selects a result → `Action::PlayStream` (moviebox) or 4KHDHub/BDIX resolve.
2. The provider resolves a `PlaybackSource` (url + optional headers/subtitle).
3. `launch_player` builds the player command (`player.rs`), optionally downloads the
- subtitle to a temp file, and spawns the player with null stdin/stdout and piped
- stderr; a blocking task waits and reports crashes.
-4. Playback is handed to mpv / VLC / IINA / Android intent per the active player.
+ subtitle to a temp file, and spawns the player in a detached OS session (`setsid` /
+ `DETACHED_PROCESS`) with null stdin/stdout and file-backed stderr logging; a
+ blocking task waits and reports crashes while the TUI remains open.
## Configuration and persistence
diff --git a/docs/cache.md b/docs/cache.md
index b90b41f..83b47d4 100644
--- a/docs/cache.md
+++ b/docs/cache.md
@@ -27,7 +27,8 @@ The envelope stores the expiration timestamp (`expires_at: u64`) alongside the s
| `search` | 24 Hours | Search query results per provider |
| `details` | Dynamic (CloudFront TTL) | Subject details, cast, and signed streaming cookies (auto-adapts to upstream cookie expiration, min 1h, max 24h) |
| `streams` | Dynamic (Cookie Expiration) | Direct streaming and DASH manifest URLs (auto-adapts to `CloudFront-Policy` and `Edge-Cache-Cookie` expiration timestamp `:t=`, min 1m, max 2h) |
-| `posters` | 7 Days | Downloaded poster image buffers |
+| `captions` | 24 Hours | Aggregated MovieBox external subtitle lists (primary + sibling dubs, background-prefetched on Details load) |
+| `posters` | 30 Days | Downloaded poster image buffers |
| `tv` | 24 Hours | Remote M3U playlist text snapshots |
## Durability & Safety
diff --git a/docs/testing.md b/docs/testing.md
index 7902599..cfa41c5 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -4,7 +4,7 @@ This document describes the testing architecture, quality assurance procedures,
## 1. Test Architecture
-The test suite comprises **510 automated tests across 12 test suites** (381 unit tests in `src/lib.rs` and 129 integration tests across 10 focused suites in `tests/`), running fully offline by default without mocking or live network dependencies.
+The test suite runs in an isolated process sandbox (`TEST_SANDBOX_DIR` in `src/config.rs`) that redirects `config_dir()`, `data_dir()`, and `cache_dir()` to temporary directories and guards external browser launches (`open_external_url` in `src/net.rs`), ensuring tests never read, mutate, or delete host user files (`~/.config`, `~/.local/share`, `~/.cache`).
The MovieBox-TUI test architecture follows a strict separation of concerns:
```text
@@ -48,7 +48,7 @@ Integration tests live in the `tests/` directory and test externally observable
- **`history_audit.rs`**: Validates cross-mode watch progress, series advancement and completion tracking, threshold boundaries for in-progress states, history disk persistence roundtrips, Lua tracker reconciliation, update precision preservation, repeated play deduplication, and `/history` search list integration.
- **`favorites_lifecycle.rs`**: Validates Favorites persistence boundaries, identity deduplication, `/favorites` loading, landing-row navigation, and independence from watch-history clearing.
- **`performance_audit.rs`**: Validates empirical performance benchmarks and regression thresholds across algorithmic hot paths (SIMD text truncation, MD5 hex table lookup, M3U capacity preallocation, and headless frame draw latencies).
-- **`live_stream_verification.rs`**: Validates real-world stream link resolution across MovieBox signed CDN endpoints and 4KHDHub multi-mirror releases. The tests are `#[ignore]`-gated for offline execution; opt in with `cargo test --test live_stream_verification -- --ignored`.
+- **`live_stream_verification.rs`**: Validates real-world stream link resolution across MovieBox signed CDN endpoints, 4KHDHub multi-mirror releases, and Dramachi streams. The tests are `#[ignore]`-gated for offline execution; opt in with `cargo test --test live_stream_verification -- --ignored`.
---
## 2. Running Automated Tests
diff --git a/src/config.rs b/src/config.rs
index 7ac01c4..89633c1 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -55,10 +55,34 @@ impl Default for Config {
pub const APP_NAME: &str = "moviebox-tui";
+static TEST_SANDBOX_DIR: std::sync::LazyLock<Option<PathBuf>> = std::sync::LazyLock::new(|| {
+ let is_test_binary = cfg!(test)
+ || std::env::var_os("NEXTEST").is_some()
+ || std::env::current_exe()
+ .ok()
+ .and_then(|p| p.parent().and_then(|d| d.file_name()).map(|n| n == "deps"))
+ .unwrap_or(false);
+ if is_test_binary {
+ let dir =
+ std::env::temp_dir().join(format!("moviebox_test_sandbox_{}", std::process::id()));
+ let _ = std::fs::create_dir_all(&dir);
+ Some(dir)
+ } else {
+ None
+ }
+});
+
+pub fn is_test_environment() -> bool {
+ TEST_SANDBOX_DIR.is_some()
+}
+
pub fn config_dir() -> Option<PathBuf> {
if let Ok(dir) = std::env::var("MOVIEBOX_CONFIG_DIR") {
return Some(PathBuf::from(dir));
}
+ if let Some(sandbox) = TEST_SANDBOX_DIR.as_ref() {
+ return Some(sandbox.join("config").join(APP_NAME));
+ }
if let Some(dir) = dirs::config_dir() {
return Some(dir.join(APP_NAME));
}
@@ -89,6 +113,9 @@ pub fn data_dir() -> Option<PathBuf> {
if let Ok(dir) = std::env::var("MOVIEBOX_DATA_DIR") {
return Some(PathBuf::from(dir));
}
+ if let Some(sandbox) = TEST_SANDBOX_DIR.as_ref() {
+ return Some(sandbox.join("data").join(APP_NAME));
+ }
if let Some(dir) = dirs::data_dir() {
return Some(dir.join(APP_NAME));
}
@@ -119,6 +146,9 @@ pub fn cache_dir() -> PathBuf {
if let Ok(dir) = std::env::var("MOVIEBOX_CACHE_DIR") {
return PathBuf::from(dir);
}
+ if let Some(sandbox) = TEST_SANDBOX_DIR.as_ref() {
+ return sandbox.join("cache").join(APP_NAME);
+ }
if let Some(dir) = dirs::cache_dir() {
return dir.join(APP_NAME);
}
diff --git a/src/net.rs b/src/net.rs
index 25c9daf..6e40ef2 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -131,6 +131,13 @@ pub fn is_http_url(source: &str) -> bool {
let trimmed = source.trim();
trimmed.starts_with("http://") || trimmed.starts_with("https://")
}
+
+pub fn open_external_url(url: &str) -> std::io::Result<()> {
+ if crate::config::is_test_environment() {
+ return Ok(());
+ }
+ open::that(url)
+}
#[cfg(test)]
mod tests {
use super::*;
@@ -167,11 +174,41 @@ mod tests {
);
}
- #[test]
- fn clones_share_lazy_state_slot() {
- let original = FallbackResolver::new();
- let _clone = original.clone();
- let _builder = http_client_builder();
+ #[tokio::test]
+ async fn probe_url_falls_back_from_head_to_ranged_get() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ for _ in 0..2 {
+ if let Ok((mut stream, _)) = listener.accept().await {
+ let mut buf = [0u8; 1024];
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let req = String::from_utf8_lossy(&buf[..n]);
+ if req.starts_with("HEAD ") {
+ let _ = stream
+ .write_all(
+ b"HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n",
+ )
+ .await;
+ } else if req.starts_with("GET ")
+ && req.to_ascii_lowercase().contains("range: bytes=0-0")
+ {
+ let _ = stream
+ .write_all(
+ b"HTTP/1.1 206 Partial Content\r\nContent-Length: 1\r\n\r\nX",
+ )
+ .await;
+ } else {
+ let _ = stream
+ .write_all(b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n")
+ .await;
+ }
+ }
+ }
+ });
+ let url = format!("http://{addr}/video.mkv");
+ assert!(probe_url(&url, std::time::Duration::from_secs(2)).await);
}
#[test]
fn test_is_http_url() {
diff --git a/src/player.rs b/src/player.rs
index 48101b0..3658701 100644
--- a/src/player.rs
+++ b/src/player.rs
@@ -2044,4 +2044,49 @@ mod tests {
let status = child.wait().expect("wait detached sh");
assert!(status.success());
}
+
+ #[test]
+ fn test_iina_command_dash_vs_direct_and_script_filtering() {
+ let direct_cmd = command(
+ PlayerKind::Iina,
+ "https://cdn.example.com/movie.mkv",
+ Some("/tmp/sub.srt"),
+ &[("Referer".to_string(), "https://example.com".to_string())],
+ Some((1280, 720)),
+ Some(120),
+ Some(("moviebox", "subj_1", 1, 1)),
+ Some(1080),
+ );
+ let direct_args: Vec<String> = direct_cmd
+ .get_args()
+ .map(|a| a.to_string_lossy().into_owned())
+ .collect();
+ assert!(direct_args.iter().any(|a| a.ends_with("hwdec=auto-safe")));
+ assert!(
+ direct_args
+ .iter()
+ .any(|a| a.ends_with("stream-buffer-size=4M"))
+ );
+ assert!(direct_args.iter().any(|a| a.ends_with("ytdl=no")));
+ assert!(!direct_args.iter().any(|a| a.contains("force-seekable=yes")));
+ #[cfg(target_os = "macos")]
+ assert!(!direct_args.iter().any(|a| a.starts_with("--mpv-script=")));
+
+ let dash_cmd = command(
+ PlayerKind::Iina,
+ "http://127.0.0.1:9000/https/cdn.example.com/dash/index.mpd",
+ None,
+ &[],
+ None,
+ None,
+ None,
+ Some(720),
+ );
+ let dash_args: Vec<String> = dash_cmd
+ .get_args()
+ .map(|a| a.to_string_lossy().into_owned())
+ .collect();
+ assert!(dash_args.iter().any(|a| a.ends_with("force-seekable=yes")));
+ assert!(!dash_args.iter().any(|a| a.ends_with("ytdl=no")));
+ }
}
diff --git a/src/providers/addons/aggregator.rs b/src/providers/addons/aggregator.rs
index 8274d58..29a1ac4 100644
--- a/src/providers/addons/aggregator.rs
+++ b/src/providers/addons/aggregator.rs
@@ -138,3 +138,84 @@ fn quality_score(quality: Option<&str>) -> u32 {
_ => 0,
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ #[tokio::test]
+ async fn test_aggregate_streams_merges_deduplicates_sorts_and_reports_blocked_torrents() {
+ let listener1 = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr1 = listener1.local_addr().unwrap();
+ tokio::spawn(async move {
+ if let Ok((mut stream, _)) = listener1.accept().await {
+ let mut buf = [0u8; 1024];
+ let _ = stream.read(&mut buf).await;
+ let body = r#"{"streams":[
+ {"name":"AddonA 720p","title":"Movie.720p.mp4\n💾 1.0 GB","url":"https://cdn.example.com/720p.mp4"},
+ {"name":"AddonA 4K","title":"Movie.2160p.HEVC.mkv\n💾 10.0 GB","url":"https://cdn.example.com/2160p.mkv"}
+ ]}"#;
+ let resp = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
+ body.len(),
+ body
+ );
+ let _ = stream.write_all(resp.as_bytes()).await;
+ }
+ });
+
+ let listener2 = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr2 = listener2.local_addr().unwrap();
+ tokio::spawn(async move {
+ if let Ok((mut stream, _)) = listener2.accept().await {
+ let mut buf = [0u8; 1024];
+ let _ = stream.read(&mut buf).await;
+ let body = r#"{"streams":[
+ {"name":"TorrentOnly","title":"P2P Swarm","infoHash":"0123456789abcdef0123456789abcdef01234567"}
+ ]}"#;
+ let resp = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
+ body.len(),
+ body
+ );
+ let _ = stream.write_all(resp.as_bytes()).await;
+ }
+ });
+
+ let addons = vec![
+ InstalledAddon {
+ manifest_url: format!("http://{addr1}/manifest.json"),
+ name: "HTTP Addon".to_string(),
+ version: Some("1.0.0".to_string()),
+ description: None,
+ enabled: true,
+ provides_catalog: false,
+ provides_meta: false,
+ provides_stream: true,
+ id_prefixes: vec![],
+ types: vec!["movie".to_string()],
+ },
+ InstalledAddon {
+ manifest_url: format!("http://{addr2}/manifest.json"),
+ name: "P2P Addon".to_string(),
+ version: Some("1.0.0".to_string()),
+ description: None,
+ enabled: true,
+ provides_catalog: false,
+ provides_meta: false,
+ provides_stream: true,
+ id_prefixes: vec![],
+ types: vec!["movie".to_string()],
+ },
+ ];
+
+ let client = AddonClient::new();
+ let (releases, blocked) =
+ aggregate_streams(&client, &addons, "tt1234567", 0, 0, false).await;
+ assert_eq!(blocked, vec!["P2P Addon".to_string()]);
+ assert_eq!(releases.len(), 2);
+ assert_eq!(releases[0].quality.as_deref(), Some("2160p"));
+ assert_eq!(releases[1].quality.as_deref(), Some("720p"));
+ }
+}
diff --git a/src/providers/bdix/circleftp/parser.rs b/src/providers/bdix/circleftp/parser.rs
index 74b173f..e279b9d 100644
--- a/src/providers/bdix/circleftp/parser.rs
+++ b/src/providers/bdix/circleftp/parser.rs
@@ -64,3 +64,56 @@ pub fn circleftp_search_to_catalog(response: &CircleFtpSearchResponse) -> Vec<Ca
}
items
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_circleftp_search_to_catalog_maps_movies_and_series() {
+ let json_str = r#"{
+ "posts": [
+ {
+ "id": 101,
+ "title": "Dune: Part Two",
+ "type": "movie",
+ "year": 2024,
+ "image": "dune2.jpg"
+ },
+ {
+ "id": 202,
+ "name": "Severance",
+ "type": "series",
+ "year": "2022",
+ "imageSm": "sev_sm.jpg"
+ }
+ ]
+ }"#;
+ let response: CircleFtpSearchResponse = serde_json::from_str(json_str).unwrap();
+ let catalog = circleftp_search_to_catalog(&response);
+ assert_eq!(catalog.len(), 2);
+ assert_eq!(catalog[0].id.value, "101");
+ assert_eq!(catalog[0].title, "Dune: Part Two");
+ assert_eq!(catalog[0].media_type, MediaType::Movie);
+ assert_eq!(catalog[0].year.as_deref(), Some("2024"));
+ assert!(
+ catalog[0]
+ .poster_url
+ .as_deref()
+ .unwrap()
+ .ends_with("dune2.jpg")
+ );
+
+ assert_eq!(catalog[1].id.value, "202");
+ assert_eq!(catalog[1].title, "Severance");
+ assert_eq!(catalog[1].media_type, MediaType::Series);
+ assert_eq!(catalog[1].year.as_deref(), Some("2022"));
+ assert!(
+ catalog[1]
+ .poster_url
+ .as_deref()
+ .unwrap()
+ .ends_with("sev_sm.jpg")
+ );
+ }
+}
diff --git a/src/providers/bdix/dhakaflix/client.rs b/src/providers/bdix/dhakaflix/client.rs
index 5a2c5a0..8e63fd1 100644
--- a/src/providers/bdix/dhakaflix/client.rs
+++ b/src/providers/bdix/dhakaflix/client.rs
@@ -443,4 +443,34 @@ mod tests {
assert_eq!(base, "http://172.16.50.4");
assert_eq!(path, "/movies/action/film.mkv");
}
+
+ #[tokio::test]
+ async fn test_dhakaflix_streams_extracts_and_parses_video_releases() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ if let Ok((mut stream, _)) = listener.accept().await {
+ let mut buf = [0u8; 1024];
+ let _ = stream.read(&mut buf).await;
+ let body = r#"{"items":[{"href":"/Movies/Inception.2010.2160p.HEVC.Dual.mkv","size":4294967296},{"href":"/Movies/notes.txt","size":128}]}"#;
+ let resp = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
+ body.len(),
+ body
+ );
+ let _ = stream.write_all(resp.as_bytes()).await;
+ }
+ });
+
+ let client = DhakaFlixClient::new();
+ let id = format!("http://{addr}:/Movies/Inception/");
+ let releases = client.streams(&id).await.expect("streams");
+ assert_eq!(releases.len(), 1);
+ assert_eq!(releases[0].filename, "Inception.2010.2160p.HEVC.Dual.mkv");
+ assert_eq!(releases[0].quality.as_deref(), Some("4K"));
+ assert_eq!(releases[0].codec.as_deref(), Some("HEVC"));
+ assert_eq!(releases[0].language.as_deref(), Some("Dual Audio"));
+ assert_eq!(releases[0].size_bytes, Some(4_294_967_296));
+ }
}
diff --git a/src/providers/fourkhdhub/client.rs b/src/providers/fourkhdhub/client.rs
index 388063d..6d1773e 100644
--- a/src/providers/fourkhdhub/client.rs
+++ b/src/providers/fourkhdhub/client.rs
@@ -401,4 +401,35 @@ mod tests {
assert!(client.provider_url("movie/inception-2010").is_ok());
assert!(client.provider_url("https://evil.com/movie").is_err());
}
+
+ #[tokio::test]
+ async fn preflight_blocks_loopback_ssrf_and_prioritizes_seekable_mirrors() {
+ let client = FourKHdHubClient::new().expect("client");
+ assert!(
+ client
+ .preflight("http://127.0.0.1:8080/video.mkv", &[])
+ .await
+ .is_err()
+ );
+
+ let mut candidates = [
+ (
+ false,
+ 0_u8,
+ "https://r2.dev/unseekable.mkv",
+ "10Gbps Server",
+ ),
+ (false, 4_u8, "https://workers.dev/quota.mkv", "HubCloud"),
+ (
+ true,
+ 1_u8,
+ "https://pixeldrain.dev/seekable.mkv",
+ "PixelDrain",
+ ),
+ ];
+ candidates.sort_by_key(|(is_seekable, score, _, _)| (!*is_seekable, *score));
+ assert_eq!(candidates[0].2, "https://pixeldrain.dev/seekable.mkv");
+ assert_eq!(candidates[1].2, "https://r2.dev/unseekable.mkv");
+ assert_eq!(candidates[2].2, "https://workers.dev/quota.mkv");
+ }
}
diff --git a/src/providers/models.rs b/src/providers/models.rs
index 4091072..02543ff 100644
--- a/src/providers/models.rs
+++ b/src/providers/models.rs
@@ -533,4 +533,61 @@ mod tests {
"4KHDHub error (502)."
);
}
+
+ #[test]
+ fn test_parse_size_bytes_formats_and_units() {
+ assert_eq!(parse_size_bytes("1.5 GB"), Some(1_610_612_736));
+ assert_eq!(parse_size_bytes("2 GiB"), Some(2_147_483_648));
+ assert_eq!(parse_size_bytes("450MB"), Some(471_859_200));
+ assert_eq!(parse_size_bytes("512 KB"), Some(524_288));
+ assert_eq!(parse_size_bytes("1 TB"), Some(1_099_511_627_776));
+ assert_eq!(parse_size_bytes("💾 2.25 GB ⚡"), Some(2_415_919_104));
+ assert_eq!(parse_size_bytes("No size here"), None);
+ assert_eq!(parse_size_bytes(""), None);
+ }
+
+ #[test]
+ fn test_media_details_sibling_ids_deduplicates_and_sorts() {
+ let details = MediaDetails {
+ id: ProviderMediaId {
+ provider: ProviderKind::MovieBox,
+ value: "sub_main".to_string(),
+ },
+ title: "Test".to_string(),
+ media_type: MediaType::Series,
+ year: None,
+ description: None,
+ tagline: None,
+ imdb_rating: None,
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: None,
+ duration: None,
+ genres: vec![],
+ seasons: vec![],
+ dubs: vec![
+ AudioTrackOption {
+ subject_id: "sub_hi".to_string(),
+ language: "Hindi".to_string(),
+ label: "Hindi".to_string(),
+ },
+ AudioTrackOption {
+ subject_id: "sub_main".to_string(),
+ language: "English".to_string(),
+ label: "English".to_string(),
+ },
+ AudioTrackOption {
+ subject_id: String::new(),
+ language: "Empty".to_string(),
+ label: "Empty".to_string(),
+ },
+ ],
+ };
+ assert_eq!(
+ details.sibling_ids(),
+ vec!["sub_hi".to_string(), "sub_main".to_string()]
+ );
+ }
}
diff --git a/src/providers/moviebox/adapt.rs b/src/providers/moviebox/adapt.rs
index fdf2a95..18a0bf1 100644
--- a/src/providers/moviebox/adapt.rs
+++ b/src/providers/moviebox/adapt.rs
@@ -1042,72 +1042,32 @@ mod tests {
}
#[test]
- fn test_resolve_dash_manifest_from_policy_standard_base64() {
- let policy_json = r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/item1/*","Condition":{"DateLessThan":{"AWS:EpochTime":1700000000}}}]}"#;
- let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
- let cookie = format!(
- "CloudFront-Policy={b64};CloudFront-Signature=abc;CloudFront-Key-Pair-Id=K123;"
- );
- let resolved = resolve_dash_manifest_from_policy(&cookie);
- assert_eq!(
- resolved.as_deref(),
- Some("https://sacdn.hakunaymatata.com/dash/item1/index.mpd")
- );
- }
-
- #[test]
- fn test_resolve_dash_manifest_from_policy_with_dash_substitution() {
- let policy_json =
- r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/test_dash/*"}]}"#;
- let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
- let cf_b64 = b64.replace('+', "-");
- let cookie = format!("CloudFront-Policy={cf_b64};CloudFront-Signature=abc;");
- let resolved = resolve_dash_manifest_from_policy(&cookie);
- assert_eq!(
- resolved.as_deref(),
- Some("https://sacdn.hakunaymatata.com/dash/test_dash/index.mpd")
- );
- }
-
- #[test]
- fn test_resolve_dash_manifest_from_policy_with_underscore_substitution() {
- let policy_json = r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/test_underscore/*"}]}"#;
- let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
- let cf_b64 = b64.replace('=', "_");
- let cookie = format!("CloudFront-Policy={cf_b64};CloudFront-Signature=abc;");
- let resolved = resolve_dash_manifest_from_policy(&cookie);
- assert_eq!(
- resolved.as_deref(),
- Some("https://sacdn.hakunaymatata.com/dash/test_underscore/index.mpd")
- );
- }
-
- #[test]
- fn test_resolve_dash_manifest_from_policy_with_tilde_substitution() {
- let policy_json =
- r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/test_tilde/*"}]}"#;
- let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
- let cf_b64 = b64.replace('/', "~");
- let cookie = format!("CloudFront-Policy={cf_b64};CloudFront-Signature=abc;");
- let resolved = resolve_dash_manifest_from_policy(&cookie);
- assert_eq!(
- resolved.as_deref(),
- Some("https://sacdn.hakunaymatata.com/dash/test_tilde/index.mpd")
- );
- }
-
- #[test]
- fn test_resolve_dash_manifest_from_policy_restores_missing_padding() {
- let policy_json =
- r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/test_pad/*"}]}"#;
- let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
- let unpadded = b64.trim_end_matches('=');
- let cookie = format!("CloudFront-Policy={unpadded};CloudFront-Signature=abc;");
- let resolved = resolve_dash_manifest_from_policy(&cookie);
- assert_eq!(
- resolved.as_deref(),
- Some("https://sacdn.hakunaymatata.com/dash/test_pad/index.mpd")
- );
+ fn test_resolve_dash_manifest_from_policy_base64_variants() {
+ for (slug, transform) in [
+ ("item1", "standard"),
+ ("test_dash", "dash"),
+ ("test_underscore", "underscore"),
+ ("test_tilde", "tilde"),
+ ("test_pad", "unpadded"),
+ ] {
+ let policy_json = format!(
+ r#"{{"Statement":[{{"Resource":"https://sacdn.hakunaymatata.com/dash/{slug}/*"}}]}}"#
+ );
+ let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
+ let cf_b64 = match transform {
+ "dash" => b64.replace('+', "-"),
+ "underscore" => b64.replace('=', "_"),
+ "tilde" => b64.replace('/', "~"),
+ "unpadded" => b64.trim_end_matches('=').to_string(),
+ _ => b64,
+ };
+ let cookie = format!("CloudFront-Policy={cf_b64};CloudFront-Signature=abc;");
+ let resolved = resolve_dash_manifest_from_policy(&cookie);
+ assert_eq!(
+ resolved.as_deref(),
+ Some(format!("https://sacdn.hakunaymatata.com/dash/{slug}/index.mpd").as_str())
+ );
+ }
}
#[test]
@@ -1127,38 +1087,22 @@ mod tests {
}
#[test]
- fn test_resolve_dash_manifest_resource_conversion() {
- let policy_json =
- r#"{"Statement":[{"Resource":"https://sacdn.hakunaymatata.com/dash/example/*"}]}"#;
- let b64 = base64::engine::general_purpose::STANDARD.encode(policy_json.as_bytes());
- let cookie = format!("CloudFront-Policy={b64};");
- let resolved = resolve_dash_manifest_from_policy(&cookie);
- assert_eq!(
- resolved.as_deref(),
- Some("https://sacdn.hakunaymatata.com/dash/example/index.mpd")
- );
- }
-
- #[test]
- fn test_resolve_dash_manifest_from_edge_cache_cookie() {
- let cookie = "Edge-Cache-Cookie=urlprefix=aHR0cHM6Ly9zYmNkbjMuaGFrdW5heW1hdGF0YS5jb20vZGFzaC8zMjY0NzcyNTg4MzMzMTU3NDI0XzBfMF8xMDgwX2gyNjVfNTYwLw:sign=f1a522f7bf4c548c981ad6efa88925ad:t=1789908742";
- let resolved = resolve_dash_manifest_from_policy(cookie);
- assert_eq!(
- resolved.as_deref(),
- Some(
- "https://sbcdn3.hakunaymatata.com/dash/3264772588333157424_0_0_1080_h265_560/index.mpd"
- )
- );
- }
-
- #[test]
- fn test_resolve_dash_manifest_from_edge_cache_cookie_unpadded() {
- let cookie = "Edge-Cache-Cookie=urlprefix=aHR0cHM6Ly9zYmNkbjMuaGFrdW5heW1hdGF0YS5jb20vZGFzaC9pdGVtMQ:sign=abc:t=123";
- let resolved = resolve_dash_manifest_from_policy(cookie);
- assert_eq!(
- resolved.as_deref(),
- Some("https://sbcdn3.hakunaymatata.com/dash/item1/index.mpd")
- );
+ fn test_resolve_dash_manifest_from_edge_cache_cookies() {
+ for (cookie, expected) in [
+ (
+ "Edge-Cache-Cookie=urlprefix=aHR0cHM6Ly9zYmNkbjMuaGFrdW5heW1hdGF0YS5jb20vZGFzaC8zMjY0NzcyNTg4MzMzMTU3NDI0XzBfMF8xMDgwX2gyNjVfNTYwLw:sign=f1a522f7bf4c548c981ad6efa88925ad:t=1789908742",
+ "https://sbcdn3.hakunaymatata.com/dash/3264772588333157424_0_0_1080_h265_560/index.mpd",
+ ),
+ (
+ "Edge-Cache-Cookie=urlprefix=aHR0cHM6Ly9zYmNkbjMuaGFrdW5heW1hdGF0YS5jb20vZGFzaC9pdGVtMQ:sign=abc:t=123",
+ "https://sbcdn3.hakunaymatata.com/dash/item1/index.mpd",
+ ),
+ ] {
+ assert_eq!(
+ resolve_dash_manifest_from_policy(cookie).as_deref(),
+ Some(expected)
+ );
+ }
}
#[test]
diff --git a/src/providers/tv/parser.rs b/src/providers/tv/parser.rs
index eb8c482..b19c845 100644
--- a/src/providers/tv/parser.rs
+++ b/src/providers/tv/parser.rs
@@ -130,7 +130,7 @@ impl M3UParser {
let mut current_channel = Channel::default();
for line in content.lines() {
- let line = line.trim();
+ let line = line.trim().trim_start_matches('\u{feff}');
if line.is_empty() {
continue;
}
@@ -274,4 +274,19 @@ http://example.com/movie.m3u8
let _ = std::fs::remove_dir_all(&temp_dir);
}
+
+ #[test]
+ fn test_parse_m3u_handles_utf8_bom_and_stream_inf_headers() {
+ let parser = M3UParser::new();
+ let content = "\u{feff}#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=2500000\n#EXTINF:-1 tvg-id=\"sp1\" group-title=\"Sports\",Sports Live\n#EXTVLCOPT:http-user-agent=CustomUA\nhttps://live.example.com/sports.m3u8\n";
+ let channels = parser.parse_m3u(content);
+ assert_eq!(channels.len(), 1);
+ assert_eq!(channels[0].id, "sp1");
+ assert_eq!(channels[0].name, "Sports Live");
+ assert_eq!(channels[0].group, "Sports");
+ assert_eq!(
+ channels[0].stream_url,
+ "https://live.example.com/sports.m3u8"
+ );
+ }
}
diff --git a/src/proxy.rs b/src/proxy.rs
index 1b30b2b..2942468 100644
--- a/src/proxy.rs
+++ b/src/proxy.rs
@@ -1411,4 +1411,82 @@ mod tests {
assert_eq!(request_count.load(Ordering::Relaxed), 3);
server.abort();
}
+
+ #[tokio::test]
+ async fn test_warmup_dash_sidecar_populates_manifest_and_opening_segments() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ loop {
+ let Ok((mut socket, _)) = listener.accept().await else {
+ break;
+ };
+ tokio::spawn(async move {
+ let mut buf = [0u8; 1024];
+ let n = socket.read(&mut buf).await.unwrap_or(0);
+ let req = String::from_utf8_lossy(&buf[..n]);
+ if req.contains("/dash/index.mpd") {
+ let mpd = r#"<MPD><Period><AdaptationSet contentType="video"><Representation id="0" height="720" bandwidth="1000"><SegmentTemplate initialization="init-stream$RepresentationID$.m4s" media="chunk-stream$RepresentationID$-$Number%05d$.m4s"/></Representation></AdaptationSet></Period></MPD>"#;
+ let hdr = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/dash+xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ mpd.len(),
+ mpd
+ );
+ let _ = socket.write_all(hdr.as_bytes()).await;
+ } else {
+ let seg = b"SEGMENT_BYTES";
+ let hdr = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: video/iso.segment\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ seg.len()
+ );
+ let _ = socket.write_all(hdr.as_bytes()).await;
+ let _ = socket.write_all(seg).await;
+ }
+ });
+ }
+ });
+
+ let target_url = format!("http://{addr}/dash/index.mpd");
+ let ctx = ProxyContext {
+ proxy_port: addr.port(),
+ client: crate::net::http_client_builder_base().build().unwrap(),
+ auth_headers: Arc::new(Vec::new()),
+ target_host: Some(addr.to_string()),
+ subtitle_url: None,
+ max_height: Some(720),
+ segment_cache: Arc::new(SegmentCache::default()),
+ manifest_cache: Arc::new(Mutex::new(None)),
+ };
+
+ warmup_dash_sidecar(&ctx, &target_url).await;
+ for _ in 0..20 {
+ if ctx
+ .segment_cache
+ .get(&format!("http://{addr}/dash/chunk-stream0-00001.m4s"))
+ .is_some()
+ {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+
+ assert!(ctx.manifest_cache.lock().unwrap().is_some());
+ assert!(
+ ctx.segment_cache
+ .get(&format!("http://{addr}/dash/init-stream0.m4s"))
+ .is_some()
+ );
+ assert!(
+ ctx.segment_cache
+ .get(&format!("http://{addr}/dash/init-stream3.m4s"))
+ .is_some()
+ );
+ assert!(
+ ctx.segment_cache
+ .get(&format!("http://{addr}/dash/chunk-stream0-00001.m4s"))
+ .is_some()
+ );
+ server.abort();
+ }
}
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index 65fd8b0..10e0f2b 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -139,7 +139,7 @@ impl App {
}
KeyCode::Char('o') | KeyCode::Char('O') => {
let url = crate::updater::check::release_tag_url(version);
- let _ = open::that(&url);
+ let _ = crate::net::open_external_url(&url);
self.state.update_available = None;
return None;
}
diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rs
index 03151a5..080d6f5 100644
--- a/src/tui/app/mouse.rs
+++ b/src/tui/app/mouse.rs
@@ -343,7 +343,7 @@ impl App {
}
} else if col < layout.open_btn_end_x {
let url = crate::updater::check::release_tag_url(ver);
- let _ = open::that(&url);
+ let _ = crate::net::open_external_url(&url);
}
self.state.update_available = None;
}
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index ab9c6bc..12fb3fa 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -1627,4 +1627,41 @@ mod tests {
assert_eq!(app.state.selected_season, 2);
assert_eq!(app.state.selected_episode, 5);
}
+
+ #[tokio::test]
+ async fn test_non_mpv_update_progress_is_retained_across_player_exited() {
+ let mut app = crate::tui::app::App::new();
+ let item = crate::history::WatchHistoryItem {
+ provider: "moviebox".to_string(),
+ subject_id: "vlc_retain_test".to_string(),
+ title: "VLC Retention Movie".to_string(),
+ cover_url: None,
+ stype: 1,
+ release_year: "2026".to_string(),
+ season: 0,
+ episode: 0,
+ progress_seconds: 0,
+ duration_seconds: Some(3600),
+ completed: false,
+ timestamp: 1000,
+ stream_filename: Some("Movie.1080p.mkv".to_string()),
+ };
+ app.state.history.record_start(&item, 0);
+ app.handle_playback(crate::tui::action::Action::UpdateProgress {
+ item: Box::new(item),
+ progress: 420,
+ duration: Some(3600),
+ completed: false,
+ })
+ .await;
+ app.handle_playback(crate::tui::action::Action::PlayerExited)
+ .await;
+
+ let saved = app
+ .state
+ .history
+ .get_item("moviebox", "vlc_retain_test", 0, 0, None)
+ .expect("history item exists");
+ assert_eq!(saved.progress_seconds, 420);
+ }
}
diff --git a/src/tui/app/system.rs b/src/tui/app/system.rs
index c84fd64..f5bbd2a 100644
--- a/src/tui/app/system.rs
+++ b/src/tui/app/system.rs
@@ -590,7 +590,7 @@ impl App {
}
4 => {
const REPO_URL: &str = "https://github.com/mesamirh/MovieBox-Tui";
- match open::that(REPO_URL) {
+ match crate::net::open_external_url(REPO_URL) {
Ok(()) => {
self.state.notify(
NotificationKind::Info,
@@ -1009,3 +1009,37 @@ impl App {
self.persist_config();
}
}
+
+#[cfg(test)]
+mod tests {
+ use crate::tui::{action::Action, app::App, overlay::NotificationKind, state::Screen};
+
+ #[tokio::test]
+ async fn test_set_status_routes_warnings_and_non_home_messages_to_notifications() {
+ let mut app = App::new();
+ app.state.active_screen = Screen::Details;
+ app.handle_system(Action::SetStatus(
+ "Warning: External subtitle unavailable; playing stream directly.".to_string(),
+ ))
+ .await;
+
+ let warn_notif = app.state.notifications.back().expect("warning toast");
+ assert_eq!(warn_notif.kind, NotificationKind::Warning);
+ assert_eq!(warn_notif.title, "Notice");
+ assert_eq!(
+ warn_notif.message,
+ "External subtitle unavailable; playing stream directly."
+ );
+
+ app.state.notifications.clear();
+ app.state.active_screen = Screen::Home;
+ app.state.addon_manager_popup = true;
+ app.handle_system(Action::SetStatus("Installed Cinemeta v1.0.0".to_string()))
+ .await;
+
+ let info_notif = app.state.notifications.back().expect("info toast");
+ assert_eq!(info_notif.kind, NotificationKind::Info);
+ assert_eq!(info_notif.title, "Status");
+ assert_eq!(info_notif.message, "Installed Cinemeta v1.0.0");
+ }
+}
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index a5f48a6..6ad09d3 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -2085,15 +2085,6 @@ mod tests {
Season, SourceMirror,
};
- #[test]
- fn test_stream_loading_spinner_frames() {
- assert_eq!(stream_loading_spinner(0, false), "⠋");
- assert_eq!(stream_loading_spinner(1, false), "⠙");
- assert_eq!(stream_loading_spinner(9, false), "⠏");
- assert_eq!(stream_loading_spinner(10, false), "⠋");
- assert_eq!(stream_loading_spinner(0, true), "..");
- }
-
#[test]
fn test_stream_list_tabular_alignment_and_headers() {
let backend = ratatui::backend::TestBackend::new(120, 30);
diff --git a/src/tui/theme.rs b/src/tui/theme.rs
index 7645c13..2204d36 100644
--- a/src/tui/theme.rs
+++ b/src/tui/theme.rs
@@ -1193,13 +1193,6 @@ mod tests {
}
}
#[test]
- fn test_theme_color() {
- let with_fg = Style::default().fg(Color::Red);
- assert_eq!(theme_color(with_fg, Color::Blue), Color::Red);
- let without_fg = Style::default();
- assert_eq!(theme_color(without_fg, Color::Blue), Color::Blue);
- }
- #[test]
fn test_classify_terminal_konsole_and_xfce4_are_truecolor() {
assert_eq!(
classify_terminal("", "xterm-256color", "Konsole"),
diff --git a/tests/live_stream_verification.rs b/tests/live_stream_verification.rs
index dbca1c8..a5339b5 100644
--- a/tests/live_stream_verification.rs
+++ b/tests/live_stream_verification.rs
@@ -25,7 +25,7 @@ async fn test_live_movie_stream_real_urls() {
link
);
assert!(
- link.contains("sacdn.hakunaymatata.com") && link.ends_with("/index.mpd"),
+ link.contains("hakunaymatata.com") && link.ends_with("/index.mpd"),
"Stream URL should be a valid MPEG-DASH manifest: {}",
link
);
@@ -703,3 +703,25 @@ async fn test_live_moviebox_breaking_bad_series_captions_latency() {
"must include English"
);
}
+
+#[tokio::test]
+#[ignore = "live network test; run with cargo test --test live_stream_verification -- --ignored"]
+async fn test_live_dramachi_search_details_and_streams() {
+ let client = moviebox_tui::providers::dramachi::DramachiClient::new();
+ let items = client
+ .search("Squid Game", 1)
+ .await
+ .expect("dramachi search");
+ assert!(!items.is_empty());
+ let details = client
+ .details(&items[0].id.value)
+ .await
+ .expect("dramachi details");
+ assert!(!details.title.is_empty());
+ let streams = client
+ .episode_streams(&items[0].id.value, 1, 1)
+ .await
+ .expect("dramachi streams");
+ assert!(!streams.is_empty());
+ assert!(streams[0].direct_url().unwrap().starts_with("http"));
+}
diff --git a/tests/performance_audit.rs b/tests/performance_audit.rs
index b15e3d5..5a29aab 100644
--- a/tests/performance_audit.rs
+++ b/tests/performance_audit.rs
@@ -86,8 +86,11 @@ fn test_benchmark_performance_improvements_matrix() {
baseline_truncate_duration.as_nanos() as f64
/ opt_truncate_duration.as_nanos().max(1) as f64
);
- if !cfg!(debug_assertions) {
- assert!(opt_truncate_duration <= baseline_truncate_duration);
+ for title in sample_titles {
+ assert_eq!(
+ truncate_width(title, 30),
+ baseline_truncate_width(title, 30)
+ );
}
let sample_urls = [
@@ -124,8 +127,8 @@ fn test_benchmark_performance_improvements_matrix() {
opt_md5_duration,
baseline_md5_duration.as_nanos() as f64 / opt_md5_duration.as_nanos().max(1) as f64
);
- if !cfg!(debug_assertions) {
- assert!(opt_md5_duration <= baseline_md5_duration);
+ for url in sample_urls {
+ assert_eq!(md5_hex(url), baseline_md5_hex(url));
}
let mut clean_title_duration = std::time::Duration::MAX;
diff --git a/tests/settings_hub.rs b/tests/settings_hub.rs
index dc442ca..b1c097c 100644
--- a/tests/settings_hub.rs
+++ b/tests/settings_hub.rs
@@ -4,26 +4,12 @@ use moviebox_tui::{
tui::{
action::Action,
app::App,
- state::{AppState, SettingsCategory, settings_player_label},
- widgets::settings::{
- category_tab_rects, settings_category_tab_at, settings_row_at, settings_row_rects,
- },
+ state::{AppState, SettingsCategory},
+ widgets::settings::{settings_category_tab_at, settings_row_at, settings_row_rects},
},
};
use ratatui::layout::Rect;
-#[test]
-fn test_settings_modal_has_active_modal() {
- let mut state = AppState::default();
- assert!(!state.has_active_modal());
-
- state.show_settings_popup = true;
- assert!(state.has_active_modal());
-
- state.show_settings_popup = false;
- assert!(!state.has_active_modal());
-}
-
#[test]
fn test_settings_toggle_modes_safety_guard() {
let mut state = AppState {
@@ -40,52 +26,6 @@ fn test_settings_toggle_modes_safety_guard() {
assert!(state.can_disable_tv_mode());
}
-#[test]
-fn test_settings_player_choices_and_labels() {
- let mut state = AppState::default();
- assert_eq!(state.settings_player_choices(), Vec::<&str>::new());
-
- state.available_players = vec![PlayerKind::Mpv, PlayerKind::Vlc, PlayerKind::Iina];
- assert_eq!(state.settings_player_choices(), vec!["mpv", "vlc", "iina"]);
-
- state.default_player = Some("custom_player".to_string());
- assert_eq!(state.settings_player_choices(), vec!["mpv", "vlc", "iina"]);
-
- assert_eq!(settings_player_label(None), "None");
- assert_eq!(settings_player_label(Some("auto")), "None");
- assert_eq!(settings_player_label(Some("mpv")), "mpv");
- assert_eq!(settings_player_label(Some("vlc")), "VLC");
- assert_eq!(settings_player_label(Some("iina")), "IINA");
- assert_eq!(settings_player_label(Some("android")), "Android Player");
- assert_eq!(settings_player_label(Some("custom_player")), "Custom");
-}
-
-#[test]
-fn test_settings_player_and_theme_cycling() {
- let mut state = AppState {
- available_players: vec![PlayerKind::Mpv, PlayerKind::Vlc],
- ..Default::default()
- };
- assert_eq!(state.default_player, None);
-
- state.cycle_settings_player(true);
- assert_eq!(state.default_player, Some("vlc".to_string()));
-
- state.cycle_settings_player(true);
- assert_eq!(state.default_player, Some("mpv".to_string()));
-
- state.cycle_settings_player(false);
- assert_eq!(state.default_player, Some("vlc".to_string()));
-
- state.cycle_settings_player(false);
- assert_eq!(state.default_player, Some("mpv".to_string()));
-
- let original_theme = state.active_theme_kind.clone();
- let next_theme = state.cycle_settings_theme(true);
- assert_ne!(original_theme, next_theme);
- assert_eq!(state.active_theme_kind, next_theme);
-}
-
#[tokio::test]
async fn test_settings_keyboard_navigation_and_actions() {
let mut app = App::new();
@@ -286,23 +226,6 @@ async fn test_settings_mouse_tab_and_row_clicks() {
);
}
-#[test]
-fn test_settings_compact_tabs_rects() {
- let popup = Rect::new(4, 2, 60, 20);
- let tabs_area = Rect::new(popup.x + 3, popup.y + 1, popup.width - 6, 2);
- let rects = category_tab_rects(tabs_area, false, SettingsCategory::General);
- assert!(!rects.is_empty());
-
- let hit = settings_category_tab_at(
- popup,
- rects[0].1.x,
- popup.y + 1,
- false,
- SettingsCategory::General,
- );
- assert_eq!(hit, Some(SettingsCategory::General));
-}
-
#[test]
fn test_expand_download_path() {
assert_eq!(AppState::expand_download_path(""), None);
diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rs
index 4ddd8da..f594235 100644
--- a/tests/tui_acceptance.rs
+++ b/tests/tui_acceptance.rs
@@ -39,44 +39,15 @@ async fn test_season_download_remembers_explicit_no_subtitle_choice() {
assert_eq!(app.state().season_subtitle_preference, Some(None));
}
-#[tokio::test]
-async fn test_download_subtitle_popup_renders_in_app_draw() {
- let backend = TestBackend::new(100, 30);
- let mut terminal = Terminal::new(backend).unwrap();
- let mut app = App::new();
-
- app.state_mut().is_download_subtitle_popup = true;
- app.state_mut().subtitle_list = vec![
- ("None".to_string(), String::new()),
- (
- "English".to_string(),
- "https://example.com/en.srt".to_string(),
- ),
- ];
- app.state_mut().subtitle_list_state.select(Some(0));
-
- terminal.draw(|frame| app.draw(frame)).unwrap();
-
- let content = terminal
- .backend()
- .buffer()
- .content()
- .iter()
- .map(|c| c.symbol())
- .collect::<String>();
-
- assert!(content.contains("Subtitles"));
- assert!(content.contains("No subtitles"));
- assert!(content.contains("English"));
-}
-
#[tokio::test]
async fn test_tui_all_theme_rendering() {
+ let mut app = App::new();
for theme_kind in ThemeKind::ALL {
+ app.handle_action(Action::SelectTheme(theme_kind.as_str().to_string()))
+ .await;
+ assert_eq!(app.state().active_theme_kind, theme_kind.as_str());
let backend = TestBackend::new(100, 30);
let mut terminal = Terminal::new(backend).unwrap();
- let mut app = App::new();
- let _ = theme_kind;
let res = terminal.draw(|frame| app.draw(frame));
assert!(res.is_ok(), "Failed to render theme {:?}", theme_kind);
}
@@ -197,7 +168,7 @@ async fn test_mouse_click_outside_theme_popup_dismisses() {
assert!(app.state().show_theme_popup);
app.handle_action(Action::MouseClick(0, 0)).await;
- assert!(!app.state().show_help);
+ assert!(!app.state().show_theme_popup);
}
#[tokio::test]
diff --git a/tests/update_lifecycle.rs b/tests/update_lifecycle.rs
index 375bb67..4ca1366 100644
--- a/tests/update_lifecycle.rs
+++ b/tests/update_lifecycle.rs
@@ -82,45 +82,6 @@ async fn test_update_modal_update_now_click() {
assert!(app.state().update_available.is_none());
}
-#[tokio::test]
-async fn test_update_modal_open_release_click() {
- let mut app = App::new();
- app.state_mut().update_available = Some((
- "0.1.13".to_string(),
- "### Notes\n• Major performance improvements".to_string(),
- ));
-
- let (cols, rows) = crossterm::terminal::size().unwrap_or((80, 24));
- let area = Rect::new(0, 0, cols, rows);
- let layout = update_modal_layout(area, &app.state().update_available.as_ref().unwrap().1);
-
- let click_x = layout.update_btn_end_x + 5;
- let click_y = layout.button_row_y;
-
- app.handle_action(Action::MouseClick(click_x, click_y))
- .await;
-
- assert!(app.state().update_available.is_none());
-}
-
-#[tokio::test]
-async fn test_update_modal_dismiss_click() {
- let mut app = App::new();
- app.state_mut().update_available = Some(("0.1.13".to_string(), "• Bug fix".to_string()));
-
- let (cols, rows) = crossterm::terminal::size().unwrap_or((80, 24));
- let area = Rect::new(0, 0, cols, rows);
- let layout = update_modal_layout(area, &app.state().update_available.as_ref().unwrap().1);
-
- let click_x = layout.open_btn_end_x + 5;
- let click_y = layout.button_row_y;
-
- app.handle_action(Action::MouseClick(click_x, click_y))
- .await;
-
- assert!(app.state().update_available.is_none());
-}
-
#[tokio::test]
async fn test_active_work_protection_download_active_defers_update() {
let mut app = App::new();