github.com/zaolin/u-root@v0.0.0-20200428085104-64aaafd46c6d/cmds/core/elvish/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) Errorf(format string, args ...interface{}) { 13 *t = append(*t, fmt.Sprintf(format, args...)) 14 } 15 16 // Simple functions to test. 17 18 func add(x, y int) int { 19 return x + y 20 } 21 22 func addsub(x int, y int) (int, int) { 23 return x + y, x - y 24 } 25 26 func TestTTPass(t *testing.T) { 27 var testT testT 28 Test(&testT, Fn("addsub", addsub), Table{ 29 Args(1, 10).Rets(11, -9), 30 }) 31 if len(testT) > 0 { 32 t.Errorf("Test errors when test should pass") 33 } 34 } 35 36 func TestTTFailDefaultFmtOneReturn(t *testing.T) { 37 var testT testT 38 Test(&testT, 39 Fn("add", add), 40 Table{Args(1, 10).Rets(12)}, 41 ) 42 assertOneError(t, testT, "add(1, 10) -> 11, want 12") 43 } 44 45 func TestTTFailDefaultFmtMultiReturn(t *testing.T) { 46 var testT testT 47 Test(&testT, 48 Fn("addsub", addsub), 49 Table{Args(1, 10).Rets(11, -90)}, 50 ) 51 assertOneError(t, testT, "addsub(1, 10) -> (11, -9), want (11, -90)") 52 } 53 54 func TestTTFailCustomFmt(t *testing.T) { 55 var testT testT 56 Test(&testT, 57 Fn("addsub", addsub).ArgsFmt("x = %d, y = %d").RetsFmt("(a = %d, b = %d)"), 58 Table{Args(1, 10).Rets(11, -90)}, 59 ) 60 assertOneError(t, testT, 61 "addsub(x = 1, y = 10) -> (a = 11, b = -9), want (a = 11, b = -90)") 62 } 63 64 func assertOneError(t *testing.T, testT testT, want string) { 65 switch len(testT) { 66 case 0: 67 t.Errorf("Test didn't error when it should") 68 case 1: 69 if testT[0] != want { 70 t.Errorf("Test wrote message %q, want %q", testT[0], want) 71 } 72 default: 73 t.Errorf("Test wrote too many error messages") 74 } 75 }