1// Copyright 2021 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//     https://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
15package detect
16
17import (
18	"context"
19	"testing"
20
21	"golang.org/x/oauth2/google"
22	"google.golang.org/api/option"
23)
24
25func TestIt(t *testing.T) {
26	tests := []struct {
27		name         string
28		projectID    string
29		env          map[string]string
30		adcProjectID string
31		want         string
32	}{
33		{
34			name:      "noop",
35			projectID: "noop",
36			want:      "noop",
37		},
38		{
39			name:      "environment project id",
40			projectID: projectIDSentinel,
41			env:       map[string]string{envProjectID: "environment-project-id"},
42			want:      "environment-project-id",
43		},
44		{
45			name:         "adc project id",
46			projectID:    projectIDSentinel,
47			adcProjectID: "adc-project-id",
48			want:         "adc-project-id",
49		},
50		{
51			name:      "emulator project id",
52			projectID: projectIDSentinel,
53			env:       map[string]string{"EMULATOR_HOST": "something"},
54			want:      "emulated-project",
55		},
56	}
57
58	for _, tc := range tests {
59		t.Run(tc.name, func(t *testing.T) {
60			envLookupFunc = func(k string) string {
61				if tc.env == nil {
62					return ""
63				}
64				return tc.env[k]
65			}
66			adcLookupFunc = func(context.Context, ...option.ClientOption) (*google.Credentials, error) {
67				return &google.Credentials{ProjectID: tc.adcProjectID}, nil
68			}
69
70			got, err := ProjectID(context.Background(), tc.projectID, "EMULATOR_HOST")
71			if err != nil {
72				t.Fatalf("unexpected error from ProjectID(): %v", err)
73			}
74			if got != tc.want {
75				t.Fatalf("ProjectID() = %q, want %q", got, tc.want)
76			}
77		})
78	}
79
80}
81