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

99 lines
2.3 KiB

9 years ago
  1. package triangle
  2. import (
  3. "math"
  4. "testing"
  5. )
  6. const targetTestVersion = 2
  7. type testCase struct {
  8. want Kind
  9. a, b, c float64
  10. }
  11. // basic test cases
  12. var testData = []testCase{
  13. {Equ, 2, 2, 2}, // same length
  14. {Equ, 10, 10, 10}, // a little bigger
  15. {Iso, 3, 4, 4}, // last two sides equal
  16. {Iso, 4, 3, 4}, // first and last sides equal
  17. {Iso, 4, 4, 3}, // first two sides equal
  18. {Iso, 10, 10, 2}, // again
  19. {Iso, 2, 4, 2}, // a "triangle" that is just a line is still OK
  20. {Sca, 3, 4, 5}, // no sides equal
  21. {Sca, 10, 11, 12}, // again
  22. {Sca, 5, 4, 2}, // descending order
  23. {Sca, .4, .6, .3}, // small sides
  24. {Sca, 1, 4, 3}, // a "triangle" that is just a line is still OK
  25. {NaT, 0, 0, 0}, // zero length
  26. {NaT, 3, 4, -5}, // negative length
  27. {NaT, 1, 1, 3}, // fails triangle inequality
  28. {NaT, 2, 5, 2}, // another
  29. {NaT, 7, 3, 2}, // another
  30. }
  31. // generate cases with NaN and Infs, append to basic cases
  32. func init() {
  33. nan := math.NaN()
  34. pinf := math.Inf(1)
  35. ninf := math.Inf(-1)
  36. nf := make([]testCase, 4*4*4)
  37. i := 0
  38. for _, a := range []float64{3, nan, pinf, ninf} {
  39. for _, b := range []float64{4, nan, pinf, ninf} {
  40. for _, c := range []float64{5, nan, pinf, ninf} {
  41. nf[i] = testCase{NaT, a, b, c}
  42. i++
  43. }
  44. }
  45. }
  46. testData = append(testData, nf[1:]...)
  47. }
  48. // Test that the kinds are not equal to each other.
  49. // If they are equal, then TestKind will return false positives.
  50. func TestKindsNotEqual(t *testing.T) {
  51. kindsAndNames := []struct {
  52. kind Kind
  53. name string
  54. }{
  55. {Equ, "Equ"},
  56. {Iso, "Iso"},
  57. {Sca, "Sca"},
  58. {NaT, "NaT"},
  59. }
  60. for i, pair1 := range kindsAndNames {
  61. for j := i + 1; j < len(kindsAndNames); j++ {
  62. pair2 := kindsAndNames[j]
  63. if pair1.kind == pair2.kind {
  64. t.Fatalf("%s should not be equal to %s", pair1.name, pair2.name)
  65. }
  66. }
  67. }
  68. }
  69. func TestKind(t *testing.T) {
  70. for _, test := range testData {
  71. got := KindFromSides(test.a, test.b, test.c)
  72. if got != test.want {
  73. t.Fatalf("Triangle with sides, %g, %g, %g = %v, want %v",
  74. test.a, test.b, test.c, got, test.want)
  75. }
  76. }
  77. }
  78. func TestTestVersion(t *testing.T) {
  79. if testVersion != targetTestVersion {
  80. t.Fatalf("Found testVersion = %v, want %v", testVersion, targetTestVersion)
  81. }
  82. }
  83. func BenchmarkKind(b *testing.B) {
  84. for i := 0; i < b.N; i++ {
  85. for _, test := range testData {
  86. KindFromSides(test.a, test.b, test.c)
  87. }
  88. }
  89. }