github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/tt/tt_test.go (about) 1 package tt 2 3 import ( 4 "fmt" 5 "testing" 6 ) 7 8 // testT implements the T interface and is used to verify the Test function's 9 // interaction with T. 10 type testT []string 11 12 func (t *testT) Helper() {} 13 14 func (t *testT) Errorf(format string, args ...interface{}) { 15 *t = append(*t, fmt.Sprintf(format, args...)) 16 } 17 18 // Simple functions to test. 19 20 func add(x, y int) int { 21 return x + y 22 } 23 24 func addsub(x int, y int) (int, int) { 25 return x + y, x - y 26 } 27 28 func TestTTPass(t *testing.T) { 29 var testT testT 30 Test(&testT, Fn("addsub", addsub), Table{ 31 Args(1, 10).Rets(11, -9), 32 }) 33 if len(testT) > 0 { 34 t.Errorf("Test errors when test should pass") 35 } 36 } 37 38 func TestTTFailDefaultFmtOneReturn(t *testing.T) { 39 var testT testT 40 Test(&testT, 41 Fn("add", add), 42 Table{Args(1, 10).Rets(12)}, 43 ) 44 assertOneError(t, testT, "add(1, 10) -> 11, want 12") 45 } 46 47 func TestTTFailDefaultFmtMultiReturn(t *testing.T) { 48 var testT testT 49 Test(&testT, 50 Fn("addsub", addsub), 51 Table{Args(1, 10).Rets(11, -90)}, 52 ) 53 assertOneError(t, testT, "addsub(1, 10) -> (11, -9), want (11, -90)") 54 } 55 56 func TestTTFailCustomFmt(t *testing.T) { 57 var testT testT 58 Test(&testT, 59 Fn("addsub", addsub).ArgsFmt("x = %d, y = %d").RetsFmt("(a = %d, b = %d)"), 60 Table{Args(1, 10).Rets(11, -90)}, 61 ) 62 assertOneError(t, testT, 63 "addsub(x = 1, y = 10) -> (a = 11, b = -9), want (a = 11, b = -90)") 64 } 65 66 func assertOneError(t *testing.T, testT testT, want string) { 67 switch len(testT) { 68 case 0: 69 t.Errorf("Test didn't error when it should") 70 case 1: 71 if testT[0] != want { 72 t.Errorf("Test wrote message %q, want %q", testT[0], want) 73 } 74 default: 75 t.Errorf("Test wrote too many error messages") 76 } 77 }