server_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2013 The Gorilla WebSocket 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 websocket
  5. import (
  6. "net/http"
  7. "reflect"
  8. "testing"
  9. )
  10. var subprotocolTests = []struct {
  11. h string
  12. protocols []string
  13. }{
  14. {"", nil},
  15. {"foo", []string{"foo"}},
  16. {"foo,bar", []string{"foo", "bar"}},
  17. {"foo, bar", []string{"foo", "bar"}},
  18. {" foo, bar", []string{"foo", "bar"}},
  19. {" foo, bar ", []string{"foo", "bar"}},
  20. }
  21. func TestSubprotocols(t *testing.T) {
  22. for _, st := range subprotocolTests {
  23. r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {st.h}}}
  24. protocols := Subprotocols(&r)
  25. if !reflect.DeepEqual(st.protocols, protocols) {
  26. t.Errorf("SubProtocols(%q) returned %#v, want %#v", st.h, protocols, st.protocols)
  27. }
  28. }
  29. }
  30. var isWebSocketUpgradeTests = []struct {
  31. ok bool
  32. h http.Header
  33. }{
  34. {false, http.Header{"Upgrade": {"websocket"}}},
  35. {false, http.Header{"Connection": {"upgrade"}}},
  36. {true, http.Header{"Connection": {"upgRade"}, "Upgrade": {"WebSocket"}}},
  37. }
  38. func TestIsWebSocketUpgrade(t *testing.T) {
  39. for _, tt := range isWebSocketUpgradeTests {
  40. ok := IsWebSocketUpgrade(&http.Request{Header: tt.h})
  41. if tt.ok != ok {
  42. t.Errorf("IsWebSocketUpgrade(%v) returned %v, want %v", tt.h, ok, tt.ok)
  43. }
  44. }
  45. }
  46. var checkSameOriginTests = []struct {
  47. ok bool
  48. r *http.Request
  49. }{
  50. {false, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": []string{"https://other.org"}}}},
  51. {true, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": []string{"https://example.org"}}}},
  52. {true, &http.Request{Host: "Example.org", Header: map[string][]string{"Origin": []string{"https://example.org"}}}},
  53. }
  54. func TestCheckSameOrigin(t *testing.T) {
  55. for _, tt := range checkSameOriginTests {
  56. ok := checkSameOrigin(tt.r)
  57. if tt.ok != ok {
  58. t.Errorf("checkSameOrigin(%+v) returned %v, want %v", tt.r, ok, tt.ok)
  59. }
  60. }
  61. }