-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_example.rs
More file actions
103 lines (83 loc) · 2.5 KB
/
basic_example.rs
File metadata and controls
103 lines (83 loc) · 2.5 KB
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
//! Basic example on how to use [`OutputSubject`] and [`OutputTracker`] to
//! track data in a component that can be read an asserted to verify if the
//! component does what is expected.
//!
//! This example uses the non-threadsafe variant.
//!
//! This same example but with using the threadsafe variant is available as
//! [`threadsafe_example`]
mod fixture;
use output_tracker::non_threadsafe::{Error, OutputSubject, OutputTracker};
//
// Production code
//
#[derive(Debug, Clone, PartialEq)]
struct Message {
topic: String,
content: String,
}
/// Outbound adapter for sending messages.
struct Adapter {
// equip outbound adapter with output subject
output_subject: OutputSubject<Message>,
}
impl Adapter {
fn new() -> Self {
Self {
output_subject: OutputSubject::new(),
}
}
/// Create an `OutputTracker` for tracking messages that are sent.
fn track_messages(&self) -> Result<OutputTracker<Message>, Error> {
self.output_subject.create_tracker()
}
fn send_message(&self, message: Message) {
// do some I/O for production
// track that message was sent
// we ignore errors from the tracker here as it is not important for the business logic.
_ = self.output_subject.emit(message);
}
}
//
// Tests
//
use asserting::prelude::*;
#[test]
fn send_message_via_adapter() {
//
// Arrange
//
let adapter = Adapter::new();
// activate the output tracker
let tracker = adapter
.track_messages()
.unwrap_or_else(|err| panic!("failed to create message tracker {err}"));
//
// Act
//
adapter.send_message(Message {
topic: "weather report".to_string(),
content: "it will be snowing tomorrow".to_string(),
});
adapter.send_message(Message {
topic: "no shadow".to_string(),
content: "keep your face to the sunshine and you cannot see a shadow".to_string(),
});
//
// Assert
//
// read the output from the output tracker
let tracker_output = tracker
.output()
.unwrap_or_else(|err| panic!("failed to get output from tracker: {err}"));
assert_that!(tracker_output).contains_exactly([
Message {
topic: "weather report".to_string(),
content: "it will be snowing tomorrow".to_string(),
},
Message {
topic: "no shadow".to_string(),
content: "keep your face to the sunshine and you cannot see a shadow".to_string(),
},
]);
}