bevy_pipe_affect 0.3.0

Write systems as pure functions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! [`Effect`]s that queue `Commands`.
use std::marker::PhantomData;

use bevy::prelude::*;

use crate::Effect;

/// [`Effect`] that pushes a generic command to the command queue.
///
/// This effect is mostly intended to "fill the gaps" of `bevy_pipe_affect`, as not all commands or
/// world mutations provided by bevy have an equivalent effect.
/// Using this typically requires writing some impure code anyway, so users should also consider
/// writing their own custom [`Effect`] instead.
/// (Then, if it's general-purpose enough, consider contributing it upstream!)
///
/// Can be constructed with [`command_queue`].
///
/// # Example
/// In this example, a system is written that gives all `Player`s a `Score` of 0 if they do not
/// already have a score.
/// ```
/// use bevy::prelude::*;
/// use bevy_pipe_affect::prelude::*;
///
/// #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Component)]
/// # #[derive(proptest_derive::Arbitrary)]
/// struct Player;
///
/// #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Component)]
/// # #[derive(proptest_derive::Arbitrary)]
/// struct Score(u32);
///
/// #[derive(Clone, Debug, Default, PartialEq, Eq)]
/// struct InitScores(Vec<Entity>);
///
/// impl Command for InitScores {
///     fn apply(self, world: &mut World) {
///         world.insert_batch_if_new(self.0.into_iter().map(|entity| (entity, Score(0))));
///     }
/// }
///
/// /// Pure-ish system using effects.
/// fn init_player_score_pureish(query: Query<Entity, With<Player>>) -> CommandQueue<InitScores> {
///     command_queue(InitScores(query.iter().collect()))
/// }
///
/// /// Equivalent impure system.
/// fn init_player_score_impure(query: Query<Entity, With<Player>>, mut commands: Commands) {
///     commands.queue(InitScores(query.iter().collect()));
/// }
/// #
/// # use proptest::prelude::*;
/// #
/// # fn app_setup(component_table: Vec<(Option<Player>, Option<Score>)>) -> App {
/// #     let mut app = App::new();
/// #
/// #     component_table.into_iter().for_each(|(player, score)| {
/// #         let mut entity = app.world_mut().spawn_empty();
/// #         if let Some(player) = player {
/// #             entity.insert(player);
/// #         }
/// #         if let Some(score) = score {
/// #             entity.insert(score);
/// #         }
/// #     });
/// #
/// #     app
/// # }
/// #
/// # fn test_state(world: &mut World) -> Vec<(Entity, Option<&Player>, Option<&Score>)> {
/// #     let mut query = world.query::<(Entity, Option<&Player>, Option<&Score>)>();
/// #     query.iter(world).collect()
/// # }
/// #
/// # proptest! {
/// #     fn main(component_table: Vec<(Option<Player>, Option<Score>)>) {
/// #          let mut pure_app = app_setup(component_table.clone());
/// #          pure_app.add_systems(Update, init_player_score_pureish.pipe(affect));
/// #
/// #          let mut impure_app = app_setup(component_table.clone());
/// #          impure_app.add_systems(Update, init_player_score_impure);
/// #
/// #          for _ in 0..3 {
/// #              prop_assert_eq!(test_state(pure_app.world_mut()), test_state(impure_app.world_mut()));
/// #              pure_app.update();
/// #              impure_app.update();
/// #          }
/// #     }
/// # }
/// ```
#[doc = include_str!("defer_command_note.md")]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct CommandQueue<C>
where
    C: Command,
{
    /// The command to push onto the queue.
    pub command: C,
}

/// Construct a new [`CommandQueue`] [`Effect`].
pub fn command_queue<C>(command: C) -> CommandQueue<C>
where
    C: Command,
{
    CommandQueue { command }
}

impl<C> Effect for CommandQueue<C>
where
    C: Command,
{
    type MutParam = Commands<'static, 'static>;

    fn affect(self, param: &mut <Self::MutParam as bevy::ecs::system::SystemParam>::Item<'_, '_>) {
        param.queue(self.command)
    }
}

/// [`Effect`] that queues a command for inserting the provided `Resource` in the `World`.
///
/// Can be constucted with [`command_insert_resource`].
///
/// # Example
/// In this example, a sysstem is written that inserts a `Score` of 0.
/// ```
/// use bevy::prelude::*;
/// use bevy_pipe_affect::prelude::*;
///
/// #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Resource)]
/// # #[derive(proptest_derive::Arbitrary)]
/// struct Score(u32);
///
/// /// Pure system using effects.
/// fn init_score_pure() -> CommandInsertResource<Score> {
///     command_insert_resource(Score(0))
/// }
///
/// /// Equivalent impure system.
/// fn init_score_impure(mut commands: Commands) {
///     commands.insert_resource(Score(0))
/// }
/// #
/// # use proptest::prelude::*;
/// #
/// # fn app_setup(score: Option<Score>) -> App {
/// #     let mut app = App::new();
/// #     if let Some(score) = score {
/// #         app.insert_resource(score);
/// #     }
/// #
/// #     app
/// # }
/// #
/// # fn resource_state(world: &World) -> Option<&Score> {
/// #     world.get_resource::<Score>()
/// # }
/// #
/// # proptest! {
/// #     fn main(score: Option<Score>) {
/// #         let mut pure_app = app_setup(score);
/// #         pure_app.add_systems(Update, init_score_pure.pipe(affect));
/// #
/// #         let mut impure_app = app_setup(score);
/// #         impure_app.add_systems(Update, init_score_impure);
/// #
/// #         for _ in 0..3 {
/// #              prop_assert_eq!(resource_state(pure_app.world_mut()), resource_state(impure_app.world_mut()));
/// #              pure_app.update();
/// #              impure_app.update();
/// #         }
/// #     }
/// # }
/// ```
#[doc = include_str!("defer_command_note.md")]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct CommandInsertResource<R>
where
    R: Resource,
{
    /// The initial value of the inserted resource.
    pub resource: R,
}

/// Construct a new [`CommandInsertResource`] [`Effect`].
pub fn command_insert_resource<R>(resource: R) -> CommandInsertResource<R>
where
    R: Resource,
{
    CommandInsertResource { resource }
}

impl<R> Effect for CommandInsertResource<R>
where
    R: Resource,
{
    type MutParam = Commands<'static, 'static>;

    fn affect(self, param: &mut <Self::MutParam as bevy::ecs::system::SystemParam>::Item<'_, '_>) {
        param.insert_resource(self.resource);
    }
}

/// [`Effect`] that queues a command for removing a `Resource` from the `World`.
///
/// Can be constructed with [`command_remove_resource`].
///
/// # Example
/// In this example, a system is written that removes the `GoToLevel` resource (presumably, after
/// some level transition has completed).
/// ```
/// use bevy::prelude::*;
/// use bevy_pipe_affect::prelude::*;
///
/// #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Resource)]
/// # #[derive(proptest_derive::Arbitrary)]
/// struct GoToLevel(usize);
///
/// /// Pure system using effects.
/// fn complete_level_transition_pure() -> CommandRemoveResource<GoToLevel> {
///     command_remove_resource::<GoToLevel>()
/// }
///
/// /// Equivalent impure system.
/// fn complete_level_transition_impure(mut commands: Commands) {
///     commands.remove_resource::<GoToLevel>()
/// }
/// #
/// # use proptest::prelude::*;
/// #
/// # fn app_setup(resource: Option<GoToLevel>) -> App {
/// #     let mut app = App::new();
/// #
/// #     if let Some(resource) = resource {
/// #         app.insert_resource(resource);
/// #     }
/// #
/// #     app
/// # }
/// #
/// # fn test_state(world: &World) -> Option<&GoToLevel> {
/// #     world.get_resource::<GoToLevel>()
/// # }
/// #
/// # proptest! {
/// #     fn main(resource: Option<GoToLevel>) {
/// #         let mut pure_app = app_setup(resource);
/// #         pure_app.add_systems(Update, complete_level_transition_pure.pipe(affect));
/// #
/// #         let mut impure_app = app_setup(resource);
/// #         impure_app.add_systems(Update, complete_level_transition_impure);
/// #
/// #         for _ in 0..3 {
/// #              prop_assert_eq!(test_state(pure_app.world_mut()), test_state(impure_app.world_mut()));
/// #              pure_app.update();
/// #              impure_app.update();
/// #         }
/// #     }
/// # }
/// ```
#[doc = include_str!("defer_command_note.md")]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct CommandRemoveResource<R>
where
    R: Resource,
{
    resource: PhantomData<R>,
}

impl<R> CommandRemoveResource<R>
where
    R: Resource,
{
    /// Construct a new [`CommandRemoveResource`]
    pub fn new() -> Self {
        CommandRemoveResource {
            resource: PhantomData,
        }
    }
}

/// Construct a new [`CommandRemoveResource`] [`Effect`].
pub fn command_remove_resource<R>() -> CommandRemoveResource<R>
where
    R: Resource,
{
    CommandRemoveResource::new()
}

impl<R> Effect for CommandRemoveResource<R>
where
    R: Resource,
{
    type MutParam = Commands<'static, 'static>;

    fn affect(self, param: &mut <Self::MutParam as bevy::ecs::system::SystemParam>::Item<'_, '_>) {
        param.remove_resource::<R>();
    }
}

/// [`Effect`] that queues a command for spawning an entity with the provided `Bundle`.
///
/// See [`CommandSpawnAnd`] if you need to produce an extra effect with the spawned `Entity` id.
///
/// Can be constructed with [`command_spawn`].
///
/// # Example
/// In this example, a system is written that spawns an `Enemy`.
/// ```
/// use bevy::prelude::*;
/// use bevy_pipe_affect::prelude::*;
///
/// #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Component)]
/// struct Enemy;
///
/// /// Pure system using effects.
/// fn spawn_enemy_pure() -> CommandSpawn<Enemy> {
///     command_spawn(Enemy)
/// }
///
/// /// Equivalent impure system.
/// fn spawn_enemy_impure(mut commands: Commands) {
///     commands.spawn(Enemy);
/// }
/// #
/// # fn app_setup() -> App {
/// #     App::new()
/// # }
/// #
/// # fn test_state(world: &mut World) -> Vec<(Entity, Option<&Enemy>)> {
/// #     let mut query = world.query::<(Entity, Option<&Enemy>)>();
/// #     query.iter(world).collect()
/// # }
/// #
/// # fn main() {
/// #     let mut pure_app = app_setup();
/// #     pure_app.add_systems(Update, spawn_enemy_pure.pipe(affect));
/// #
/// #     let mut impure_app = app_setup();
/// #     impure_app.add_systems(Update, spawn_enemy_impure);
/// #
/// #     for _ in 0..32 {
/// #         assert_eq!(
/// #             test_state(pure_app.world_mut()),
/// #             test_state(impure_app.world_mut())
/// #         );
/// #         pure_app.update();
/// #         impure_app.update();
/// #     }
/// # }
/// ```
#[doc = include_str!("defer_command_note.md")]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct CommandSpawn<B>
where
    B: Bundle,
{
    /// The bundle to spawn.
    pub bundle: B,
}

/// Construct a new [`CommandSpawn`] [`Effect`], without an extra effect.
pub fn command_spawn<B>(bundle: B) -> CommandSpawn<B>
where
    B: Bundle,
{
    CommandSpawn { bundle }
}

impl<B> Effect for CommandSpawn<B>
where
    B: Bundle,
{
    type MutParam = Commands<'static, 'static>;

    fn affect(self, param: &mut <Self::MutParam as bevy::ecs::system::SystemParam>::Item<'_, '_>) {
        param.spawn(self.bundle);
    }
}

/// [`Effect`] that queues a command for spawning an entity with the provided `Bundle`, then
/// supplies the entity id to the provided effect-producing function to cause another effect.
///
/// See [`CommandSpawn`] if you do not need to produce an extra effect.
///
/// Can be constructed with [`command_spawn_and`].
///
/// # Example
/// In this example, a system is written that spawns a `Player`, and a `Sword` as a child of the
/// player.
/// ```
/// use bevy::prelude::*;
/// use bevy_pipe_affect::prelude::*;
///
/// #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Component)]
/// struct Player;
///
/// #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Component)]
/// struct Sword;
///
/// /// Pure system using effects.
/// fn spawn_armed_player_pure() -> CommandSpawnAnd<Player, CommandSpawn<(Sword, ChildOf)>> {
///     command_spawn_and(Player, |player_entity| {
///         command_spawn((Sword, ChildOf(player_entity)))
///     })
/// }
///
/// /// Equivalent impure system.
/// fn spawn_armed_player_impure(mut commands: Commands) {
///     commands.spawn(Player).with_children(|parent| {
///         parent.spawn(Sword);
///     });
/// }
/// #
/// # fn app_setup() -> App {
/// #     App::new()
/// # }
/// #
/// # fn test_state(
/// #     world: &mut World,
/// # ) -> Vec<(Entity, Option<&Player>, Option<&Sword>, Option<&ChildOf>)> {
/// #     let mut query =
/// #         world.query::<(Entity, Option<&Player>, Option<&Sword>, Option<&ChildOf>)>();
/// #     query.iter(world).collect()
/// # }
/// #
/// # fn main() {
/// #     let mut pure_app = app_setup();
/// #     pure_app.add_systems(Update, spawn_armed_player_pure.pipe(affect));
/// #
/// #     let mut impure_app = app_setup();
/// #     impure_app.add_systems(Update, spawn_armed_player_impure);
/// #
/// #     for _ in 0..32 {
/// #         assert_eq!(
/// #             test_state(pure_app.world_mut()),
/// #             test_state(impure_app.world_mut())
/// #         );
/// #         pure_app.update();
/// #         impure_app.update();
/// #     }
/// # }
/// ```
///
/// Not shown...
/// - In this example, [`CommandSpawn`] is used as the additional [`Effect`], but any other effect
/// could be produced.
#[doc = include_str!("defer_command_note.md")]
#[derive(derive_more::Debug)]
pub struct CommandSpawnAnd<B, E>
where
    B: Bundle,
    E: Effect,
{
    /// The bundle to spawn.
    pub bundle: B,
    /// The `Entity -> Effect` function that may cause another effect.
    #[debug("Entity -> {}", std::any::type_name::<E>())]
    pub f: Box<dyn FnOnce(Entity) -> E>,
}

/// Construct a new [`CommandSpawnAnd`] [`Effect`], with an extra effect using the `Entity`.
pub fn command_spawn_and<B, F, E>(bundle: B, f: F) -> CommandSpawnAnd<B, E>
where
    B: Bundle,
    F: FnOnce(Entity) -> E + 'static,
    E: Effect,
{
    CommandSpawnAnd {
        bundle,
        f: Box::new(f),
    }
}

impl<B, E> Default for CommandSpawnAnd<B, E>
where
    B: Bundle + Default,
    E: Effect + Default,
{
    fn default() -> Self {
        CommandSpawnAnd {
            bundle: default(),
            f: Box::new(|_| default()),
        }
    }
}

impl<B, E> Effect for CommandSpawnAnd<B, E>
where
    B: Bundle,
    E: Effect,
{
    type MutParam = (Commands<'static, 'static>, E::MutParam);

    fn affect(self, param: &mut <Self::MutParam as bevy::ecs::system::SystemParam>::Item<'_, '_>) {
        let entity = param.0.spawn(self.bundle).id();

        (self.f)(entity).affect(&mut param.1);
    }
}

/// [`Effect`] that queues a command for triggering the given event.
///
/// Can be constructed with [`command_trigger`].
///
/// # Example
/// In this example, a system is written that triggers a `Winner` event if any entity has a score
/// above 100.
/// ```
/// use bevy::prelude::*;
/// use bevy_pipe_affect::prelude::*;
///
/// #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Component)]
/// # #[derive(proptest_derive::Arbitrary)]
/// struct Score(u8);
///
/// #[derive(Copy, Clone, Debug, PartialEq, Eq, Event)]
/// struct Winner(Entity);
///
/// /// Pure system using effects.
/// fn declare_winner_pure(query: Query<(Entity, &Score)>) -> Option<CommandTrigger<Winner>> {
///     query
///         .iter()
///         .find(|(_, score)| score.0 >= 100)
///         .map(|(entity, _)| command_trigger(Winner(entity)))
/// }
///
/// /// Equivalent impure system.
/// fn declare_winner_impure(query: Query<(Entity, &Score)>, mut commands: Commands) {
///     if let Some((entity, _)) = query.iter().find(|(_, score)| score.0 >= 100) {
///         commands.trigger(Winner(entity))
///     }
/// }
/// #
/// # use proptest::prelude::*;
/// #
/// # fn reset_winner_score(winner: On<Winner>) -> QueryEntityAffect<ComponentSet<Score>> {
/// #     query_entity_affect(winner.0, component_set(Score(0)))
/// # }
/// #
/// # fn app_setup(component_table: Vec<Option<Score>>) -> App {
/// #     let mut app = App::new();
/// #     app.add_systems(
/// #         Update,
/// #         (|| command_spawn(Observer::new(reset_winner_score.pipe(affect)))).pipe(affect),
/// #     );
/// #     component_table.into_iter().for_each(|score| {
/// #         let mut entity = app.world_mut().spawn_empty();
/// #         if let Some(score) = score {
/// #             entity.insert(score);
/// #         }
/// #     });
/// #
/// #     app
/// # }
/// #
/// # fn test_state(world: &mut World) -> Vec<(Entity, Option<&Score>)> {
/// #     let mut query = world.query::<(Entity, Option<&Score>)>();
/// #     query.iter(world).collect()
/// # }
/// #
/// # proptest! {
/// #     fn main(component_table: Vec<Option<Score>>) {
/// #         let mut pure_app = app_setup(component_table.clone());
/// #         pure_app.add_systems(Update, declare_winner_pure.pipe(affect));
/// #
/// #         let mut impure_app = app_setup(component_table.clone());
/// #         impure_app.add_systems(Update, declare_winner_impure);
/// #
/// #         for _ in 0..3 {
/// #             prop_assert_eq!(test_state(pure_app.world_mut()), test_state(impure_app.world_mut()));
/// #             pure_app.update();
/// #             impure_app.update();
/// #         }
/// #     }
/// # }
/// ```
#[doc = include_str!("defer_command_note.md")]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub struct CommandTrigger<E>
where
    E: Event,
    for<'a> E::Trigger<'a>: Default,
{
    /// The event being triggered.
    pub event: E,
}

/// Construct a new [`CommandTrigger`] [`Effect`].
pub fn command_trigger<E>(event: E) -> CommandTrigger<E>
where
    E: Event,
    for<'a> E::Trigger<'a>: Default,
{
    CommandTrigger { event }
}

impl<E> Effect for CommandTrigger<E>
where
    E: Event,
    for<'a> E::Trigger<'a>: Default,
{
    type MutParam = Commands<'static, 'static>;

    fn affect(self, param: &mut <Self::MutParam as bevy::ecs::system::SystemParam>::Item<'_, '_>) {
        param.trigger(self.event);
    }
}

#[cfg(test)]
mod tests {
    use proptest::prelude::*;

    use super::*;
    use crate::effects::number_data::{NumberComponent, NumberEvent, NumberResource};
    use crate::prelude::affect;

    proptest! {
        #[test]
        fn command_queue_can_spawn_entities_non_exclusively(component in any::<NumberComponent<0>>()) {
            let mut app = App::new();

            let component_count = app.world_mut().query_filtered::<(), With<NumberComponent<0>>>().iter(app.world()).count();

            assert_eq!(component_count, 0);

            let spawn_component_system = move || {
                command_queue(move |world: &mut World| {
                    world.spawn(component.clone());
                })
            };


            assert!(!IntoSystem::into_system(spawn_component_system.pipe(affect)).is_exclusive());

            app.add_systems(
                Update,
                spawn_component_system.pipe(affect),
            );

            app.update();

            let component_count = app.world_mut().query_filtered::<(), With<NumberComponent<0>>>().iter(app.world()).count();

            assert_eq!(component_count, 1);

            app.update();

            let component_count = app.world_mut().query_filtered::<(), With<NumberComponent<0>>>().iter(app.world()).count();

            assert_eq!(component_count, 2);
        }

        #[test]
        fn resource_commands_correctly_insert_and_remove(resource in any::<NumberResource>()) {
            let mut app = App::new();

            assert!(app.world().get_resource::<NumberResource>().is_none());

            #[derive(Debug, Clone, PartialEq, Eq, Hash, SystemSet)]
            struct InsertSystem;

            app.add_systems(
                Update,
                (move || command_insert_resource(resource)).pipe(affect).in_set(InsertSystem),
            );

            app.update();

            assert_eq!(app.world().get_resource::<NumberResource>(), Some(&resource));

            app.add_systems(
                Update,
                (move || command_remove_resource::<NumberResource>()).pipe(affect).after(InsertSystem),
            );

            app.update();

            assert!(app.world().get_resource::<NumberResource>().is_none());
        }

        #[test]
        fn command_trigger_correctly_triggers_observers(event in any::<NumberEvent>()) {
            let mut app = App::new();

            app.add_systems(
                Startup,
                (move || command_spawn(Observer::new((|event: On<NumberEvent>| command_insert_resource(NumberResource(event.0))).pipe(affect)))).pipe(affect),
            );

            app.update();
            assert!(app.world().get_resource::<NumberResource>().is_none());

            app.update();
            assert!(app.world().get_resource::<NumberResource>().is_none());

            app.add_systems(
                Update,
                (move || command_trigger(event)).pipe(affect)
            );

            app.update();

            assert_eq!(app.world().get_resource::<NumberResource>(), Some(&NumberResource(event.0)));
        }
    }

    #[test]
    fn command_spawn_effect_can_create_parent_child_relationship() {
        let mut app = App::new();

        let children_count = app
            .world_mut()
            .query::<&ChildOf>()
            .iter(app.world())
            .count();

        assert_eq!(children_count, 0);

        #[derive(Resource)]
        struct ParentEntity(Entity);

        app.add_systems(
            Update,
            (move || {
                command_spawn_and((), move |parent| {
                    (
                        command_spawn(ChildOf(parent)),
                        command_insert_resource(ParentEntity(parent)),
                    )
                })
            })
            .pipe(affect),
        );

        app.update();

        let children_count = app
            .world_mut()
            .query::<&ChildOf>()
            .iter(app.world())
            .count();

        assert_eq!(children_count, 1);

        let parent_entity = app.world().resource::<ParentEntity>().0;

        app.world_mut()
            .query::<&ChildOf>()
            .iter(app.world())
            .for_each(|child_of| {
                assert_eq!(child_of.0, parent_entity);
            });

        let children_of_parent_count = app
            .world()
            .entity(parent_entity)
            .get::<Children>()
            .iter()
            .count();

        assert_eq!(children_of_parent_count, 1);
    }
}