userspace_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2016 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package tcpproxy
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "net"
  19. "net/http"
  20. "net/http/httptest"
  21. "net/url"
  22. "testing"
  23. "time"
  24. )
  25. func TestUserspaceProxy(t *testing.T) {
  26. l, err := net.Listen("tcp", "127.0.0.1:0")
  27. if err != nil {
  28. t.Fatal(err)
  29. }
  30. defer l.Close()
  31. want := "hello proxy"
  32. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  33. fmt.Fprint(w, want)
  34. }))
  35. defer ts.Close()
  36. u, err := url.Parse(ts.URL)
  37. if err != nil {
  38. t.Fatal(err)
  39. }
  40. p := tcpProxy{
  41. l: l,
  42. donec: make(chan struct{}),
  43. monitorInterval: time.Second,
  44. remotes: []*remote{
  45. {addr: u.Host},
  46. },
  47. }
  48. go p.run()
  49. defer p.stop()
  50. u.Host = l.Addr().String()
  51. res, err := http.Get(u.String())
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. got, gerr := ioutil.ReadAll(res.Body)
  56. res.Body.Close()
  57. if gerr != nil {
  58. t.Fatal(gerr)
  59. }
  60. if string(got) != want {
  61. t.Errorf("got = %s, want %s", got, want)
  62. }
  63. }