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.
 
 
 

81 lines
2.0 KiB

  1. // Copyright 2016 Google LLC
  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 metadata
  15. import (
  16. "bytes"
  17. "io/ioutil"
  18. "net/http"
  19. "os"
  20. "sync"
  21. "testing"
  22. )
  23. func TestOnGCE_Stress(t *testing.T) {
  24. if testing.Short() {
  25. t.Skip("skipping in -short mode")
  26. }
  27. var last bool
  28. for i := 0; i < 100; i++ {
  29. onGCEOnce = sync.Once{}
  30. now := OnGCE()
  31. if i > 0 && now != last {
  32. t.Errorf("%d. changed from %v to %v", i, last, now)
  33. }
  34. last = now
  35. }
  36. t.Logf("OnGCE() = %v", last)
  37. }
  38. func TestOnGCE_Force(t *testing.T) {
  39. onGCEOnce = sync.Once{}
  40. old := os.Getenv(metadataHostEnv)
  41. defer os.Setenv(metadataHostEnv, old)
  42. os.Setenv(metadataHostEnv, "127.0.0.1")
  43. if !OnGCE() {
  44. t.Error("OnGCE() = false; want true")
  45. }
  46. }
  47. func TestOverrideUserAgent(t *testing.T) {
  48. const userAgent = "my-user-agent"
  49. rt := &rrt{}
  50. c := NewClient(&http.Client{Transport: userAgentTransport{userAgent, rt}})
  51. c.Get("foo")
  52. if got, want := rt.gotUserAgent, userAgent; got != want {
  53. t.Errorf("got %q, want %q", got, want)
  54. }
  55. }
  56. type userAgentTransport struct {
  57. userAgent string
  58. base http.RoundTripper
  59. }
  60. func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  61. req.Header.Set("User-Agent", t.userAgent)
  62. return t.base.RoundTrip(req)
  63. }
  64. type rrt struct {
  65. gotUserAgent string
  66. }
  67. func (r *rrt) RoundTrip(req *http.Request) (*http.Response, error) {
  68. r.gotUserAgent = req.Header.Get("User-Agent")
  69. return &http.Response{Body: ioutil.NopCloser(bytes.NewReader(nil))}, nil
  70. }