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

+166
View File
@@ -0,0 +1,166 @@
use super::*;
use crate::launch_profile::rules::RuleAction;
const MODERN_FIXTURE: &str = r#"{
"id": "1.20.1",
"type": "release",
"mainClass": "net.minecraft.client.main.Main",
"assetIndex": {
"id": "5",
"url": "https://example.invalid/5.json",
"sha1": "0000000000000000000000000000000000000000"
},
"javaVersion": {
"component": "java-runtime-gamma",
"majorVersion": 17
},
"libraries": [
{
"name": "org.lwjgl:lwjgl:3.3.1",
"downloads": {
"artifact": {
"url": "https://example.invalid/lwjgl.jar",
"path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar",
"sha1": "1111111111111111111111111111111111111111",
"size": 100
}
},
"rules": [
{ "action": "allow", "os": { "name": "linux" } }
]
}
],
"arguments": {
"game": [
"--username", "${auth_player_name}",
{
"rules": [{ "action": "allow", "features": { "is_demo_user": true } }],
"value": "--demo"
}
],
"jvm": [
"-Djava.library.path=${natives_directory}",
{
"rules": [{ "action": "allow", "os": { "name": "osx" } }],
"value": ["-XstartOnFirstThread"]
}
]
}
}"#;
const LEGACY_FIXTURE: &str = r#"{
"id": "1.7.10",
"type": "release",
"mainClass": "net.minecraft.client.main.Main",
"minecraftArguments": "--username ${auth_player_name} --version ${version_name} --gameDir ${game_directory}",
"assetIndex": {
"id": "1.7.10",
"url": "https://example.invalid/1.7.10.json",
"sha1": "0000000000000000000000000000000000000000"
},
"libraries": []
}"#;
const LOADER_FIXTURE: &str = r#"{
"id": "1.20.1-forge-47.2.0",
"inheritsFrom": "1.20.1",
"mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher",
"libraries": [
{ "name": "net.minecraftforge:forge:47.2.0" }
],
"arguments": {
"game": ["--launchTarget", "forge_client"],
"jvm": [
"--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler",
"-DlibraryDirectory=${library_directory}"
]
}
}"#;
#[test]
fn parses_modern_arguments_object() {
let profile: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap();
assert_eq!(profile.id, "1.20.1");
assert_eq!(
profile.main_class.as_deref(),
Some("net.minecraft.client.main.Main")
);
assert!(profile.inherits_from.is_none());
assert!(profile.minecraft_arguments.is_none());
let args = profile.arguments.as_ref().expect("arguments present");
assert_eq!(args.game.len(), 3);
assert_eq!(args.jvm.len(), 2);
// first game arg should be a literal "--username"
match &args.game[0] {
Argument::Literal(s) => assert_eq!(s, "--username"),
_ => panic!("expected literal"),
}
// third game arg should be a conditional with a single-string value
match &args.game[2] {
Argument::Conditional { rules, value } => {
assert_eq!(rules.len(), 1);
assert_eq!(rules[0].action, RuleAction::Allow);
assert!(matches!(value, ArgumentValue::Single(_)));
}
_ => panic!("expected conditional"),
}
// second jvm arg should be a conditional with a multi-string value
match &args.jvm[1] {
Argument::Conditional { value, .. } => {
assert!(matches!(value, ArgumentValue::Multiple(_)));
}
_ => panic!("expected conditional"),
}
}
#[test]
fn parses_legacy_minecraft_arguments_string() {
let profile: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap();
assert_eq!(profile.id, "1.7.10");
assert!(profile.arguments.is_none());
assert!(
profile
.minecraft_arguments
.as_deref()
.unwrap()
.contains("${version_name}")
);
assert!(profile.libraries.is_empty());
}
#[test]
fn parses_loader_profile_with_inherits_from() {
let profile: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap();
assert_eq!(profile.id, "1.20.1-forge-47.2.0");
assert_eq!(profile.inherits_from.as_deref(), Some("1.20.1"));
assert!(profile.asset_index.is_none()); // inherited from parent
let args = profile.arguments.as_ref().unwrap();
assert_eq!(args.game.len(), 2);
assert_eq!(args.jvm.len(), 3);
}
#[test]
fn modern_profile_round_trips() {
let original: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap();
let serialized = serde_json::to_string(&original).unwrap();
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
assert_eq!(original, reparsed);
}
#[test]
fn loader_profile_round_trips() {
let original: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap();
let serialized = serde_json::to_string(&original).unwrap();
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
assert_eq!(original, reparsed);
}
#[test]
fn legacy_profile_round_trips() {
let original: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap();
let serialized = serde_json::to_string(&original).unwrap();
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
assert_eq!(original, reparsed);
}
+278
View File
@@ -0,0 +1,278 @@
use super::*;
use crate::launch_profile::model::Arguments;
use crate::launch_profile::rules::{FeatureSet, OsCondition, Rule, RuleAction};
use std::path::PathBuf;
// owns the path buffers + FeatureSet so each test just calls
// fx.template_ctx() and fx.rule_ctx() instead of declaring four PathBufs
// and a RuleContext inline. all tests use linux/x86_64; if a test needs
// a different OS it sets it explicitly.
struct Fixture {
lib: PathBuf,
nat: PathBuf,
game: PathBuf,
assets: PathBuf,
features: FeatureSet,
}
impl Fixture {
fn new() -> Self {
Self {
lib: PathBuf::from("/m/libraries"),
nat: PathBuf::from("/m/natives"),
game: PathBuf::from("/i/.minecraft"),
assets: PathBuf::from("/m/assets"),
features: FeatureSet::default(),
}
}
fn template_ctx(&self) -> TemplateContext<'_> {
TemplateContext {
library_directory: &self.lib,
classpath_separator: ":",
version_name: "1.20.1",
version_type: "release",
natives_directory: &self.nat,
classpath: "a.jar:b.jar",
game_directory: &self.game,
assets_root: &self.assets,
assets_index_name: "5",
auth_player_name: "Player",
auth_uuid: "00000000-0000-0000-0000-000000000000",
auth_access_token: "token",
auth_xuid: "0",
user_type: "msa",
user_properties: "{}",
launcher_name: "rmcl",
launcher_version: "0.3.0",
clientid: "0",
}
}
fn rule_ctx(&self) -> RuleContext<'_> {
RuleContext {
os_name: "linux",
os_version: "6.0",
arch: "x86_64",
features: &self.features,
}
}
}
fn minimal_profile() -> LaunchProfile {
LaunchProfile {
id: "test".into(),
main_class: Some("net.test.Main".into()),
..Default::default()
}
}
#[test]
fn legacy_minecraft_arguments_render_into_game() {
let fx = Fixture::new();
let mut profile = minimal_profile();
profile.minecraft_arguments =
Some("--username ${auth_player_name} --version ${version_name}".into());
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
assert_eq!(rendered.main_class, "net.test.Main");
assert!(rendered.jvm.is_empty());
assert_eq!(
rendered.game,
vec!["--username", "Player", "--version", "1.20.1"]
);
}
#[test]
fn modern_arguments_render_with_literals_and_substitutions() {
let fx = Fixture::new();
let mut profile = minimal_profile();
profile.arguments = Some(Arguments {
game: vec![
Argument::Literal("--username".into()),
Argument::Literal("${auth_player_name}".into()),
],
jvm: vec![Argument::Literal(
"-Djava.library.path=${natives_directory}".into(),
)],
});
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
assert_eq!(rendered.game, vec!["--username", "Player"]);
assert_eq!(rendered.jvm, vec!["-Djava.library.path=/m/natives"]);
}
#[test]
fn conditional_argument_with_single_value_is_filtered_by_os_rule() {
let fx = Fixture::new();
let osx_only = Argument::Conditional {
rules: vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("osx".into()),
arch: None,
..Default::default()
}),
features: None,
}],
value: ArgumentValue::Single("-XstartOnFirstThread".into()),
};
let mut profile = minimal_profile();
profile.arguments = Some(Arguments {
game: Vec::new(),
jvm: vec![osx_only],
});
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
assert!(
rendered.jvm.is_empty(),
"osx-only arg should be skipped on linux"
);
}
#[test]
fn conditional_argument_with_multiple_value_pushes_all() {
let fx = Fixture::new();
let linux_arg = Argument::Conditional {
rules: vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("linux".into()),
arch: None,
..Default::default()
}),
features: None,
}],
value: ArgumentValue::Multiple(vec![
"--add-opens".into(),
"java.base/sun.security.util=ALL-UNNAMED".into(),
]),
};
let mut profile = minimal_profile();
profile.arguments = Some(Arguments {
game: Vec::new(),
jvm: vec![linux_arg],
});
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
assert_eq!(
rendered.jvm,
vec!["--add-opens", "java.base/sun.security.util=ALL-UNNAMED"]
);
}
#[test]
fn missing_main_class_returns_error() {
let fx = Fixture::new();
let mut profile = minimal_profile();
profile.main_class = None;
let result = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx());
assert!(matches!(result, Err(RenderError::MissingMainClass)));
}
#[tokio::test]
async fn end_to_end_resolve_then_render_modern_forge_shape() {
// exercises the full pipeline: load a synthetic vanilla profile
// from disk, load a synthetic loader profile with inheritsFrom,
// resolve the chain, then render args. catches integration bugs
// that unit tests of each layer would miss.
use crate::launch_profile::resolve;
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
let vanilla_path = tmp
.path()
.join("cache/minecraft/versions")
.join("1.20.1")
.join("meta.json");
std::fs::create_dir_all(vanilla_path.parent().unwrap()).unwrap();
let vanilla_json = br#"{
"id": "1.20.1",
"mainClass": "net.minecraft.client.main.Main",
"libraries": [
{
"name": "org.lwjgl:lwjgl:3.3.1",
"downloads": {
"artifact": {
"url": "https://example.invalid/lwjgl.jar",
"path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar",
"sha1": "1111111111111111111111111111111111111111",
"size": 100
}
}
}
],
"arguments": {
"game": ["--username", "${auth_player_name}", "--version", "${version_name}"],
"jvm": ["-Djava.library.path=${natives_directory}"]
}
}"#;
std::fs::write(&vanilla_path, vanilla_json).unwrap();
let loader_json = r#"{
"id": "1.20.1-forge-47.2.0",
"inheritsFrom": "1.20.1",
"mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher",
"libraries": [
{ "name": "net.minecraftforge:forge:47.2.0" }
],
"arguments": {
"game": ["--launchTarget", "forge_client"],
"jvm": [
"--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler"
]
}
}"#;
let loader_profile: LaunchProfile = serde_json::from_str(loader_json).unwrap();
let merged = resolve::resolve(loader_profile, tmp.path()).await.unwrap();
let fx = Fixture::new();
let rendered = render_args(&merged, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
// child main_class wins after merge
assert_eq!(
rendered.main_class,
"cpw.mods.bootstraplauncher.BootstrapLauncher"
);
// game args: parent first then child
assert_eq!(
rendered.game,
vec![
"--username",
"Player",
"--version",
"1.20.1",
"--launchTarget",
"forge_client"
]
);
// jvm args: parent first then child
assert_eq!(
rendered.jvm,
vec![
"-Djava.library.path=/m/natives",
"--add-opens",
"java.base/sun.security.util=cpw.mods.securejarhandler"
]
);
}
#[test]
fn modern_arguments_takes_precedence_over_legacy_field() {
// a profile that somehow has both arguments and minecraft_arguments
// should use arguments only (legacy is fallback).
let fx = Fixture::new();
let mut profile = minimal_profile();
profile.arguments = Some(Arguments {
game: vec![Argument::Literal("--from-arguments".into())],
jvm: Vec::new(),
});
profile.minecraft_arguments = Some("--from-legacy".into());
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
assert_eq!(rendered.game, vec!["--from-arguments"]);
}
+419
View File
@@ -0,0 +1,419 @@
use super::*;
use crate::launch_profile::model::{Argument, ArgumentValue, AssetIndex, JavaVersion, Library};
use crate::launch_profile::rules::{Rule, RuleAction};
fn empty_profile(id: &str) -> LaunchProfile {
LaunchProfile {
id: id.into(),
..Default::default()
}
}
fn lib(name: &str) -> Library {
Library {
name: name.into(),
..Default::default()
}
}
fn allow_linux_rule() -> Rule {
Rule {
action: RuleAction::Allow,
os: Some(crate::launch_profile::rules::OsCondition {
name: Some("linux".into()),
..Default::default()
}),
features: None,
}
}
#[test]
fn child_id_wins() {
let mut child = empty_profile("child");
let parent = empty_profile("parent");
child.main_class = None;
let merged = merge_into(child, parent);
assert_eq!(merged.id, "child");
}
#[test]
fn merge_carries_parent_inherits_from() {
// merge_into preserves parent's inherits_from so resolve() can keep
// walking. resolve() itself clears the final result's inherits_from
// after the loop exits.
let mut child = empty_profile("child");
child.inherits_from = Some("parent".into());
let mut parent = empty_profile("parent");
parent.inherits_from = Some("grandparent".into());
let merged = merge_into(child, parent);
assert_eq!(merged.inherits_from.as_deref(), Some("grandparent"));
}
#[test]
fn merge_with_root_parent_clears_inherits_from() {
// parent with no inherits_from means the chain ends.
let mut child = empty_profile("child");
child.inherits_from = Some("parent".into());
let parent = empty_profile("parent");
let merged = merge_into(child, parent);
assert!(merged.inherits_from.is_none());
}
#[test]
fn child_main_class_overrides_parent() {
let mut child = empty_profile("child");
let mut parent = empty_profile("parent");
child.main_class = Some("child.Main".into());
parent.main_class = Some("parent.Main".into());
let merged = merge_into(child, parent);
assert_eq!(merged.main_class.as_deref(), Some("child.Main"));
}
#[test]
fn parent_main_class_used_when_child_missing() {
let child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.main_class = Some("parent.Main".into());
let merged = merge_into(child, parent);
assert_eq!(merged.main_class.as_deref(), Some("parent.Main"));
}
#[test]
fn libraries_are_concatenated_parent_first() {
let mut child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.libraries = vec![lib("p1"), lib("p2")];
child.libraries = vec![lib("c1")];
let merged = merge_into(child, parent);
let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, vec!["p1", "p2", "c1"]);
}
#[test]
fn child_library_supersedes_parent_with_same_group_artifact() {
// forge declares log4j 2.17.0; vanilla declared 2.0-beta9. without
// dedup, both end up on the classpath and the JVM picks the first
// (vanilla) match - defeating forge's override. dedup keeps child's.
let mut child = empty_profile("forge");
let mut parent = empty_profile("vanilla");
parent.libraries = vec![
lib("org.apache.logging.log4j:log4j-core:2.0-beta9"),
lib("org.lwjgl:lwjgl:3.3.1"),
];
child.libraries = vec![
lib("org.apache.logging.log4j:log4j-core:2.17.0"),
lib("net.minecraftforge:forge:47.2.0"),
];
let merged = merge_into(child, parent);
let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect();
// parent's log4j-core is filtered (superseded by child); parent's
// lwjgl stays (no conflict); child's log4j and forge come last.
assert_eq!(
names,
vec![
"org.lwjgl:lwjgl:3.3.1",
"org.apache.logging.log4j:log4j-core:2.17.0",
"net.minecraftforge:forge:47.2.0",
]
);
}
#[test]
fn coord_key_extracts_group_artifact() {
assert_eq!(coord_key("org.lwjgl:lwjgl:3.3.1"), "org.lwjgl:lwjgl");
assert_eq!(
coord_key("org.apache.logging.log4j:log4j-core:2.17.0"),
"org.apache.logging.log4j:log4j-core"
);
// with classifier
assert_eq!(
coord_key("org.lwjgl:lwjgl:3.3.1:natives-linux"),
"org.lwjgl:lwjgl"
);
// malformed (no colons) - return as-is
assert_eq!(coord_key("malformed"), "malformed");
}
#[test]
fn arguments_are_concatenated_parent_first() {
let mut child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.arguments = Some(Arguments {
game: vec![Argument::Literal("--from-parent-game".into())],
jvm: vec![Argument::Literal("--from-parent-jvm".into())],
});
child.arguments = Some(Arguments {
game: vec![Argument::Literal("--from-child-game".into())],
jvm: vec![Argument::Literal("--from-child-jvm".into())],
});
let merged = merge_into(child, parent);
let args = merged.arguments.expect("arguments present");
assert_eq!(
args.game,
vec![
Argument::Literal("--from-parent-game".into()),
Argument::Literal("--from-child-game".into()),
]
);
assert_eq!(
args.jvm,
vec![
Argument::Literal("--from-parent-jvm".into()),
Argument::Literal("--from-child-jvm".into()),
]
);
}
#[test]
fn arguments_from_child_only_carry_through() {
let mut child = empty_profile("child");
let parent = empty_profile("parent");
child.arguments = Some(Arguments {
game: vec![Argument::Literal("--child".into())],
jvm: Vec::new(),
});
let merged = merge_into(child, parent);
let args = merged.arguments.expect("arguments present");
assert_eq!(args.game.len(), 1);
assert!(args.jvm.is_empty());
}
#[test]
fn arguments_from_parent_only_carry_through() {
let child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.arguments = Some(Arguments {
game: Vec::new(),
jvm: vec![Argument::Literal("--parent-jvm".into())],
});
let merged = merge_into(child, parent);
let args = merged.arguments.expect("arguments present");
assert!(args.game.is_empty());
assert_eq!(args.jvm.len(), 1);
}
#[test]
fn conditional_arguments_with_rules_survive_merge() {
// make sure the Argument::Conditional shape isn't accidentally
// flattened or filtered during merging - rule eval happens later
// at render time, not during merge.
let mut child = empty_profile("child");
let parent = empty_profile("parent");
child.arguments = Some(Arguments {
game: vec![Argument::Conditional {
rules: vec![allow_linux_rule()],
value: ArgumentValue::Single("--linux-only".into()),
}],
jvm: Vec::new(),
});
let merged = merge_into(child, parent);
let args = merged.arguments.expect("arguments present");
match &args.game[0] {
Argument::Conditional { rules, .. } => {
assert_eq!(rules.len(), 1);
assert_eq!(rules[0].action, RuleAction::Allow);
}
_ => panic!("expected conditional argument to survive merge"),
}
}
#[test]
fn legacy_minecraft_arguments_child_overrides_parent() {
let mut child = empty_profile("child");
let mut parent = empty_profile("parent");
child.minecraft_arguments = Some("--child".into());
parent.minecraft_arguments = Some("--parent".into());
let merged = merge_into(child, parent);
assert_eq!(merged.minecraft_arguments.as_deref(), Some("--child"));
}
#[test]
fn asset_index_inherits_from_parent_when_child_absent() {
let child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.asset_index = Some(AssetIndex {
id: "5".into(),
url: "https://example.invalid/5.json".into(),
sha1: "0".repeat(40),
size: None,
total_size: None,
});
let merged = merge_into(child, parent);
assert!(merged.asset_index.is_some());
assert_eq!(merged.asset_index.unwrap().id, "5");
}
#[test]
fn java_version_inherits_from_parent_when_child_absent() {
let child = empty_profile("child");
let mut parent = empty_profile("parent");
parent.java_version = Some(JavaVersion {
component: Some("java-runtime-gamma".into()),
major_version: 17,
});
let merged = merge_into(child, parent);
assert_eq!(
merged.java_version.as_ref().map(|j| j.major_version),
Some(17)
);
}
use tempfile::TempDir;
fn write_profile(meta_dir: &Path, profile: &LaunchProfile) {
let path = meta_dir
.join("cache/minecraft/versions")
.join(&profile.id)
.join("meta.json");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let json = serde_json::to_string_pretty(profile).unwrap();
std::fs::write(&path, json).unwrap();
}
#[tokio::test]
async fn resolve_returns_unchanged_when_no_inherits_from() {
let tmp = TempDir::new().unwrap();
let profile = empty_profile("standalone");
let resolved = resolve(profile, tmp.path()).await.unwrap();
assert_eq!(resolved.id, "standalone");
assert!(resolved.inherits_from.is_none());
}
#[tokio::test]
async fn resolve_single_level_inheritance_merges_parent() {
let tmp = TempDir::new().unwrap();
let mut parent = empty_profile("1.20.1");
parent.main_class = Some("net.minecraft.client.main.Main".into());
parent.libraries = vec![lib("vanilla-lib")];
write_profile(tmp.path(), &parent);
let mut child = empty_profile("1.20.1-forge-47.2.0");
child.inherits_from = Some("1.20.1".into());
child.libraries = vec![lib("forge-lib")];
let resolved = resolve(child, tmp.path()).await.unwrap();
assert_eq!(resolved.id, "1.20.1-forge-47.2.0");
assert!(resolved.inherits_from.is_none());
assert_eq!(
resolved.main_class.as_deref(),
Some("net.minecraft.client.main.Main")
);
let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, vec!["vanilla-lib", "forge-lib"]);
}
#[tokio::test]
async fn resolve_errors_when_parent_missing() {
let tmp = TempDir::new().unwrap();
let mut child = empty_profile("1.20.1-forge-47.2.0");
child.inherits_from = Some("1.20.1".into());
let err = resolve(child, tmp.path()).await.unwrap_err();
assert!(
matches!(err, ResolveError::ParentNotFound(_)),
"expected ParentNotFound, got {err:?}"
);
}
#[tokio::test]
async fn resolve_errors_when_parent_is_invalid_json() {
let tmp = TempDir::new().unwrap();
let parent_path = tmp
.path()
.join("cache/minecraft/versions")
.join("1.20.1")
.join("meta.json");
std::fs::create_dir_all(parent_path.parent().unwrap()).unwrap();
std::fs::write(&parent_path, "{ not valid json").unwrap();
let mut child = empty_profile("1.20.1-forge-47.2.0");
child.inherits_from = Some("1.20.1".into());
let err = resolve(child, tmp.path()).await.unwrap_err();
assert!(
matches!(err, ResolveError::ParseError(_, _)),
"expected ParseError, got {err:?}"
);
}
#[tokio::test]
async fn resolve_multi_level_chain_merges_all_parents() {
let tmp = TempDir::new().unwrap();
// chain: grandchild -> child -> root (vanilla).
let mut root = empty_profile("1.20.1");
root.main_class = Some("net.minecraft.client.main.Main".into());
root.libraries = vec![lib("vanilla-lib")];
write_profile(tmp.path(), &root);
let mut child = empty_profile("1.20.1-forge-47.2.0");
child.inherits_from = Some("1.20.1".into());
child.libraries = vec![lib("forge-lib")];
write_profile(tmp.path(), &child);
let mut grandchild = empty_profile("1.20.1-forge-47.2.0-modpack");
grandchild.inherits_from = Some("1.20.1-forge-47.2.0".into());
grandchild.libraries = vec![lib("modpack-lib")];
let resolved = resolve(grandchild, tmp.path()).await.unwrap();
assert_eq!(resolved.id, "1.20.1-forge-47.2.0-modpack");
assert!(resolved.inherits_from.is_none());
assert_eq!(
resolved.main_class.as_deref(),
Some("net.minecraft.client.main.Main")
);
// libs: root ++ child ++ grandchild (each parent prepended)
let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, vec!["vanilla-lib", "forge-lib", "modpack-lib"]);
}
#[tokio::test]
async fn resolve_detects_circular_chain() {
let tmp = TempDir::new().unwrap();
// a -> b -> a (cycle)
let mut a = empty_profile("a");
a.inherits_from = Some("b".into());
write_profile(tmp.path(), &a);
let mut b = empty_profile("b");
b.inherits_from = Some("a".into());
write_profile(tmp.path(), &b);
// start from a fresh "a" profile that asks to inherit from b
let mut entry = empty_profile("a");
entry.inherits_from = Some("b".into());
let err = resolve(entry, tmp.path()).await.unwrap_err();
assert!(
matches!(err, ResolveError::CircularInheritance(ref s) if s == "a"),
"expected CircularInheritance(a), got {err:?}"
);
}
#[tokio::test]
async fn resolve_caps_depth() {
let tmp = TempDir::new().unwrap();
// build a chain 0 -> 1 -> 2 -> ... -> 10. with cap of 8, hitting 10
// should fail with DepthExceeded.
for i in 0..=10 {
let mut p = empty_profile(&format!("v{i}"));
if i < 10 {
p.inherits_from = Some(format!("v{}", i + 1));
}
write_profile(tmp.path(), &p);
}
let mut entry = empty_profile("entry");
entry.inherits_from = Some("v0".into());
let err = resolve(entry, tmp.path()).await.unwrap_err();
assert!(
matches!(err, ResolveError::DepthExceeded(_)),
"expected DepthExceeded, got {err:?}"
);
}
+269
View File
@@ -0,0 +1,269 @@
use super::*;
fn linux_ctx<'a>(features: &'a FeatureSet) -> RuleContext<'a> {
RuleContext {
os_name: "linux",
os_version: "6.0",
arch: "x86_64",
features,
}
}
#[test]
fn empty_rules_allow() {
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(evaluate(&[], &ctx));
}
#[test]
fn single_allow_matching_os_allows() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("linux".into()),
arch: None,
..Default::default()
}),
features: None,
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(evaluate(&rules, &ctx));
}
#[test]
fn single_disallow_matching_os_disallows() {
let rules = vec![Rule {
action: RuleAction::Disallow,
os: Some(OsCondition {
name: Some("linux".into()),
arch: None,
..Default::default()
}),
features: None,
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(!evaluate(&rules, &ctx));
}
#[test]
fn allow_without_os_match_disallows_by_default() {
// explicit allow for windows; we are on linux; nothing matches;
// default state remains disallow.
let rules = vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("windows".into()),
arch: None,
..Default::default()
}),
features: None,
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(!evaluate(&rules, &ctx));
}
#[test]
fn last_matching_rule_wins_when_allow_then_disallow() {
let rules = vec![
Rule {
action: RuleAction::Allow,
os: None,
features: None,
},
Rule {
action: RuleAction::Disallow,
os: Some(OsCondition {
name: Some("osx".into()),
arch: None,
..Default::default()
}),
features: None,
},
];
let features = FeatureSet::default();
let osx_ctx = RuleContext {
os_name: "osx",
os_version: "6.0",
arch: "x86_64",
features: &features,
};
assert!(!evaluate(&rules, &osx_ctx));
// and on linux: only the first rule matches → still allow.
let lin = linux_ctx(&features);
assert!(evaluate(&rules, &lin));
}
#[test]
fn last_matching_rule_wins_when_disallow_then_allow() {
let rules = vec![
Rule {
action: RuleAction::Disallow,
os: None,
features: None,
},
Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("linux".into()),
arch: None,
..Default::default()
}),
features: None,
},
];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(evaluate(&rules, &ctx));
}
#[test]
fn arch_mismatch_blocks_rule() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("linux".into()),
arch: Some("arm64".into()),
version: None,
}),
features: None,
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
// we are on linux but x86_64, not arm64 → rule does not match.
assert!(!evaluate(&rules, &ctx));
}
#[test]
fn feature_required_true_matches_when_ctx_true() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: None,
features: Some(FeatureSet {
is_demo_user: Some(true),
..Default::default()
}),
}];
let demo_features = FeatureSet {
is_demo_user: Some(true),
..Default::default()
};
let ctx = RuleContext {
os_name: "linux",
os_version: "6.0",
arch: "x86_64",
features: &demo_features,
};
assert!(evaluate(&rules, &ctx));
}
#[test]
fn feature_required_true_blocks_when_ctx_false() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: None,
features: Some(FeatureSet {
is_demo_user: Some(true),
..Default::default()
}),
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(!evaluate(&rules, &ctx));
}
#[test]
fn no_os_no_features_rule_always_matches() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: None,
features: None,
}];
let features = FeatureSet::default();
let ctx = linux_ctx(&features);
assert!(evaluate(&rules, &ctx));
}
#[test]
fn os_version_pattern_matches_against_host() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("osx".into()),
arch: None,
version: Some("^10\\.".into()),
}),
features: None,
}];
let features = FeatureSet::default();
let ctx_match = RuleContext {
os_name: "osx",
os_version: "10.15.7",
arch: "x86_64",
features: &features,
};
assert!(evaluate(&rules, &ctx_match));
let ctx_mismatch = RuleContext {
os_name: "osx",
os_version: "13.2.1",
arch: "x86_64",
features: &features,
};
assert!(!evaluate(&rules, &ctx_mismatch));
}
#[test]
fn os_version_pattern_does_not_match_when_host_unknown() {
let rules = vec![Rule {
action: RuleAction::Allow,
os: Some(OsCondition {
name: Some("windows".into()),
arch: None,
version: Some("^10\\.".into()),
}),
features: None,
}];
let features = FeatureSet::default();
let ctx = RuleContext {
os_name: "windows",
os_version: "",
arch: "x86_64",
features: &features,
};
assert!(!evaluate(&rules, &ctx));
}
#[test]
fn rule_deserializes_from_mojang_json() {
// shape lifted from real mojang library rules.
let json = r#"{
"action": "allow",
"os": { "name": "osx" }
}"#;
let rule: Rule = serde_json::from_str(json).unwrap();
assert_eq!(rule.action, RuleAction::Allow);
assert_eq!(
rule.os.as_ref().and_then(|o| o.name.as_deref()),
Some("osx")
);
assert!(rule.os.as_ref().and_then(|o| o.arch.as_ref()).is_none());
assert!(rule.features.is_none());
}
#[test]
fn rule_deserializes_with_features() {
let json = r#"{
"action": "allow",
"features": { "is_demo_user": true }
}"#;
let rule: Rule = serde_json::from_str(json).unwrap();
assert_eq!(rule.action, RuleAction::Allow);
assert!(rule.os.is_none());
assert_eq!(
rule.features.as_ref().and_then(|f| f.is_demo_user),
Some(true)
);
}
+102
View File
@@ -0,0 +1,102 @@
use super::*;
use std::path::PathBuf;
// owns the path buffers so tests don't have to declare them inline; the
// ctx() method borrows from self to build a TemplateContext with the
// standard set of values. windows() returns a fixture with backslash
// paths so the OS-independence test stays self-contained.
struct Fixture {
lib: PathBuf,
nat: PathBuf,
game: PathBuf,
assets: PathBuf,
user_properties: String,
}
impl Fixture {
fn unix() -> Self {
Self {
lib: PathBuf::from("/m/libraries"),
nat: PathBuf::from("/m/natives"),
game: PathBuf::from("/i/.minecraft"),
assets: PathBuf::from("/m/assets"),
user_properties: "{}".to_string(),
}
}
fn windows() -> Self {
Self {
lib: PathBuf::from(r"C:\Users\test\.minecraft\libraries"),
nat: PathBuf::from(r"C:\Users\test\.minecraft\natives"),
game: PathBuf::from(r"C:\Users\test\.minecraft"),
assets: PathBuf::from(r"C:\Users\test\.minecraft\assets"),
user_properties: "{}".to_string(),
}
}
fn ctx(&self) -> TemplateContext<'_> {
TemplateContext {
library_directory: &self.lib,
classpath_separator: ":",
version_name: "1.20.1",
version_type: "release",
natives_directory: &self.nat,
classpath: "a.jar:b.jar",
game_directory: &self.game,
assets_root: &self.assets,
assets_index_name: "5",
auth_player_name: "Player",
auth_uuid: "00000000-0000-0000-0000-000000000000",
auth_access_token: "token",
auth_xuid: "0",
user_type: "msa",
user_properties: &self.user_properties,
launcher_name: "rmcl",
launcher_version: "0.3.0",
clientid: "0",
}
}
}
#[rstest::rstest]
#[case::no_placeholders("--add-modules ALL-MODULE-PATH", "--add-modules ALL-MODULE-PATH")]
#[case::single_known("v=${version_name}", "v=1.20.1")]
#[case::unknown_placeholder("x=${not_a_real_var}y", "x=${not_a_real_var}y")]
#[case::unclosed_placeholder("--prefix ${unclosed", "--prefix ${unclosed")]
#[case::dollar_without_brace("$$ literal $5 $", "$$ literal $5 $")]
#[case::multiple("${version_name}-${auth_player_name}", "1.20.1-Player")]
#[case::path(
"-DlibraryDirectory=${library_directory}",
"-DlibraryDirectory=/m/libraries"
)]
#[case::empty_input("", "")]
fn substitute_handles(#[case] input: &str, #[case] expected: &str) {
let fx = Fixture::unix();
assert_eq!(substitute(input, &fx.ctx()), expected);
}
#[test]
fn substituted_value_is_not_recursively_substituted() {
// simulate a user_properties value that happens to contain a ${...}
// pattern. it should NOT trigger another substitution pass.
let mut fx = Fixture::unix();
fx.user_properties = "${version_name}".to_string();
assert_eq!(
substitute("${user_properties}", &fx.ctx()),
"${version_name}"
);
}
#[test]
fn windows_style_backslashes_in_value_pass_through() {
// simulate a Windows install where library_directory is a path with
// backslashes. the substitution must not interpret backslashes as
// escape sequences or do anything else clever - it just copies the
// value into the output.
let fx = Fixture::windows();
let result = substitute("-Dpath=${library_directory}", &fx.ctx());
assert!(
result.contains(r"C:\Users\test\.minecraft\libraries"),
"expected backslashes preserved, got: {result}"
);
}