go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/casviewer/client_test.go (about) 1 // Copyright 2020 The LUCI Authors. 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 15 package casviewer 16 17 import ( 18 "context" 19 "net/http" 20 "testing" 21 22 . "github.com/smartystreets/goconvey/convey" 23 24 "go.chromium.org/luci/server/auth/authtest" 25 "go.chromium.org/luci/server/router" 26 ) 27 28 func TestClient(t *testing.T) { 29 t.Parallel() 30 31 Convey("ClientCache", t, func() { 32 Convey("Get", func() { 33 c := newContext() 34 inst1 := "projects/test-proj/instances/inst1" 35 inst2 := "projects/test-proj/instances/inst2" 36 37 // First time, it creates a new client. 38 cl1, err := GetClient(c.Request.Context(), inst1) 39 So(err, ShouldBeNil) 40 So(cl1, ShouldNotBeNil) 41 42 // The client should be reused for the same instance. 43 cl2, err := GetClient(c.Request.Context(), inst1) 44 So(err, ShouldBeNil) 45 So(cl2, ShouldEqual, cl1) 46 47 // A new client for a different instance will be created. 48 cl3, err := GetClient(c.Request.Context(), inst2) 49 So(err, ShouldBeNil) 50 So(cl3, ShouldNotBeNil) 51 So(cl3, ShouldNotPointTo, cl1) 52 }) 53 54 Convey("Clear", func() { 55 c := newContext() 56 inst1 := "projects/test-proj/instances/inst1" 57 inst2 := "projects/test-proj/instances/inst2" 58 59 // Create clients. 60 var err error 61 _, err = GetClient(c.Request.Context(), inst1) 62 So(err, ShouldBeNil) 63 _, err = GetClient(c.Request.Context(), inst2) 64 So(err, ShouldBeNil) 65 66 cc, err := clientCache(c.Request.Context()) 67 So(err, ShouldBeNil) 68 cc.Clear() 69 70 So(cc.clients, ShouldBeEmpty) 71 }) 72 }) 73 } 74 75 // newContext creats a fake context. 76 func newContext() *router.Context { 77 cc := NewClientCache(context.Background()) 78 79 ctx := context.Background() 80 ctx = authtest.MockAuthConfig(ctx) 81 c := &router.Context{ 82 Request: (&http.Request{}).WithContext(ctx), 83 } 84 withClientCacheMW(cc)(c, func(_ *router.Context) {}) 85 return c 86 }