gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/grpc/internal/googlecloud/googlecloud_test.go (about) 1 /* 2 * 3 * Copyright 2021 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 package googlecloud 20 21 import ( 22 "io" 23 "os" 24 "strings" 25 "testing" 26 ) 27 28 func setupManufacturerReader(testOS string, reader func() (io.Reader, error)) func() { 29 tmpOS := runningOS 30 tmpReader := manufacturerReader 31 32 // Set test OS and reader function. 33 runningOS = testOS 34 manufacturerReader = reader 35 return func() { 36 runningOS = tmpOS 37 manufacturerReader = tmpReader 38 } 39 } 40 41 func setup(testOS string, testReader io.Reader) func() { 42 reader := func() (io.Reader, error) { 43 return testReader, nil 44 } 45 return setupManufacturerReader(testOS, reader) 46 } 47 48 func setupError(testOS string, err error) func() { 49 reader := func() (io.Reader, error) { 50 return nil, err 51 } 52 return setupManufacturerReader(testOS, reader) 53 } 54 55 func TestIsRunningOnGCE(t *testing.T) { 56 for _, tc := range []struct { 57 description string 58 testOS string 59 testReader io.Reader 60 out bool 61 }{ 62 // Linux tests. 63 {"linux: not a GCP platform", "linux", strings.NewReader("not GCP"), false}, 64 {"Linux: GCP platform (Google)", "linux", strings.NewReader("Google"), true}, 65 {"Linux: GCP platform (Google Compute Engine)", "linux", strings.NewReader("Google Compute Engine"), true}, 66 {"Linux: GCP platform (Google Compute Engine) with extra spaces", "linux", strings.NewReader(" Google Compute Engine "), true}, 67 // Windows tests. 68 {"windows: not a GCP platform", "windows", strings.NewReader("not GCP"), false}, 69 {"windows: GCP platform (Google)", "windows", strings.NewReader("Google"), true}, 70 {"windows: GCP platform (Google) with extra spaces", "windows", strings.NewReader(" Google "), true}, 71 } { 72 reverseFunc := setup(tc.testOS, tc.testReader) 73 if got, want := isRunningOnGCE(), tc.out; got != want { 74 t.Errorf("%v: isRunningOnGCE()=%v, want %v", tc.description, got, want) 75 } 76 reverseFunc() 77 } 78 } 79 80 func TestIsRunningOnGCENoProductNameFile(t *testing.T) { 81 reverseFunc := setupError("linux", os.ErrNotExist) 82 if isRunningOnGCE() { 83 t.Errorf("ErrNotExist: isRunningOnGCE()=true, want false") 84 } 85 reverseFunc() 86 }