github.com/bkosm/gompose/v2@v2.3.1/testing_test.go (about) 1 package gompose 2 3 import ( 4 "fmt" 5 "net/http" 6 "testing" 7 ) 8 9 type ft struct { 10 helperCalls uint 11 fatalCalls uint 12 } 13 14 func (f *ft) Helper() { 15 f.helperCalls++ 16 } 17 18 func (f *ft) Fatal(_ ...any) { 19 f.fatalCalls++ 20 } 21 22 func TestMustTWorks(t *testing.T) { 23 t.Parallel() 24 25 t.Run("records errors", func(t *testing.T) { 26 t.Parallel() 27 28 ft := &ft{} 29 fn := MustT[*http.Request](ft) 30 31 val := fn(http.NewRequest("", "\n", nil)) 32 33 if ft.helperCalls != 1 { 34 t.Fatal("helper was not called") 35 } 36 if ft.fatalCalls != 1 { 37 t.Fatal("did not record the error") 38 } 39 if val != nil { 40 t.Fatal("did not return nil") 41 } 42 }) 43 44 t.Run("returns the value", func(t *testing.T) { 45 t.Parallel() 46 47 ft := &ft{} 48 fn := MustT[*http.Request](ft) 49 50 val := fn(http.NewRequest("", "", nil)) 51 52 if ft.helperCalls != 1 { 53 t.Fatal("helper was not called") 54 } 55 if ft.fatalCalls != 0 { 56 t.Fatal("recorded an error") 57 } 58 if val == nil { 59 t.Fatal("returned nil") 60 } 61 }) 62 63 t.Run("panics when the required methods are not present on the argument", func(t *testing.T) { 64 t.Parallel() 65 66 defer func() { 67 if err := recover(); err == nil { 68 t.Fatal("did not panic") 69 } 70 }() 71 72 fn := MustT[*http.Request](interface{}(nil)) 73 _ = fn(http.NewRequest("", "", nil)) 74 }) 75 } 76 77 var t = &ft{} 78 79 func ExampleMustT() { 80 fn := MustT[*http.Request](t) 81 82 rq := fn(http.NewRequest(http.MethodGet, fmt.Sprintf("http://localhost:%d", containerPort), nil)) 83 fmt.Println(rq.URL.Scheme) 84 // Output: 85 // http 86 }