@ftrdotdev/pi-qrspi 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,183 @@
1
+ # Dependency Injection
2
+
3
+ Dependency injection (DI) is the practice of supplying a component's dependencies from outside rather than having the component create or locate them itself. It is the primary mechanism that makes code testable without resorting to global state, monkey-patching, or mocking internals.
4
+
5
+ The core rule: a unit under test should never instantiate its own collaborators that cross a boundary. If it does, you cannot substitute a double in tests.
6
+
7
+ ---
8
+
9
+ ## Patterns
10
+
11
+ ### Constructor Injection
12
+
13
+ Dependencies are declared as constructor parameters and stored for use across all methods. This is the default pattern in object-oriented code.
14
+
15
+ ```
16
+ // Without DI — untestable, EmailSender is hard-coded
17
+ class OrderService:
18
+ confirmOrder(orderId: string) -> void:
19
+ sender = new SmtpEmailSender() // creates its own dependency
20
+ sender.send(...)
21
+
22
+ // With constructor injection — EmailSender is a substitutable parameter
23
+ class OrderService:
24
+ emailSender: EmailSender
25
+
26
+ constructor(emailSender: EmailSender):
27
+ this.emailSender = emailSender
28
+
29
+ confirmOrder(orderId: string) -> void:
30
+ this.emailSender.send(...)
31
+
32
+ // In production
33
+ service = OrderService(emailSender: SmtpEmailSender())
34
+
35
+ // In tests
36
+ service = OrderService(emailSender: SpyEmailSender())
37
+ ```
38
+
39
+ Use constructor injection when:
40
+
41
+ - The dependency is required for the object to function at all
42
+ - The same dependency is used across multiple methods
43
+ - You want the object's dependencies to be explicit and visible at instantiation
44
+
45
+ **Anti-pattern**: Injecting every possible collaborator regardless of whether it crosses a boundary. Injecting a pure utility class that has no I/O and no external state adds noise without testability benefit. Only inject what needs to be substitutable.
46
+
47
+ ---
48
+
49
+ ### Functional (Argument) Injection
50
+
51
+ Dependencies are passed as parameters to the function that needs them. This is the natural pattern in functional code and for stateless operations.
52
+
53
+ ```
54
+ // Without DI
55
+ function sendWelcomeEmail(userId: string) -> void:
56
+ user = DatabaseClient.findById(userId) // global, untestable
57
+ SmtpClient.send(user.email, ...)
58
+
59
+ // With argument injection
60
+ function sendWelcomeEmail(
61
+ userId: string,
62
+ findUser: (id: string) -> User,
63
+ sendEmail: (to: string, subject: string, body: string) -> void
64
+ ) -> void:
65
+ user = findUser(userId)
66
+ sendEmail(user.email, ...)
67
+
68
+ // In production
69
+ sendWelcomeEmail(
70
+ userId: "123",
71
+ findUser: db.findById,
72
+ sendEmail: smtp.send
73
+ )
74
+
75
+ // In tests
76
+ calls = []
77
+ sendWelcomeEmail(
78
+ userId: "123",
79
+ findUser: (_) -> User(email: "a@b.com"),
80
+ sendEmail: (to, subj, body) -> calls.append({to, subj, body})
81
+ )
82
+ assert calls[0].to == "a@b.com"
83
+ ```
84
+
85
+ Use argument injection when:
86
+
87
+ - The function is stateless and the dependency is only needed for that call
88
+ - You are working in a functional style where objects with persistent state are uncommon
89
+ - The dependency varies per call rather than per instance
90
+
91
+ **Anti-pattern**: Passing so many function arguments that the signature becomes a configuration object. When a function needs more than two or three injected dependencies, it is doing too much and should be decomposed.
92
+
93
+ ---
94
+
95
+ ### Factory Injection
96
+
97
+ A factory — a function or object that creates instances — is injected rather than the instance itself. Used when a new instance must be created per operation rather than shared.
98
+
99
+ ```
100
+ interface ConnectionFactory:
101
+ create() -> DatabaseConnection
102
+
103
+ class ReportService:
104
+ connectionFactory: ConnectionFactory
105
+
106
+ constructor(connectionFactory: ConnectionFactory):
107
+ this.connectionFactory = connectionFactory
108
+
109
+ generateReport(params: ReportParams) -> Report:
110
+ conn = this.connectionFactory.create()
111
+ // conn is scoped to this operation
112
+ ...
113
+
114
+ // In tests
115
+ class FakeConnectionFactory implements ConnectionFactory:
116
+ create() -> DatabaseConnection:
117
+ return InMemoryConnection()
118
+ ```
119
+
120
+ Use factory injection when the dependency has a lifecycle tied to an individual operation, not to the service itself — open/close semantics, request-scoped resources, or objects that carry operation-specific context.
121
+
122
+ ---
123
+
124
+ ### DI Containers
125
+
126
+ A DI container is a runtime registry that resolves and wires dependencies automatically based on configuration. Useful in large applications where manually wiring the full object graph at startup becomes unwieldy.
127
+
128
+ ```
129
+ // Registration
130
+ container.register(EmailSender, SmtpEmailSender)
131
+ container.register(OrderRepository, PostgresOrderRepository)
132
+ container.register(OrderService, OrderService) // container infers its deps
133
+
134
+ // Resolution
135
+ service = container.resolve(OrderService)
136
+ // OrderService is constructed with its declared dependencies automatically
137
+ ```
138
+
139
+ Use a DI container when:
140
+
141
+ - The application has a large number of services with deep dependency graphs
142
+ - You want lifecycle management (singleton, transient, scoped) handled centrally
143
+
144
+ Do not reach for a container in tests. Tests should wire their subjects manually — this keeps the test's intent explicit and avoids hidden wiring that obscures what is being exercised. The container is a production convenience, not a test tool.
145
+
146
+ **Anti-pattern**: Using a DI container in unit or integration tests to resolve the subject under test. If a test relies on the container, it is testing the container's wiring as much as the behavior, and failing tests become harder to diagnose.
147
+
148
+ ---
149
+
150
+ ## Choosing a Pattern
151
+
152
+ ```
153
+ Is the dependency used across multiple methods on the same object?
154
+ Yes → Constructor injection
155
+
156
+ Is the dependency only needed for a single stateless function call?
157
+ Yes → Argument injection
158
+
159
+ Does the dependency need to be created fresh per operation?
160
+ Yes → Factory injection
161
+
162
+ Is the object graph large enough that manual wiring is unmanageable?
163
+ Yes → DI container (production only; wire manually in tests)
164
+ ```
165
+
166
+ ---
167
+
168
+ ## Depth of Injection
169
+
170
+ Inject one level deep. The subject under test receives its direct dependencies. Those dependencies may themselves have dependencies, but the test does not need to know about them — it only wires what the subject directly declares.
171
+
172
+ ```
173
+ // OrderService depends on PaymentGateway and EmailSender
174
+ // PaymentGateway depends on HttpClient — the test does not see HttpClient
175
+
176
+ service = OrderService(
177
+ gateway: FakePaymentGateway(), // boundary double
178
+ emailSender: SpyEmailSender() // boundary double
179
+ )
180
+ // HttpClient is FakePaymentGateway's internal concern
181
+ ```
182
+
183
+ If a test needs to wire three or more levels of the dependency tree to exercise a single behavior, the abstraction boundaries between those levels are probably not earning their keep.
@@ -0,0 +1,172 @@
1
+ # Test Doubles
2
+
3
+ Test doubles are controlled replacements for real dependencies in tests. The word "mock" is colloquially used for all of them, but the types are meaningfully distinct — using the wrong one produces tests that are either too brittle or too blind.
4
+
5
+ Taxonomy from Meszaros, _xUnit Test Patterns_.
6
+
7
+ ---
8
+
9
+ ## The Five Types
10
+
11
+ ### Dummy
12
+
13
+ Satisfies a required parameter signature but is never actually invoked in the code path under test.
14
+
15
+ ```
16
+ interface Logger:
17
+ log(message: string) -> void
18
+
19
+ class DummyLogger implements Logger:
20
+ log(message: string) -> void:
21
+ // no-op
22
+
23
+ order = Order(id: "123", logger: DummyLogger())
24
+ // Logger is structurally required but never called for this behavior
25
+ assert order.total() == 42.00
26
+ ```
27
+
28
+ Use when a dependency is required by the constructor or function signature but is not exercised by the behavior you are testing.
29
+
30
+ **Anti-pattern**: Using a dummy when the dependency _is_ exercised. Calls silently disappear, hiding behavior from the test.
31
+
32
+ ---
33
+
34
+ ### Stub
35
+
36
+ Returns a pre-configured response to a specific call. Does not verify whether or how often it was called.
37
+
38
+ ```
39
+ interface PricingService:
40
+ getPrice(productId: string) -> decimal
41
+
42
+ class StubPricingService implements PricingService:
43
+ getPrice(productId: string) -> decimal:
44
+ return 9.99
45
+
46
+ checkout = Checkout(pricing: StubPricingService())
47
+ total = checkout.calculate(cartWith(productId: "ABC"))
48
+ assert total == 9.99
49
+ ```
50
+
51
+ Use when the test needs a dependency to return a specific value to exercise a code path, and you do not care whether or how often it was called.
52
+
53
+ **Anti-pattern**: Returning the same value for all inputs when the system under test uses the input to branch. The stub then hides a real contract your code depends on.
54
+
55
+ ---
56
+
57
+ ### Fake
58
+
59
+ A working lightweight implementation, not suitable for production. Has real behavior — it processes inputs and maintains state — just simplified.
60
+
61
+ ```
62
+ interface UserRepository:
63
+ save(user: User) -> void
64
+ findById(id: string) -> User | null
65
+
66
+ class InMemoryUserRepository implements UserRepository:
67
+ store: Map<string, User> = {}
68
+
69
+ save(user: User) -> void:
70
+ store[user.id] = user
71
+
72
+ findById(id: string) -> User | null:
73
+ return store[id] ?? null
74
+
75
+ repo = InMemoryUserRepository()
76
+ service = UserService(repo)
77
+ service.register(User(id: "1", name: "Alice"))
78
+ found = service.findById("1")
79
+ assert found.name == "Alice"
80
+ ```
81
+
82
+ Use when behavior of the dependency matters across multiple interactions — state needs to persist between calls within a test or across a suite. Prefer fakes over chains of stubs when a test involves multiple reads and writes through the same dependency.
83
+
84
+ **Anti-pattern**: A fake that replicates production logic rather than simplifying it. If it can fail in the same ways as the real implementation, you have a second production system to maintain.
85
+
86
+ ---
87
+
88
+ ### Spy
89
+
90
+ Records calls made to it for assertion after the fact. Can wrap a real or stub implementation.
91
+
92
+ ```
93
+ interface EmailSender:
94
+ send(to: string, subject: string, body: string) -> void
95
+
96
+ class SpyEmailSender implements EmailSender:
97
+ calls: List<{to, subject, body}> = []
98
+
99
+ send(to: string, subject: string, body: string) -> void:
100
+ calls.append({to, subject, body})
101
+
102
+ sender = SpyEmailSender()
103
+ notifications = NotificationService(emailSender: sender)
104
+ notifications.notifyShipped(orderId: "99")
105
+
106
+ assert sender.calls.length == 1
107
+ assert sender.calls[0].to == "customer@example.com"
108
+ ```
109
+
110
+ Use when you want to verify a side effect occurred — something was sent, published, logged — without caring about how the dependency processed it internally. The observable outcome is the fact of the call.
111
+
112
+ **Anti-pattern**: Asserting on every argument of every call regardless of whether it is contractually meaningful. This locks the test to implementation specifics. Assert on what the behavior guarantees, not the full call signature.
113
+
114
+ ---
115
+
116
+ ### Mock
117
+
118
+ Pre-programmed with expectations verified at end of test. Combines stub (return values) with spy (call verification) but defines expectations upfront rather than asserting after.
119
+
120
+ ```
121
+ mock = Mock(PaymentGateway)
122
+ mock.expect(charge(amount: 49.99, currency: "EUR")).returns(SuccessResult).once()
123
+
124
+ order = Order(gateway: mock)
125
+ order.confirm()
126
+
127
+ mock.verify() // fails if charge was not called exactly as specified
128
+ ```
129
+
130
+ Use when the interaction with the dependency _is_ the behavior under test — not just a side effect, but the core observable outcome. Payment gateways called with correct parameters, events published to a message broker, audit logs written with specific content.
131
+
132
+ **Anti-pattern — over-mocking**: Mocking every collaborator regardless of whether the interaction is the behavior under test. Over-mocked tests verify _how_ code works, not _what_ it does. They break on every internal refactor even when behavior is unchanged.
133
+
134
+ **Anti-pattern — mocking internals**: Only mock at the boundary of what you own. Never mock a collaborator that lives inside the same module as the code under test. If you need to, the module boundary is in the wrong place.
135
+
136
+ ---
137
+
138
+ ## Decision Guide
139
+
140
+ ```
141
+ Does the dependency need to return a value the code under test consumes?
142
+ └─ Does state need to persist across multiple calls in the same test?
143
+ Yes → Fake
144
+ No → Stub
145
+
146
+ Is the interaction with the dependency itself the observable outcome?
147
+ └─ Does the exact call sequence or count matter to the behavior?
148
+ Yes → Mock
149
+ No → Spy
150
+
151
+ Is the dependency required by the signature but never invoked?
152
+ Yes → Dummy
153
+ ```
154
+
155
+ ---
156
+
157
+ ## Where to Draw the Mock Boundary
158
+
159
+ Mock at the edge of what you own. A boundary is any dependency your code calls but does not define:
160
+
161
+ - External services — HTTP APIs, payment gateways, identity providers
162
+ - Infrastructure — databases, file systems, caches, message queues
163
+ - Non-determinism — system clock, random number generation, environment variables
164
+ - Modules you do not control in this test
165
+
166
+ Do not mock:
167
+
168
+ - Classes and functions within the same module as the code under test
169
+ - Value objects and domain entities
170
+ - Pure functions
171
+
172
+ The test for "should I mock this?" is: _if I refactor the internal structure without changing observable behavior, would this double break?_ If yes, it is coupled to an implementation detail, not a boundary.
@@ -0,0 +1,215 @@
1
+ # Test Patterns
2
+
3
+ Patterns for structuring, naming, and asserting in tests. The goal throughout is that each test reads as an unambiguous specification of a behavior, fails with a message that diagnoses the problem without requiring a debugger, and survives refactors that leave the behavior intact.
4
+
5
+ ---
6
+
7
+ ## Structure: Arrange / Act / Assert
8
+
9
+ Every test has three phases. Keep them visually distinct.
10
+
11
+ ```
12
+ test "order total includes tax when region is taxable":
13
+ // Arrange — set up subject and inputs
14
+ repo = InMemoryProductRepository()
15
+ pricing = StubPricingService(basePrice: 100.00)
16
+ order = Order(repo: repo, pricing: pricing, region: Region.EU)
17
+
18
+ // Act — invoke exactly one behavior
19
+ total = order.calculate()
20
+
21
+ // Assert — verify the observable outcome
22
+ assert total == 120.00
23
+ ```
24
+
25
+ Each section should be present and identifiable. If the arrange section grows beyond five or six lines, move fixture construction into a builder (see below). If the assert section checks more than one distinct concern, split the test.
26
+
27
+ **Anti-pattern — multiple acts**: Two calls to the system under test in a single test. When the test fails, you cannot tell which act caused it.
28
+
29
+ **Anti-pattern — assertion-free tests**: A test that exercises code but asserts nothing. It can only catch exceptions — it is blind to wrong output.
30
+
31
+ ---
32
+
33
+ ## Naming
34
+
35
+ A test name is a specification statement. It should describe the behavior, the condition, and the expected outcome — not the method being called.
36
+
37
+ Prefer the form: `[subject] [does what] when [condition]`
38
+
39
+ Or equivalently: `given [context], [subject] [does what]`
40
+
41
+ ```
42
+ // Poor — names the method, not the behavior
43
+ test "calculateTotal"
44
+ test "getUser returns user"
45
+ test "processPayment test"
46
+
47
+ // Good — specifies behavior under a condition
48
+ test "order total includes tax when region is EU"
49
+ test "user lookup returns null when id does not exist"
50
+ test "payment is declined when card has insufficient funds"
51
+ ```
52
+
53
+ The test name is the first thing read when a test fails. It should make the expected behavior obvious without opening the test body.
54
+
55
+ **Anti-pattern**: Naming tests after implementation units (class names, method names). These names survive refactors that change the behavior they were meant to specify.
56
+
57
+ ---
58
+
59
+ ## One Behavior Per Test
60
+
61
+ Each test specifies one behavioral claim. Multiple assertions are acceptable when they describe facets of the same observable outcome — but each assertion should be about the same behavior, not about separate behaviors.
62
+
63
+ ```
64
+ // Acceptable — both assertions describe the same outcome (confirmed order state)
65
+ test "order is marked confirmed and assigned a reference when payment succeeds":
66
+ order = Order(gateway: SucceedingPaymentGateway())
67
+ order.confirm()
68
+ assert order.status == Status.CONFIRMED
69
+ assert order.reference != null
70
+
71
+ // Problematic — two separate behaviors in one test
72
+ test "order confirmation and email":
73
+ order = Order(gateway: SucceedingPaymentGateway(), emailSender: SpyEmailSender())
74
+ order.confirm()
75
+ assert order.status == Status.CONFIRMED // behavior 1
76
+ assert emailSender.calls.length == 1 // behavior 2 — split this out
77
+ ```
78
+
79
+ When two unrelated behaviors are tested together, a failure on the first assertion hides whether the second behavior was correct.
80
+
81
+ ---
82
+
83
+ ## Assertion Quality
84
+
85
+ An assertion should tell you what the actual value was, what was expected, and in which context — without requiring a debugger.
86
+
87
+ ```
88
+ // Weak — tells you a boolean was false; nothing else
89
+ assert order.isValid()
90
+
91
+ // Strong — tells you the field, actual value, and expectation
92
+ assert order.status == Status.CONFIRMED,
93
+ message: "expected CONFIRMED after payment but got {order.status}"
94
+ ```
95
+
96
+ For collection assertions, assert on specific elements rather than the whole structure unless the entire structure is the contract:
97
+
98
+ ```
99
+ // Fragile — breaks if unrelated elements are added to the list
100
+ assert notifications == [Notification(type: "SHIPPED", userId: "1")]
101
+
102
+ // Resilient — asserts on what the behavior guarantees
103
+ assert notifications.any(n -> n.type == "SHIPPED" and n.userId == "1")
104
+ ```
105
+
106
+ **Anti-pattern**: Catching exceptions in the test body to inspect them without re-throwing. If the assertion fails, the test passes silently.
107
+
108
+ ```
109
+ // Wrong
110
+ try:
111
+ order.confirm()
112
+ catch PaymentError as e:
113
+ assert e.code == "INSUFFICIENT_FUNDS"
114
+ // If confirm() does NOT throw, the test passes — the behavior is untested
115
+
116
+ // Correct — use your framework's assert-throws primitive
117
+ assertThrows(PaymentError, code: "INSUFFICIENT_FUNDS"):
118
+ order.confirm()
119
+ ```
120
+
121
+ ---
122
+
123
+ ## Fixture Patterns
124
+
125
+ Complex objects required as inputs should be constructed through patterns that keep test bodies readable and resilient to schema changes.
126
+
127
+ ### Object Mother
128
+
129
+ A factory that produces canonical, pre-configured instances for a domain concept. Good for objects whose exact values rarely matter to the test.
130
+
131
+ ```
132
+ class OrderMother:
133
+ static standard() -> Order:
134
+ return Order(
135
+ id: "order-1",
136
+ items: [Item(productId: "p-1", quantity: 1)],
137
+ region: Region.DOMESTIC,
138
+ status: Status.PENDING
139
+ )
140
+
141
+ static withRegion(region: Region) -> Order:
142
+ return Order(
143
+ id: "order-1",
144
+ items: [Item(productId: "p-1", quantity: 1)],
145
+ region: region,
146
+ status: Status.PENDING
147
+ )
148
+
149
+ // Usage
150
+ test "tax is applied for EU orders":
151
+ order = OrderMother.withRegion(Region.EU)
152
+ ...
153
+ ```
154
+
155
+ Use Object Mother when tests share a canonical form and only vary on one or two attributes.
156
+
157
+ **Anti-pattern**: An Object Mother with dozens of methods for every possible combination. Use a builder instead.
158
+
159
+ ---
160
+
161
+ ### Test Data Builder
162
+
163
+ A fluent builder that constructs objects incrementally. Each call returns the builder for chaining. Use when tests vary on many combinations of attributes.
164
+
165
+ ```
166
+ class OrderBuilder:
167
+ _id: string = "order-1"
168
+ _region: Region = Region.DOMESTIC
169
+ _status: Status = Status.PENDING
170
+ _items: List = [Item(productId: "p-1", quantity: 1)]
171
+
172
+ withId(id: string) -> OrderBuilder:
173
+ _id = id; return this
174
+
175
+ withRegion(region: Region) -> OrderBuilder:
176
+ _region = region; return this
177
+
178
+ withStatus(status: Status) -> OrderBuilder:
179
+ _status = status; return this
180
+
181
+ build() -> Order:
182
+ return Order(id: _id, region: _region, status: _status, items: _items)
183
+
184
+ // Usage
185
+ test "cancelled orders cannot be confirmed":
186
+ order = OrderBuilder().withStatus(Status.CANCELLED).build()
187
+ assertThrows(InvalidStateError):
188
+ order.confirm()
189
+ ```
190
+
191
+ The builder always has defaults for every field. A test only specifies the fields that are meaningful to its behavior — everything else is noise suppressed by the default.
192
+
193
+ ---
194
+
195
+ ## Test Pyramid
196
+
197
+ Not all tests operate at the same level. The pyramid describes the recommended distribution: many fast, narrowly-focused tests at the base; fewer, broader tests toward the top.
198
+
199
+ ```
200
+ [ End-to-End ] few — verify system behavior from the outside
201
+ [ Integration ] moderate — verify collaboration across real components
202
+ [ Unit Tests ] many — verify behavior of a single component in isolation
203
+ ```
204
+
205
+ **Unit tests** — one component, collaborators doubled at boundaries. Fast, deterministic, run on every change. Cover the majority of behavioral cases including edge cases and error paths.
206
+
207
+ **Integration tests** — two or more real components wired together, typically including one real infrastructure dependency (a database, a message broker). Verify that components collaborate correctly. Slower; run before merge or deploy.
208
+
209
+ **End-to-end tests** — the full system exercised from its outermost interface (HTTP endpoint, CLI, UI). Verify critical paths work from the user's perspective. Slow, potentially flaky; kept minimal and focused on the behaviors that represent the most risk if broken.
210
+
211
+ The London school (default here for unit tests) draws the unit boundary at a single class or function, doubling collaborators at module edges. The Chicago school draws the unit boundary at a cluster of related objects, wiring real collaborators and only doubling external infrastructure. Both are valid; the choice determines where your doubles live, not whether you write tests.
212
+
213
+ **Anti-pattern — inverting the pyramid**: More end-to-end tests than unit tests. End-to-end tests are slow, brittle, and give poor failure diagnostics. Relying on them means behavioral regressions are caught late and are expensive to diagnose.
214
+
215
+ **Anti-pattern — the ice cream cone**: A large suite of manual or UI tests at the top, almost no automated tests below. Common in codebases where testing was retrofitted rather than practiced from the start.