refactor: reorganize source and tests

This commit is contained in:
objz committed 2026-07-27 11:28:57 +02:00
1 parent 15d76c18a0
commit c6205a337c
139 files changed
+5532 -5548

No files matched your search

+4 -78
View File
@@ -19,22 +19,6 @@ pub async fn handle_account(matches: &ArgMatches) -> CliResult {
}
}
// trait indirection so a mock store can be swapped in for tests
trait AccountStoreLike {
fn has_microsoft_account(&self) -> bool;
fn add_account(&mut self, account: Account);
}
impl AccountStoreLike for AccountStore {
fn has_microsoft_account(&self) -> bool {
AccountStore::has_microsoft_account(self)
}
fn add_account(&mut self, account: Account) {
self.add(account);
}
}
fn list_accounts() -> CliResult {
let store = AccountStore::load();
let rows = store
@@ -109,7 +93,7 @@ async fn add_microsoft_account() -> CliResult {
}
}
fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> CliResult {
fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult {
let username = username.trim();
if username.is_empty() {
return Err(io::Error::other("offline username cannot be empty").into());
@@ -121,7 +105,7 @@ fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> Cl
.into());
}
store.add_account(crate::auth::create_offline_account(username));
store.add(crate::auth::create_offline_account(username));
Ok(())
}
@@ -160,63 +144,5 @@ fn find_account_index(accounts: &[Account], username: &str) -> Option<usize> {
use super::utils::{confirm, required_arg};
#[cfg(test)]
mod tests {
use super::{AccountStoreLike, add_offline_account};
use crate::auth::{Account, AccountType};
#[derive(Default)]
struct MockStore {
accounts: Vec<Account>,
}
impl AccountStoreLike for MockStore {
fn has_microsoft_account(&self) -> bool {
self.accounts
.iter()
.any(|account| account.account_type == AccountType::Microsoft)
}
fn add_account(&mut self, account: Account) {
self.accounts.push(account);
}
}
fn microsoft_account() -> Account {
Account {
uuid: "00000000-0000-0000-0000-000000000001".to_owned(),
username: "Owner".to_owned(),
account_type: AccountType::Microsoft,
active: false,
refresh_token: Some("refresh".to_owned()),
cached_mc_token: None,
cached_mc_token_expires_at: None,
}
}
#[test]
fn creates_offline_account_after_microsoft_account_exists() {
let mut store = MockStore::default();
store.add_account(microsoft_account());
add_offline_account(&mut store, "Steve").expect("offline account should be added");
assert_eq!(store.accounts.len(), 2);
assert_eq!(store.accounts[1].username, "Steve");
assert_eq!(store.accounts[1].account_type, AccountType::Offline);
}
#[test]
fn rejects_offline_account_before_microsoft_account_exists() {
let mut store = MockStore::default();
let err = add_offline_account(&mut store, "Steve")
.expect_err("offline account should require a microsoft account");
assert!(err.to_string().contains("Microsoft account"));
assert!(store.accounts.is_empty());
}
#[test]
fn rejects_empty_offline_username() {
let mut store = MockStore::default();
assert!(add_offline_account(&mut store, " ").is_err());
}
}
#[path = "tests/account.rs"]
mod tests;
+2 -37
View File
@@ -116,40 +116,5 @@ fn toggle_entry(
}
#[cfg(test)]
mod tests {
use super::find_entry_by_stem;
use crate::instance::ContentEntry;
use std::path::PathBuf;
fn entry(file_stem: &str) -> ContentEntry {
ContentEntry {
file_stem: file_stem.to_string(),
name: file_stem.to_string(),
source_slug: None,
installed_path: None,
provider_project: None,
title_suffix: None,
footer_label: None,
description: String::new(),
enabled: true,
icon_bytes: None,
provider_icon: false,
provider_description: false,
path: PathBuf::from(file_stem),
icon_lines: None,
}
}
#[test]
fn matches_by_stem_case_insensitively() {
let entries = vec![entry("Sodium"), entry("Lithium")];
let found = find_entry_by_stem(&entries, "sOdIuM").expect("entry should match");
assert_eq!(found.file_stem, "Sodium");
}
#[test]
fn returns_none_for_missing_stem() {
let entries = vec![entry("Sodium")];
assert!(find_entry_by_stem(&entries, "iris").is_none());
}
}
#[path = "tests/content.rs"]
mod tests;
+1
View File
@@ -120,4 +120,5 @@ fn select_version<'a>(
}
#[cfg(test)]
#[path = "tests/import.rs"]
mod tests;
+4 -20
View File
@@ -7,8 +7,8 @@ use clap::ArgMatches;
use super::utils::{confirm, required_arg};
use crate::cli::output::{format_datetime, print_table};
use crate::instance::runtime::RunState;
use crate::instance::{InstanceManager, ModLoader};
use crate::running::RunState;
type CliResult = Result<(), Box<dyn std::error::Error>>;
const LOCAL_CONFIG_PROFILE: &str = "instance default";
@@ -143,7 +143,7 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult {
// poll until the game process exits. in CLI mode this blocks here
// so the user gets a proper exit code at the end.
loop {
match crate::running::get(name) {
match crate::instance::runtime::get(name) {
Some(RunState::Crashed(Some(code))) => {
println!("Game exited with status {}", code);
break;
@@ -354,21 +354,5 @@ fn apply_config_update(
}
#[cfg(test)]
mod tests {
use super::parse_resolution;
#[test]
fn parses_valid_resolution() {
assert_eq!(
parse_resolution("1920x1080").expect("should parse"),
(1920, 1080)
);
}
#[test]
fn rejects_invalid_resolution_format() {
assert!(parse_resolution("1920").is_err());
assert!(parse_resolution("1920xa").is_err());
assert!(parse_resolution("0x1080").is_err());
}
}
#[path = "tests/instance.rs"]
mod tests;
+7 -38
View File
@@ -20,7 +20,7 @@ pub async fn handle_log(matches: &ArgMatches) -> CliResult {
fn list_logs(instance: &str) -> CliResult {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
require_instance(&instances_dir, instance)?;
let rows = crate::instance::log_files::scan_log_files(&instances_dir, instance)
let rows = crate::instance::logs::files::scan_log_files(&instances_dir, instance)
.into_iter()
.map(|entry| {
let size = std::fs::metadata(&entry.path)
@@ -42,7 +42,7 @@ async fn show_log(matches: &ArgMatches) -> CliResult {
require_instance(&instances_dir, instance)?;
let path = resolve_log_path(&instances_dir, instance, file)?;
let lines = crate::instance::log_files::read_log_file(&path);
let lines = crate::instance::logs::files::read_log_file(&path);
for line in &lines {
println!("{}", line);
}
@@ -53,7 +53,7 @@ async fn show_log(matches: &ArgMatches) -> CliResult {
let mut last_len = lines.len();
loop {
tokio::time::sleep(Duration::from_millis(500)).await;
let new_lines = crate::instance::log_files::read_log_file(&path);
let new_lines = crate::instance::logs::files::read_log_file(&path);
for line in new_lines.iter().skip(last_len) {
println!("{}", line);
}
@@ -71,14 +71,14 @@ pub(crate) fn resolve_log_path(
file: Option<&str>,
) -> Result<PathBuf, io::Error> {
if let Some(name) = file {
let path = crate::instance::log_files::log_dir(instances_dir, instance).join(name);
let path = crate::instance::logs::files::log_dir(instances_dir, instance).join(name);
if !path.exists() {
return Err(io::Error::other(format!("log '{}' not found", name)));
}
return Ok(path);
}
crate::instance::log_files::scan_log_files(instances_dir, instance)
crate::instance::logs::files::scan_log_files(instances_dir, instance)
.into_iter()
.next()
.map(|entry| entry.path)
@@ -88,36 +88,5 @@ pub(crate) fn resolve_log_path(
use super::utils::{require_instance, required_arg};
#[cfg(test)]
mod tests {
use super::resolve_log_path;
#[test]
fn resolves_latest_log_when_no_file_is_given() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("demo/minecraft/logs/launches");
std::fs::create_dir_all(&dir).expect("log directory should exist");
std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log");
std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log");
let path = resolve_log_path(tmp.path(), "demo", None).expect("latest log should resolve");
assert_eq!(
path.file_name().and_then(|name| name.to_str()),
Some("2024-01-02_03-04-05.log")
);
}
#[test]
fn resolves_named_log_file() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("demo/minecraft/logs/launches");
std::fs::create_dir_all(&dir).expect("log directory should exist");
std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
let path = resolve_log_path(tmp.path(), "demo", Some("latest.log"))
.expect("named log should resolve");
assert_eq!(
path.file_name().and_then(|name| name.to_str()),
Some("latest.log")
);
}
}
#[path = "tests/log.rs"]
mod tests;
+2 -18
View File
@@ -289,21 +289,5 @@ fn build_content_command(name: &'static str, about: &'static str) -> Command {
}
#[cfg(test)]
mod tests {
use super::build_command;
#[test]
fn parses_instance_list_subcommand() {
let matches = build_command()
.try_get_matches_from(["rmcl", "instance", "list"])
.expect("command should parse");
let instance = matches
.subcommand_matches("instance")
.expect("instance subcommand should be present");
assert_eq!(
instance.subcommand_name(),
Some("list"),
"instance list should resolve to the list subcommand"
);
}
}
#[path = "tests/arguments.rs"]
mod tests;
+2 -27
View File
@@ -78,30 +78,5 @@ fn render_separator(widths: &[usize]) -> String {
}
#[cfg(test)]
mod tests {
use super::{format_datetime, render_table};
use chrono::{TimeZone, Utc};
#[test]
fn render_table_aligns_columns() {
let rendered = render_table(
&["Name", "State"],
&[
vec!["Alpha".to_string(), "enabled".to_string()],
vec!["Longer Name".to_string(), "off".to_string()],
],
);
let lines: Vec<&str> = rendered.lines().collect();
assert_eq!(lines[0], "Name State ");
assert_eq!(lines[1], "----------- -------");
assert_eq!(lines[2], "Alpha enabled");
assert_eq!(lines[3], "Longer Name off ");
}
#[test]
fn formats_datetime_consistently() {
let dt = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap();
assert_eq!(format_datetime(&dt), "2024-01-02 03:04:05 UTC");
}
}
#[path = "tests/output.rs"]
mod tests;
+44
View File
@@ -0,0 +1,44 @@
use super::add_offline_account;
use crate::auth::{Account, AccountStore, AccountType};
fn microsoft_account() -> Account {
Account {
uuid: "00000000-0000-0000-0000-000000000001".to_owned(),
username: "Owner".to_owned(),
account_type: AccountType::Microsoft,
active: false,
refresh_token: Some("refresh".to_owned()),
cached_mc_token: None,
cached_mc_token_expires_at: None,
}
}
#[test]
fn creates_offline_account_after_microsoft_account_exists() {
let temp = tempfile::tempdir().unwrap();
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
store.add(microsoft_account());
add_offline_account(&mut store, "Steve").expect("offline account should be added");
assert_eq!(store.accounts.len(), 2);
assert_eq!(store.accounts[1].username, "Steve");
assert_eq!(store.accounts[1].account_type, AccountType::Offline);
}
#[test]
fn rejects_offline_account_before_microsoft_account_exists() {
let temp = tempfile::tempdir().unwrap();
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
let err = add_offline_account(&mut store, "Steve")
.expect_err("offline account should require a microsoft account");
assert!(err.to_string().contains("Microsoft account"));
assert!(store.accounts.is_empty());
}
#[test]
fn rejects_empty_offline_username() {
let temp = tempfile::tempdir().unwrap();
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
assert!(add_offline_account(&mut store, " ").is_err());
}
+16
View File
@@ -0,0 +1,16 @@
use super::build_command;
#[test]
fn parses_instance_list_subcommand() {
let matches = build_command()
.try_get_matches_from(["rmcl", "instance", "list"])
.expect("command should parse");
let instance = matches
.subcommand_matches("instance")
.expect("instance subcommand should be present");
assert_eq!(
instance.subcommand_name(),
Some("list"),
"instance list should resolve to the list subcommand"
);
}
+35
View File
@@ -0,0 +1,35 @@
use super::find_entry_by_stem;
use crate::instance::ContentEntry;
use std::path::PathBuf;
fn entry(file_stem: &str) -> ContentEntry {
ContentEntry {
file_stem: file_stem.to_string(),
name: file_stem.to_string(),
source_slug: None,
installed_path: None,
provider_project: None,
title_suffix: None,
footer_label: None,
description: String::new(),
enabled: true,
icon_bytes: None,
provider_icon: false,
provider_description: false,
path: PathBuf::from(file_stem),
icon_lines: None,
}
}
#[test]
fn matches_by_stem_case_insensitively() {
let entries = vec![entry("Sodium"), entry("Lithium")];
let found = find_entry_by_stem(&entries, "sOdIuM").expect("entry should match");
assert_eq!(found.file_stem, "Sodium");
}
#[test]
fn returns_none_for_missing_stem() {
let entries = vec![entry("Sodium")];
assert!(find_entry_by_stem(&entries, "iris").is_none());
}
File renamed without changes.
+16
View File
@@ -0,0 +1,16 @@
use super::parse_resolution;
#[test]
fn parses_valid_resolution() {
assert_eq!(
parse_resolution("1920x1080").expect("should parse"),
(1920, 1080)
);
}
#[test]
fn rejects_invalid_resolution_format() {
assert!(parse_resolution("1920").is_err());
assert!(parse_resolution("1920xa").is_err());
assert!(parse_resolution("0x1080").is_err());
}
+31
View File
@@ -0,0 +1,31 @@
use super::resolve_log_path;
#[test]
fn resolves_latest_log_when_no_file_is_given() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("demo/minecraft/logs/launches");
std::fs::create_dir_all(&dir).expect("log directory should exist");
std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log");
std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log");
let path = resolve_log_path(tmp.path(), "demo", None).expect("latest log should resolve");
assert_eq!(
path.file_name().and_then(|name| name.to_str()),
Some("2024-01-02_03-04-05.log")
);
}
#[test]
fn resolves_named_log_file() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("demo/minecraft/logs/launches");
std::fs::create_dir_all(&dir).expect("log directory should exist");
std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
let path =
resolve_log_path(tmp.path(), "demo", Some("latest.log")).expect("named log should resolve");
assert_eq!(
path.file_name().and_then(|name| name.to_str()),
Some("latest.log")
);
}
+25
View File
@@ -0,0 +1,25 @@
use super::{format_datetime, render_table};
use chrono::{TimeZone, Utc};
#[test]
fn render_table_aligns_columns() {
let rendered = render_table(
&["Name", "State"],
&[
vec!["Alpha".to_string(), "enabled".to_string()],
vec!["Longer Name".to_string(), "off".to_string()],
],
);
let lines: Vec<&str> = rendered.lines().collect();
assert_eq!(lines[0], "Name State ");
assert_eq!(lines[1], "----------- -------");
assert_eq!(lines[2], "Alpha enabled");
assert_eq!(lines[3], "Longer Name off ");
}
#[test]
fn formats_datetime_consistently() {
let dt = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap();
assert_eq!(format_datetime(&dt), "2024-01-02 03:04:05 UTC");
}
+41
View File
@@ -0,0 +1,41 @@
use super::filter_manifest_versions;
use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest};
use std::collections::HashSet;
fn manifest() -> VersionManifest {
VersionManifest {
latest: LatestVersions {
release: "1.20.1".to_string(),
snapshot: "24w01a".to_string(),
},
versions: vec![
VersionEntry {
id: "1.20.1".to_string(),
version_type: "release".to_string(),
url: "https://example.com/release".to_string(),
sha1: "a".to_string(),
},
VersionEntry {
id: "24w01a".to_string(),
version_type: "snapshot".to_string(),
url: "https://example.com/snapshot".to_string(),
sha1: "b".to_string(),
},
],
}
}
#[test]
fn filters_out_snapshots_by_default() {
let rows = filter_manifest_versions(&manifest(), None, false);
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].id, "1.20.1");
}
#[test]
fn intersects_supported_versions() {
let supported = HashSet::from(["24w01a".to_string()]);
let rows = filter_manifest_versions(&manifest(), Some(&supported), true);
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].id, "24w01a");
}
+2 -43
View File
@@ -96,46 +96,5 @@ fn filter_manifest_versions(
}
#[cfg(test)]
mod tests {
use super::filter_manifest_versions;
use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest};
use std::collections::HashSet;
fn manifest() -> VersionManifest {
VersionManifest {
latest: LatestVersions {
release: "1.20.1".to_string(),
snapshot: "24w01a".to_string(),
},
versions: vec![
VersionEntry {
id: "1.20.1".to_string(),
version_type: "release".to_string(),
url: "https://example.com/release".to_string(),
sha1: "a".to_string(),
},
VersionEntry {
id: "24w01a".to_string(),
version_type: "snapshot".to_string(),
url: "https://example.com/snapshot".to_string(),
sha1: "b".to_string(),
},
],
}
}
#[test]
fn filters_out_snapshots_by_default() {
let rows = filter_manifest_versions(&manifest(), None, false);
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].id, "1.20.1");
}
#[test]
fn intersects_supported_versions() {
let supported = HashSet::from(["24w01a".to_string()]);
let rows = filter_manifest_versions(&manifest(), Some(&supported), true);
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].id, "24w01a");
}
}
#[path = "tests/version.rs"]
mod tests;