-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvoke_test.go
More file actions
469 lines (395 loc) · 11.1 KB
/
invoke_test.go
File metadata and controls
469 lines (395 loc) · 11.1 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
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
package statekit_test
import (
"context"
"errors"
"sync"
"testing"
"time"
"go.klarlabs.de/statekit"
"go.klarlabs.de/statekit/internal/ir"
)
// TestInvoke_ServiceStartsOnEntry verifies that a service is started when entering a state
func TestInvoke_ServiceStartsOnEntry(t *testing.T) {
t.Parallel()
serviceStarted := false
var wg sync.WaitGroup
wg.Add(1)
machine, err := statekit.NewMachine[struct{}]("test").
WithInitial("loading").
WithService("fetchData", func(ctx ir.ServiceContext[struct{}]) error {
serviceStarted = true
wg.Done()
// Block until cancelled
<-ctx.Context.(context.Context).Done()
return nil
}).
State("loading").
Invoke("fetchData").End().
Done().
State("done").Final().
Done().
Build()
if err != nil {
t.Fatalf("Failed to build machine: %v", err)
}
interp := statekit.NewInterpreter(machine)
interp.Start()
// Wait for service to start
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
// Service started
case <-time.After(time.Second):
t.Fatal("Service did not start")
}
if !serviceStarted {
t.Error("Expected service to be started")
}
interp.Stop()
}
// TestInvoke_ServiceCancelledOnExit verifies that a service is cancelled when exiting a state
func TestInvoke_ServiceCancelledOnExit(t *testing.T) {
t.Parallel()
serviceCancelled := false
serviceStarted := make(chan struct{})
serviceDone := make(chan struct{})
machine, err := statekit.NewMachine[struct{}]("test").
WithInitial("loading").
WithService("fetchData", func(ctx ir.ServiceContext[struct{}]) error {
close(serviceStarted)
<-ctx.Context.(context.Context).Done()
serviceCancelled = true
close(serviceDone)
return nil
}).
State("loading").
Invoke("fetchData").End().
On("CANCEL").Target("idle").
Done().
State("idle").
Done().
Build()
if err != nil {
t.Fatalf("Failed to build machine: %v", err)
}
interp := statekit.NewInterpreter(machine)
interp.Start()
// Wait for service to start
select {
case <-serviceStarted:
case <-time.After(time.Second):
t.Fatal("Service did not start")
}
// Transition away from loading - should cancel the service
interp.Send(statekit.Event{Type: "CANCEL"})
// Wait for service to be cancelled
select {
case <-serviceDone:
case <-time.After(time.Second):
t.Fatal("Service was not cancelled")
}
if !serviceCancelled {
t.Error("Expected service to be cancelled")
}
}
// TestInvoke_OnDoneTransition verifies that OnDone triggers a transition when service completes
func TestInvoke_OnDoneTransition(t *testing.T) {
t.Parallel()
machine, err := statekit.NewMachine[struct{}]("test").
WithInitial("loading").
WithService("fetchData", func(ctx ir.ServiceContext[struct{}]) error {
// Complete immediately
return nil
}).
State("loading").
Invoke("fetchData").OnDone("success").End().
Done().
State("success").Final().
Done().
Build()
if err != nil {
t.Fatalf("Failed to build machine: %v", err)
}
interp := statekit.NewInterpreter(machine)
interp.Start()
// Wait for service to complete and transition
time.Sleep(100 * time.Millisecond)
state := interp.State()
if state.Value != "success" {
t.Errorf("Expected state 'success', got '%s'", state.Value)
}
if !interp.Done() {
t.Error("Expected machine to be done")
}
}
// TestInvoke_OnErrorTransition verifies that OnError triggers a transition when service fails
func TestInvoke_OnErrorTransition(t *testing.T) {
t.Parallel()
machine, err := statekit.NewMachine[struct{}]("test").
WithInitial("loading").
WithService("fetchData", func(ctx ir.ServiceContext[struct{}]) error {
return errors.New("network error")
}).
State("loading").
Invoke("fetchData").OnDone("success").OnError("failure").End().
Done().
State("success").Final().
Done().
State("failure").Final().
Done().
Build()
if err != nil {
t.Fatalf("Failed to build machine: %v", err)
}
interp := statekit.NewInterpreter(machine)
interp.Start()
// Wait for service to fail and transition
time.Sleep(100 * time.Millisecond)
state := interp.State()
if state.Value != "failure" {
t.Errorf("Expected state 'failure', got '%s'", state.Value)
}
}
// TestInvoke_OnDoneAction verifies that OnDoneAction executes when service completes
func TestInvoke_OnDoneAction(t *testing.T) {
t.Parallel()
type Context struct {
ActionExecuted bool
}
machine, err := statekit.NewMachine[Context]("test").
WithInitial("loading").
WithService("fetchData", func(ctx ir.ServiceContext[Context]) error {
return nil
}).
WithAction("setDone", func(ctx *Context, e statekit.Event) {
ctx.ActionExecuted = true
}).
State("loading").
Invoke("fetchData").OnDone("success").OnDoneAction("setDone").End().
Done().
State("success").Final().
Done().
Build()
if err != nil {
t.Fatalf("Failed to build machine: %v", err)
}
interp := statekit.NewInterpreter(machine)
interp.Start()
// Wait for service to complete
time.Sleep(100 * time.Millisecond)
state := interp.State()
if !state.Context.ActionExecuted {
t.Error("Expected action to be executed")
}
}
// TestInvoke_ServiceSendsEvents verifies that services can send events back to the machine
func TestInvoke_ServiceSendsEvents(t *testing.T) {
t.Parallel()
type Context struct {
ReceivedEvent bool
}
machine, err := statekit.NewMachine[Context]("test").
WithInitial("loading").
WithService("fetchData", func(ctx ir.ServiceContext[Context]) error {
// Send an event back to the machine
ctx.Send(statekit.Event{Type: "DATA_RECEIVED"})
// Block until cancelled
<-ctx.Context.(context.Context).Done()
return nil
}).
WithAction("markReceived", func(ctx *Context, e statekit.Event) {
ctx.ReceivedEvent = true
}).
State("loading").
Invoke("fetchData").End().
On("DATA_RECEIVED").Target("processing").Do("markReceived").
Done().
State("processing").
Done().
Build()
if err != nil {
t.Fatalf("Failed to build machine: %v", err)
}
interp := statekit.NewInterpreter(machine)
interp.Start()
// Wait for event to be processed
time.Sleep(100 * time.Millisecond)
state := interp.State()
if state.Value != "processing" {
t.Errorf("Expected state 'processing', got '%s'", state.Value)
}
if !state.Context.ReceivedEvent {
t.Error("Expected action to be executed from sent event")
}
interp.Stop()
}
// TestInvoke_MultipleServices verifies that multiple services can be invoked on a single state
func TestInvoke_MultipleServices(t *testing.T) {
t.Parallel()
service1Started := make(chan struct{})
service2Started := make(chan struct{})
machine, err := statekit.NewMachine[struct{}]("test").
WithInitial("loading").
WithService("service1", func(ctx ir.ServiceContext[struct{}]) error {
close(service1Started)
<-ctx.Context.(context.Context).Done()
return nil
}).
WithService("service2", func(ctx ir.ServiceContext[struct{}]) error {
close(service2Started)
<-ctx.Context.(context.Context).Done()
return nil
}).
State("loading").
Invoke("service1").ID("svc1").End().
Invoke("service2").ID("svc2").End().
Done().
Build()
if err != nil {
t.Fatalf("Failed to build machine: %v", err)
}
interp := statekit.NewInterpreter(machine)
interp.Start()
// Wait for both services to start
select {
case <-service1Started:
case <-time.After(time.Second):
t.Fatal("Service 1 did not start")
}
select {
case <-service2Started:
case <-time.After(time.Second):
t.Fatal("Service 2 did not start")
}
interp.Stop()
}
// TestInvoke_StopCancelsAllServices verifies that Stop() cancels all active services
func TestInvoke_StopCancelsAllServices(t *testing.T) {
t.Parallel()
var cancelled sync.WaitGroup
cancelled.Add(2)
machine, err := statekit.NewMachine[struct{}]("test").
WithInitial("loading").
WithService("service1", func(ctx ir.ServiceContext[struct{}]) error {
<-ctx.Context.(context.Context).Done()
cancelled.Done()
return nil
}).
WithService("service2", func(ctx ir.ServiceContext[struct{}]) error {
<-ctx.Context.(context.Context).Done()
cancelled.Done()
return nil
}).
State("loading").
Invoke("service1").End().
Invoke("service2").End().
Done().
Build()
if err != nil {
t.Fatalf("Failed to build machine: %v", err)
}
interp := statekit.NewInterpreter(machine)
interp.Start()
// Give services time to start
time.Sleep(50 * time.Millisecond)
// Stop should cancel all services
interp.Stop()
// Wait for both to be cancelled
done := make(chan struct{})
go func() {
cancelled.Wait()
close(done)
}()
select {
case <-done:
// All services cancelled
case <-time.After(time.Second):
t.Fatal("Not all services were cancelled")
}
}
// TestInvoke_ServiceContextHasMachineContext verifies service receives current machine context
func TestInvoke_ServiceContextHasMachineContext(t *testing.T) {
t.Parallel()
type Context struct {
Value string
}
receivedValue := ""
done := make(chan struct{})
machine, err := statekit.NewMachine[Context]("test").
WithInitial("loading").
WithContext(Context{Value: "test-value"}).
WithService("fetchData", func(ctx ir.ServiceContext[Context]) error {
receivedValue = ctx.MachineContext.Value
close(done)
return nil
}).
State("loading").
Invoke("fetchData").End().
Done().
Build()
if err != nil {
t.Fatalf("Failed to build machine: %v", err)
}
interp := statekit.NewInterpreter(machine)
interp.Start()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("Service did not complete")
}
if receivedValue != "test-value" {
t.Errorf("Expected service to receive 'test-value', got '%s'", receivedValue)
}
}
// TestInvoke_DoesNotTransitionIfStateChanged verifies completed service doesn't transition if state changed
func TestInvoke_DoesNotTransitionIfStateChanged(t *testing.T) {
t.Parallel()
serviceStarted := make(chan struct{})
serviceCanComplete := make(chan struct{})
machine, err := statekit.NewMachine[struct{}]("test").
WithInitial("loading").
WithService("slowFetch", func(ctx ir.ServiceContext[struct{}]) error {
close(serviceStarted)
// Wait until we're told we can complete
select {
case <-serviceCanComplete:
return nil
case <-ctx.Context.(context.Context).Done():
return nil
}
}).
State("loading").
Invoke("slowFetch").OnDone("success").End().
On("CANCEL").Target("cancelled").
Done().
State("success").Final().
Done().
State("cancelled").Final().
Done().
Build()
if err != nil {
t.Fatalf("Failed to build machine: %v", err)
}
interp := statekit.NewInterpreter(machine)
interp.Start()
// Wait for service to start
<-serviceStarted
// Transition away before service completes
interp.Send(statekit.Event{Type: "CANCEL"})
// Verify we're in cancelled state
if interp.State().Value != "cancelled" {
t.Errorf("Expected state 'cancelled', got '%s'", interp.State().Value)
}
// Now let the service complete
close(serviceCanComplete)
// Give time for any potential transition
time.Sleep(100 * time.Millisecond)
// Should still be in cancelled state, not success
if interp.State().Value != "cancelled" {
t.Errorf("Expected state 'cancelled' after service complete, got '%s'", interp.State().Value)
}
}