#[test]
fn version_triple_accepts_exactly_three_numbers() {
assert_eq!(version_triple("3.21.0"), Some((3, 21, 0)));
assert_eq!(version_triple("10.0.100"), Some((10, 0, 100)));
for rejected in ["3.21", "3.21.0.1", "v3.21.0", "3.21.x", "", "3..0"] {
assert_eq!(version_triple(rejected), None, "{rejected}");
}
}
#[test]
fn minimum_version_at_or_below_the_binary_loads() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".fallowrc.json");
let running = env!("CARGO_PKG_VERSION");
std::fs::write(
&path,
format!(r#"{{"minimumVersion": "{running}", "entry": ["src/main.ts"]}}"#),
)
.unwrap();
let config = FallowConfig::load(&path).expect("current version satisfies its own floor");
assert_eq!(config.minimum_version.as_deref(), Some(running));
assert_eq!(config.entry, vec!["src/main.ts".to_string()]);
}
#[test]
fn a_config_written_for_a_newer_binary_names_both_versions() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"minimumVersion": "999.0.0", "someFieldFromTheFuture": true}"#,
)
.unwrap();
let error = FallowConfig::load(&path).expect_err("a newer floor must stop the run");
let message = error.to_string();
assert!(
message.contains("requires fallow 999.0.0 or newer"),
"{message}"
);
assert!(message.contains(env!("CARGO_PKG_VERSION")), "{message}");
assert!(!message.contains("unknown field"), "{message}");
}
#[test]
fn circular_dependencies_allow_rejects_an_entry_that_cannot_be_a_cycle() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"circularDependencies": {"allow": [
["src/a.ts", "src/b.ts"],
["src/a.ts"],
["src/a.ts", "./src/b.ts", "src/b.ts"]
]}}"#,
)
.unwrap();
let message = FallowConfig::load(&path)
.expect_err("a one-file entry and a repeated file fail the load")
.to_string();
assert!(
message.contains(
"circularDependencies.allow[1] lists 1 file; an entry lists the 2 or more files of one cycle"
),
"{message}"
);
assert!(
message.contains(
"circularDependencies.allow[2] lists 'src/b.ts' more than once; a cycle has each file once"
),
"{message}"
);
}
#[test]
fn circular_dependencies_allow_accepts_valid_entries() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"circularDependencies": {"allow": [["src/a.ts", "src/b.ts"]]}}"#,
)
.unwrap();
let config = FallowConfig::load(&path).expect("a valid entry loads");
assert_eq!(config.circular_dependencies.allow.len(), 1);
}
#[test]
fn an_unknown_field_still_fails_on_a_binary_that_meets_the_floor() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"minimumVersion": "0.1.0", "ignorePaths": ["dist/**"]}"#,
)
.unwrap();
let error = FallowConfig::load(&path).expect_err("a typo is still a typo");
assert!(error.to_string().contains("unknown field"), "{error}");
}
#[test]
fn a_floor_declared_by_an_extended_base_config_still_applies() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("base.json"),
r#"{"minimumVersion": "999.0.0"}"#,
)
.unwrap();
let path = dir.path().join(".fallowrc.json");
std::fs::write(&path, r#"{"extends": ["./base.json"]}"#).unwrap();
let error = FallowConfig::load(&path).expect_err("an inherited floor must stop the run");
assert!(
error
.to_string()
.contains("requires fallow 999.0.0 or newer"),
"{error}"
);
}
#[test]
fn a_malformed_minimum_version_is_a_config_error() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".fallowrc.json");
std::fs::write(&path, r#"{"minimumVersion": "v3.21"}"#).unwrap();
let error = FallowConfig::load(&path).expect_err("a malformed floor must not be ignored");
assert!(
error
.to_string()
.contains("minimumVersion must be MAJOR.MINOR.PATCH"),
"{error}"
);
}
use super::*;
use crate::CacheConfig;
use crate::PackageJson;
use crate::config::format::OutputFormat;
use crate::config::rules::Severity;
fn test_dir(_name: &str) -> tempfile::TempDir {
tempfile::tempdir().expect("create temp dir")
}
#[derive(Default)]
struct MockRemoteFetcher {
responses: rustc_hash::FxHashMap<String, serde_json::Value>,
requests: Vec<String>,
}
impl MockRemoteFetcher {
fn with_response(mut self, url: &str, value: serde_json::Value) -> Self {
self.responses.insert(url.to_string(), value);
self
}
}
impl RemoteConfigFetcher for MockRemoteFetcher {
fn fetch(&mut self, url: &str, _source: &str) -> Result<serde_json::Value, miette::Report> {
self.requests.push(url.to_string());
self.responses
.get(url)
.cloned()
.ok_or_else(|| miette::miette!("missing mock response for {url}"))
}
}
#[test]
fn fallow_config_deserialize_minimal() {
let toml_str = r#"
entry = ["src/main.ts"]
"#;
let config: FallowConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.entry, vec!["src/main.ts"]);
assert!(config.ignore_patterns.is_empty());
}
#[test]
fn fallow_config_deserialize_ignore_exports() {
let toml_str = r#"
[[ignoreExports]]
file = "src/types/*.ts"
exports = ["*"]
[[ignoreExports]]
file = "src/constants.ts"
exports = ["FOO", "BAR"]
"#;
let config: FallowConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.ignore_exports.len(), 2);
assert_eq!(config.ignore_exports[0].file, "src/types/*.ts");
assert_eq!(config.ignore_exports[0].exports, vec!["*"]);
assert_eq!(config.ignore_exports[1].exports, vec!["FOO", "BAR"]);
}
#[test]
fn fallow_config_deserialize_ignore_dependencies() {
let toml_str = r#"
ignoreDependencies = ["autoprefixer", "postcss"]
"#;
let config: FallowConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.ignore_dependencies, vec!["autoprefixer", "postcss"]);
}
#[test]
fn fallow_config_deserialize_ignore_command_entries() {
let toml_config: FallowConfig =
toml::from_str(r#"ignoreCommandEntries = ["my-codegen", "*"]"#).unwrap();
assert_eq!(toml_config.ignore_command_entries, vec!["my-codegen", "*"]);
let json_config: FallowConfig =
serde_json::from_str(r#"{"ignoreCommandEntries": ["my-codegen"]}"#).unwrap();
assert_eq!(json_config.ignore_command_entries, vec!["my-codegen"]);
let default_config: FallowConfig = serde_json::from_str("{}").unwrap();
assert!(default_config.ignore_command_entries.is_empty());
let serialized = serde_json::to_value(&default_config).unwrap();
assert!(serialized.get("ignoreCommandEntries").is_none());
}
#[test]
fn fallow_config_deserialize_ignore_unresolved_imports() {
let toml_str = r#"
ignoreUnresolvedImports = ["@example/icons", "@example/icons/**", "../generated/**"]
"#;
let config: FallowConfig = toml::from_str(toml_str).unwrap();
assert_eq!(
config.ignore_unresolved_imports,
vec!["@example/icons", "@example/icons/**", "../generated/**"]
);
}
#[test]
fn fallow_config_resolve_default_ignores() {
let config = FallowConfig::default();
let resolved = config.resolve(
PathBuf::from("/tmp/test"),
OutputFormat::Human,
4,
true,
true,
None,
);
assert!(resolved.ignore_patterns.is_match("node_modules/foo/bar.ts"));
assert!(resolved.ignore_patterns.is_match("dist/bundle.js"));
assert!(resolved.ignore_patterns.is_match("build/output.js"));
assert!(resolved.ignore_patterns.is_match(".git/config"));
assert!(resolved.ignore_patterns.is_match("coverage/report.js"));
assert!(resolved.ignore_patterns.is_match("foo.min.js"));
assert!(resolved.ignore_patterns.is_match("bar.min.mjs"));
}
#[test]
fn fallow_config_resolve_custom_ignores() {
let config = FallowConfig {
entry: vec!["src/**/*.ts".to_string()],
ignore_patterns: vec!["**/*.generated.ts".to_string()],
ignore_findings: vec!["**/*.test.ts".to_string(), "!src/public/**".to_string()],
..Default::default()
};
let resolved = config.resolve(
PathBuf::from("/tmp/test"),
OutputFormat::Json,
4,
false,
true,
None,
);
assert!(resolved.ignore_patterns.is_match("src/foo.generated.ts"));
assert!(
resolved
.ignore_findings
.is_ignored("src/private/app.test.ts")
);
assert!(
!resolved
.ignore_findings
.is_ignored("src/public/app.test.ts")
);
assert_eq!(resolved.entry_patterns, vec!["src/**/*.ts"]);
assert!(matches!(resolved.output, OutputFormat::Json));
assert!(!resolved.no_cache);
}
#[test]
fn fallow_config_resolve_cache_dir() {
let config = FallowConfig::default();
let resolved = config.resolve(
PathBuf::from("/tmp/project"),
OutputFormat::Human,
4,
true,
true,
None,
);
assert_eq!(resolved.cache_dir, PathBuf::from("/tmp/project/.fallow"));
assert!(resolved.no_cache);
}
#[test]
fn package_json_entry_points_main() {
let pkg: PackageJson = serde_json::from_str(r#"{"main": "dist/index.js"}"#).unwrap();
let entries = pkg.entry_points();
assert!(entries.contains(&"dist/index.js".to_string()));
}
#[test]
fn package_json_entry_points_module() {
let pkg: PackageJson = serde_json::from_str(r#"{"module": "dist/index.mjs"}"#).unwrap();
let entries = pkg.entry_points();
assert!(entries.contains(&"dist/index.mjs".to_string()));
}
#[test]
fn package_json_entry_points_types() {
let pkg: PackageJson = serde_json::from_str(r#"{"types": "dist/index.d.ts"}"#).unwrap();
let entries = pkg.entry_points();
assert!(entries.contains(&"dist/index.d.ts".to_string()));
}
#[test]
fn package_json_entry_points_bin_string() {
let pkg: PackageJson = serde_json::from_str(r#"{"bin": "bin/cli.js"}"#).unwrap();
let entries = pkg.entry_points();
assert!(entries.contains(&"bin/cli.js".to_string()));
}
#[test]
fn package_json_entry_points_bin_object() {
let pkg: PackageJson =
serde_json::from_str(r#"{"bin": {"cli": "bin/cli.js", "serve": "bin/serve.js"}}"#).unwrap();
let entries = pkg.entry_points();
assert!(entries.contains(&"bin/cli.js".to_string()));
assert!(entries.contains(&"bin/serve.js".to_string()));
}
#[test]
fn package_json_entry_points_exports_string() {
let pkg: PackageJson = serde_json::from_str(r#"{"exports": "./dist/index.js"}"#).unwrap();
let entries = pkg.entry_points();
assert!(entries.contains(&"./dist/index.js".to_string()));
}
#[test]
fn package_json_entry_points_exports_object() {
let pkg: PackageJson = serde_json::from_str(
r#"{"exports": {".": {"import": "./dist/index.mjs", "require": "./dist/index.cjs"}}}"#,
)
.unwrap();
let entries = pkg.entry_points();
assert!(entries.contains(&"./dist/index.mjs".to_string()));
assert!(entries.contains(&"./dist/index.cjs".to_string()));
}
#[test]
fn package_json_dependency_names() {
let pkg: PackageJson = serde_json::from_str(
r#"{
"dependencies": {"react": "^18", "lodash": "^4"},
"devDependencies": {"typescript": "^5"},
"peerDependencies": {"react-dom": "^18"}
}"#,
)
.unwrap();
let all = pkg.all_dependency_names();
assert!(all.contains(&"react".to_string()));
assert!(all.contains(&"lodash".to_string()));
assert!(all.contains(&"typescript".to_string()));
assert!(all.contains(&"react-dom".to_string()));
let prod = pkg.production_dependency_names();
assert!(prod.contains(&"react".to_string()));
assert!(!prod.contains(&"typescript".to_string()));
let dev = pkg.dev_dependency_names();
assert!(dev.contains(&"typescript".to_string()));
assert!(!dev.contains(&"react".to_string()));
}
#[test]
fn package_json_no_dependencies() {
let pkg: PackageJson = serde_json::from_str(r#"{"name": "test"}"#).unwrap();
assert!(pkg.all_dependency_names().is_empty());
assert!(pkg.production_dependency_names().is_empty());
assert!(pkg.dev_dependency_names().is_empty());
assert!(pkg.entry_points().is_empty());
}
#[test]
fn rules_deserialize_toml_kebab_case() {
let toml_str = r#"
[rules]
unused-files = "error"
unused-exports = "warn"
unused-types = "off"
"#;
let config: FallowConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.rules.unused_files, Severity::Error);
assert_eq!(config.rules.unused_exports, Severity::Warn);
assert_eq!(config.rules.unused_types, Severity::Off);
assert_eq!(config.rules.unresolved_imports, Severity::Error);
}
#[test]
fn config_without_rules_defaults_to_error() {
let toml_str = r#"
entry = ["src/main.ts"]
"#;
let config: FallowConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.rules.unused_files, Severity::Error);
assert_eq!(config.rules.unused_exports, Severity::Error);
}
#[test]
fn fallow_config_denies_unknown_fields() {
let toml_str = r"
unknown_field = true
";
let result: Result<FallowConfig, _> = toml::from_str(toml_str);
assert!(result.is_err());
}
#[test]
fn fallow_config_deserialize_json() {
let json_str = r#"{"entry": ["src/main.ts"]}"#;
let config: FallowConfig = serde_json::from_str(json_str).unwrap();
assert_eq!(config.entry, vec!["src/main.ts"]);
}
#[test]
fn fallow_config_deserialize_jsonc() {
let jsonc_str = r#"{
"entry": ["src/main.ts"],
"rules": {
"unused-files": "warn"
}
}"#;
let config: FallowConfig = crate::jsonc::parse_to_value(jsonc_str).unwrap();
assert_eq!(config.entry, vec!["src/main.ts"]);
assert_eq!(config.rules.unused_files, Severity::Warn);
}
#[test]
fn fallow_config_json_with_schema_field() {
let json_str = r#"{"$schema": "./node_modules/fallow/schema.json", "entry": ["src/main.ts"]}"#;
let config: FallowConfig = serde_json::from_str(json_str).unwrap();
assert_eq!(config.entry, vec!["src/main.ts"]);
}
#[test]
fn fallow_config_json_schema_generation() {
let schema = FallowConfig::json_schema();
assert!(schema.is_object());
let obj = schema.as_object().unwrap();
assert!(obj.contains_key("properties"));
}
#[test]
fn json_schema_advertises_the_jsonc_dialect_it_parses() {
let options = crate::jsonc::parse_options();
let schema = FallowConfig::json_schema();
let root = schema.as_object().expect("schema should be an object");
assert_eq!(
root.get("allowTrailingCommas")
.and_then(serde_json::Value::as_bool),
Some(options.allow_trailing_commas),
"schema should advertise the parser's trailing-comma support"
);
assert_eq!(
root.get("allowComments")
.and_then(serde_json::Value::as_bool),
Some(options.allow_comments),
"schema should advertise the parser's comment support"
);
}
#[test]
fn config_format_detection() {
assert!(matches!(
ConfigFormat::from_path(Path::new("fallow.toml")),
ConfigFormat::Toml
));
assert!(matches!(
ConfigFormat::from_path(Path::new(".fallowrc.json")),
ConfigFormat::Json
));
assert!(matches!(
ConfigFormat::from_path(Path::new(".fallowrc.jsonc")),
ConfigFormat::Json
));
assert!(matches!(
ConfigFormat::from_path(Path::new(".fallow.toml")),
ConfigFormat::Toml
));
}
#[test]
fn config_names_priority_order() {
assert_eq!(CONFIG_NAMES[0], ".fallowrc.json");
assert_eq!(CONFIG_NAMES[1], ".fallowrc.jsonc");
assert_eq!(CONFIG_NAMES[2], "fallow.toml");
assert_eq!(CONFIG_NAMES[3], ".fallow.toml");
}
#[test]
fn load_json_config_file() {
let dir = test_dir("json-config");
let config_path = dir.path().join(".fallowrc.json");
std::fs::write(
&config_path,
r#"{"entry": ["src/index.ts"], "rules": {"unused-exports": "warn"}}"#,
)
.unwrap();
let config = FallowConfig::load(&config_path).unwrap();
assert_eq!(config.entry, vec!["src/index.ts"]);
assert_eq!(config.rules.unused_exports, Severity::Warn);
}
#[test]
fn load_records_explicit_private_type_leaks_setting() {
let dir = test_dir("explicit-private-type-leaks");
let config_path = dir.path().join(".fallowrc.json");
std::fs::write(&config_path, r#"{"rules": {"private-type-leaks": "off"}}"#).unwrap();
let config = FallowConfig::load(&config_path).unwrap();
assert_eq!(config.rules.private_type_leaks, Severity::Off);
assert!(config.rules.private_type_leaks_configured);
}
#[test]
fn load_records_explicit_private_type_leaks_singular_alias() {
let dir = test_dir("explicit-private-type-leak-alias");
let config_path = dir.path().join(".fallowrc.json");
std::fs::write(&config_path, r#"{"rules": {"private-type-leak": "off"}}"#).unwrap();
let config = FallowConfig::load(&config_path).unwrap();
assert!(config.rules.private_type_leaks_configured);
}
#[test]
fn load_leaves_defaulted_private_type_leaks_unmarked() {
let dir = test_dir("defaulted-private-type-leaks");
let config_path = dir.path().join(".fallowrc.json");
std::fs::write(&config_path, r#"{"rules": {"unused-exports": "warn"}}"#).unwrap();
let config = FallowConfig::load(&config_path).unwrap();
assert_eq!(config.rules.private_type_leaks, Severity::Off);
assert!(!config.rules.private_type_leaks_configured);
}
#[test]
fn serde_round_trip_drops_explicit_private_type_leaks_flag() {
let dir = test_dir("round-trip-private-type-leaks");
let config_path = dir.path().join(".fallowrc.json");
std::fs::write(&config_path, r#"{"rules": {"private-type-leaks": "off"}}"#).unwrap();
let config = FallowConfig::load(&config_path).unwrap();
assert!(config.rules.private_type_leaks_configured);
let serialized = serde_json::to_value(&config).unwrap();
let round_tripped: FallowConfig = serde_json::from_value(serialized).unwrap();
assert_eq!(round_tripped.rules.private_type_leaks, Severity::Off);
assert!(
!round_tripped.rules.private_type_leaks_configured,
"a serde round-trip drops the serde(skip) flag; any code path that \
round-trips a loaded FallowConfig must re-record it (see the field \
docs on RulesConfig::private_type_leaks_configured)"
);
}
#[test]
fn tailwind_ignore_patterns_round_trip_as_strings() {
let dir = test_dir("tailwind-ignore-patterns");
let path = dir.path().join(".fallowrc.json");
let patterns = serde_json::json!(["^icon-\\[", "^bg-\\[#abc\\]$"]);
std::fs::write(
&path,
serde_json::json!({"health": {"tailwindIgnorePatterns": patterns}}).to_string(),
)
.unwrap();
let config = FallowConfig::load(&path).unwrap();
let serialized = serde_json::to_value(&config).unwrap();
assert_eq!(serialized["health"]["tailwindIgnorePatterns"], patterns);
let round_tripped: FallowConfig = serde_json::from_value(serialized).unwrap();
let resolved = round_tripped.resolve(
dir.path().to_path_buf(),
OutputFormat::Json,
1,
true,
true,
None,
);
assert!(resolved.tailwind_ignore_patterns[0].is_match("icon-[lucide--eye]"));
assert!(!resolved.tailwind_ignore_patterns[0].is_match("icon-size-[17px]"));
}
#[test]
fn invalid_tailwind_ignore_pattern_names_the_config_entry() {
let dir = test_dir("invalid-tailwind-ignore-pattern");
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"health":{"tailwindIgnorePatterns":["^icon-", "["]}}"#,
)
.unwrap();
let error = FallowConfig::load(&path).unwrap_err().to_string();
assert!(
error.contains("health.tailwindIgnorePatterns[1]"),
"{error}"
);
assert!(error.contains("regex"), "{error}");
}
#[test]
fn load_json_config_file_with_health_threshold_override() {
let dir = test_dir("json-health-threshold-override");
let config_path = dir.path().join(".fallowrc.json");
std::fs::write(
&config_path,
r#"{
"health": {
"thresholdOverrides": [
{
"files": ["src/legacy.ts"],
"functions": ["legacyFlow"],
"maxCyclomatic": 30,
"maxCognitive": 25,
"maxCrap": 80.5,
"reason": "legacy migration"
}
]
}
}"#,
)
.unwrap();
let config = FallowConfig::load(&config_path).unwrap();
let override_config = &config.health.threshold_overrides[0];
assert_eq!(override_config.files, vec!["src/legacy.ts"]);
assert_eq!(override_config.functions, vec!["legacyFlow"]);
assert_eq!(override_config.max_cyclomatic, Some(30));
assert_eq!(override_config.max_cognitive, Some(25));
assert_eq!(override_config.max_crap, Some(80.5));
assert_eq!(override_config.reason.as_deref(), Some("legacy migration"));
}
#[test]
fn load_jsonc_config_file() {
let dir = test_dir("jsonc-config");
let config_path = dir.path().join(".fallowrc.json");
std::fs::write(
&config_path,
r#"{
"entry": ["src/index.ts"],
/* Block comment */
"rules": {
"unused-exports": "warn"
}
}"#,
)
.unwrap();
let config = FallowConfig::load(&config_path).unwrap();
assert_eq!(config.entry, vec!["src/index.ts"]);
assert_eq!(config.rules.unused_exports, Severity::Warn);
}
#[test]
fn load_jsonc_config_file_with_health_threshold_override() {
let dir = test_dir("jsonc-health-threshold-override");
let config_path = dir.path().join(".fallowrc.jsonc");
std::fs::write(
&config_path,
r#"{
"health": {
// Empty functions means every function in matching files.
"thresholdOverrides": [
{ "files": ["src/legacy.ts"], "maxCognitive": 25 }
]
}
}"#,
)
.unwrap();
let config = FallowConfig::load(&config_path).unwrap();
let override_config = &config.health.threshold_overrides[0];
assert_eq!(override_config.files, vec!["src/legacy.ts"]);
assert!(override_config.functions.is_empty());
assert_eq!(override_config.max_cognitive, Some(25));
}
#[test]
fn load_fallowrc_jsonc_extension() {
let dir = test_dir("jsonc-extension");
let config_path = dir.path().join(".fallowrc.jsonc");
std::fs::write(
&config_path,
r#"{
"ignoreDependencies": ["tailwindcss-react-aria-components"],
"entry": ["src/index.ts"]
}"#,
)
.unwrap();
let config = FallowConfig::load(&config_path).unwrap();
assert_eq!(config.entry, vec!["src/index.ts"]);
assert_eq!(
config.ignore_dependencies,
vec!["tailwindcss-react-aria-components"]
);
}
#[test]
fn json_config_ignore_dependencies_camel_case() {
let json_str = r#"{"ignoreDependencies": ["autoprefixer", "postcss"]}"#;
let config: FallowConfig = serde_json::from_str(json_str).unwrap();
assert_eq!(config.ignore_dependencies, vec!["autoprefixer", "postcss"]);
}
#[test]
fn json_config_ignore_unresolved_imports_camel_case() {
let json_str = r#"{"ignoreUnresolvedImports": ["@example/icons", "@example/icons/**"]}"#;
let config: FallowConfig = serde_json::from_str(json_str).unwrap();
assert_eq!(
config.ignore_unresolved_imports,
vec!["@example/icons", "@example/icons/**"]
);
}
#[test]
fn json_config_all_fields() {
let json_str = r#"{
"ignoreDependencies": ["lodash"],
"ignoreExports": [{"file": "src/*.ts", "exports": ["*"]}],
"rules": {
"unused-files": "off",
"unused-exports": "warn",
"unused-dependencies": "error",
"unused-dev-dependencies": "off",
"unused-types": "warn",
"unused-enum-members": "error",
"unused-class-members": "off",
"unresolved-imports": "warn",
"unlisted-dependencies": "error",
"duplicate-exports": "off"
},
"duplicates": {
"minTokens": 100,
"minLines": 10,
"skipLocal": true,
"ignoreSymlinks": true
}
}"#;
let config: FallowConfig = serde_json::from_str(json_str).unwrap();
assert_eq!(config.ignore_dependencies, vec!["lodash"]);
assert_eq!(config.rules.unused_files, Severity::Off);
assert_eq!(config.rules.unused_exports, Severity::Warn);
assert_eq!(config.rules.unused_dependencies, Severity::Error);
assert_eq!(config.duplicates.min_tokens, 100);
assert_eq!(config.duplicates.min_lines, 10);
assert!(config.duplicates.skip_local);
assert!(config.duplicates.ignore_symlinks);
}
#[test]
fn extends_single_base() {
let dir = test_dir("extends-single");
std::fs::write(
dir.path().join("base.json"),
r#"{"rules": {"unused-files": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["base.json"], "entry": ["src/index.ts"]}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(config.entry, vec!["src/index.ts"]);
assert_eq!(config.rules.unused_exports, Severity::Error);
}
#[test]
fn extends_overlay_overrides_base() {
let dir = test_dir("extends-overlay");
std::fs::write(
dir.path().join("base.json"),
r#"{"ignoreFindings": ["generated/**"], "rules": {"unused-files": "warn", "unused-exports": "off"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["base.json"], "ignoreFindings": ["**/*.test.ts"], "rules": {"unused-files": "error"}}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.ignore_findings, vec!["**/*.test.ts"]);
assert_eq!(config.rules.unused_files, Severity::Error);
assert_eq!(config.rules.unused_exports, Severity::Off);
}
#[test]
fn extends_chained() {
let dir = test_dir("extends-chained");
std::fs::write(
dir.path().join("grandparent.json"),
r#"{"rules": {"unused-files": "off", "unused-exports": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join("parent.json"),
r#"{"extends": ["grandparent.json"], "rules": {"unused-files": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["parent.json"]}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(config.rules.unused_exports, Severity::Warn);
}
#[test]
fn extends_local_diamond_reuses_resolved_base() {
let dir = test_dir("extends-local-diamond");
std::fs::write(
dir.path().join("base.json"),
r#"{"ignorePatterns": ["generated/**"]}"#,
)
.unwrap();
std::fs::write(
dir.path().join("left.json"),
r#"{"extends": ["base.json"], "rules": {"unused-files": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join("right.json"),
r#"{"extends": ["base.json"], "rules": {"unused-exports": "off"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["left.json", "right.json"]}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.ignore_patterns, vec!["generated/**"]);
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(config.rules.unused_exports, Severity::Off);
}
#[test]
fn extends_circular_detected() {
let dir = test_dir("extends-circular");
std::fs::write(dir.path().join("a.json"), r#"{"extends": ["b.json"]}"#).unwrap();
std::fs::write(dir.path().join("b.json"), r#"{"extends": ["a.json"]}"#).unwrap();
let result = FallowConfig::load(&dir.path().join("a.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("Circular extends"),
"Expected circular error, got: {err_msg}"
);
}
#[test]
fn remote_extends_are_denied_before_fetch_by_default() {
let dir = test_dir("remote-default-denied");
let url = "https://config-user:config-password@config.example:8443/base.json?token=config-token#config-fragment";
std::fs::write(
dir.path().join(".fallowrc.json"),
format!(r#"{{"extends": "{url}"}}"#),
)
.unwrap();
let mut fetcher = MockRemoteFetcher::default().with_response(url, serde_json::json!({}));
let error = load_with_fetcher(
&dir.path().join(".fallowrc.json"),
ConfigLoadOptions::default(),
&mut fetcher,
)
.unwrap_err()
.to_string();
assert!(
error.contains("https://config.example:8443/base.json"),
"denial must name the URL without secrets"
);
for secret in [
"config-user",
"config-password",
"config-token",
"config-fragment",
] {
assert!(
!error.contains(secret),
"denial must not expose a secret value"
);
}
assert!(
error.contains("--allow-remote-extends"),
"denial must name the CLI opt-in"
);
assert!(
error.contains("ConfigLoadOptions"),
"denial must name the library opt-in"
);
assert!(
fetcher.requests.is_empty(),
"denial must happen before fetch"
);
}
#[test]
fn remote_parent_and_requested_url_secrets_are_redacted_in_errors() {
let dir = test_dir("remote-error-redaction");
let parent = "https://parent-user:parent-password@[2001:db8::1]:8443/base.json?token=parent-token#parent-fragment";
let requested = "http://child-user:child-password@child.example/child.json?token=child-token#child-fragment";
std::fs::write(
dir.path().join(".fallowrc.json"),
format!(r#"{{"extends": "{parent}"}}"#),
)
.unwrap();
let mut fetcher = MockRemoteFetcher::default()
.with_response(parent, serde_json::json!({"extends": requested}));
let error = load_with_fetcher(
&dir.path().join(".fallowrc.json"),
ConfigLoadOptions::new(true),
&mut fetcher,
)
.unwrap_err()
.to_string();
assert!(
error.contains("http://child.example/child.json"),
"error must preserve the requested host and path"
);
assert!(
error.contains("https://[2001:db8::1]:8443/base.json"),
"error must preserve the remote parent host, port, and path"
);
for secret in [
"parent-user",
"parent-password",
"parent-token",
"parent-fragment",
"child-user",
"child-password",
"child-token",
"child-fragment",
] {
assert!(
!error.contains(secret),
"remote error must not expose a secret value"
);
}
}
#[test]
fn remote_fetch_network_error_redacts_requested_url_and_source() {
let url = "https://request-user:request-password@127.0.0.1:0/config.json?token=request-token#request-fragment";
let source = "https://source-user:source-password@source.example/parent.json?token=source-token#source-fragment";
let error = fetch_url_config(url, source, ConfigLoadOptions::default().extends_timeout)
.expect_err("the reserved local port must reject the request")
.to_string();
assert!(
error.contains("https://127.0.0.1:0/config.json"),
"network error must preserve the requested host, port, and path"
);
assert!(
error.contains("https://source.example/parent.json"),
"network error must preserve the source host and path"
);
for secret in [
"request-user",
"request-password",
"request-token",
"request-fragment",
"source-user",
"source-password",
"source-token",
"source-fragment",
] {
assert!(
!error.contains(secret),
"network error must not expose a secret value"
);
}
}
#[test]
fn remote_fetch_error_detail_does_not_trust_normalized_urls() {
let url = "https://request-user:request-password@config.example/config.json?token=request-token#request-fragment";
let normalized_error = ureq::Error::BadUri(
"https://request-user:request-password@config.example/config.json?token=request-token"
.to_string(),
);
assert!(
remote_fetch_error_display(&normalized_error, url) == "request failed",
"normalized network errors must not bypass URL redaction"
);
}
#[test]
fn remote_fetch_error_detail_does_not_trust_redirect_like_payloads() {
let original = "https://config.example/config.json";
let error = ureq::Error::BadUri(
"http://redirect-user:redirect-password@example.com/next.json?token=secret#anchor"
.to_string(),
);
let display = remote_fetch_error_display(&error, original);
assert_eq!(display, "request failed");
for secret in [
"redirect-user",
"redirect-password",
"token=secret",
"anchor",
] {
assert!(
!display.contains(secret),
"untrusted error detail must be hidden"
);
}
}
#[test]
fn remote_extends_dispatch_when_explicitly_allowed() {
let dir = test_dir("remote-explicitly-allowed");
let url = "https://config.example/base.json";
std::fs::write(
dir.path().join(".fallowrc.json"),
format!(r#"{{"extends": "{url}"}}"#),
)
.unwrap();
let mut fetcher = MockRemoteFetcher::default()
.with_response(url, serde_json::json!({"rules": {"unused-files": "warn"}}));
let config = load_with_fetcher(
&dir.path().join(".fallowrc.json"),
ConfigLoadOptions::new(true),
&mut fetcher,
)
.unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(fetcher.requests, vec![url]);
}
#[test]
fn uppercase_https_remote_extends_dispatch_when_allowed() {
let dir = test_dir("remote-uppercase-scheme");
let url = "HTTPS://config.example/base.json";
std::fs::write(
dir.path().join(".fallowrc.json"),
format!(r#"{{"extends": "{url}"}}"#),
)
.unwrap();
let mut fetcher = MockRemoteFetcher::default()
.with_response(url, serde_json::json!({"rules": {"unused-files": "warn"}}));
let config = load_with_fetcher(
&dir.path().join(".fallowrc.json"),
ConfigLoadOptions::new(true),
&mut fetcher,
)
.unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(fetcher.requests, vec![url]);
}
#[test]
fn remote_extends_diamond_reuses_mocked_base() {
let dir = test_dir("remote-diamond");
let left = "https://config.example/left.json";
let right = "https://config.example/right.json";
let base = "https://config.example/base.json";
std::fs::write(
dir.path().join(".fallowrc.json"),
format!(r#"{{"extends": ["{left}", "{right}"]}}"#),
)
.unwrap();
let mut fetcher = MockRemoteFetcher::default()
.with_response(
left,
serde_json::json!({
"extends": base,
"rules": {"unused-files": "warn"}
}),
)
.with_response(
right,
serde_json::json!({
"extends": base,
"rules": {"unused-exports": "off"}
}),
)
.with_response(
base,
serde_json::json!({"ignorePatterns": ["generated/**"]}),
);
let config = load_with_fetcher(
&dir.path().join(".fallowrc.json"),
ConfigLoadOptions::new(true),
&mut fetcher,
)
.unwrap();
assert_eq!(config.ignore_patterns, vec!["generated/**"]);
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(config.rules.unused_exports, Severity::Off);
assert_eq!(
fetcher
.requests
.iter()
.filter(|request| *request == base)
.count(),
1,
"the shared remote base should be fetched once"
);
}
#[test]
fn remote_extends_active_cycle_still_fails() {
let dir = test_dir("remote-cycle");
let first = "https://config.example/first.json";
let second = "https://config.example/second.json";
std::fs::write(
dir.path().join(".fallowrc.json"),
format!(r#"{{"extends": "{first}"}}"#),
)
.unwrap();
let mut fetcher = MockRemoteFetcher::default()
.with_response(first, serde_json::json!({"extends": second}))
.with_response(second, serde_json::json!({"extends": first}));
let error = load_with_fetcher(
&dir.path().join(".fallowrc.json"),
ConfigLoadOptions::new(true),
&mut fetcher,
)
.unwrap_err()
.to_string();
assert!(
error.contains("Circular extends"),
"unexpected error: {error}"
);
}
#[test]
fn query_distinct_remote_extends_remain_distinct() {
let dir = test_dir("remote-query-distinct");
let first = "https://config.example/base.json?profile=one";
let second = "https://config.example/base.json?profile=two";
std::fs::write(
dir.path().join(".fallowrc.json"),
format!(r#"{{"extends": ["{first}", "{second}"]}}"#),
)
.unwrap();
let mut fetcher = MockRemoteFetcher::default()
.with_response(
first,
serde_json::json!({"rules": {"unused-files": "warn"}}),
)
.with_response(
second,
serde_json::json!({"rules": {"unused-exports": "off"}}),
);
let config = load_with_fetcher(
&dir.path().join(".fallowrc.json"),
ConfigLoadOptions::new(true),
&mut fetcher,
)
.unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(config.rules.unused_exports, Severity::Off);
assert_eq!(fetcher.requests, vec![first, second]);
}
#[test]
fn extends_missing_file_errors() {
let dir = test_dir("extends-missing");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["nonexistent.json"]}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("not found"),
"Expected not found error, got: {err_msg}"
);
}
#[test]
fn sealed_allows_in_directory_extends() {
let dir = test_dir("sealed-allows-local");
std::fs::write(
dir.path().join("base.json"),
r#"{"ignorePatterns": ["gen/**"]}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"sealed": true, "extends": ["./base.json"]}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert!(config.sealed);
assert_eq!(config.ignore_patterns, vec!["gen/**"]);
}
#[test]
fn load_rejects_invalid_boundary_coverage_allow_unmatched_glob() {
let dir = test_dir("boundary-coverage-invalid-glob");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"boundaries":{"coverage":{"allowUnmatched":["[invalid"]}}}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("boundaries.coverage.allowUnmatched"),
"expected coverage field in error, got: {err_msg}"
);
}
#[test]
fn sealed_rejects_extends_escaping_directory() {
let dir = test_dir("sealed-rejects-escape");
let sub = dir.path().join("packages").join("app");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(
dir.path().join("base.json"),
r#"{"ignorePatterns": ["dist/**"]}"#,
)
.unwrap();
std::fs::write(
sub.join(".fallowrc.json"),
r#"{"sealed": true, "extends": ["../../base.json"]}"#,
)
.unwrap();
let result = FallowConfig::load(&sub.join(".fallowrc.json"));
assert!(
result.is_err(),
"Expected sealed config to reject escaping extends"
);
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("sealed"),
"Error must mention sealed: {err_msg}"
);
assert!(
err_msg.contains("outside the config's directory"),
"Error must explain the constraint: {err_msg}"
);
}
#[test]
fn sealed_rejects_https_extends() {
let dir = test_dir("sealed-rejects-https");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"sealed": true, "extends": ["https://example.com/base.json"]}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("sealed"),
"Error must mention sealed: {err_msg}"
);
assert!(
err_msg.contains("URL extends"),
"Error must mention URL: {err_msg}"
);
}
#[test]
fn sealed_rejects_npm_extends() {
let dir = test_dir("sealed-rejects-npm");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"sealed": true, "extends": ["npm:@scope/config"]}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("sealed"),
"Error must mention sealed: {err_msg}"
);
assert!(
err_msg.contains("npm extends"),
"Error must mention npm: {err_msg}"
);
}
#[test]
fn sealed_default_is_false() {
let dir = test_dir("sealed-default");
std::fs::write(dir.path().join(".fallowrc.json"), "{}").unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert!(!config.sealed);
}
#[test]
fn sealed_false_allows_escaping_extends() {
let dir = test_dir("sealed-false-allows");
let sub = dir.path().join("packages").join("app");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(
dir.path().join("base.json"),
r#"{"ignorePatterns": ["dist/**"]}"#,
)
.unwrap();
std::fs::write(
sub.join(".fallowrc.json"),
r#"{"extends": ["../../base.json"]}"#,
)
.unwrap();
let config = FallowConfig::load(&sub.join(".fallowrc.json")).unwrap();
assert!(!config.sealed);
assert_eq!(config.ignore_patterns, vec!["dist/**"]);
}
#[test]
fn extends_string_sugar() {
let dir = test_dir("extends-string");
std::fs::write(
dir.path().join("base.json"),
r#"{"ignorePatterns": ["gen/**"]}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "base.json"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.ignore_patterns, vec!["gen/**"]);
}
#[test]
fn extends_deep_merge_preserves_arrays() {
let dir = test_dir("extends-array");
std::fs::write(dir.path().join("base.json"), r#"{"entry": ["src/a.ts"]}"#).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["base.json"], "entry": ["src/b.ts"]}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.entry, vec!["src/b.ts"]);
}
fn create_npm_package(root: &Path, name: &str, config_json: &str) {
let pkg_dir = root.join("node_modules").join(name);
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(pkg_dir.join(".fallowrc.json"), config_json).unwrap();
}
fn create_npm_package_with_main(root: &Path, name: &str, main: &str, config_json: &str) {
let pkg_dir = root.join("node_modules").join(name);
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("package.json"),
format!(r#"{{"name": "{name}", "main": "{main}"}}"#),
)
.unwrap();
std::fs::write(pkg_dir.join(main), config_json).unwrap();
}
#[test]
fn extends_npm_basic_unscoped() {
let dir = test_dir("npm-basic");
create_npm_package(
dir.path(),
"fallow-config-acme",
r#"{"rules": {"unused-files": "warn"}}"#,
);
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:fallow-config-acme"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
}
#[test]
fn extends_npm_scoped_package() {
let dir = test_dir("npm-scoped");
create_npm_package(
dir.path(),
"@company/fallow-config",
r#"{"rules": {"unused-exports": "off"}, "ignorePatterns": ["generated/**"]}"#,
);
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:@company/fallow-config"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_exports, Severity::Off);
assert_eq!(config.ignore_patterns, vec!["generated/**"]);
}
#[test]
fn extends_npm_with_subpath() {
let dir = test_dir("npm-subpath");
let pkg_dir = dir.path().join("node_modules/@company/fallow-config");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("strict.json"),
r#"{"rules": {"unused-files": "error", "unused-exports": "error"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:@company/fallow-config/strict.json"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Error);
assert_eq!(config.rules.unused_exports, Severity::Error);
}
#[test]
fn extends_npm_package_json_main() {
let dir = test_dir("npm-main");
create_npm_package_with_main(
dir.path(),
"fallow-config-acme",
"config.json",
r#"{"rules": {"unused-types": "off"}}"#,
);
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:fallow-config-acme"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_types, Severity::Off);
}
#[test]
fn extends_npm_package_json_exports_string() {
let dir = test_dir("npm-exports-str");
let pkg_dir = dir.path().join("node_modules/fallow-config-co");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("package.json"),
r#"{"name": "fallow-config-co", "exports": "./base.json"}"#,
)
.unwrap();
std::fs::write(
pkg_dir.join("base.json"),
r#"{"rules": {"circular-dependencies": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:fallow-config-co"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.circular_dependencies, Severity::Warn);
}
#[test]
fn extends_npm_package_json_exports_object() {
let dir = test_dir("npm-exports-obj");
let pkg_dir = dir.path().join("node_modules/@co/cfg");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("package.json"),
r#"{"name": "@co/cfg", "exports": {".": {"default": "./fallow.json"}}}"#,
)
.unwrap();
std::fs::write(pkg_dir.join("fallow.json"), r#"{"entry": ["src/app.ts"]}"#).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:@co/cfg"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.entry, vec!["src/app.ts"]);
}
#[test]
fn extends_npm_exports_takes_priority_over_main() {
let dir = test_dir("npm-exports-prio");
let pkg_dir = dir.path().join("node_modules/my-config");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("package.json"),
r#"{"name": "my-config", "main": "./old.json", "exports": "./new.json"}"#,
)
.unwrap();
std::fs::write(
pkg_dir.join("old.json"),
r#"{"rules": {"unused-files": "off"}}"#,
)
.unwrap();
std::fs::write(
pkg_dir.join("new.json"),
r#"{"rules": {"unused-files": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:my-config"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
}
#[test]
fn extends_npm_walk_up_directories() {
let dir = test_dir("npm-walkup");
create_npm_package(
dir.path(),
"shared-config",
r#"{"rules": {"unused-files": "warn"}}"#,
);
let sub = dir.path().join("packages/app");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(
sub.join(".fallowrc.json"),
r#"{"extends": "npm:shared-config"}"#,
)
.unwrap();
let config = FallowConfig::load(&sub.join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
}
#[test]
fn extends_npm_overlay_overrides_base() {
let dir = test_dir("npm-overlay");
create_npm_package(
dir.path(),
"@company/base",
r#"{"rules": {"unused-files": "warn", "unused-exports": "off"}, "entry": ["src/base.ts"]}"#,
);
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:@company/base", "rules": {"unused-files": "error"}, "entry": ["src/app.ts"]}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Error);
assert_eq!(config.rules.unused_exports, Severity::Off);
assert_eq!(config.entry, vec!["src/app.ts"]);
}
#[test]
fn extends_npm_chained_with_relative() {
let dir = test_dir("npm-chained");
let pkg_dir = dir.path().join("node_modules/my-config");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("base.json"),
r#"{"rules": {"unused-files": "warn"}}"#,
)
.unwrap();
std::fs::write(
pkg_dir.join(".fallowrc.json"),
r#"{"extends": ["base.json"], "rules": {"unused-exports": "off"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:my-config"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(config.rules.unused_exports, Severity::Off);
}
#[test]
fn extends_npm_mixed_with_relative_paths() {
let dir = test_dir("npm-mixed");
create_npm_package(
dir.path(),
"shared-base",
r#"{"rules": {"unused-files": "off"}}"#,
);
std::fs::write(
dir.path().join("local-overrides.json"),
r#"{"rules": {"unused-files": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["npm:shared-base", "local-overrides.json"]}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
}
#[test]
fn extends_npm_missing_package_errors() {
let dir = test_dir("npm-missing");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:nonexistent-package"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("not found"),
"Expected 'not found' error, got: {err_msg}"
);
assert!(
err_msg.contains("nonexistent-package"),
"Expected package name in error, got: {err_msg}"
);
assert!(
err_msg.contains("install it"),
"Expected install hint in error, got: {err_msg}"
);
}
#[test]
fn extends_npm_no_config_in_package_errors() {
let dir = test_dir("npm-no-config");
let pkg_dir = dir.path().join("node_modules/empty-pkg");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(pkg_dir.join("README.md"), "# empty").unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:empty-pkg"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("No fallow config found"),
"Expected 'No fallow config found' error, got: {err_msg}"
);
}
#[test]
fn extends_npm_missing_subpath_errors() {
let dir = test_dir("npm-missing-sub");
let pkg_dir = dir.path().join("node_modules/@co/config");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:@co/config/nonexistent.json"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("nonexistent.json"),
"Expected subpath in error, got: {err_msg}"
);
}
#[test]
fn extends_npm_empty_specifier_errors() {
let dir = test_dir("npm-empty");
std::fs::write(dir.path().join(".fallowrc.json"), r#"{"extends": "npm:"}"#).unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("Empty npm specifier"),
"Expected 'Empty npm specifier' error, got: {err_msg}"
);
}
#[test]
fn extends_npm_space_after_colon_trimmed() {
let dir = test_dir("npm-space");
create_npm_package(
dir.path(),
"fallow-config-acme",
r#"{"rules": {"unused-files": "warn"}}"#,
);
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm: fallow-config-acme"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
}
#[test]
fn extends_npm_exports_node_condition() {
let dir = test_dir("npm-node-cond");
let pkg_dir = dir.path().join("node_modules/node-config");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("package.json"),
r#"{"name": "node-config", "exports": {".": {"node": "./node.json"}}}"#,
)
.unwrap();
std::fs::write(
pkg_dir.join("node.json"),
r#"{"rules": {"unused-files": "off"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:node-config"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Off);
}
#[test]
fn parse_npm_specifier_unscoped() {
assert_eq!(parse_npm_specifier("my-config"), ("my-config", None));
}
#[test]
fn parse_npm_specifier_unscoped_with_subpath() {
assert_eq!(
parse_npm_specifier("my-config/strict.json"),
("my-config", Some("strict.json"))
);
}
#[test]
fn parse_npm_specifier_scoped() {
assert_eq!(
parse_npm_specifier("@company/fallow-config"),
("@company/fallow-config", None)
);
}
#[test]
fn parse_npm_specifier_scoped_with_subpath() {
assert_eq!(
parse_npm_specifier("@company/fallow-config/strict.json"),
("@company/fallow-config", Some("strict.json"))
);
}
#[test]
fn parse_npm_specifier_scoped_with_nested_subpath() {
assert_eq!(
parse_npm_specifier("@company/fallow-config/presets/strict.json"),
("@company/fallow-config", Some("presets/strict.json"))
);
}
#[test]
fn extends_npm_subpath_traversal_rejected() {
let dir = test_dir("npm-traversal-sub");
let pkg_dir = dir.path().join("node_modules/evil-pkg");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
dir.path().join("secret.json"),
r#"{"entry": ["stolen.ts"]}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:evil-pkg/../../secret.json"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("traversal") || err_msg.contains("not found"),
"Expected traversal or not-found error, got: {err_msg}"
);
}
#[test]
fn extends_npm_dotdot_package_name_rejected() {
let dir = test_dir("npm-dotdot-name");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:../relative"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("path traversal"),
"Expected 'path traversal' error, got: {err_msg}"
);
}
#[test]
fn extends_npm_scoped_without_name_rejected() {
let dir = test_dir("npm-scope-only");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:@scope"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("@scope/name"),
"Expected scoped name format error, got: {err_msg}"
);
}
#[test]
fn extends_npm_malformed_package_json_errors() {
let dir = test_dir("npm-bad-pkgjson");
let pkg_dir = dir.path().join("node_modules/bad-pkg");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(pkg_dir.join("package.json"), "{ not valid json }").unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:bad-pkg"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("Failed to parse"),
"Expected parse error, got: {err_msg}"
);
}
#[test]
fn extends_npm_exports_traversal_rejected() {
let dir = test_dir("npm-exports-escape");
let pkg_dir = dir.path().join("node_modules/evil-exports");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("package.json"),
r#"{"name": "evil-exports", "exports": "../../secret.json"}"#,
)
.unwrap();
std::fs::write(
dir.path().join("secret.json"),
r#"{"entry": ["stolen.ts"]}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:evil-exports"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("traversal"),
"Expected traversal error, got: {err_msg}"
);
}
#[test]
fn deep_merge_scalar_overlay_replaces_base() {
let mut base = serde_json::json!("hello");
deep_merge_json(&mut base, serde_json::json!("world"));
assert_eq!(base, serde_json::json!("world"));
}
#[test]
fn deep_merge_array_overlay_replaces_base() {
let mut base = serde_json::json!(["a", "b"]);
deep_merge_json(&mut base, serde_json::json!(["c"]));
assert_eq!(base, serde_json::json!(["c"]));
}
#[test]
fn deep_merge_nested_object_merge() {
let mut base = serde_json::json!({
"level1": {
"level2": {
"a": 1,
"b": 2
}
}
});
let overlay = serde_json::json!({
"level1": {
"level2": {
"b": 99,
"c": 3
}
}
});
deep_merge_json(&mut base, overlay);
assert_eq!(base["level1"]["level2"]["a"], 1);
assert_eq!(base["level1"]["level2"]["b"], 99);
assert_eq!(base["level1"]["level2"]["c"], 3);
}
#[test]
fn deep_merge_overlay_adds_new_fields() {
let mut base = serde_json::json!({"existing": true});
let overlay = serde_json::json!({"new_field": "added", "another": 42});
deep_merge_json(&mut base, overlay);
assert_eq!(base["existing"], true);
assert_eq!(base["new_field"], "added");
assert_eq!(base["another"], 42);
}
#[test]
fn deep_merge_null_overlay_replaces_object() {
let mut base = serde_json::json!({"key": "value"});
deep_merge_json(&mut base, serde_json::json!(null));
assert_eq!(base, serde_json::json!(null));
}
#[test]
fn deep_merge_empty_object_overlay_preserves_base() {
let mut base = serde_json::json!({"a": 1, "b": 2});
deep_merge_json(&mut base, serde_json::json!({}));
assert_eq!(base, serde_json::json!({"a": 1, "b": 2}));
}
#[test]
fn rules_severity_error_warn_off_from_json() {
let json_str = r#"{
"rules": {
"unused-files": "error",
"unused-exports": "warn",
"unused-types": "off"
}
}"#;
let config: FallowConfig = serde_json::from_str(json_str).unwrap();
assert_eq!(config.rules.unused_files, Severity::Error);
assert_eq!(config.rules.unused_exports, Severity::Warn);
assert_eq!(config.rules.unused_types, Severity::Off);
}
#[test]
fn rules_omitted_default_to_error() {
let json_str = r#"{
"rules": {
"unused-files": "warn"
}
}"#;
let config: FallowConfig = serde_json::from_str(json_str).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(config.rules.unused_exports, Severity::Error);
assert_eq!(config.rules.unused_types, Severity::Error);
assert_eq!(config.rules.unused_dependencies, Severity::Error);
assert_eq!(config.rules.unresolved_imports, Severity::Error);
assert_eq!(config.rules.unlisted_dependencies, Severity::Error);
assert_eq!(config.rules.duplicate_exports, Severity::Error);
assert_eq!(config.rules.circular_dependencies, Severity::Error);
assert_eq!(config.rules.type_only_dependencies, Severity::Warn);
}
#[test]
fn find_and_load_returns_none_when_no_config() {
let dir = test_dir("find-none");
std::fs::create_dir(dir.path().join(".git")).unwrap();
let result = FallowConfig::find_and_load(dir.path()).unwrap();
assert!(result.is_none());
}
#[test]
fn find_and_load_finds_fallowrc_json() {
let dir = test_dir("find-json");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["src/main.ts"]}"#,
)
.unwrap();
let (config, path) = FallowConfig::find_and_load(dir.path()).unwrap().unwrap();
assert_eq!(config.entry, vec!["src/main.ts"]);
assert!(path.ends_with(".fallowrc.json"));
}
#[test]
fn find_and_load_finds_fallowrc_jsonc() {
let dir = test_dir("find-jsonc");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.jsonc"),
r#"{
"entry": ["src/main.ts"]
}"#,
)
.unwrap();
let (config, path) = FallowConfig::find_and_load(dir.path()).unwrap().unwrap();
assert_eq!(config.entry, vec!["src/main.ts"]);
assert!(path.ends_with(".fallowrc.jsonc"));
}
#[test]
fn find_and_load_prefers_fallowrc_json_over_jsonc() {
let dir = test_dir("find-json-vs-jsonc");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["from-json.ts"]}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.jsonc"),
r#"{"entry": ["from-jsonc.ts"]}"#,
)
.unwrap();
let (config, path) = FallowConfig::find_and_load(dir.path()).unwrap().unwrap();
assert_eq!(config.entry, vec!["from-json.ts"]);
assert!(path.ends_with(".fallowrc.json"));
}
#[test]
fn find_and_load_prefers_fallowrc_json_over_toml() {
let dir = test_dir("find-priority");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["from-json.ts"]}"#,
)
.unwrap();
std::fs::write(
dir.path().join("fallow.toml"),
"entry = [\"from-toml.ts\"]\n",
)
.unwrap();
let (config, path) = FallowConfig::find_and_load(dir.path()).unwrap().unwrap();
assert_eq!(config.entry, vec!["from-json.ts"]);
assert!(path.ends_with(".fallowrc.json"));
}
#[test]
fn shadowed_config_names_empty_when_single_config() {
let dir = test_dir("shadow-single");
std::fs::write(dir.path().join(".fallowrc.json"), "").unwrap();
assert!(shadowed_config_names(dir.path(), 0).is_empty());
}
#[test]
fn shadowed_config_names_reports_lower_precedence_toml() {
let dir = test_dir("shadow-json-toml");
std::fs::write(dir.path().join(".fallowrc.json"), "").unwrap();
std::fs::write(dir.path().join("fallow.toml"), "").unwrap();
assert_eq!(shadowed_config_names(dir.path(), 0), vec!["fallow.toml"]);
}
#[test]
fn shadowed_config_names_reports_jsonc_sibling() {
let dir = test_dir("shadow-json-jsonc");
std::fs::write(dir.path().join(".fallowrc.json"), "").unwrap();
std::fs::write(dir.path().join(".fallowrc.jsonc"), "").unwrap();
assert_eq!(
shadowed_config_names(dir.path(), 0),
vec![".fallowrc.jsonc"]
);
}
#[test]
fn shadowed_config_names_reports_all_lower_when_four_coexist() {
let dir = test_dir("shadow-all-four");
for name in CONFIG_NAMES {
std::fs::write(dir.path().join(name), "").unwrap();
}
assert_eq!(
shadowed_config_names(dir.path(), 0),
vec![".fallowrc.jsonc", "fallow.toml", ".fallow.toml"],
);
}
#[test]
fn shadowed_config_names_scoped_to_indices_after_winner() {
let dir = test_dir("shadow-toml-dottoml");
std::fs::write(dir.path().join("fallow.toml"), "").unwrap();
std::fs::write(dir.path().join(".fallow.toml"), "").unwrap();
assert_eq!(shadowed_config_names(dir.path(), 2), vec![".fallow.toml"]);
}
#[test]
fn find_and_load_warns_when_configs_coexist() {
let dir = test_dir("coexist-warn");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["from-json.ts"]}"#,
)
.unwrap();
std::fs::write(
dir.path().join("fallow.toml"),
"entry = [\"from-toml.ts\"]\n",
)
.unwrap();
let (result, captured) =
capture_coexisting_config_warnings(|| FallowConfig::find_and_load(dir.path()));
let (config, path) = result.unwrap().unwrap();
assert_eq!(config.entry, vec!["from-json.ts"]);
assert!(path.ends_with(".fallowrc.json"));
assert_eq!(captured.len(), 1);
let (chosen, shadowed) = &captured[0];
assert_eq!(chosen, ".fallowrc.json");
assert_eq!(shadowed, &vec!["fallow.toml".to_owned()]);
}
#[test]
fn find_and_load_does_not_warn_for_single_config() {
let dir = test_dir("coexist-none");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["only.ts"]}"#,
)
.unwrap();
let (result, captured) =
capture_coexisting_config_warnings(|| FallowConfig::find_and_load(dir.path()));
assert!(result.unwrap().is_some());
assert!(captured.is_empty());
}
#[test]
fn find_and_load_warns_per_directory_independently() {
let make = |name: &str| {
let dir = test_dir(name);
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(dir.path().join(".fallowrc.json"), r#"{"entry": ["a.ts"]}"#).unwrap();
std::fs::write(dir.path().join("fallow.toml"), "entry = [\"a.ts\"]\n").unwrap();
dir
};
let first = make("coexist-dir-a");
let second = make("coexist-dir-b");
let ((), captured) = capture_coexisting_config_warnings(|| {
FallowConfig::find_and_load(first.path()).unwrap();
FallowConfig::find_and_load(second.path()).unwrap();
});
assert_eq!(captured.len(), 2);
assert!(captured.iter().all(|(chosen, shadowed)| {
chosen == ".fallowrc.json" && shadowed == &vec!["fallow.toml".to_owned()]
}));
}
#[test]
fn explicit_load_does_not_warn_about_coexisting_configs() {
let dir = test_dir("coexist-explicit");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["chosen.ts"]}"#,
)
.unwrap();
std::fs::write(dir.path().join("fallow.toml"), "entry = [\"other.ts\"]\n").unwrap();
let chosen = dir.path().join("fallow.toml");
let (result, captured) = capture_coexisting_config_warnings(|| FallowConfig::load(&chosen));
assert!(result.is_ok());
assert!(captured.is_empty());
}
#[test]
fn find_and_load_finds_fallow_toml() {
let dir = test_dir("find-toml");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join("fallow.toml"),
"entry = [\"src/index.ts\"]\n",
)
.unwrap();
let (config, _) = FallowConfig::find_and_load(dir.path()).unwrap().unwrap();
assert_eq!(config.entry, vec!["src/index.ts"]);
}
#[test]
fn find_and_load_stops_at_git_dir() {
let dir = test_dir("find-git-stop");
let sub = dir.path().join("sub");
std::fs::create_dir(&sub).unwrap();
std::fs::create_dir(dir.path().join(".git")).unwrap();
let result = FallowConfig::find_and_load(&sub).unwrap();
assert!(result.is_none());
}
#[test]
fn find_and_load_walks_past_package_json_in_monorepo() {
let dir = test_dir("find-monorepo");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["src/index.ts"]}"#,
)
.unwrap();
let sub = dir.path().join("packages").join("app");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(sub.join("package.json"), r#"{"name": "@scope/app"}"#).unwrap();
let (config, path) = FallowConfig::find_and_load(&sub).unwrap().unwrap();
assert_eq!(config.entry, vec!["src/index.ts"]);
assert_eq!(path, dir.path().join(".fallowrc.json"));
}
#[test]
fn find_and_load_sub_package_config_wins_over_root() {
let dir = test_dir("find-monorepo-override");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["src/root.ts"]}"#,
)
.unwrap();
let sub = dir.path().join("packages").join("app");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(sub.join("package.json"), r#"{"name": "@scope/app"}"#).unwrap();
std::fs::write(sub.join(".fallowrc.json"), r#"{"entry": ["src/sub.ts"]}"#).unwrap();
let (config, path) = FallowConfig::find_and_load(&sub).unwrap().unwrap();
assert_eq!(config.entry, vec!["src/sub.ts"]);
assert_eq!(path, sub.join(".fallowrc.json"));
}
#[test]
fn find_and_load_stops_at_git_file_submodule() {
let dir = test_dir("find-git-file");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["src/parent.ts"]}"#,
)
.unwrap();
let submodule = dir.path().join("vendor").join("lib");
std::fs::create_dir_all(&submodule).unwrap();
std::fs::write(submodule.join(".git"), "gitdir: ../../.git/modules/lib\n").unwrap();
let result = FallowConfig::find_and_load(&submodule).unwrap();
assert!(
result.is_none(),
"submodule boundary should stop config walk",
);
}
#[test]
fn find_and_load_stops_at_hg_dir() {
let dir = test_dir("find-hg-stop");
let sub = dir.path().join("sub");
std::fs::create_dir(&sub).unwrap();
std::fs::create_dir(dir.path().join(".hg")).unwrap();
let result = FallowConfig::find_and_load(&sub).unwrap();
assert!(result.is_none());
}
#[test]
fn find_and_load_returns_error_for_invalid_config() {
let dir = test_dir("find-invalid");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r"{ this is not valid json }",
)
.unwrap();
let result = FallowConfig::find_and_load(dir.path());
assert!(result.is_err());
}
#[test]
fn load_toml_config_file() {
let dir = test_dir("toml-config");
let config_path = dir.path().join("fallow.toml");
std::fs::write(
&config_path,
r#"
entry = ["src/index.ts"]
ignorePatterns = ["dist/**"]
[rules]
unused-files = "warn"
[duplicates]
minTokens = 100
"#,
)
.unwrap();
let config = FallowConfig::load(&config_path).unwrap();
assert_eq!(config.entry, vec!["src/index.ts"]);
assert_eq!(config.ignore_patterns, vec!["dist/**"]);
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(config.duplicates.min_tokens, 100);
}
#[test]
fn load_toml_config_file_with_health_threshold_override() {
let dir = test_dir("toml-health-threshold-override");
let config_path = dir.path().join("fallow.toml");
std::fs::write(
&config_path,
r#"
[health]
thresholdOverrides = [
{ files = ["src/legacy.ts"], functions = ["legacyFlow"], maxCyclomatic = 30, maxCognitive = 25, maxCrap = 80.5, reason = "legacy migration" }
]
"#,
)
.unwrap();
let config = FallowConfig::load(&config_path).unwrap();
let override_config = &config.health.threshold_overrides[0];
assert_eq!(override_config.files, vec!["src/legacy.ts"]);
assert_eq!(override_config.functions, vec!["legacyFlow"]);
assert_eq!(override_config.max_cyclomatic, Some(30));
assert_eq!(override_config.max_cognitive, Some(25));
assert_eq!(override_config.max_crap, Some(80.5));
assert_eq!(override_config.reason.as_deref(), Some("legacy migration"));
}
#[test]
fn extends_absolute_path_rejected() {
let dir = test_dir("extends-absolute");
#[cfg(unix)]
let abs_path = "/absolute/path/config.json";
#[cfg(windows)]
let abs_path = "C:\\absolute\\path\\config.json";
let json = format!(r#"{{"extends": ["{}"]}}"#, abs_path.replace('\\', "\\\\"));
std::fs::write(dir.path().join(".fallowrc.json"), json).unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("must be relative"),
"Expected 'must be relative' error, got: {err_msg}"
);
}
#[test]
fn extends_windows_drive_absolute_path_rejected_on_any_host() {
let dir = test_dir("extends-windows-absolute");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["C:\\absolute\\path\\config.json"]}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("must be relative"),
"Expected 'must be relative' error, got: {err_msg}"
);
}
#[cfg(windows)]
#[test]
fn extends_posix_rooted_absolute_path_rejected_on_windows() {
let dir = test_dir("extends-posix-rooted-absolute");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["/absolute/path/config.json"]}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("must be relative"),
"Expected 'must be relative' error, got: {err_msg}"
);
}
#[test]
fn resolve_production_mode_disables_dev_deps() {
let config = FallowConfig {
production: true.into(),
..Default::default()
};
let resolved = config.resolve(
PathBuf::from("/tmp/test"),
OutputFormat::Human,
4,
false,
true,
None,
);
assert!(resolved.production);
assert_eq!(resolved.rules.unused_dev_dependencies, Severity::Off);
assert_eq!(resolved.rules.unused_optional_dependencies, Severity::Off);
assert_eq!(resolved.rules.unused_files, Severity::Error);
assert_eq!(resolved.rules.unused_exports, Severity::Error);
}
#[test]
fn include_entry_exports_deserializes_from_camelcase_json() {
let json = r#"{ "includeEntryExports": true }"#;
let config: FallowConfig = serde_json::from_str(json).unwrap();
assert!(config.include_entry_exports);
}
#[test]
fn include_entry_exports_deserializes_from_camelcase_toml() {
let toml_str = "includeEntryExports = true\n";
let config: FallowConfig = toml::from_str(toml_str).unwrap();
assert!(config.include_entry_exports);
}
#[test]
fn include_entry_exports_default_is_false() {
let config: FallowConfig = serde_json::from_str("{}").unwrap();
assert!(!config.include_entry_exports);
}
#[test]
fn include_entry_exports_propagates_through_resolve() {
let config = FallowConfig {
include_entry_exports: true,
auto_imports: false,
cache: CacheConfig::default(),
..Default::default()
};
let resolved = config.resolve(
PathBuf::from("/tmp/test"),
OutputFormat::Human,
1,
true,
true,
None,
);
assert!(resolved.include_entry_exports);
}
#[test]
fn fail_on_parse_error_reads_from_json_and_toml_and_reaches_the_resolved_config() {
let json: FallowConfig = serde_json::from_str(r#"{"failOnParseError": true}"#).unwrap();
assert!(json.fail_on_parse_error);
let toml: FallowConfig = toml::from_str("failOnParseError = true").unwrap();
assert!(toml.fail_on_parse_error);
let unset: FallowConfig = serde_json::from_str("{}").unwrap();
assert!(
!unset.fail_on_parse_error,
"the gate is never armed by default"
);
let resolved = json.resolve(
PathBuf::from("/tmp/test"),
OutputFormat::Human,
1,
true,
true,
None,
);
assert!(resolved.fail_on_parse_error);
}
#[test]
fn config_format_defaults_to_toml_for_unknown() {
assert!(matches!(
ConfigFormat::from_path(Path::new("config.yaml")),
ConfigFormat::Toml
));
assert!(matches!(
ConfigFormat::from_path(Path::new("config")),
ConfigFormat::Toml
));
}
#[test]
fn deep_merge_object_over_scalar_replaces() {
let mut base = serde_json::json!("just a string");
let overlay = serde_json::json!({"key": "value"});
deep_merge_json(&mut base, overlay);
assert_eq!(base, serde_json::json!({"key": "value"}));
}
#[test]
fn deep_merge_scalar_over_object_replaces() {
let mut base = serde_json::json!({"key": "value"});
let overlay = serde_json::json!(42);
deep_merge_json(&mut base, overlay);
assert_eq!(base, serde_json::json!(42));
}
#[test]
fn extends_non_string_non_array_fails_loud() {
let dir = test_dir("extends-numeric");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": 42, "entry": ["src/index.ts"]}"#,
)
.unwrap();
let err = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap_err();
assert!(
err.to_string()
.contains("extends must be a string or an array of strings"),
"unexpected error: {err}"
);
}
#[test]
fn extends_multiple_bases_later_wins() {
let dir = test_dir("extends-multi-base");
std::fs::write(
dir.path().join("base-a.json"),
r#"{"rules": {"unused-files": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join("base-b.json"),
r#"{"rules": {"unused-files": "off"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["base-a.json", "base-b.json"]}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Off);
}
#[test]
fn load_rejects_empty_security_request_receivers() {
let dir = test_dir("empty-security-request-receivers");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"security": {"requestReceivers": ["req", " "]}}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
let err = result.expect_err("empty receiver should be rejected");
assert!(
err.to_string().contains("security.requestReceivers"),
"error should name security.requestReceivers: {err}"
);
}
#[test]
fn resolve_normalizes_security_request_receivers() {
let dir = test_dir("normalize-security-request-receivers");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"security": {"requestReceivers": [" HttpReq ", "httpreq", "R"]}}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json"))
.unwrap()
.resolve(
dir.path().to_path_buf(),
OutputFormat::Human,
1,
true,
true,
None,
);
assert_eq!(
config.security.request_receivers,
vec!["httpreq".to_string(), "r".to_string()]
);
}
#[test]
fn fallow_config_deserialize_production() {
let json_str = r#"{"production": true}"#;
let config: FallowConfig = serde_json::from_str(json_str).unwrap();
assert!(config.production);
}
#[test]
fn package_json_optional_dependency_names() {
let pkg: PackageJson =
serde_json::from_str(r#"{"optionalDependencies": {"fsevents": "^2", "chokidar": "^3"}}"#)
.unwrap();
let opt = pkg.optional_dependency_names();
assert_eq!(opt.len(), 2);
assert!(opt.contains(&"fsevents".to_string()));
assert!(opt.contains(&"chokidar".to_string()));
}
#[test]
fn package_json_optional_deps_empty_when_missing() {
let pkg: PackageJson = serde_json::from_str(r#"{"name": "test"}"#).unwrap();
assert!(pkg.optional_dependency_names().is_empty());
}
#[test]
fn find_config_path_returns_fallowrc_json() {
let dir = test_dir("find-path-json");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["src/main.ts"]}"#,
)
.unwrap();
let path = FallowConfig::find_config_path(dir.path());
assert!(path.is_some());
assert!(path.unwrap().ends_with(".fallowrc.json"));
}
#[test]
fn find_config_path_returns_fallow_toml() {
let dir = test_dir("find-path-toml");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join("fallow.toml"),
"entry = [\"src/main.ts\"]\n",
)
.unwrap();
let path = FallowConfig::find_config_path(dir.path());
assert!(path.is_some());
assert!(path.unwrap().ends_with("fallow.toml"));
}
#[test]
fn find_config_path_returns_dot_fallow_toml() {
let dir = test_dir("find-path-dot-toml");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallow.toml"),
"entry = [\"src/main.ts\"]\n",
)
.unwrap();
let path = FallowConfig::find_config_path(dir.path());
assert!(path.is_some());
assert!(path.unwrap().ends_with(".fallow.toml"));
}
#[test]
fn find_config_path_prefers_json_over_toml() {
let dir = test_dir("find-path-priority");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["json.ts"]}"#,
)
.unwrap();
std::fs::write(dir.path().join("fallow.toml"), "entry = [\"toml.ts\"]\n").unwrap();
let path = FallowConfig::find_config_path(dir.path());
assert!(path.unwrap().ends_with(".fallowrc.json"));
}
#[test]
fn find_config_path_none_when_no_config() {
let dir = test_dir("find-path-none");
std::fs::create_dir(dir.path().join(".git")).unwrap();
let path = FallowConfig::find_config_path(dir.path());
assert!(path.is_none());
}
#[test]
fn find_config_path_walks_past_package_json_in_monorepo() {
let dir = test_dir("find-path-monorepo");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["src/index.ts"]}"#,
)
.unwrap();
let sub = dir.path().join("packages").join("app");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(sub.join("package.json"), r#"{"name": "@scope/app"}"#).unwrap();
let path = FallowConfig::find_config_path(&sub).unwrap();
assert_eq!(path, dir.path().join(".fallowrc.json"));
}
#[test]
fn extends_toml_base() {
let dir = test_dir("extends-toml");
std::fs::write(
dir.path().join("base.json"),
r#"{"rules": {"unused-files": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join("fallow.toml"),
"extends = [\"base.json\"]\nentry = [\"src/index.ts\"]\n",
)
.unwrap();
let config = FallowConfig::load(&dir.path().join("fallow.toml")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
assert_eq!(config.entry, vec!["src/index.ts"]);
}
#[test]
fn deep_merge_boolean_overlay() {
let mut base = serde_json::json!(true);
deep_merge_json(&mut base, serde_json::json!(false));
assert_eq!(base, serde_json::json!(false));
}
#[test]
fn deep_merge_number_overlay() {
let mut base = serde_json::json!(42);
deep_merge_json(&mut base, serde_json::json!(99));
assert_eq!(base, serde_json::json!(99));
}
#[test]
fn deep_merge_disjoint_objects() {
let mut base = serde_json::json!({"a": 1});
let overlay = serde_json::json!({"b": 2});
deep_merge_json(&mut base, overlay);
assert_eq!(base, serde_json::json!({"a": 1, "b": 2}));
}
#[test]
fn max_extends_depth_is_reasonable() {
assert_eq!(MAX_EXTENDS_DEPTH, 10);
}
#[test]
fn config_names_has_four_entries() {
assert_eq!(CONFIG_NAMES.len(), 4);
for name in CONFIG_NAMES {
assert!(
name.starts_with('.') || name.starts_with("fallow"),
"unexpected config name: {name}"
);
}
}
#[test]
fn package_json_peer_dependency_names() {
let pkg: PackageJson = serde_json::from_str(
r#"{
"dependencies": {"react": "^18"},
"peerDependencies": {"react-dom": "^18", "react-native": "^0.72"}
}"#,
)
.unwrap();
let all = pkg.all_dependency_names();
assert!(all.contains(&"react".to_string()));
assert!(all.contains(&"react-dom".to_string()));
assert!(all.contains(&"react-native".to_string()));
}
#[test]
fn package_json_scripts_field() {
let pkg: PackageJson = serde_json::from_str(
r#"{
"scripts": {
"build": "tsc",
"test": "vitest",
"lint": "fallow check"
}
}"#,
)
.unwrap();
let scripts = pkg.scripts.unwrap();
assert_eq!(scripts.len(), 3);
assert_eq!(scripts.get("build"), Some(&"tsc".to_string()));
assert_eq!(scripts.get("lint"), Some(&"fallow check".to_string()));
}
#[test]
fn extends_toml_chain() {
let dir = test_dir("extends-toml-chain");
std::fs::write(
dir.path().join("base.json"),
r#"{"entry": ["src/base.ts"]}"#,
)
.unwrap();
std::fs::write(
dir.path().join("middle.json"),
r#"{"extends": ["base.json"], "rules": {"unused-files": "off"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join("fallow.toml"),
"extends = [\"middle.json\"]\n",
)
.unwrap();
let config = FallowConfig::load(&dir.path().join("fallow.toml")).unwrap();
assert_eq!(config.entry, vec!["src/base.ts"]);
assert_eq!(config.rules.unused_files, Severity::Off);
}
#[test]
fn find_and_load_walks_up_directories() {
let dir = test_dir("find-walk-up");
let sub = dir.path().join("src").join("deep");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["src/main.ts"]}"#,
)
.unwrap();
std::fs::create_dir(dir.path().join(".git")).unwrap();
let (config, path) = FallowConfig::find_and_load(&sub).unwrap().unwrap();
assert_eq!(config.entry, vec!["src/main.ts"]);
assert!(path.ends_with(".fallowrc.json"));
}
#[test]
fn json_schema_contains_entry_field() {
let schema = FallowConfig::json_schema();
let obj = schema.as_object().unwrap();
let props = obj.get("properties").and_then(|v| v.as_object());
assert!(props.is_some(), "schema should have properties");
assert!(
props.unwrap().contains_key("entry"),
"schema should contain entry property"
);
}
#[test]
fn fallow_config_json_duplicates_all_fields() {
let json = r#"{
"duplicates": {
"enabled": true,
"mode": "semantic",
"minTokens": 200,
"minLines": 20,
"threshold": 10.5,
"ignore": ["**/*.test.ts"],
"skipLocal": true,
"crossLanguage": true,
"normalization": {
"ignoreIdentifiers": true,
"ignoreStringValues": false
}
}
}"#;
let config: FallowConfig = serde_json::from_str(json).unwrap();
assert!(config.duplicates.enabled);
assert_eq!(
config.duplicates.mode,
crate::config::DetectionMode::Semantic
);
assert_eq!(config.duplicates.min_tokens, 200);
assert_eq!(config.duplicates.min_lines, 20);
assert!((config.duplicates.threshold - 10.5).abs() < f64::EPSILON);
assert!(config.duplicates.skip_local);
assert!(config.duplicates.cross_language);
assert_eq!(
config.duplicates.normalization.ignore_identifiers,
Some(true)
);
assert_eq!(
config.duplicates.normalization.ignore_string_values,
Some(false)
);
}
#[test]
fn normalize_url_basic() {
assert_eq!(
normalize_url_for_dedup("https://example.com/config.json"),
"https://example.com/config.json"
);
}
#[test]
fn remote_config_display_redacts_url_secrets_and_preserves_local_paths() {
let cases = [
(
"https://user:password@example.com/config.json",
"https://example.com/config.json",
),
(
"https://example.com/config.json?token=query-secret#fragment-secret",
"https://example.com/config.json",
),
(
"https://user:password@[2001:db8::1]:8443/config.json?token=query-secret#fragment-secret",
"https://[2001:db8::1]:8443/config.json",
),
(
"/workspace/configs/base.json?literal-query#literal-fragment",
"/workspace/configs/base.json?literal-query#literal-fragment",
),
];
for (case_index, (input, expected)) in cases.into_iter().enumerate() {
assert!(
remote_config_display(input) == expected,
"remote config display case {case_index} must be sanitized"
);
}
}
#[test]
fn remote_fetch_error_redacts_require_https_only_redirect_target() {
let redirect_target =
"http://redirect-user:redirect-password@example.com/config.json?token=secret#anchor";
let dependency_error = ureq::Error::RequireHttpsOnly(redirect_target.to_string());
let display =
remote_fetch_error_display(&dependency_error, "https://config.example.com/config.json");
assert_eq!(
display,
"configured for https only: http://example.com/config.json"
);
for secret in [
"redirect-user",
"redirect-password",
"token=secret",
"anchor",
] {
assert!(
!display.contains(secret),
"redirect secret must be redacted"
);
}
}
#[test]
fn normalize_url_preserves_non_root_trailing_slash() {
assert_eq!(
normalize_url_for_dedup("https://example.com/config/"),
"https://example.com/config/"
);
}
#[test]
fn normalize_url_uppercase_scheme_and_host() {
assert_eq!(
normalize_url_for_dedup("HTTPS://Example.COM/Config.json"),
"https://example.com/Config.json"
);
}
#[test]
fn normalize_url_root_path() {
assert_eq!(
normalize_url_for_dedup("https://example.com/"),
"https://example.com"
);
assert_eq!(
normalize_url_for_dedup("https://example.com"),
"https://example.com"
);
}
#[test]
fn normalize_url_preserves_path_case() {
assert_eq!(
normalize_url_for_dedup("https://GitHub.COM/Org/Repo/Fallow.json"),
"https://github.com/Org/Repo/Fallow.json"
);
}
#[test]
fn normalize_url_preserves_userinfo_case_and_normalizes_host() {
assert_eq!(
normalize_url_for_dedup(
"HTTPS://CaseSensitiveUser:CaseSensitivePassword@Example.COM/Config.json"
),
"https://CaseSensitiveUser:CaseSensitivePassword@example.com/Config.json"
);
}
#[test]
fn normalize_url_preserves_query_string() {
assert_eq!(
normalize_url_for_dedup("https://example.com/config.json?v=1"),
"https://example.com/config.json?v=1"
);
}
#[test]
fn normalize_url_strips_fragment() {
assert_eq!(
normalize_url_for_dedup("https://example.com/config.json#section"),
"https://example.com/config.json"
);
}
#[test]
fn normalize_url_preserves_query_and_strips_fragment() {
assert_eq!(
normalize_url_for_dedup("https://example.com/config.json?v=1#section"),
"https://example.com/config.json?v=1"
);
}
#[test]
fn normalize_url_query_selects_resource_but_fragment_does_not() {
assert_ne!(
normalize_url_for_dedup("https://example.com/config.json?tenant=one"),
normalize_url_for_dedup("https://example.com/config.json?tenant=two")
);
assert_eq!(
normalize_url_for_dedup("https://example.com/config.json?tenant=one#first"),
normalize_url_for_dedup("https://example.com/config.json?tenant=one#second")
);
}
#[test]
fn normalize_url_default_https_port() {
assert_eq!(
normalize_url_for_dedup("https://example.com:443/config.json"),
"https://example.com/config.json"
);
assert_eq!(
normalize_url_for_dedup("https://example.com:8443/config.json"),
"https://example.com:8443/config.json"
);
}
#[test]
fn normalize_url_only_strips_the_scheme_default_port() {
assert_eq!(
normalize_url_for_dedup("http://example.com:80/config.json"),
"http://example.com/config.json"
);
assert_eq!(
normalize_url_for_dedup("http://example.com:443/config.json"),
"http://example.com:443/config.json"
);
assert_eq!(
normalize_url_for_dedup("https://example.com:80/config.json"),
"https://example.com:80/config.json"
);
}
#[test]
fn normalize_url_canonicalizes_numeric_ports_and_root_query_path() {
assert_eq!(
normalize_url_for_dedup("https://example.com:0443/?profile=one"),
"https://example.com?profile=one"
);
assert_eq!(
normalize_url_for_dedup("https://example.com:080/config.json"),
"https://example.com:80/config.json"
);
}
#[test]
fn normalize_url_canonicalizes_equivalent_ipv6_hosts() {
assert_eq!(
normalize_url_for_dedup("https://[2001:0DB8:0:0:0:0:0:1]/config.json"),
"https://[2001:db8::1]/config.json"
);
}
#[test]
fn extends_http_rejected() {
let dir = test_dir("http-rejected");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "http://example.com/config.json"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("https://"),
"Expected https hint in error, got: {err_msg}"
);
assert!(
err_msg.contains("http://"),
"Expected http:// mention in error, got: {err_msg}"
);
}
#[test]
fn extends_url_circular_detection() {
let mut visited = FxHashSet::default();
let url = "https://example.com/config.json";
let normalized = normalize_url_for_dedup(url);
visited.insert(normalized.clone());
assert!(
!visited.insert(normalized),
"Same URL should be detected as duplicate"
);
}
#[test]
fn extends_url_circular_case_insensitive() {
let mut visited = FxHashSet::default();
visited.insert(normalize_url_for_dedup("https://Example.COM/config.json"));
let normalized = normalize_url_for_dedup("HTTPS://example.com/config.json");
assert!(
!visited.insert(normalized),
"Case-different URLs should normalize to the same key"
);
}
#[test]
fn extract_extends_array() {
let mut value = serde_json::json!({
"extends": ["a.json", "b.json"],
"entry": ["src/index.ts"]
});
let extends = extract_extends(&mut value, "test.json").unwrap();
assert_eq!(extends, vec!["a.json", "b.json"]);
assert!(value.get("extends").is_none());
assert!(value.get("entry").is_some());
}
#[test]
fn extract_extends_string_sugar() {
let mut value = serde_json::json!({
"extends": "base.json",
"entry": ["src/index.ts"]
});
let extends = extract_extends(&mut value, "test.json").unwrap();
assert_eq!(extends, vec!["base.json"]);
}
#[test]
fn extract_extends_none() {
let mut value = serde_json::json!({"entry": ["src/index.ts"]});
let extends = extract_extends(&mut value, "test.json").unwrap();
assert!(extends.is_empty());
}
#[test]
fn url_timeout_default() {
let timeout = ConfigLoadOptions::default().extends_timeout;
assert!(timeout.as_secs() <= 300, "Timeout should be reasonable");
}
#[test]
fn extends_url_mixed_with_file_and_npm() {
let dir = test_dir("url-mixed");
std::fs::write(
dir.path().join("local.json"),
r#"{"rules": {"unused-files": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["local.json", "https://unreachable.invalid/config.json"]}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("unreachable.invalid"),
"Expected URL in error message, got: {err_msg}"
);
}
#[test]
fn extends_https_url_default_denial_has_opt_in_hint() {
let dir = test_dir("url-unreachable");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "https://unreachable.invalid/config.json"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("unreachable.invalid"),
"Expected URL in error, got: {err_msg}"
);
assert!(
err_msg.contains("--allow-remote-extends"),
"Expected remediation hint, got: {err_msg}"
);
}
#[test]
fn collect_unknown_rule_keys_flags_top_level_typo() {
let merged = serde_json::json!({
"rules": {
"unsued-files": "warn",
"unused-exports": "off"
}
});
let findings = collect_unknown_rule_keys(&merged);
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].context, "rules");
assert_eq!(findings[0].key, "unsued-files");
assert_eq!(findings[0].suggestion, Some("unused-files"));
}
#[test]
fn collect_unknown_rule_keys_flags_overrides_typo() {
let merged = serde_json::json!({
"overrides": [
{
"files": ["src/**/*.ts"],
"rules": {
"unsued-files": "warn"
}
},
{
"files": ["tests/**/*.ts"],
"rules": {
"circular-dependnecy": "off"
}
}
]
});
let findings = collect_unknown_rule_keys(&merged);
assert_eq!(findings.len(), 2);
assert_eq!(findings[0].context, "overrides[0].rules");
assert_eq!(findings[1].context, "overrides[1].rules");
assert_eq!(findings[1].suggestion, Some("circular-dependency"));
}
#[test]
fn collect_unknown_rule_keys_empty_for_valid_config() {
let merged = serde_json::json!({
"rules": {
"unused-files": "warn",
"unused-file": "off",
"circular-dependency": "off",
"boundary-violations": "warn"
},
"overrides": [
{
"files": ["src/**"],
"rules": {
"unused-exports": "warn"
}
}
]
});
let findings = collect_unknown_rule_keys(&merged);
assert!(
findings.is_empty(),
"valid rule names and aliases must not be flagged: {findings:?}"
);
}
#[test]
fn collect_unknown_rule_keys_ignores_missing_rules_section() {
let merged = serde_json::json!({
"entry": ["src/main.ts"]
});
let findings = collect_unknown_rule_keys(&merged);
assert!(findings.is_empty());
}
#[test]
fn load_wires_warn_on_unknown_rule_keys_into_load_path() {
let dir = test_dir("wiring");
let path = dir.path().join(".fallowrc.json");
let typo = format!(
"wiring-probe-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos())
);
std::fs::write(&path, format!(r#"{{"rules": {{"{typo}": "warn"}}}}"#)).unwrap();
let (config_res, captured) = capture_unknown_rule_warnings(|| FallowConfig::load(&path));
assert!(
config_res.is_ok(),
"load should succeed in phase 1: {:?}",
config_res.err()
);
assert_eq!(
captured.len(),
1,
"FallowConfig::load must invoke warn_on_unknown_rule_keys exactly once for one new unknown key, got: {captured:?}"
);
assert_eq!(captured[0].key, typo);
assert_eq!(captured[0].context, "rules");
}
#[test]
fn load_with_misspelled_rule_succeeds_and_ignores_typo() {
let dir = test_dir("misspelled-rule");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"rules": {"unsued-files": "warn"}}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json"))
.expect("load should succeed in phase 1");
assert_eq!(config.rules.unused_files, Severity::Error);
}
#[test]
fn validate_resolved_boundaries_passes_on_valid_config() {
let dir = test_dir("boundaries-valid");
let config = FallowConfig {
boundaries: crate::BoundaryConfig {
coverage: crate::BoundaryCoverageConfig::default(),
calls: crate::BoundaryCallsConfig::default(),
preset: None,
zones: vec![
crate::BoundaryZone {
name: "ui".to_string(),
patterns: vec!["src/components/**".to_string()],
auto_discover: vec![],
root: None,
public_files: vec![],
},
crate::BoundaryZone {
name: "db".to_string(),
patterns: vec!["src/db/**".to_string()],
auto_discover: vec![],
root: None,
public_files: vec![],
},
],
rules: vec![crate::BoundaryRule {
from: "ui".to_string(),
allow: vec!["db".to_string()],
allow_type_only: vec![],
}],
},
..FallowConfig::default()
};
config
.validate_resolved_boundaries(dir.path())
.expect("valid config should pass");
}
#[test]
fn validate_resolved_boundaries_aggregates_unknown_zone_refs() {
let dir = test_dir("boundaries-unknown-zones");
let config = FallowConfig {
boundaries: crate::BoundaryConfig {
coverage: crate::BoundaryCoverageConfig::default(),
calls: crate::BoundaryCallsConfig::default(),
preset: None,
zones: vec![crate::BoundaryZone {
name: "ui".to_string(),
patterns: vec!["src/ui/**".to_string()],
auto_discover: vec![],
root: None,
public_files: vec![],
}],
rules: vec![
crate::BoundaryRule {
from: "typo-from".to_string(),
allow: vec!["typo-allow".to_string()],
allow_type_only: vec!["typo-type-only".to_string()],
},
crate::BoundaryRule {
from: "ui".to_string(),
allow: vec!["another-typo".to_string()],
allow_type_only: vec![],
},
],
},
..FallowConfig::default()
};
let errors = config
.validate_resolved_boundaries(dir.path())
.expect_err("invalid zone refs should fail");
assert_eq!(errors.len(), 4, "got: {errors:?}");
let rendered: Vec<String> = errors.iter().map(ToString::to_string).collect();
assert!(
rendered
.iter()
.any(|m| m.contains("typo-from") && m.contains("rules[0]") && m.contains("from"))
);
assert!(
rendered
.iter()
.any(|m| m.contains("typo-allow") && m.contains("rules[0]") && m.contains("allow"))
);
assert!(rendered.iter().any(|m| m.contains("typo-type-only")
&& m.contains("rules[0]")
&& m.contains("allowTypeOnly")));
assert!(
rendered
.iter()
.any(|m| m.contains("another-typo") && m.contains("rules[1]") && m.contains("allow"))
);
}
#[test]
fn validate_resolved_boundaries_flags_redundant_root_prefix() {
let dir = test_dir("boundaries-redundant-prefix");
let config = FallowConfig {
boundaries: crate::BoundaryConfig {
coverage: crate::BoundaryCoverageConfig::default(),
calls: crate::BoundaryCallsConfig::default(),
preset: None,
zones: vec![crate::BoundaryZone {
name: "ui".to_string(),
patterns: vec!["packages/app/src/**".to_string()],
auto_discover: vec![],
root: Some("packages/app/".to_string()),
public_files: vec![],
}],
rules: vec![],
},
..FallowConfig::default()
};
let errors = config
.validate_resolved_boundaries(dir.path())
.expect_err("redundant root prefix should fail");
assert_eq!(errors.len(), 1, "got: {errors:?}");
let rendered = errors[0].to_string();
assert!(rendered.contains("FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX"));
assert!(rendered.contains("zone 'ui'"));
}
#[test]
fn validate_resolved_boundaries_aggregates_unknown_zones_and_root_prefixes() {
let dir = test_dir("boundaries-mixed-errors");
let config = FallowConfig {
boundaries: crate::BoundaryConfig {
coverage: crate::BoundaryCoverageConfig::default(),
calls: crate::BoundaryCallsConfig::default(),
preset: None,
zones: vec![crate::BoundaryZone {
name: "ui".to_string(),
patterns: vec!["packages/app/src/**".to_string()],
auto_discover: vec![],
root: Some("packages/app/".to_string()),
public_files: vec![],
}],
rules: vec![crate::BoundaryRule {
from: "ui".to_string(),
allow: vec!["typo-zone".to_string()],
allow_type_only: vec![],
}],
},
..FallowConfig::default()
};
let errors = config
.validate_resolved_boundaries(dir.path())
.expect_err("mixed errors should fail");
assert_eq!(errors.len(), 2, "got: {errors:?}");
let rendered: Vec<String> = errors.iter().map(ToString::to_string).collect();
assert!(
rendered
.iter()
.any(|m| m.contains("typo-zone") && m.contains("rules[0]"))
);
assert!(
rendered
.iter()
.any(|m| m.contains("FALLOW-BOUNDARY-ROOT-REDUNDANT-PREFIX"))
);
}
#[test]
fn validate_resolved_boundaries_passes_on_bulletproof_preset() {
let dir = test_dir("boundaries-bulletproof");
std::fs::create_dir_all(dir.path().join("src/features/auth")).unwrap();
let config = FallowConfig {
boundaries: crate::BoundaryConfig {
coverage: crate::BoundaryCoverageConfig::default(),
calls: crate::BoundaryCallsConfig::default(),
preset: Some(crate::BoundaryPreset::Bulletproof),
zones: vec![],
rules: vec![],
},
..FallowConfig::default()
};
config
.validate_resolved_boundaries(dir.path())
.expect("Bulletproof with discoverable features should pass");
}
#[test]
#[cfg_attr(miri, ignore)]
fn parse_config_to_value_strips_utf8_bom() {
let dir = test_dir("parse-bom");
let path = dir.path().join("fallow.toml");
let content_with_bom = "\u{FEFF}entry = [\"src/main.ts\"]\n";
std::fs::write(&path, content_with_bom).unwrap();
let value = parse_config_to_value(&path).unwrap();
assert!(
value.get("entry").is_some(),
"BOM should be stripped before TOML parsing"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn parse_config_to_value_toml_parse_error() {
let dir = test_dir("parse-toml-error");
let path = dir.path().join("fallow.toml");
std::fs::write(&path, "entry = [unquoted\n").unwrap();
let result = parse_config_to_value(&path);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("Failed to parse config file"),
"error should mention parse failure: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn parse_config_to_value_json_parse_error() {
let dir = test_dir("parse-json-error");
let path = dir.path().join(".fallowrc.json");
std::fs::write(&path, "{ this is not json }").unwrap();
let result = parse_config_to_value(&path);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("Failed to parse config file"),
"error should mention parse failure: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn parse_config_to_value_missing_file_error() {
let dir = test_dir("parse-missing");
let path = dir.path().join("nonexistent.toml");
let result = parse_config_to_value(&path);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("Failed to read config file"),
"error should mention read failure: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn find_and_load_stops_at_svn_dir() {
let dir = test_dir("find-svn-stop");
let sub = dir.path().join("sub");
std::fs::create_dir(&sub).unwrap();
std::fs::create_dir(dir.path().join(".svn")).unwrap();
let result = FallowConfig::find_and_load(&sub).unwrap();
assert!(result.is_none(), "svn boundary should stop config walk");
}
#[test]
#[cfg_attr(miri, ignore)]
fn extends_npm_single_dot_package_name_rejected() {
let dir = test_dir("npm-dot-name");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:./relative"}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("path traversal"),
"single-dot component should be rejected as path traversal: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn extends_npm_main_points_to_nonexistent_falls_through_to_config_name() {
let dir = test_dir("npm-main-missing");
let pkg_dir = dir.path().join("node_modules/my-config");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("package.json"),
r#"{"name": "my-config", "main": "./missing.json"}"#,
)
.unwrap();
std::fs::write(
pkg_dir.join(".fallowrc.json"),
r#"{"rules": {"unused-files": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:my-config"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_files, Severity::Warn);
}
#[test]
#[cfg_attr(miri, ignore)]
fn extends_npm_exports_nonexistent_falls_through_to_main() {
let dir = test_dir("npm-exports-missing-file");
let pkg_dir = dir.path().join("node_modules/cfg-pkg");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("package.json"),
r#"{"name": "cfg-pkg", "exports": "./missing-exports.json", "main": "./real.json"}"#,
)
.unwrap();
std::fs::write(
pkg_dir.join("real.json"),
r#"{"rules": {"unused-types": "off"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:cfg-pkg"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_types, Severity::Off);
}
#[test]
fn normalize_url_no_scheme_returns_raw() {
assert_eq!(normalize_url_for_dedup("not-a-url"), "not-a-url");
assert_eq!(normalize_url_for_dedup("/absolute/path"), "/absolute/path");
}
#[test]
fn normalize_url_fragment_only_stripped() {
assert_eq!(
normalize_url_for_dedup("https://example.com/file.json#anchor"),
"https://example.com/file.json"
);
}
#[test]
fn url_timeout_uses_env_var_when_set() {
assert_eq!(extends_timeout_from_env_value(Some("15")).as_secs(), 15);
}
#[test]
fn url_timeout_zero_falls_back_to_default() {
assert_eq!(
extends_timeout_from_env_value(Some("0")),
Duration::from_secs(DEFAULT_URL_TIMEOUT_SECS),
"zero should fall back to the hardcoded default"
);
}
#[test]
fn url_timeout_non_numeric_falls_back_to_default() {
assert_eq!(
extends_timeout_from_env_value(Some("not-a-number")),
Duration::from_secs(DEFAULT_URL_TIMEOUT_SECS),
"non-numeric value should fall back to the hardcoded default"
);
}
#[test]
fn url_timeout_absent_uses_default() {
assert_eq!(
extends_timeout_from_env_value(None),
Duration::from_secs(DEFAULT_URL_TIMEOUT_SECS)
);
}
#[test]
fn resolve_url_extends_depth_limit_error() {
let mut visited = FxHashSet::default();
let result = resolve_url_extends(
"https://example.invalid/config.json",
&mut visited,
MAX_EXTENDS_DEPTH, );
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("too deep"),
"error should mention depth limit: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn local_source_files_follow_the_local_extends_chain() {
let dir = test_dir("local-sources");
let root = dunce::canonicalize(dir.path()).unwrap();
std::fs::create_dir_all(root.join("shared")).unwrap();
std::fs::write(
root.join(".fallowrc.json"),
r#"{"extends": ["./shared/base.json", "https://example.com/remote.json"]}"#,
)
.unwrap();
std::fs::write(
root.join("shared/base.json"),
r#"{"extends": "./leaf.json", "entry": []}"#,
)
.unwrap();
std::fs::write(root.join("shared/leaf.json"), r#"{"entry": []}"#).unwrap();
assert_eq!(
FallowConfig::local_source_files(&root.join(".fallowrc.json")),
vec![
root.join(".fallowrc.json"),
root.join("shared/base.json"),
root.join("shared/leaf.json"),
],
"the list holds the config and each local extends target, and no remote one"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn local_source_files_stop_at_a_missing_extends_target() {
let dir = test_dir("local-sources-missing");
let root = dunce::canonicalize(dir.path()).unwrap();
std::fs::write(root.join("fallow.json"), r#"{"extends": "./gone.json"}"#).unwrap();
assert_eq!(
FallowConfig::local_source_files(&root.join("fallow.json")),
vec![root.join("fallow.json")]
);
assert!(FallowConfig::local_source_files(&root.join("absent.json")).is_empty());
}
#[test]
#[cfg_attr(miri, ignore)]
fn resolve_extends_file_depth_limit_error() {
let dir = test_dir("extends-file-depth");
let path = dir.path().join(".fallowrc.json");
std::fs::write(&path, r#"{"entry": []}"#).unwrap();
let mut visited = FxHashSet::default();
let result = resolve_extends(&path, &mut visited, MAX_EXTENDS_DEPTH);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("too deep"),
"error should mention depth limit: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn extends_http_url_in_file_extends_rejected() {
let dir = test_dir("file-extends-http");
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": ["http://example.com/config.json"]}"#,
)
.unwrap();
let result = FallowConfig::load(&dir.path().join(".fallowrc.json"));
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("https://"),
"error should suggest https: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn sealed_config_dir_returns_some_when_sealed() {
let dir = test_dir("sealed-dir");
let result = sealed_config_dir(dir.path(), true);
assert!(result.is_ok());
assert!(
result.unwrap().is_some(),
"sealed=true must return Some(canonicalized path)"
);
}
#[test]
fn sealed_config_dir_returns_none_when_not_sealed() {
let result = sealed_config_dir(Path::new("/nonexistent/path"), false);
assert!(result.is_ok());
assert!(result.unwrap().is_none(), "sealed=false must return None");
}
#[test]
fn collect_unknown_rule_keys_override_without_rules_key() {
let merged = serde_json::json!({
"overrides": [
{
"files": ["src/**/*.ts"]
},
{
"files": ["tests/**"],
"rules": {
"unsued-exports": "off"
}
}
]
});
let findings = collect_unknown_rule_keys(&merged);
assert_eq!(
findings.len(),
1,
"only the entry with rules should produce a finding"
);
assert_eq!(findings[0].context, "overrides[1].rules");
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_fails_on_deserialization_error() {
let dir = test_dir("deser-error");
let path = dir.path().join(".fallowrc.json");
std::fs::write(&path, r#"{"entry": "not-an-array"}"#).unwrap();
let result = FallowConfig::load(&path);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("invalid type") && err.contains(&path.display().to_string()),
"error should lead with the reason and name the config file: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn unknown_override_field_error_names_path_once_and_hints_at_jsonc() {
let dir = test_dir("override-unknown-field");
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"overrides": [{"files": ["src/**"], "reason": "legacy"}]}"#,
)
.unwrap();
let err = FallowConfig::find_and_load(dir.path())
.expect_err("unknown override field must be rejected");
let path_str = path.display().to_string();
assert!(
err.contains("unknown field `reason`"),
"error should lead with the serde reason: {err}"
);
assert_eq!(
err.matches(&path_str).count(),
1,
"path must appear exactly once: {err}"
);
assert!(
err.contains("// comment") && err.contains("JSONC"),
"error should point annotations at JSONC comments: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_rejects_threshold_override_with_empty_files() {
let dir = test_dir("threshold-empty-files");
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{
"health": {
"thresholdOverrides": [
{"files": [], "maxCyclomatic": 30}
]
}
}"#,
)
.unwrap();
let result = FallowConfig::load(&path);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("thresholdOverrides"),
"error should mention thresholdOverrides: {err}"
);
assert!(
err.contains("files"),
"error should name the files field: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_rejects_threshold_override_with_no_threshold_set() {
let dir = test_dir("threshold-no-threshold");
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{
"health": {
"thresholdOverrides": [
{"files": ["src/legacy.ts"]}
]
}
}"#,
)
.unwrap();
let result = FallowConfig::load(&path);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("maxCyclomatic") || err.contains("maxCognitive") || err.contains("maxCrap"),
"error should name at least one threshold field: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_rejects_invalid_ignore_catalog_references_consumer_glob() {
let dir = test_dir("invalid-catalog-consumer-glob");
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{
"ignoreCatalogReferences": [
{"package": "react", "consumer": "[invalid-glob"}
]
}"#,
)
.unwrap();
let result = FallowConfig::load(&path);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("ignoreCatalogReferences"),
"error should mention the field: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_accepts_ignore_catalog_references_without_consumer() {
let dir = test_dir("catalog-ref-no-consumer");
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"ignoreCatalogReferences": [{"package": "react"}]}"#,
)
.unwrap();
let config = FallowConfig::load(&path).unwrap();
assert_eq!(config.ignore_catalog_references.len(), 1);
assert!(config.ignore_catalog_references[0].consumer.is_none());
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_accepts_unused_component_props_ignore_pattern() {
let dir = test_dir("unused-component-props-ignore-pattern");
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"unusedComponentProps": {"ignorePattern": "^_"}}"#,
)
.unwrap();
let config = FallowConfig::load(&path).unwrap();
assert_eq!(
config.unused_component_props.ignore_pattern.as_deref(),
Some("^_")
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_rejects_invalid_unused_component_props_ignore_pattern() {
let dir = test_dir("unused-component-props-bad-regex");
let path = dir.path().join(".fallowrc.json");
std::fs::write(&path, r#"{"unusedComponentProps": {"ignorePattern": "["}}"#).unwrap();
let result = FallowConfig::load(&path);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("unusedComponentProps.ignorePattern"),
"error should mention the field: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_rejects_unknown_unused_component_props_field() {
let dir = test_dir("unused-component-props-unknown-field");
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"unusedComponentProps": {"ignorePatterns": "^_"}}"#,
)
.unwrap();
assert!(FallowConfig::load(&path).is_err());
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_rejects_unknown_override_entry_key() {
let dir = test_dir("override-entry-unknown-key");
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"overrides": [{"files": ["src/**"], "rule": {"unused-files": "off"}}]}"#,
)
.unwrap();
assert!(FallowConfig::load(&path).is_err());
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_rejects_unknown_ignore_exports_entry_key() {
let dir = test_dir("ignore-exports-entry-unknown-key");
let path = dir.path().join(".fallowrc.json");
std::fs::write(
&path,
r#"{"ignoreExports": [{"file": "src/a.ts", "exports": ["*"], "reason": "legacy"}]}"#,
)
.unwrap();
assert!(FallowConfig::load(&path).is_err());
}
#[test]
fn validate_user_globs_framework_plugin_invalid_entry_glob() {
use crate::{ExternalPluginDef, external_plugin::EntryPointRole};
let config = FallowConfig {
framework: vec![ExternalPluginDef {
schema: None,
name: "test-plugin".to_owned(),
detection: None,
enablers: vec![],
entry_points: vec!["[invalid-glob".to_owned()],
entry_point_role: Some(EntryPointRole::Support),
manifest_entries: vec![],
config_patterns: vec![],
config_default_export_opt_out: vec![],
always_used: vec![],
tooling_dependencies: vec![],
used_exports: vec![],
used_class_members: vec![],
}],
..FallowConfig::default()
};
let result = config.validate_user_globs();
assert!(
result.is_err(),
"invalid entry_points glob should fail validation"
);
let errors = result.unwrap_err();
assert!(!errors.is_empty());
}
#[test]
fn validate_user_globs_rejects_invalid_production_ignore_glob() {
let config: FallowConfig =
serde_json::from_str(r#"{"production": {"ignore": ["[invalid-glob"]}}"#).unwrap();
let errors = config.validate_user_globs().unwrap_err();
assert!(
errors
.iter()
.any(|error| error.to_string().contains("production.ignore")),
"the error names the field: {errors:?}"
);
}
#[test]
fn validate_user_globs_rejects_unmatchable_production_ignore_prefixes() {
let config: FallowConfig = serde_json::from_str(
r#"{"production": {"ignore": ["!scripts/keep/**", "./scripts/**", "scripts/**"]}}"#,
)
.unwrap();
let errors: Vec<String> = config
.validate_user_globs()
.unwrap_err()
.iter()
.map(ToString::to_string)
.collect();
assert_eq!(errors.len(), 2, "{errors:?}");
assert!(
errors[0].contains("production.ignore: '!scripts/keep/**'")
&& errors[0].contains("negated pattern"),
"{errors:?}"
);
assert!(
errors[1].contains("production.ignore: './scripts/**'")
&& errors[1].contains("'scripts/**'"),
"{errors:?}"
);
}
#[test]
fn validate_user_globs_rejects_invalid_ignore_dependencies_glob() {
let config = FallowConfig {
ignore_dependencies: vec![
"lodash".to_owned(),
"@acme/*".to_owned(),
"@broken/[".to_owned(),
],
..FallowConfig::default()
};
let errors = config
.validate_user_globs()
.expect_err("an unclosed character class is not a valid glob");
assert_eq!(errors.len(), 1);
let message = errors[0].to_string();
assert!(message.contains("ignoreDependencies"), "{message}");
assert!(message.contains("@broken/["), "{message}");
}
#[test]
#[cfg_attr(miri, ignore)]
fn shadowed_config_names_empty_when_last_config_wins() {
let dir = test_dir("shadow-last");
std::fs::write(dir.path().join(".fallow.toml"), "").unwrap();
assert!(shadowed_config_names(dir.path(), 3).is_empty());
}
#[test]
fn warn_on_coexisting_configs_empty_shadowed_is_silent() {
let ((), captured) = capture_coexisting_config_warnings(|| {
warn_on_coexisting_configs(Path::new(".fallowrc.json"), &[]);
});
assert!(
captured.is_empty(),
"empty shadowed list must produce no warning"
);
}
#[test]
fn extract_extends_rejects_number_value() {
let mut value = serde_json::json!({"extends": 42});
let err = extract_extends(&mut value, "test.json").unwrap_err();
assert!(
err.to_string()
.contains("extends must be a string or an array of strings, got a number"),
"unexpected error: {err}"
);
}
#[test]
fn extract_extends_rejects_object_value() {
let mut value = serde_json::json!({"extends": {"path": "./base.json"}});
let err = extract_extends(&mut value, "test.json").unwrap_err();
assert!(
err.to_string()
.contains("extends must be a string or an array of strings, got an object"),
"unexpected error: {err}"
);
}
#[test]
fn extract_extends_rejects_non_string_array_entry() {
let mut value = serde_json::json!({"extends": ["a.json", 42]});
let err = extract_extends(&mut value, "test.json").unwrap_err();
assert!(
err.to_string()
.contains("extends entries must be strings, got a number"),
"unexpected error: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn load_rejects_malformed_extends_value() {
let dir = test_dir("malformed-extends");
let path = dir.path().join(".fallowrc.json");
std::fs::write(&path, r#"{"extends": 42}"#).unwrap();
let err = FallowConfig::load(&path).unwrap_err();
assert!(
err.to_string()
.contains("extends must be a string or an array of strings"),
"unexpected error: {err}"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn config_resource_identity_cannot_collide_across_kinds() {
let dir = test_dir("visit-circular");
let path = dir.path().join("config.json");
std::fs::write(&path, "{}").unwrap();
let canonical = dunce::canonicalize(path).unwrap();
let local = ConfigResourceId::Local(canonical.clone());
let remote = ConfigResourceId::Remote(canonical.to_string_lossy().into_owned());
assert_ne!(local, remote);
}
#[test]
#[cfg_attr(miri, ignore)]
fn merge_order_lists_each_source_of_an_extends_lattice_once() {
const LEVELS: usize = 4;
const WIDTH: usize = 3;
let dir = test_dir("merge-order-lattice");
let name = |level: usize, index: usize| format!("l{level}-{index}.json");
for level in 0..LEVELS {
for index in 0..WIDTH {
let extends: Vec<String> = if level == 0 {
Vec::new()
} else {
(0..WIDTH)
.map(|below| format!("./{}", name(level - 1, below)))
.collect()
};
let body = serde_json::json!({ "extends": extends });
std::fs::write(dir.path().join(name(level, index)), body.to_string()).unwrap();
}
}
let root = dir.path().join(".fallowrc.json");
let top: Vec<String> = (0..WIDTH)
.map(|index| format!("./{}", name(LEVELS - 1, index)))
.collect();
std::fs::write(&root, serde_json::json!({ "extends": top }).to_string()).unwrap();
let order = FallowConfig::merge_order(&root).expect("lattice resolves");
let distinct: FxHashSet<&Option<PathBuf>> = order.iter().collect();
assert_eq!(distinct.len(), order.len(), "each source appears once");
assert_eq!(order.len(), LEVELS * WIDTH + 1);
assert_eq!(
order.last(),
Some(&Some(dunce::canonicalize(&root).unwrap())),
"the root config merges last"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn find_config_path_stops_at_svn_dir() {
let dir = test_dir("find-path-svn");
let sub = dir.path().join("sub");
std::fs::create_dir(&sub).unwrap();
std::fs::create_dir(dir.path().join(".svn")).unwrap();
let path = FallowConfig::find_config_path(&sub);
assert!(path.is_none(), "svn root should stop config search");
}
#[test]
fn deep_merge_array_over_object_replaces() {
let mut base = serde_json::json!({"key": "value"});
deep_merge_json(&mut base, serde_json::json!(["a", "b"]));
assert_eq!(base, serde_json::json!(["a", "b"]));
}
#[test]
#[cfg_attr(miri, ignore)]
fn find_and_load_returns_error_for_invalid_glob_in_config() {
let dir = test_dir("find-invalid-glob");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"entry": ["[invalid-glob"]}"#,
)
.unwrap();
let result = FallowConfig::find_and_load(dir.path());
assert!(
result.is_err(),
"invalid glob should surface as an error from find_and_load"
);
}
#[test]
#[cfg_attr(miri, ignore)]
fn find_and_load_rejects_bare_finding_ignore_negation() {
let dir = test_dir("find-bare-finding-ignore-negation");
std::fs::create_dir(dir.path().join(".git")).unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"ignoreFindings": ["!"]}"#,
)
.unwrap();
let error = FallowConfig::find_and_load(dir.path()).unwrap_err();
assert!(error.contains("ignoreFindings"), "error: {error}");
assert!(error.contains("requires a pattern"), "error: {error}");
}
#[test]
#[cfg_attr(miri, ignore)]
fn find_and_load_rejects_finding_ignore_pattern_that_is_too_long() {
let dir = test_dir("find-oversized-finding-ignore-set");
std::fs::create_dir(dir.path().join(".git")).unwrap();
let alternatives = (0..50_000)
.map(|index| format!("name{index}"))
.collect::<Vec<_>>()
.join(",");
let config = serde_json::json!({
"ignoreFindings": [format!("**/{{{alternatives}}}.ts")]
});
std::fs::write(
dir.path().join(".fallowrc.json"),
serde_json::to_vec(&config).unwrap(),
)
.unwrap();
let error = FallowConfig::find_and_load(dir.path()).unwrap_err();
assert!(error.contains("ignoreFindings"), "error: {error}");
assert!(error.contains("longer than 512 bytes"), "error: {error}");
}
#[test]
fn resolve_package_exports_dot_key_array_returns_none() {
let pkg = serde_json::json!({
"exports": {".": ["array-value"]}
});
let result = resolve_package_exports(&pkg, Path::new("/tmp"));
assert!(result.is_none(), "array dot-export should return None");
}
#[test]
fn resolve_package_exports_exports_is_array_returns_none() {
let pkg = serde_json::json!({
"exports": ["./index.js"]
});
let result = resolve_package_exports(&pkg, Path::new("/tmp"));
assert!(result.is_none(), "array-form exports should return None");
}
#[test]
fn resolve_package_exports_object_no_dot_key_returns_none() {
let pkg = serde_json::json!({
"exports": {"./sub": "./sub.js"}
});
let result = resolve_package_exports(&pkg, Path::new("/tmp"));
assert!(result.is_none(), "no dot key should return None");
}
#[test]
fn resolve_package_exports_conditions_without_known_key_returns_none() {
let pkg = serde_json::json!({
"exports": {".": {"browser": "./browser.js"}}
});
let result = resolve_package_exports(&pkg, Path::new("/tmp"));
assert!(result.is_none(), "unknown condition key should return None");
}
#[test]
#[cfg_attr(miri, ignore)]
fn extends_npm_exports_import_condition() {
let dir = test_dir("npm-import-cond");
let pkg_dir = dir.path().join("node_modules/import-config");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("package.json"),
r#"{"name": "import-config", "exports": {".": {"import": "./esm.json"}}}"#,
)
.unwrap();
std::fs::write(
pkg_dir.join("esm.json"),
r#"{"rules": {"unused-types": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:import-config"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_types, Severity::Warn);
}
#[test]
#[cfg_attr(miri, ignore)]
fn extends_npm_exports_require_condition() {
let dir = test_dir("npm-require-cond");
let pkg_dir = dir.path().join("node_modules/require-config");
std::fs::create_dir_all(&pkg_dir).unwrap();
std::fs::write(
pkg_dir.join("package.json"),
r#"{"name": "require-config", "exports": {".": {"require": "./cjs.json"}}}"#,
)
.unwrap();
std::fs::write(
pkg_dir.join("cjs.json"),
r#"{"rules": {"unused-class-members": "warn"}}"#,
)
.unwrap();
std::fs::write(
dir.path().join(".fallowrc.json"),
r#"{"extends": "npm:require-config"}"#,
)
.unwrap();
let config = FallowConfig::load(&dir.path().join(".fallowrc.json")).unwrap();
assert_eq!(config.rules.unused_class_members, Severity::Warn);
}
#[test]
#[cfg_attr(miri, ignore)]
fn parse_config_to_value_rejects_toml_nesting_that_evades_the_parser_limit() {
const REPEATS: usize = 200_000;
let dir = test_dir("parse-toml-deep-nesting");
let path = dir.path().join("fallow.toml");
let content = format!(
"a = {{{}}}\nb = {}{}\n",
"[]".repeat(REPEATS),
"[".repeat(REPEATS),
"]".repeat(REPEATS)
);
std::fs::write(&path, content).unwrap();
let err = parse_config_to_value(&path).unwrap_err().to_string();
assert!(err.contains("Failed to parse config file"), "{err}");
}
#[test]
fn boundary_zone_parses_public_files_and_omits_them_when_empty() {
let config: FallowConfig = serde_json::from_str(
r#"{"boundaries": {"zones": [
{"name": "billing", "patterns": ["src/billing/**"], "publicFiles": ["src/billing/index.ts"]},
{"name": "orders", "patterns": ["src/orders/**"]}
]}}"#,
)
.expect("publicFiles must parse");
let zones = &config.boundaries.zones;
assert_eq!(zones[0].public_files, vec!["src/billing/index.ts"]);
assert!(
zones[1].public_files.is_empty(),
"publicFiles defaults to empty"
);
let rendered = serde_json::to_string(&zones[1]).expect("zone serializes");
assert!(
!rendered.contains("publicFiles"),
"an empty publicFiles is omitted, got {rendered}"
);
}
#[test]
fn public_file_globs_use_the_zone_root() {
let config: crate::BoundaryConfig = serde_json::from_str(
r#"{"zones": [
{"name": "billing", "root": "packages/app/", "patterns": ["src/billing/**"], "publicFiles": ["src/billing/index.ts"]}
]}"#,
)
.expect("config parses");
let resolved = config.resolve();
assert!(resolved.has_public_files("billing"));
assert!(resolved.is_public_file("billing", "packages/app/src/billing/index.ts"));
assert!(!resolved.is_public_file("billing", "src/billing/index.ts"));
assert!(!resolved.is_public_file("unknown", "packages/app/src/billing/index.ts"));
}
#[test]
fn validate_resolved_boundaries_flags_a_public_file_glob_that_repeats_the_root() {
let dir = test_dir("boundaries-public-api-root-prefix");
let config: FallowConfig = serde_json::from_str(
r#"{"boundaries": {"zones": [
{"name": "billing", "root": "packages/app", "patterns": ["src/billing/**"],
"publicFiles": ["packages/app/src/billing/index.ts"]}
]}}"#,
)
.expect("config parses");
let errors = config
.validate_resolved_boundaries(dir.path())
.expect_err("a publicFiles glob that repeats the root must fail");
let rendered: Vec<String> = errors.iter().map(ToString::to_string).collect();
assert!(
rendered.len() == 1 && rendered[0].contains("packages/app/src/billing/index.ts"),
"got: {rendered:?}"
);
}