| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package runtimecomp |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | type mockService struct{} |
| 11 | |
| 12 | func (mockService) RegisterComponent(ComponentConfig) error { return nil } |
| 13 | func (mockService) UnregisterComponent(string) {} |
| 14 | func (mockService) RegisterProducer(string, func() error) error { |
| 15 | return nil |
| 16 | } |
| 17 | func (mockService) UnregisterProducer(string) {} |
| 18 | |
| 19 | func TestContextHelpers(t *testing.T) { |
| 20 | tests := map[string]struct { |
| 21 | ctx context.Context |
| 22 | service Service |
| 23 | wantOK bool |
| 24 | }{ |
| 25 | "nil context and nil service": { |
| 26 | ctx: nil, |
| 27 | service: nil, |
| 28 | wantOK: false, |
| 29 | }, |
| 30 | "background context without service": { |
| 31 | ctx: context.Background(), |
| 32 | service: nil, |
| 33 | wantOK: false, |
| 34 | }, |
| 35 | "context with service": { |
| 36 | ctx: context.Background(), |
| 37 | service: mockService{}, |
| 38 | wantOK: true, |
| 39 | }, |
| 40 | } |
| 41 | |
| 42 | for name, test := range tests { |
| 43 | t.Run(name, func(t *testing.T) { |
| 44 | ctx := ContextWithService(test.ctx, test.service) |
| 45 | got, ok := ServiceFromContext(ctx) |
| 46 | if ok != test.wantOK { |
| 47 | t.Fatalf("ServiceFromContext() ok = %v, want %v", ok, test.wantOK) |
| 48 | } |
| 49 | if !test.wantOK { |
| 50 | if got != nil { |
| 51 | t.Fatalf("ServiceFromContext() service = %#v, want nil", got) |
| 52 | } |
| 53 | return |
| 54 | } |
| 55 | if got == nil { |
| 56 | t.Fatalf("ServiceFromContext() service = nil, want non-nil") |
| 57 | } |
| 58 | }) |
| 59 | } |
| 60 | } |