flow_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2014 The Go Authors.
  2. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS
  3. // Licensed under the same terms as Go itself:
  4. // https://code.google.com/p/go/source/browse/LICENSE
  5. package http2
  6. import (
  7. "testing"
  8. "time"
  9. )
  10. func TestFlow(t *testing.T) {
  11. f := newFlow(10)
  12. if got, want := f.cur(), int32(10); got != want {
  13. t.Fatalf("size = %d; want %d", got, want)
  14. }
  15. if got, want := f.wait(1), int32(1); got != want {
  16. t.Errorf("wait = %d; want %d", got, want)
  17. }
  18. if got, want := f.cur(), int32(9); got != want {
  19. t.Fatalf("size = %d; want %d", got, want)
  20. }
  21. if got, want := f.wait(20), int32(9); got != want {
  22. t.Errorf("wait = %d; want %d", got, want)
  23. }
  24. if got, want := f.cur(), int32(0); got != want {
  25. t.Fatalf("size = %d; want %d", got, want)
  26. }
  27. // Wait for 10, which should block, so start a background goroutine
  28. // to refill it.
  29. go func() {
  30. time.Sleep(50 * time.Millisecond)
  31. f.add(50)
  32. }()
  33. if got, want := f.wait(1), int32(1); got != want {
  34. t.Errorf("after block, got %d; want %d", got, want)
  35. }
  36. if got, want := f.cur(), int32(49); got != want {
  37. t.Fatalf("size = %d; want %d", got, want)
  38. }
  39. }
  40. func TestFlowAdd(t *testing.T) {
  41. f := newFlow(0)
  42. if !f.add(1) {
  43. t.Fatal("failed to add 1")
  44. }
  45. if !f.add(-1) {
  46. t.Fatal("failed to add -1")
  47. }
  48. if got, want := f.cur(), int32(0); got != want {
  49. t.Fatalf("size = %d; want %d", got, want)
  50. }
  51. if !f.add(1<<31 - 1) {
  52. t.Fatal("failed to add 2^31-1")
  53. }
  54. if got, want := f.cur(), int32(1<<31-1); got != want {
  55. t.Fatalf("size = %d; want %d", got, want)
  56. }
  57. if f.add(1) {
  58. t.Fatal("adding 1 to max shouldn't be allowed")
  59. }
  60. }
  61. func TestFlowClose(t *testing.T) {
  62. f := newFlow(0)
  63. // Wait for 10, which should block, so start a background goroutine
  64. // to refill it.
  65. go func() {
  66. time.Sleep(50 * time.Millisecond)
  67. f.close()
  68. }()
  69. gotc := make(chan int32)
  70. go func() {
  71. gotc <- f.wait(1)
  72. }()
  73. select {
  74. case got := <-gotc:
  75. if got != 0 {
  76. t.Errorf("got %d; want 0", got)
  77. }
  78. case <-time.After(2 * time.Second):
  79. t.Error("timeout")
  80. }
  81. }