Files
OpenFUT/openfut-import-fifa17/src/tests.rs
T
funman300 abe9e663c1 feat(fifa17): import consumable + staff content as first-class Core content
Close 20 of the 33-record content gap (17 consumables + 3 staff; 13 Legends are
unrecoverable from PC data). Verdict A (no Core change): consumables/staff become
ordinary Core CardDefinitions (neutral player fields + honest family/role names)
and owned instances via the SAME generic import path; a catalog kind lets the
adapter exclude them from the player-only /club projection.

- adapter fut::content_taxonomy: evidence-based cardsubtypeid->family/label
  (Ghidra-derived ranges) + staff role map; unknown subtype => defer, never fabricate.
- adapter catalog: Fifa17CardIdentity/RawCard gain optional kind+subtype
  (backward-compat: legacy catalogs load as player); kind_of/subtype_of lookups.
- adapter item/club_response: shape_club_response excludes non-player kinds
  (ShapeStats.excluded_non_player); ItemIdentityResolver::kind_of default=Player.
- host Fifa17IdentityResolver overrides kind_of to delegate to the catalog so
  /club excludes consumables/staff in production.
- import: Item gains cardsubtypeid/cardassetid/amount/contract; plan_non_player_definitions
  (resourceId-grouped, subtype-consistency gated); emit_content writes non-player
  defs + catalog kind + manifest; apply mints owned instances via owned_item_id.

Real profile 33068179: 1962 players + 20 non-player = 1982 owned; 18 non-player
defs (16 consumable + 2 staff, dup resourceIds shared); 0 deferred non-player; 0 blockers.
2026-08-14 05:26:02 +00:00

885 lines
32 KiB
Rust

use super::*;
use model::Profile;
use std::collections::{BTreeMap, BTreeSet};
const VER5_176580: i64 = (5 << 24) | 176580; // versioned resourceId for asset 176580
fn roster() -> Roster {
Roster::from_json_str(
r#"[
{"id":20801,"first":"Cristiano","last":"Ronaldo","common":""},
{"id":176580,"first":"Luis","last":"Suárez","common":""},
{"id":158023,"first":"Lionel","last":"Messi","common":""}
]"#,
)
.unwrap()
}
fn entities() -> Entities {
Entities::from_maps(
BTreeMap::from([(53, "LaLiga".to_string()), (16, "Serie A".to_string())]),
BTreeMap::from([(38, "Portugal".to_string()), (45, "Spain".to_string())]),
BTreeMap::from([
(243, "Real Madrid".to_string()),
(21, "Juventus".to_string()),
]),
)
}
fn none() -> BTreeSet<i64> {
BTreeSet::new()
}
fn attrs() -> String {
r#"[{"index":0,"value":90},{"index":1,"value":91},{"index":2,"value":82},
{"index":3,"value":88},{"index":4,"value":30},{"index":5,"value":78}]"#
.to_string()
}
/// A resolvable player (nation 38, team 243, league 53 all in `entities()`).
fn player(id: i64, resource: i64, asset: i64, rating: i64) -> String {
format!(
r#"{{"id":{id},"resourceId":{resource},"assetId":{asset},"itemType":"player",
"rareflag":1,"rating":{rating},"preferredPosition":"ST","nation":38,
"teamid":243,"leagueId":53,"attributeList":{}}}"#,
attrs()
)
}
fn profile(items: &[String], squads: &str, next_item_id: i64) -> Profile {
let json = format!(
r#"{{"personaId":33068179,"personaName":"CAGE","clubName":"OpenFUT","clubAbbr":"OFC",
"coins":1000,"nextItemId":{next_item_id},"items":[{}],"squads":{}}}"#,
items.join(","),
squads
);
Profile::from_json_str(&json).unwrap()
}
fn defs(items: &[String]) -> DefinitionPlan {
plan_definitions(
&profile(items, "[]", 100000500),
&roster(),
&entities(),
&none(),
)
}
#[test]
fn classification_balances_across_disjoint_classes() {
let items = vec![
player(100000001, 20801, 20801, 94),
player(100000002, VER5_176580, 176580, 92),
r#"{"id":100000239,"resourceId":5003012,"assetId":5003012,"itemType":"player","rating":85}"#.to_string(),
r#"{"id":100000427,"resourceId":3000083,"itemType":"staff"}"#.to_string(),
];
let c = count_items(&profile(&items, "[]", 100000500));
assert_eq!(
(c.total, c.player_cards, c.consumables, c.staff, c.other),
(4, 2, 1, 1, 0)
);
assert!(c.balances());
}
#[test]
fn version_formula_card_id_and_resolved_names() {
assert_eq!(version_of(20801), 0);
assert_eq!(version_of(VER5_176580), 5);
let plan = defs(&[player(100000002, VER5_176580, 176580, 92)]);
assert_eq!(plan.supported.len(), 1);
let d = &plan.supported[0];
assert_eq!(d.card_id, format!("fifa17_{VER5_176580}"));
assert_eq!(d.version, 5);
assert_eq!(d.asset_id, 176580);
assert_eq!(d.name, "Luis Suárez"); // base-asset name, never fabricated
assert_eq!(
(d.nation.as_str(), d.league.as_str(), d.club.as_str()),
("Portugal", "LaLiga", "Real Madrid")
);
assert_eq!(d.rarity, "gold"); // rating 92 -> tier, NOT a promo label
}
#[test]
fn base_and_versioned_are_distinct_definitions() {
let plan = defs(&[
player(100000010, 176580, 176580, 92),
player(100000011, VER5_176580, 176580, 92),
]);
assert_eq!(plan.supported.len(), 2, "base and special never collapse");
assert_eq!((plan.base_defs, plan.versioned_defs), (1, 1));
}
#[test]
fn duplicate_copies_share_definition_but_keep_distinct_wire_ids() {
let plan = defs(&[
player(100000001, 20801, 20801, 94),
player(100000015, 20801, 20801, 94),
]);
assert_eq!(plan.supported.len(), 1);
assert_eq!(plan.supported[0].wire_ids, vec![100000001, 100000015]);
}
#[test]
fn new_conflict_blocks_but_approved_conflict_defers() {
let items = vec![
player(100000001, 20801, 20801, 94),
player(100000002, 20801, 20801, 93), // disagree on rating
];
// unapproved: a hard blocker
let rep = analyze(
&profile(&items, "[]", 100000500),
&roster(),
&entities(),
&none(),
);
assert!(rep.definitions.supported.is_empty());
assert_eq!(rep.definitions.conflicts.len(), 1);
assert!(!rep.definitions.conflicts[0].approved_defer);
assert!(rep.has_blockers(), "a NEW conflict must block");
// approved: deferred, not blocking
let ok = analyze(
&profile(&items, "[]", 100000500),
&roster(),
&entities(),
&BTreeSet::from([20801]),
);
assert!(ok.definitions.conflicts[0].approved_defer);
assert!(
!ok.has_blockers(),
"an approved-deferred conflict does not block"
);
assert_eq!(
ok.deferred_instances(),
2,
"both copies counted as deferred"
);
}
#[test]
fn version_formula_violation_defers_not_fabricates() {
let plan = defs(&[player(100000003, 999, 176580, 92)]); // 999 != (0<<24)|176580
assert!(plan.supported.is_empty());
assert!(matches!(
plan.deferred.first().map(|d| &d.reason),
Some(Unsupported::VersionFormula { .. })
));
}
#[test]
fn missing_roster_name_defers_never_faked() {
let plan = defs(&[player(100000004, 777777, 777777, 80)]); // 777777 not in roster
assert!(plan.supported.is_empty());
assert!(matches!(
plan.deferred.first().map(|d| &d.reason),
Some(Unsupported::NoName { asset_id: 777777 })
));
}
#[test]
fn unresolved_entity_defers() {
// nation 999 not in entities()
let item = format!(
r#"{{"id":100000005,"resourceId":20801,"assetId":20801,"itemType":"player","rareflag":1,
"rating":94,"preferredPosition":"ST","nation":999,"teamid":243,"leagueId":53,
"attributeList":{}}}"#,
attrs()
);
let plan = defs(&[item]);
assert!(plan.supported.is_empty());
assert!(matches!(
plan.deferred.first().map(|d| &d.reason),
Some(Unsupported::UnresolvedEntity { .. })
));
}
#[test]
fn identity_preserves_watermark_over_live_max() {
let items = vec![
player(100000001, 20801, 20801, 94),
player(100004605, 176580, 176580, 92),
];
let idp = plan_identity(
&profile(&items, "[]", 100004617),
&BTreeSet::from([20801, 176580]),
);
assert_eq!(
(idp.live_min, idp.live_max),
(Some(100000001), Some(100004605))
);
assert_eq!(idp.source_watermark, 100004617);
assert_eq!(
idp.next_allocation, 100004617,
"next-to-issue, not live_max+1"
);
}
#[test]
fn squad_coverage_flags_unsupported_starter_and_keeps_manager() {
let items = vec![
player(100000001, 20801, 20801, 94),
player(100000002, 176580, 176580, 92),
];
let squads = r#"[{
"formation":"f433","squadName":"OpenFUT","captain":100000001,
"manager":[{"id":100000427,"dream":false}],
"players":[
{"index":0,"itemData":{"id":100000001},"kitNumber":7},
{"index":1,"itemData":{"id":999999999},"kitNumber":9},
{"index":2,"itemData":{"id":0},"kitNumber":0}
]}]"#;
let rep = analyze(
&profile(&items, squads, 100000500),
&roster(),
&entities(),
&none(),
);
let sq = &rep.squad;
assert_eq!((sq.occupied_slots, sq.supported_slots), (2, 1));
assert_eq!(sq.unsupported_slots, vec![(1, 999999999)]);
assert_eq!(sq.manager_wire_ids, vec![100000427]);
assert_eq!(sq.captain_wire_id, Some(100000001));
assert!(rep.has_blockers());
}
#[test]
fn analyze_is_deterministic() {
let items = vec![
player(100000002, VER5_176580, 176580, 92),
player(100000001, 20801, 20801, 94),
];
let p = profile(&items, "[]", 100000500);
let a = analyze(&p, &roster(), &entities(), &none());
let b = analyze(&p, &roster(), &entities(), &none());
assert_eq!(a.definitions.supported, b.definitions.supported);
assert_eq!(a.identity.import_wire_ids, b.identity.import_wire_ids);
}
#[test]
fn emit_content_writes_public_pack_catalog_and_private_manifest() {
let items = vec![
player(100000001, 20801, 20801, 94),
player(100000002, VER5_176580, 176580, 92),
r#"{"id":100000239,"resourceId":5003012,"assetId":5003012,"itemType":"player","rating":85}"#.to_string(),
r#"{"id":100000427,"resourceId":3000083,"itemType":"staff"}"#.to_string(),
];
let squads = r#"[{"formation":"f433","squadName":"OpenFUT","captain":100000001,
"manager":[{"id":100000427}],
"players":[{"index":0,"itemData":{"id":100000001}},{"index":1,"itemData":{"id":100000002}}]}]"#;
let p = profile(&items, squads, 100000500);
let rep = analyze(&p, &roster(), &entities(), &none());
assert!(!rep.has_blockers(), "blockers: {:?}", rep.blockers());
let dir = tempfile::tempdir().unwrap();
let sum = emit_content(&rep, dir.path(), "deadbeef").unwrap();
assert_eq!(sum.definitions, 2);
assert_eq!(sum.supported_instances, 2);
assert_eq!(sum.deferred_instances, 0);
assert!(sum.content_pack.exists());
assert!(sum.host_catalog.exists());
assert!(sum.manifest.exists());
// content pack is a Core CardDefinition[] with our card_id + resolved names
let pack: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&sum.content_pack).unwrap()).unwrap();
let ids: Vec<&str> = pack
.as_array()
.unwrap()
.iter()
.map(|c| c["id"].as_str().unwrap())
.collect();
assert!(ids.contains(&"fifa17_20801"));
assert!(ids.contains(&format!("fifa17_{VER5_176580}").as_str()));
// catalog carries versioned entries
let cat: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&sum.host_catalog).unwrap()).unwrap();
assert_eq!(cat["cards"][format!("fifa17_{VER5_176580}")]["version"], 5);
assert_eq!(cat["cards"]["fifa17_20801"]["version"], 0);
// manifest preserves wire ids and is separate from public content
let man: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&sum.manifest).unwrap()).unwrap();
assert_eq!(man["identity"]["source_watermark"], 100000500);
assert_eq!(man["target"]["persona_id"], 33068179);
}
#[test]
fn emit_refuses_when_blocked() {
let items = vec![
player(100000001, 20801, 20801, 94),
player(100000002, 20801, 20801, 93), // unapproved conflict -> blocker
];
let rep = analyze(
&profile(&items, "[]", 100000500),
&roster(),
&entities(),
&none(),
);
let dir = tempfile::tempdir().unwrap();
assert!(emit_content(&rep, dir.path(), "x").is_err());
}
#[test]
fn club_only_difference_across_copies_is_not_a_conflict() {
// Two owned copies of one resourceId, identical in asset/rating/position/
// attributes but DIFFERENT nation/team/league (a club-affiliation snapshot).
// Evidence (resourceId 169193) says this is NOT a conflict: one definition,
// both preserved wire ids, display club from the first-observed copy.
let a = format!(
r#"{{"id":100000001,"resourceId":20801,"assetId":20801,"itemType":"player","rareflag":1,
"rating":94,"preferredPosition":"ST","nation":38,"teamid":243,"leagueId":53,"attributeList":{}}}"#,
attrs()
);
let b = format!(
r#"{{"id":100000002,"resourceId":20801,"assetId":20801,"itemType":"player","rareflag":1,
"rating":94,"preferredPosition":"ST","nation":45,"teamid":21,"leagueId":16,"attributeList":{}}}"#,
attrs()
);
let plan = defs(&[a, b]);
assert!(
plan.conflicts.is_empty(),
"a club-only difference must NOT be a conflict"
);
assert_eq!(plan.supported.len(), 1, "one definition");
let d = &plan.supported[0];
assert_eq!(
d.wire_ids,
vec![100000001, 100000002],
"both copies preserved"
);
assert_eq!(d.nation, "Portugal", "display club = first observed copy");
assert_eq!(d.club, "Real Madrid");
assert_eq!(d.league, "LaLiga");
}
#[test]
fn identity_difference_across_copies_is_still_a_conflict() {
// A differing rating is a real definition-identity disagreement -> conflict,
// never silently merged.
let plan = defs(&[
player(100000001, 20801, 20801, 94),
player(100000002, 20801, 20801, 90),
]);
assert!(plan.supported.is_empty());
assert_eq!(plan.conflicts.len(), 1);
}
// ------------------------------------------------------------------ apply
use crate::apply::{
apply as apply_import, content_card_ids, gate_staging, identity_dry_preflight,
local_core_preflight, owned_item_id, plan_apply, post_validate_identity, seed_identity,
};
use openfut_identity::{ExternalIdentityStore, JsonIdentityStore};
const SQUAD_F433: &str = r#"[{"formation":"f433","squadName":"OpenFUT","captain":100000001,
"squadType":"REGULAR_SQUAD","custom":"[0,0,0]",
"players":[{"index":0,"itemData":{"id":100000001},"kitNumber":7},
{"index":1,"itemData":{"id":100000002},"kitNumber":9}],
"kicktakers":[{"index":0,"id":100000001}],"manager":[{"id":100000427}]}]"#;
/// Build a report + raw profile Value from the same JSON (typed profile for
/// analysis, raw Value for the squad wire).
fn report_and_raw(
items: &[String],
squads: &str,
next_item_id: i64,
) -> (Report, serde_json::Value) {
let json = format!(
r#"{{"personaId":33068179,"personaName":"CAGE","clubName":"OpenFUT","clubAbbr":"OFC",
"coins":1000,"nextItemId":{next_item_id},"items":[{}],"squads":{}}}"#,
items.join(","),
squads
);
let prof = Profile::from_json_str(&json).unwrap();
let report = analyze(&prof, &roster(), &entities(), &none());
let raw: serde_json::Value = serde_json::from_str(&json).unwrap();
(report, raw)
}
#[test]
fn owned_item_id_is_deterministic_and_distinct() {
let a = owned_item_id(33068179, 100000001);
assert_eq!(a, owned_item_id(33068179, 100000001), "stable across calls");
assert_ne!(
a,
owned_item_id(33068179, 100000002),
"distinct per wire id"
);
assert_ne!(
a,
owned_item_id(90909090, 100000001),
"distinct per account"
);
}
#[test]
fn plan_apply_builds_generic_request_mappings_and_squad() {
let items = vec![
player(100000001, 20801, 20801, 94),
player(100000002, VER5_176580, 176580, 92),
];
let (report, raw) = report_and_raw(&items, SQUAD_F433, 100000500);
let plan = plan_apply(&report, &raw, "fp-test").unwrap();
assert_eq!(plan.request.owned.len(), 2);
assert_eq!(plan.mappings.len(), 2);
assert_eq!(plan.watermark, 100000500);
assert_eq!(plan.supported_instances, 2);
assert_eq!(plan.deferred_instances, 0);
assert_eq!(plan.source_fingerprint, "fp-test");
// card ids are fifa17_<resourceId>, base and versioned distinct.
let mut cards: Vec<&str> = plan
.request
.owned
.iter()
.map(|o| o.card_id.as_str())
.collect();
cards.sort_unstable();
assert_eq!(
cards,
vec!["fifa17_20801", &format!("fifa17_{VER5_176580}")[..]]
);
// mapping core_id == the owned_item_id for that wire (both stores agree).
for m in &plan.mappings {
assert_eq!(m.core_id, owned_item_id(33068179, m.wire_id));
}
// squad + opaque extension.
let sq = plan.request.squad.as_ref().expect("squad present");
assert_eq!(sq.formation, "f433");
assert_eq!(sq.slots.len(), 2);
assert_eq!(sq.extension.namespace, "fifa17.squad");
assert_eq!(sq.extension.schema_version, 1);
assert!(
sq.extension.payload.contains("[0,0,0]"),
"custom carried verbatim"
);
// captain flag follows wire 100000001, keyed by its OwnedItemId.
let cap_owned = owned_item_id(33068179, 100000001);
assert!(sq
.slots
.iter()
.any(|s| s.owned_item_id == cap_owned && s.is_captain));
}
#[test]
fn plan_apply_seeds_entitlements_from_unopened_packs() {
let items = [player(100000001, 20801, 20801, 94)];
let json = format!(
r#"{{"personaId":33068179,"personaName":"CAGE","clubName":"OpenFUT","clubAbbr":"OFC",
"coins":1000,"nextItemId":100000500,"items":[{}],"squads":[],"unopenedPackIds":[70,70,5]}}"#,
items.join(",")
);
let prof = Profile::from_json_str(&json).unwrap();
let report = analyze(&prof, &roster(), &entities(), &none());
assert_eq!(report.unopened_pack_ids, [70, 70, 5]);
let raw: serde_json::Value = serde_json::from_str(&json).unwrap();
let plan = plan_apply(&report, &raw, "fp-ent").unwrap();
let defs: Vec<&str> = plan
.request
.entitlements
.iter()
.map(|e| e.definition_id.as_str())
.collect();
// One entitlement per unopened pack instance, order preserved (dup 70 kept).
assert_eq!(defs, ["70", "70", "5"]);
}
#[test]
fn plan_apply_refuses_when_blockers_present() {
// unapproved same-resourceId conflict -> blocker.
let items = vec![
player(100000003, 20801, 20801, 94),
player(100000004, 20801, 20801, 90),
];
let (report, raw) = report_and_raw(&items, "[]", 100000500);
assert!(plan_apply(&report, &raw, "fp").is_err());
}
#[test]
fn gate_staging_requires_explicit_optin_for_deferred() {
// one supported + one NoName (unresolvable asset) deferred instance.
let items = vec![
player(100000001, 20801, 20801, 94),
format!(
r#"{{"id":100000009,"resourceId":999999,"assetId":999999,"itemType":"player","rating":80,
"preferredPosition":"ST","nation":38,"teamid":243,"leagueId":53,"attributeList":{}}}"#,
attrs()
),
];
let (report, raw) = report_and_raw(&items, "[]", 100000500);
let plan = plan_apply(&report, &raw, "fp").unwrap();
assert_eq!(plan.deferred_instances, 1);
assert!(gate_staging(&plan, false).is_err(), "deferred needs opt-in");
assert!(gate_staging(&plan, true).unwrap(), "staging with opt-in");
}
#[test]
fn gate_staging_production_complete_needs_no_flag() {
let items = vec![player(100000001, 20801, 20801, 94)];
let (report, raw) = report_and_raw(&items, "[]", 100000500);
let plan = plan_apply(&report, &raw, "fp").unwrap();
assert_eq!(plan.deferred_instances, 0);
assert!(!gate_staging(&plan, false).unwrap());
}
#[test]
fn local_preflight_rejects_owned_card_absent_from_content() {
let items = vec![player(100000001, 20801, 20801, 94)];
let (report, raw) = report_and_raw(&items, "[]", 100000500);
let plan = plan_apply(&report, &raw, "fp").unwrap();
let mut present = BTreeSet::new();
present.insert("fifa17_20801".to_string());
assert!(local_core_preflight(&plan, &present).is_ok());
assert!(local_core_preflight(&plan, &BTreeSet::new()).is_err());
}
#[test]
fn identity_seed_dry_postvalidate_and_idempotent_rerun() {
let items = vec![
player(100000001, 20801, 20801, 94),
player(100000002, VER5_176580, 176580, 92),
];
let (report, raw) = report_and_raw(&items, SQUAD_F433, 100004617);
let plan = plan_apply(&report, &raw, "fp").unwrap();
let dir = tempfile::tempdir().unwrap();
let store = JsonIdentityStore::open(dir.path().join("ids.json")).unwrap();
identity_dry_preflight(&store, &plan).unwrap();
seed_identity(&store, &plan).unwrap();
// every preserved wire id resolves exactly; watermark set.
for m in &plan.mappings {
assert_eq!(
store
.external_for("fifa17", "owned-item", &m.core_id)
.unwrap(),
Some(m.wire_id)
);
}
assert_eq!(store.watermark_for("fifa17", "owned-item"), Some(100004617));
post_validate_identity(&store, &plan).unwrap();
// re-seeding the SAME plan is an idempotent no-op (crash recovery).
seed_identity(&store, &plan).unwrap();
post_validate_identity(&store, &plan).unwrap();
}
#[test]
fn identity_dry_preflight_detects_conflicting_existing_mapping() {
let items = vec![player(100000001, 20801, 20801, 94)];
let (report, raw) = report_and_raw(&items, "[]", 100000500);
let plan = plan_apply(&report, &raw, "fp").unwrap();
let dir = tempfile::tempdir().unwrap();
let store = JsonIdentityStore::open(dir.path().join("ids.json")).unwrap();
// wire 100000001 already owned by a DIFFERENT core id.
store
.insert_existing_mapping("fifa17", "owned-item", "someone-else", 100000001)
.unwrap();
assert!(identity_dry_preflight(&store, &plan).is_err());
}
#[test]
fn content_card_ids_reads_emitted_pack() {
let items = vec![player(100000001, 20801, 20801, 94)];
let rep = analyze(
&profile(&items, "[]", 100000500),
&roster(),
&entities(),
&none(),
);
let dir = tempfile::tempdir().unwrap();
let sum = emit_content(&rep, dir.path(), "fp").unwrap();
let ids = content_card_ids(&sum.content_pack).unwrap();
assert!(ids.contains("fifa17_20801"));
}
/// The full apply spawns the Core binary; that end-to-end path is exercised by
/// the staged runtime gate, not here. This asserts the orchestration refuses
/// cleanly (no panic, no partial identity seed) when the Core binary is absent
/// AFTER the two local gates pass — proving ordering: gates first, spawn last.
#[test]
fn apply_fails_gracefully_when_core_binary_missing() {
use crate::apply::ApplyPaths;
let items = vec![player(100000001, 20801, 20801, 94)];
let (report, raw) = report_and_raw(&items, "[]", 100000500);
let plan = plan_apply(&report, &raw, "fp").unwrap();
let dir = tempfile::tempdir().unwrap();
// emit a real content pack so local preflight passes.
let rep2 = analyze(
&profile(&items, "[]", 100000500),
&roster(),
&entities(),
&none(),
);
let sum = emit_content(&rep2, dir.path(), "fp").unwrap();
let paths = ApplyPaths {
core_bin: dir.path().join("no-such-core-binary"),
core_db_url: "sqlite::memory:".to_string(),
content_pack: sum.content_pack,
data_dir: "data".to_string(),
identity_store: dir.path().join("ids.json"),
request_out: dir.path().join("req.json"),
completion_out: dir.path().join("done.json"),
};
let err = apply_import(&plan, &paths, false).unwrap_err();
assert!(format!("{err:#}").contains("spawn core import"), "{err:#}");
}
// -------------------------------------------------- non-player content
use openfut_adapter_fifa17::fut::catalog::Fifa17CardCatalog;
use openfut_adapter_fifa17::fut::content_taxonomy::ContentKind;
/// A consumable owned item: itemType="player" but NO attributeList; identity is
/// carried entirely by resourceId (== assetId == carddbid) + cardsubtypeid.
fn consumable(id: i64, resource: i64, subtype: i64) -> String {
format!(
r#"{{"id":{id},"resourceId":{resource},"assetId":{resource},"itemType":"player",
"cardsubtypeid":{subtype},"cardassetid":3,"amount":1,"rating":0,"rareflag":0}}"#
)
}
/// A staff owned item: itemType="staff", resourceId only (NO assetId), keyed by
/// cardsubtypeid.
fn staff(id: i64, resource: i64, subtype: i64) -> String {
format!(
r#"{{"id":{id},"resourceId":{resource},"itemType":"staff","cardsubtypeid":{subtype},"contract":10}}"#
)
}
#[test]
fn plan_non_player_supports_seventeen_consumables_and_three_staff() {
// The exact record set from the ticket: distinct resourceIds, so each is its
// own definition even where two copies share a subtype (54,54 / 100,100 /
// 202,202 / staff 8,8) — subtype duplication across DISTINCT definitions is
// not a conflict.
let consumable_subtypes = [
54, 54, 52, 91, 92, 97, 98, 100, 100, 258, 267, 271, 201, 202, 202, 217, 213,
];
let staff_subtypes = [8i64, 8, 6];
let mut items = Vec::new();
for (i, &st) in consumable_subtypes.iter().enumerate() {
let i = i as i64;
items.push(consumable(100_000_200 + i, 5_003_001 + i, st));
}
for (i, &st) in staff_subtypes.iter().enumerate() {
let i = i as i64;
items.push(staff(100_000_300 + i, 3_000_001 + i, st));
}
let plan = plan_non_player_definitions(&profile(&items, "[]", 100000500));
assert_eq!(
plan.supported.len(),
20,
"17 consumable + 3 staff definitions"
);
assert_eq!(plan.consumables, 17);
assert_eq!(plan.staff, 3);
assert!(plan.deferred.is_empty(), "0 deferred: {:?}", plan.deferred);
// Honest labels + kinds resolve from the taxonomy (spot checks).
let by_id = |cid: &str| plan.supported.iter().find(|d| d.card_id == cid).unwrap();
// subtype 201 -> Player Contract (13th consumable, resource 5003013)
let contract = by_id("fifa17_5003013");
assert_eq!(contract.name, "Player Contract");
assert_eq!(contract.kind, ContentKind::Consumable);
assert_eq!(contract.subtype, 201);
// subtype 258 -> Player Chemistry Style (10th consumable, resource 5003010)
assert_eq!(by_id("fifa17_5003010").name, "Player Chemistry Style");
// staff subtype 8 -> Fitness Coach; subtype 6 -> GK Coach
let fitness = by_id("fifa17_3000001");
assert_eq!(fitness.name, "Fitness Coach");
assert_eq!(fitness.kind, ContentKind::Staff);
assert_eq!(fitness.asset_id, None, "staff carry no assetId");
assert_eq!(by_id("fifa17_3000003").name, "GK Coach");
}
#[test]
fn unknown_subtype_consumable_defers_never_fabricated() {
let plan = plan_non_player_definitions(&profile(
&[consumable(100000300, 5009999, 999)],
"[]",
100000500,
));
assert!(plan.supported.is_empty());
assert_eq!(plan.deferred.len(), 1);
assert_eq!(plan.deferred[0].reason, "unknown_subtype");
assert_eq!(plan.deferred[0].subtype, Some(999));
assert_eq!(plan.deferred[0].wire_ids, vec![100000300]);
}
#[test]
fn missing_cardsubtypeid_defers() {
// itemType player, no attributeList, no cardsubtypeid -> consumable w/o a
// resolvable family -> DEFER (never a placeholder).
let item =
r#"{"id":100000301,"resourceId":5003050,"assetId":5003050,"itemType":"player","rating":0}"#
.to_string();
let plan = plan_non_player_definitions(&profile(&[item], "[]", 100000500));
assert!(plan.supported.is_empty());
assert_eq!(plan.deferred.len(), 1);
assert_eq!(plan.deferred[0].reason, "missing_cardsubtypeid");
}
#[test]
fn conflicting_subtype_across_copies_defers() {
// Two copies of one resourceId that disagree on subtype -> defer, never a
// silent winner.
let plan = plan_non_player_definitions(&profile(
&[
consumable(100000302, 5003060, 201),
consumable(100000303, 5003060, 202),
],
"[]",
100000500,
));
assert!(plan.supported.is_empty());
assert_eq!(plan.deferred.len(), 1);
assert_eq!(plan.deferred[0].reason, "subtype_conflict");
assert_eq!(plan.deferred[0].wire_ids, vec![100000302, 100000303]);
}
#[test]
fn non_player_deferral_is_not_a_blocker() {
// A non-player deferral (like a player NoName deferral) must NOT block emit.
let items = vec![
player(100000001, 20801, 20801, 94),
consumable(100000300, 5009999, 999), // unknown subtype -> deferred
];
let rep = analyze(
&profile(&items, "[]", 100000500),
&roster(),
&entities(),
&none(),
);
assert!(!rep.has_blockers(), "blockers: {:?}", rep.blockers());
assert_eq!(rep.non_player.deferred.len(), 1);
}
#[test]
fn emit_content_writes_non_player_defs_catalog_kind_and_manifest() {
let items = vec![
player(100000001, 20801, 20801, 94),
consumable(100000201, 5003012, 201), // Player Contract
staff(100000427, 3000083, 8), // Fitness Coach
];
let rep = analyze(
&profile(&items, "[]", 100000500),
&roster(),
&entities(),
&none(),
);
assert!(!rep.has_blockers(), "blockers: {:?}", rep.blockers());
assert_eq!(rep.non_player.supported.len(), 2);
let dir = tempfile::tempdir().unwrap();
let sum = emit_content(&rep, dir.path(), "fp").unwrap();
assert_eq!(sum.definitions, 1, "one player definition");
assert_eq!(sum.non_player_definitions, 2);
assert_eq!(sum.non_player_instances, 2);
assert_eq!(
sum.catalog_entries, 3,
"player + 2 non-player catalog entries"
);
// Content pack: neutral non-player CardDefinition with honest name.
let pack: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&sum.content_pack).unwrap()).unwrap();
let arr = pack.as_array().unwrap();
let cons = arr.iter().find(|c| c["id"] == "fifa17_5003012").unwrap();
assert_eq!(cons["name"], "Player Contract");
assert_eq!(cons["overall"], 0);
assert_eq!(cons["position"], "");
assert_eq!(cons["nation"], "");
assert_eq!(cons["rarity"], "bronze");
assert!(cons["image_path"].is_null());
// Catalog: kind+subtype on player AND non-player; staff asset falls back to
// resourceId; and the emitted catalog LOADS in the adapter with kind_of.
let cat: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&sum.host_catalog).unwrap()).unwrap();
assert_eq!(cat["cards"]["fifa17_20801"]["kind"], "player");
assert_eq!(cat["cards"]["fifa17_20801"]["subtype"], 0);
assert_eq!(cat["cards"]["fifa17_5003012"]["kind"], "consumable");
assert_eq!(cat["cards"]["fifa17_5003012"]["subtype"], 201);
assert_eq!(cat["cards"]["fifa17_5003012"]["rareflag"], 0);
assert_eq!(cat["cards"]["fifa17_3000083"]["kind"], "staff");
assert_eq!(cat["cards"]["fifa17_3000083"]["subtype"], 8);
assert_eq!(cat["cards"]["fifa17_3000083"]["asset_id"], 3000083);
let loaded = Fifa17CardCatalog::from_file(&sum.host_catalog).unwrap();
assert_eq!(loaded.kind_of("fifa17_20801"), ContentKind::Player);
assert_eq!(loaded.kind_of("fifa17_5003012"), ContentKind::Consumable);
assert_eq!(loaded.subtype_of("fifa17_5003012"), 201);
assert_eq!(loaded.kind_of("fifa17_3000083"), ContentKind::Staff);
// Manifest: private non_player section with preserved wire ids.
let man: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&sum.manifest).unwrap()).unwrap();
assert_eq!(man["non_player"]["supported_instances"], 2);
let np = man["non_player"]["supported_definitions"]
.as_array()
.unwrap();
assert_eq!(np.len(), 2);
let cons_man = np
.iter()
.find(|d| d["card_id"] == "fifa17_5003012")
.unwrap();
assert_eq!(cons_man["wire_ids"], serde_json::json!([100000201]));
assert_eq!(cons_man["kind"], "consumable");
}
#[test]
fn plan_apply_mints_non_player_owned_instances() {
let items = vec![
player(100000001, 20801, 20801, 94),
consumable(100000201, 5003012, 201),
staff(100000427, 3000083, 8),
];
let (report, raw) = report_and_raw(&items, "[]", 100000500);
let plan = plan_apply(&report, &raw, "fp").unwrap();
// 1 player + 2 non-player owned instances, minted via the identical path.
assert_eq!(plan.request.owned.len(), 3);
assert_eq!(plan.mappings.len(), 3);
assert_eq!(plan.supported_instances, 3);
assert_eq!(plan.deferred_instances, 0);
let cards: BTreeSet<&str> = plan
.request
.owned
.iter()
.map(|o| o.card_id.as_str())
.collect();
assert!(cards.contains("fifa17_5003012"), "consumable minted");
assert!(cards.contains("fifa17_3000083"), "staff minted");
// Deterministic OwnedItemId per (persona, wire) — same rule as players.
let m = plan
.mappings
.iter()
.find(|m| m.wire_id == 100000201)
.unwrap();
assert_eq!(m.core_id, owned_item_id(33068179, 100000201));
// Local preflight passes because the emitted content pack contains the
// non-player card_ids too.
let dir = tempfile::tempdir().unwrap();
let sum = emit_content(&report, dir.path(), "fp").unwrap();
let ids = content_card_ids(&sum.content_pack).unwrap();
local_core_preflight(&plan, &ids).unwrap();
}
#[test]
fn deferred_non_player_instances_gate_a_production_apply() {
// A supported player + a deferred (unknown-subtype) consumable: the deferred
// non-player instance blocks a production apply, allowed only for staging.
let items = vec![
player(100000001, 20801, 20801, 94),
consumable(100000300, 5009999, 999),
];
let (report, raw) = report_and_raw(&items, "[]", 100000500);
let plan = plan_apply(&report, &raw, "fp").unwrap();
assert_eq!(plan.deferred_instances, 1, "the deferred consumable counts");
assert!(gate_staging(&plan, false).is_err(), "production blocks");
assert!(gate_staging(&plan, true).unwrap(), "staging opt-in allows");
}