Skip to content

Commit 4638d29

Browse files
committed
Add a test of asset locking and unlocking.
1 parent bc01390 commit 4638d29

File tree

1 file changed

+51
-2
lines changed

1 file changed

+51
-2
lines changed

crates/bevy_asset/src/lib.rs

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -624,8 +624,8 @@ mod tests {
624624
},
625625
loader::{AssetLoader, LoadContext},
626626
Asset, AssetApp, AssetEvent, AssetId, AssetLoadError, AssetLoadFailedEvent, AssetPath,
627-
AssetPlugin, AssetServer, Assets, DependencyLoadState, LoadState,
628-
RecursiveDependencyLoadState,
627+
AssetPlugin, AssetServer, Assets, DependencyLoadState, LoadState, MutableAssetError,
628+
RecursiveDependencyLoadState, UnlockAssetError,
629629
};
630630
use bevy_app::{App, Update};
631631
use bevy_core::TaskPoolPlugin;
@@ -1548,6 +1548,55 @@ mod tests {
15481548
assert_eq!(events, expected_events);
15491549
}
15501550

1551+
#[test]
1552+
fn asset_locking() {
1553+
let mut app = App::new();
1554+
app.add_plugins(AssetPlugin::default())
1555+
.init_asset::<SubText>();
1556+
1557+
let mut assets = app.world_mut().resource_mut::<Assets<SubText>>();
1558+
let a = assets.add(SubText { text: "a".into() });
1559+
let b = assets.add(SubText { text: "b".into() });
1560+
let c = assets.add(SubText { text: "c".into() });
1561+
1562+
// Let everything propagate.
1563+
app.update();
1564+
1565+
let mut assets = app.world_mut().resource_mut::<Assets<SubText>>();
1566+
let a_arc = assets.lock(&a).expect("The asset exists");
1567+
let c_arc = assets.lock(&c).expect("The asset exists");
1568+
1569+
assert!(matches!(assets.get_mut(&a), Err(MutableAssetError::Locked)));
1570+
assert!(assets.get_mut(&b).is_ok());
1571+
assert!(matches!(assets.get_mut(&c), Err(MutableAssetError::Locked)));
1572+
1573+
// Aropping the Arc should allow us to unlock the asset.
1574+
drop(a_arc);
1575+
assert!(assets.try_unlock(&a).is_ok());
1576+
1577+
// The asset with the living Arc still cannot be unlocked or mutably accessed.
1578+
assert!(matches!(
1579+
assets.try_unlock(&c),
1580+
Err(UnlockAssetError::InUse),
1581+
));
1582+
assert!(matches!(assets.get_mut(&c), Err(MutableAssetError::Locked)));
1583+
1584+
// Dropping the Arc should allow the asset to be automatically unlocked.
1585+
drop(c_arc);
1586+
app.update();
1587+
1588+
let mut assets = app.world_mut().resource_mut::<Assets<SubText>>();
1589+
// The asset was automatically unlocked!
1590+
assert!(assets.get_mut(&c).is_ok());
1591+
1592+
let b_arc = assets.lock(&b).expect("The asset exists");
1593+
1594+
assets.insert(&b, SubText { text: "d".into() });
1595+
1596+
assert_eq!(b_arc.text, "b");
1597+
assert_eq!(assets.get_mut(&b).expect("The asset exists").text, "d");
1598+
}
1599+
15511600
#[test]
15521601
fn load_folder() {
15531602
// The particular usage of GatedReader in this test will cause deadlocking if running single-threaded

0 commit comments

Comments
 (0)