this repo has no description
1//! Examples of valence unit tests that need to test the behavior of the server,
2//! and not just the logic of a single function. This module is meant to be a
3//! palette of examples for how to write such tests, with various levels of
4//! complexity.
5//!
6//! Some of the tests in this file may be inferior duplicates of real tests.
7
8use bevy_app::App;
9
10use crate::client::Client;
11use crate::entity::Position;
12use crate::inventory::{Inventory, InventoryKind, OpenInventory};
13use crate::math::DVec3;
14use crate::protocol::packets::play::{InventoryS2c, OpenScreenS2c, PositionAndOnGroundC2s};
15use crate::testing::ScenarioSingleClient;
16use crate::{DefaultPlugins, Server};
17
18/// The server's tick should increment every update.
19#[test]
20fn example_test_server_tick_increment() {
21 let mut app = App::new();
22
23 app.add_plugins(DefaultPlugins);
24
25 let tick = app.world_mut().resource::<Server>().current_tick();
26
27 app.update();
28
29 let server = app.world_mut().resource::<Server>();
30 assert_eq!(server.current_tick(), tick + 1);
31}
32
33/// A unit test where we want to test what happens when a client sends a
34/// packet to the server.
35#[test]
36fn example_test_client_position() {
37 let ScenarioSingleClient {
38 mut app,
39 client,
40 mut helper,
41 ..
42 } = ScenarioSingleClient::new();
43
44 // Send a packet as the client to the server.
45 let packet = PositionAndOnGroundC2s {
46 position: DVec3::new(12.0, 64.0, 0.0),
47 on_ground: true,
48 };
49 helper.send(&packet);
50
51 // Process the packet.
52 app.update();
53
54 // Make assertions
55 let pos = app.world_mut().get::<Position>(client).unwrap();
56 assert_eq!(pos.0, DVec3::new(12.0, 64.0, 0.0));
57}
58
59/// A unit test where we want to test what packets are sent to the client.
60#[test]
61fn example_test_open_inventory() {
62 let ScenarioSingleClient {
63 mut app,
64 client,
65 mut helper,
66 ..
67 } = ScenarioSingleClient::new();
68
69 let inventory = Inventory::new(InventoryKind::Generic3x3);
70 let inventory_ent = app.world_mut().spawn(inventory).id();
71
72 // Process a tick to get past the "on join" logic.
73 app.update();
74 helper.clear_received();
75
76 // Open the inventory.
77 let open_inventory = OpenInventory::new(inventory_ent);
78 app.world_mut()
79 .get_entity_mut(client)
80 .expect("could not find client")
81 .insert(open_inventory);
82
83 app.update();
84 app.update();
85
86 // Make assertions
87 app.world_mut()
88 .get::<Client>(client)
89 .expect("client not found");
90
91 let sent_packets = helper.collect_received();
92
93 sent_packets.assert_count::<OpenScreenS2c>(1);
94 sent_packets.assert_count::<InventoryS2c>(1);
95
96 sent_packets.assert_order::<(OpenScreenS2c, InventoryS2c)>();
97}