Exercism: Go version of the 'Clock' exercise.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.2 KiB

  1. package clock
  2. import (
  3. "reflect"
  4. "testing"
  5. )
  6. // Clock type API:
  7. //
  8. // New(hour, minute int) Clock // a "constructor"
  9. // (Clock) String() string // a "stringer"
  10. // (Clock) Add(minutes int) Clock
  11. //
  12. // The Add method should also handle subtraction by accepting negative values.
  13. // To satisfy the readme requirement about clocks being equal, values of
  14. // your Clock type need to work with the == operator.
  15. //
  16. // It might help to study the time.Time type in the standard library
  17. // (https://golang.org/pkg/time/#Time) as a model. See how constructors there
  18. // (Date and Now) return Time values rather than pointers. Note also how
  19. // most time.Time methods have value receivers rather than pointer receivers.
  20. // For more background on this read
  21. // https://github.com/golang/go/wiki/CodeReviewComments#receiver-type.
  22. const targetTestVersion = 3
  23. func TestCreateClock(t *testing.T) {
  24. if testVersion != targetTestVersion {
  25. t.Fatalf("Found testVersion = %v, want %v", testVersion, targetTestVersion)
  26. }
  27. for _, n := range timeTests {
  28. if got := New(n.h, n.m); got.String() != n.want {
  29. t.Fatalf("New(%d, %d) = %q, want %q", n.h, n.m, got, n.want)
  30. }
  31. }
  32. t.Log(len(timeTests), "test cases")
  33. }
  34. func TestAddMinutes(t *testing.T) {
  35. for _, a := range addTests {
  36. if got := New(a.h, a.m).Add(a.a); got.String() != a.want {
  37. t.Fatalf("New(%d, %d).Add(%d) = %q, want %q",
  38. a.h, a.m, a.a, got, a.want)
  39. }
  40. }
  41. t.Log(len(addTests), "test cases")
  42. }
  43. func TestCompareClocks(t *testing.T) {
  44. for _, e := range eqTests {
  45. clock1 := New(e.c1.h, e.c1.m)
  46. clock2 := New(e.c2.h, e.c2.m)
  47. got := clock1 == clock2
  48. if got != e.want {
  49. t.Log("Clock1:", clock1)
  50. t.Log("Clock2:", clock2)
  51. t.Logf("Clock1 == Clock2 is %t, want %t", got, e.want)
  52. if reflect.DeepEqual(clock1, clock2) {
  53. t.Log("(Hint: see comments in clock_test.go.)")
  54. }
  55. t.FailNow()
  56. }
  57. }
  58. t.Log(len(eqTests), "test cases")
  59. }
  60. func BenchmarkAddMinutes(b *testing.B) {
  61. c := New(12, 0)
  62. b.ResetTimer()
  63. for i := 0; i < b.N; i++ {
  64. for _, a := range addTests {
  65. c.Add(a.a)
  66. }
  67. }
  68. }
  69. func BenchmarkCreateClocks(b *testing.B) {
  70. for i := 0; i < b.N; i++ {
  71. for _, n := range timeTests {
  72. New(n.h, n.m)
  73. }
  74. }
  75. }