context.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  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 testutil contains helper functions for writing tests.
  15. package testutil
  16. import (
  17. "io/ioutil"
  18. "log"
  19. "os"
  20. "golang.org/x/net/context"
  21. "golang.org/x/oauth2"
  22. "golang.org/x/oauth2/google"
  23. "google.golang.org/cloud"
  24. )
  25. const (
  26. envProjID = "GCLOUD_TESTS_GOLANG_PROJECT_ID"
  27. envPrivateKey = "GCLOUD_TESTS_GOLANG_KEY"
  28. )
  29. // ProjID returns the project ID to use in integration tests, or the empty
  30. // string if none is configured.
  31. func ProjID() string {
  32. projID := os.Getenv(envProjID)
  33. if projID == "" {
  34. return ""
  35. }
  36. return projID
  37. }
  38. // TokenSource returns the OAuth2 token source to use in integration tests,
  39. // or nil if none is configured. TokenSource will log.Fatal if the token
  40. // source is specified but missing or invalid.
  41. func TokenSource(ctx context.Context, scopes ...string) oauth2.TokenSource {
  42. key := os.Getenv(envPrivateKey)
  43. if key == "" {
  44. return nil
  45. }
  46. jsonKey, err := ioutil.ReadFile(key)
  47. if err != nil {
  48. log.Fatalf("Cannot read the JSON key file, err: %v", err)
  49. }
  50. conf, err := google.JWTConfigFromJSON(jsonKey, scopes...)
  51. if err != nil {
  52. log.Fatalf("google.JWTConfigFromJSON: %v", err)
  53. }
  54. return conf.TokenSource(ctx)
  55. }
  56. // TODO(djd): Delete this function when it's no longer used.
  57. func Context(scopes ...string) context.Context {
  58. ctx := oauth2.NoContext
  59. ts := TokenSource(ctx, scopes...)
  60. if ts == nil {
  61. return nil
  62. }
  63. return cloud.NewContext(ProjID(), oauth2.NewClient(ctx, ts))
  64. }