dnsclient_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package net
  5. import (
  6. "math/rand"
  7. "testing"
  8. )
  9. func checkDistribution(t *testing.T, data []*SRV, margin float64) {
  10. sum := 0
  11. for _, srv := range data {
  12. sum += int(srv.Weight)
  13. }
  14. results := make(map[string]int)
  15. count := 1000
  16. for j := 0; j < count; j++ {
  17. d := make([]*SRV, len(data))
  18. copy(d, data)
  19. byPriorityWeight(d).shuffleByWeight()
  20. key := d[0].Target
  21. results[key] = results[key] + 1
  22. }
  23. actual := results[data[0].Target]
  24. expected := float64(count) * float64(data[0].Weight) / float64(sum)
  25. diff := float64(actual) - expected
  26. t.Logf("actual: %v diff: %v e: %v m: %v", actual, diff, expected, margin)
  27. if diff < 0 {
  28. diff = -diff
  29. }
  30. if diff > (expected * margin) {
  31. t.Errorf("missed target weight: expected %v, %v", expected, actual)
  32. }
  33. }
  34. func testUniformity(t *testing.T, size int, margin float64) {
  35. rand.Seed(1)
  36. data := make([]*SRV, size)
  37. for i := 0; i < size; i++ {
  38. data[i] = &SRV{Target: string('a' + i), Weight: 1}
  39. }
  40. checkDistribution(t, data, margin)
  41. }
  42. func TestUniformity(t *testing.T) {
  43. testUniformity(t, 2, 0.05)
  44. testUniformity(t, 3, 0.10)
  45. testUniformity(t, 10, 0.20)
  46. testWeighting(t, 0.05)
  47. }
  48. func testWeighting(t *testing.T, margin float64) {
  49. rand.Seed(1)
  50. data := []*SRV{
  51. {Target: "a", Weight: 60},
  52. {Target: "b", Weight: 30},
  53. {Target: "c", Weight: 10},
  54. }
  55. checkDistribution(t, data, margin)
  56. }
  57. func TestWeighting(t *testing.T) {
  58. testWeighting(t, 0.05)
  59. }