tt_test.go 1.7 KB

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