Exercism: Go version of the 'Gigasecond' 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.

58 lines
1.3 KiB

6 years ago
  1. package gigasecond
  2. // Write a function AddGigasecond that works with time.Time.
  3. import (
  4. "os"
  5. "testing"
  6. "time"
  7. )
  8. // date formats used in test data
  9. const (
  10. fmtD = "2006-01-02"
  11. fmtDT = "2006-01-02T15:04:05"
  12. )
  13. func TestAddGigasecond(t *testing.T) {
  14. for _, tc := range addCases {
  15. in := parse(tc.in, t)
  16. want := parse(tc.want, t)
  17. got := AddGigasecond(in)
  18. if !got.Equal(want) {
  19. t.Fatalf(`FAIL: %s
  20. AddGigasecond(%s)
  21. = %s
  22. want %s`, tc.description, in, got, want)
  23. }
  24. t.Log("PASS:", tc.description)
  25. }
  26. t.Log("Tested", len(addCases), "cases.")
  27. }
  28. func parse(s string, t *testing.T) time.Time {
  29. tt, err := time.Parse(fmtDT, s) // try full date time format first
  30. if err != nil {
  31. tt, err = time.Parse(fmtD, s) // also allow just date
  32. }
  33. if err != nil {
  34. // can't run tests if input won't parse. if this seems to be a
  35. // development or ci environment, raise an error. if this condition
  36. // makes it to the solver though, ask for a bug report.
  37. _, statErr := os.Stat("example_gen.go")
  38. if statErr == nil || os.Getenv("TRAVIS_GO_VERSION") > "" {
  39. t.Fatal(err)
  40. } else {
  41. t.Log(err)
  42. t.Skip("(This is not your fault, and is unexpected. " +
  43. "Please file an issue at https://github.com/exercism/go.)")
  44. }
  45. }
  46. return tt
  47. }
  48. func BenchmarkAddGigasecond(b *testing.B) {
  49. for i := 0; i < b.N; i++ {
  50. AddGigasecond(time.Time{})
  51. }
  52. }