~marcopolo/di

ref: 1ba8cc87296eb180b74a9c3b24d27e3b2eba9d57 di/di_test.go -rw-r--r-- 10.8 KiB
1ba8cc87 — Marco Munizaga rename interface types and add isSet 9 months ago
                                                                                
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
package di

import (
	"crypto/tls"
	"errors"
	"fmt"
	"net/http"
	"strings"
	"testing"
)

func ExampleBuild() {
	type Username string
	type Config struct {
		User     Username
		Age      int
		Greeting func(Username, int) string
	}

	cfg := Config{
		User: "Alice",
		Age:  42,
		Greeting: func(u Username, age int) string {
			return fmt.Sprintf("Hello, %s. You've been around the sun %d times!", string(u), age)
		},
	}

	type Result struct {
		Greeting string
	}
	var res Result
	err := Build(cfg, &res)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(res.Greeting)

	// Output: Hello, Alice. You've been around the sun 42 times!
}

func ExampleNew() {
	type Username string
	type Config struct {
		User     Username
		Age      int
		Greeting func(Username, int) string
	}

	cfg := Config{
		User: "Alice",
		Age:  42,
		Greeting: func(u Username, age int) string {
			return fmt.Sprintf("Hello, %s. You've been around the sun %d times!", string(u), age)
		},
	}

	greeting, err := New[string](cfg)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(greeting)

	// Output: Hello, Alice. You've been around the sun 42 times!
}

func ExampleOptional() {
	type Config struct {
		// A *tls.Config type or Provide[*tls.Config] also works, but using the
		// Optional wrapper lets us convey the optionality explicitly
		TLSConfig Optional[*tls.Config]
		Server    Provide[*http.Server]
	}

	cfg := Config{
		Server: MustProvide[*http.Server](func(
			tlsConf Optional[*tls.Config],
		) *http.Server {
			s := &http.Server{
				Addr: ":8080",
			}
			if tlsConf.IsSome {
				s.TLSConfig = tlsConf.Val
			}
			return s
		}),
	}

	server, err := New[*http.Server](cfg)
	if err != nil {
		fmt.Println(err)
		return
	}
	if server.TLSConfig == nil {
		fmt.Println("No TLS configuration was provided")
	}

	// Output: No TLS configuration was provided
}

func ExampleSideEffect() {
	type Config struct {
		Server      *http.Server
		SideEffects []Provide[SideEffect]
	}
	type Result struct {
		StartedServer *http.Server
		_             []SideEffect
	}

	res, err := New[Result](&Config{
		Server: &http.Server{
			Addr: ":8080",
		},
		SideEffects: []Provide[SideEffect]{
			MustProvide[SideEffect](func() SideEffect {
				fmt.Println("Starting server...")
				go http.ListenAndServe(":8080", nil)
				return SideEffect{}
			}),
		},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.StartedServer.Close()

	// Output: Starting server...
}

func TestBuildSuccess(t *testing.T) {
	type A struct {
		val string
	}
	type C struct {
		val int
	}
	type B struct {
		a  *A
		cs []C
	}
	type NestedConfig struct {
		OtherSetting   bool
		NestedDecision func(c NestedConfig) uint
	}
	type ANum int
	type ConfigWithInner struct {
		NestedConfig
		SomeSetting bool
		Inner       func(c ConfigWithInner) int
	}

	tests := []struct {
		name   string
		config any
		result any
		verify func(t *testing.T, result any)
	}{
		{
			name: "complex dependencies with providers",
			config: struct {
				MakeA  Provide[*A]
				MakeB  Provide[*B]
				MakeCs []Provide[C]
			}{
				MakeA: MustProvide[*A](func() (*A, error) {
					return &A{val: "hello"}, nil
				}),
				MakeB: MustProvide[*B](func(a *A, cs []C) *B {
					return &B{a: a, cs: cs}
				}),
				MakeCs: []Provide[C]{
					MustProvide[C](C{val: 1}),
					MustProvide[C](func() (C, error) {
						return C{val: 2}, nil
					}),
				},
			},
			result: &struct {
				A *A
				B *B
			}{},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					A *A
					B *B
				})
				if res.A == nil {
					t.Fatalf("expected res.A to be populated")
				}
				if res.B == nil {
					t.Fatalf("expected res.B to be populated")
				}
				if res.B.a != res.A {
					t.Fatalf("expected B.a to reference A instance")
				}
				if len(res.B.cs) != 2 {
					t.Fatalf("wrong count. Saw %d", len(res.B.cs))
				}
				if res.B.cs[0].val != 1 {
					t.Fatalf("wrong value")
				}
				if res.B.cs[1].val != 2 {
					t.Fatalf("wrong value")
				}
				if res.A.val != "hello" {
					t.Fatalf("unexpected A value: %s", res.A.val)
				}
			},
		},
		{
			name: "simple function constructors",
			config: struct {
				MakeA func() (*A, error)
				MakeB func(*A) (*B, error)
			}{
				MakeA: func() (*A, error) {
					return &A{val: "hello"}, nil
				},
				MakeB: func(a *A) (*B, error) {
					panic("Unexpected call to MakeB")
				},
			},
			result: &struct {
				A *A
			}{},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					A *A
				})
				if res.A == nil {
					t.Fatalf("expected res.A to be populated")
				}
				if res.A.val != "hello" {
					t.Fatalf("unexpected A value: %s", res.A.val)
				}
			},
		},
		{
			name: "pre-supplied values",
			config: struct {
				A  *A
				MB func(*A) (*B, error)
			}{
				A: &A{val: "pre-supplied"},
				MB: func(a *A) (*B, error) {
					return &B{a: a}, nil
				},
			},
			result: &struct {
				A *A
				B *B
			}{},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					A *A
					B *B
				})
				if res.A == nil || res.A.val != "pre-supplied" {
					t.Fatalf("expected pre-supplied A, got %+v", res.A)
				}
				if res.B == nil || res.B.a != res.A {
					t.Fatalf("expected B referencing A, got %+v", res.B)
				}
			},
		},
		{
			name: "pre-supplied nil values",
			config: struct {
				A *A
			}{
				A: nil,
			},
			result: &struct {
				A *A
			}{},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					A *A
				})
				if res.A != nil {
					t.Fatalf("expected nil A, got %+v", res.A)
				}
			},
		},
		{
			name: "Explicit Optional Value",
			config: struct {
				A Optional[*A]
			}{},
			result: &struct {
				A Optional[*A]
			}{},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					A Optional[*A]
				})
				if res.A.IsSome {
					t.Fatalf("expected none")
				}
			},
		},
		{
			name: "Explicit Provided Optional Value",
			config: struct {
				A Optional[*A]
			}{A: Some(&A{})},
			result: &struct {
				A Optional[*A]
			}{},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					A Optional[*A]
				})
				_ = res.A.Unwrap()
			},
		},
		{
			name: "type aliases",
			config: struct {
				A ANum
				B int
			}{A: 3, B: 4},
			result: &struct {
				A ANum
			}{},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					A ANum
				})
				if res.A != 3 {
					t.Fatalf("expected A=3, got %v", res.A)
				}
			},
		},
		{
			name: "reference config in constructors",
			config: ConfigWithInner{
				SomeSetting: true,
				Inner: func(c ConfigWithInner) int {
					if c.SomeSetting {
						return 1
					}
					return 0
				},
				NestedConfig: NestedConfig{
					OtherSetting: true,
					NestedDecision: func(c NestedConfig) uint {
						if c.OtherSetting {
							return 1
						}
						return 0
					},
				},
			},
			result: &struct {
				A int
				B uint
			}{},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					A int
					B uint
				})
				if res.A != 1 {
					t.Fatalf("expected A=1, got %v", res.A)
				}
				if res.B != 1 {
					t.Fatalf("expected B=1, got %v", res.B)
				}
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			err := Build(tt.config, tt.result)
			if err != nil {
				t.Fatalf("Build failed: %v", err)
			}
			tt.verify(t, tt.result)
		})
	}
}

func TestBuildErrors(t *testing.T) {
	type A struct{}
	type B struct {
		a *A
	}
	type X struct{}
	type Y struct{}

	sentinel := errors.New("boom")

	tests := []struct {
		name           string
		config         any
		result         any
		expectedErrors []string
		verify         func(t *testing.T, result any)
	}{
		{
			name: "constructor error propagation",
			config: struct {
				MakeA func() (*A, error)
			}{
				MakeA: func() (*A, error) {
					return nil, sentinel
				},
			},
			result: &struct {
				A *A
			}{},
			expectedErrors: []string{"MakeA", "boom"},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					A *A
				})
				if res.A != nil {
					t.Fatalf("result A should not be populated on constructor failure")
				}
			},
		},
		{
			name: "missing dependency",
			config: struct {
				MakeB func(*A) (*B, error)
			}{
				MakeB: func(a *A) (*B, error) {
					return &B{a: a}, nil
				},
			},
			result: &struct {
				B *B
			}{},
			expectedErrors: []string{"*di.A", "di.A"},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					B *B
				})
				if res.B != nil {
					t.Fatalf("result B should not be populated")
				}
			},
		},
		{
			name: "cycle detection",
			config: struct {
				MakeX func(*Y) *X
				MakeY func(*X) *Y
			}{
				MakeX: func(y *Y) *X {
					return &X{}
				},
				MakeY: func(x *X) *Y {
					return &Y{}
				},
			},
			result: &struct {
				X *X
				Y *Y
			}{},
			expectedErrors: []string{"MakeX", "MakeY"},
			verify: func(t *testing.T, result any) {
				res := result.(*struct {
					X *X
					Y *Y
				})
				if res.X != nil || res.Y != nil {
					t.Fatalf("cycle should prevent any construction; got X=%v Y=%v", res.X, res.Y)
				}
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			err := Build(tt.config, tt.result)
			if err == nil {
				t.Fatalf("expected error")
			}

			errorStr := err.Error()
			var foundError bool
			for _, expectedErr := range tt.expectedErrors {
				if strings.Contains(errorStr, expectedErr) {
					foundError = true
					break
				}
			}
			if !foundError {
				t.Fatalf("expected error to contain one of %v, got: %v", tt.expectedErrors, err)
			}

			tt.verify(t, tt.result)
		})
	}
}

func TestNewFunction(t *testing.T) {
	type ANum int

	tests := []struct {
		name     string
		config   any
		expected any
	}{
		{
			name: "struct result",
			config: struct {
				A int
			}{A: 42},
			expected: struct {
				A int
			}{A: 42},
		},
		{
			name:     "primitive type result",
			config:   struct{ A int }{A: 42},
			expected: 42,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			switch expected := tt.expected.(type) {
			case struct{ A int }:
				res, err := New[struct{ A int }](tt.config)
				if err != nil {
					t.Fatalf("unexpected error: %v", err)
				}
				if res.A != expected.A {
					t.Fatalf("expected A=%d, got %v", expected.A, res.A)
				}
			case int:
				res, err := New[int](tt.config)
				if err != nil {
					t.Fatalf("unexpected error: %v", err)
				}
				if res != expected {
					t.Fatalf("expected %d, got %v", expected, res)
				}
			}
		})
	}
}

func TestBuildPrimitiveTypes(t *testing.T) {
	tests := []struct {
		name     string
		config   any
		expected int
	}{
		{
			name:     "build primitive directly",
			config:   struct{ A int }{A: 42},
			expected: 42,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var res int
			err := Build(tt.config, &res)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if res != tt.expected {
				t.Fatalf("expected %d, got %v", tt.expected, res)
			}
		})
	}
}