github.com/m3db/m3@v1.5.1-0.20231129193456-75a402aa583b/src/query/graphite/common/context_test.go (about) 1 // Copyright (c) 2019 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package common 22 23 import ( 24 "testing" 25 "time" 26 27 "github.com/stretchr/testify/assert" 28 "github.com/stretchr/testify/mock" 29 ) 30 31 type closerFunc func() error 32 33 func (f closerFunc) Close() error { 34 return f() 35 } 36 37 func TestChildContext(t *testing.T) { 38 var ( 39 ctx = NewTestContext() 40 childCtx = ctx.NewChildContext(NewChildContextOptions()) 41 called = false 42 ) 43 44 ctx.RegisterCloser(closerFunc(func() error { 45 called = true 46 return nil 47 })) 48 49 childCtx.Close() 50 assert.False(t, called, "child context has closed the context root") 51 52 ctx.Close() 53 assert.True(t, called, "parent context hasn't closed the context root") 54 } 55 56 type mockClient struct { 57 mock.Mock 58 } 59 60 func (m *mockClient) foo() { 61 m.Called() 62 } 63 64 func (m *mockClient) Close() error { 65 m.foo() 66 return nil 67 } 68 69 func TestContextClose(t *testing.T) { 70 client := &mockClient{} 71 client.On("foo").Return() 72 engine := NewEngine(nil) 73 ctx := NewContext(ContextOptions{Start: time.Now(), End: time.Now(), Engine: engine}) 74 ctx.RegisterCloser(client) 75 ctx.Close() 76 client.AssertCalled(t, "foo") 77 } 78 79 func TestChildContextClose(t *testing.T) { 80 client := &mockClient{} 81 client.On("foo").Return() 82 engine := NewEngine(nil) 83 ctx := NewContext(ContextOptions{Start: time.Now(), End: time.Now(), Engine: engine}) 84 childContext := ctx.NewChildContext(NewChildContextOptions()) 85 childContext.RegisterCloser(client) 86 childContext.Close() 87 client.AssertNotCalled(t, "foo") 88 ctx.Close() 89 client.AssertCalled(t, "foo") 90 }