Skip to content

Commit

Permalink
Add a test of asset locking and unlocking.
Browse files Browse the repository at this point in the history
  • Loading branch information
andriyDev committed Sep 22, 2024
1 parent 51f3ff1 commit 6f72525
Showing 1 changed file with 51 additions and 2 deletions.
53 changes: 51 additions & 2 deletions crates/bevy_asset/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -624,8 +624,8 @@ mod tests {
},
loader::{AssetLoader, LoadContext},
Asset, AssetApp, AssetEvent, AssetId, AssetLoadError, AssetLoadFailedEvent, AssetPath,
AssetPlugin, AssetServer, Assets, DependencyLoadState, LoadState,
RecursiveDependencyLoadState,
AssetPlugin, AssetServer, Assets, DependencyLoadState, LoadState, MutableAssetError,
RecursiveDependencyLoadState, UnlockAssetError,
};
use bevy_app::{App, Update};
use bevy_core::TaskPoolPlugin;
Expand Down Expand Up @@ -1548,6 +1548,55 @@ mod tests {
assert_eq!(events, expected_events);
}

#[test]
fn asset_locking() {
let mut app = App::new();
app.add_plugins(AssetPlugin::default())
.init_asset::<SubText>();

let mut assets = app.world_mut().resource_mut::<Assets<SubText>>();
let a = assets.add(SubText { text: "a".into() });
let b = assets.add(SubText { text: "b".into() });
let c = assets.add(SubText { text: "c".into() });

// Let everything propagate.
app.update();

let mut assets = app.world_mut().resource_mut::<Assets<SubText>>();
let a_arc = assets.lock(&a).expect("The asset exists");
let c_arc = assets.lock(&c).expect("The asset exists");

assert!(matches!(assets.get_mut(&a), Err(MutableAssetError::Locked)));
assert!(assets.get_mut(&b).is_ok());
assert!(matches!(assets.get_mut(&c), Err(MutableAssetError::Locked)));

// Aropping the Arc should allow us to unlock the asset.
drop(a_arc);
assert!(assets.try_unlock(&a).is_ok());

// The asset with the living Arc still cannot be unlocked or mutably accessed.
assert!(matches!(
assets.try_unlock(&c),
Err(UnlockAssetError::InUse),
));
assert!(matches!(assets.get_mut(&c), Err(MutableAssetError::Locked)));

// Dropping the Arc should allow the asset to be automatically unlocked.
drop(c_arc);
app.update();

let mut assets = app.world_mut().resource_mut::<Assets<SubText>>();
// The asset was automatically unlocked!
assert!(assets.get_mut(&c).is_ok());

let b_arc = assets.lock(&b).expect("The asset exists");

assets.insert(&b, SubText { text: "d".into() });

assert_eq!(b_arc.text, "b");
assert_eq!(assets.get_mut(&b).expect("The asset exists").text, "d");
}

#[test]
fn load_folder() {
// The particular usage of GatedReader in this test will cause deadlocking if running single-threaded
Expand Down

0 comments on commit 6f72525

Please sign in to comment.