github.com/google/osv-scalibr@v0.4.1/enricher/baseimage/fakeclient_test.go (about)

     1  // Copyright 2025 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  //      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 baseimage_test
    16  
    17  import (
    18  	"context"
    19  	"errors"
    20  	"testing"
    21  
    22  	"github.com/google/osv-scalibr/enricher/baseimage"
    23  )
    24  
    25  type reqRespErr struct {
    26  	req  *baseimage.Request
    27  	resp *baseimage.Response
    28  	err  error
    29  }
    30  
    31  type config struct {
    32  	ReqRespErrs []reqRespErr
    33  }
    34  
    35  type clientFake struct {
    36  	reqRespErrs        map[baseimage.Request]reqRespErr
    37  	reqNum             int
    38  	expectedRequestNum int
    39  }
    40  
    41  func newClientFake(cfg *config) (*clientFake, error) {
    42  	if cfg == nil {
    43  		return nil, errors.New("config is nil")
    44  	}
    45  	// Defense copy to avoid mutating the config.
    46  	reqRespErrs := make(map[baseimage.Request]reqRespErr, len(cfg.ReqRespErrs))
    47  	for _, reqRespErr := range cfg.ReqRespErrs {
    48  		reqRespErrs[*reqRespErr.req] = reqRespErr
    49  	}
    50  	client := &clientFake{
    51  		reqRespErrs:        reqRespErrs,
    52  		expectedRequestNum: len(cfg.ReqRespErrs),
    53  	}
    54  	return client, nil
    55  }
    56  
    57  func mustNewClientFake(t *testing.T, cfg *config) *clientFake {
    58  	t.Helper()
    59  	baseImageClientFake, err := newClientFake(cfg)
    60  	if err != nil {
    61  		t.Fatalf("Failed to create base image client: %v", err)
    62  	}
    63  	return baseImageClientFake
    64  }
    65  
    66  func (c *clientFake) QueryContainerImages(ctx context.Context, req *baseimage.Request) (*baseimage.Response, error) {
    67  	defer func() { c.reqNum++ }()
    68  
    69  	if c.reqNum >= c.expectedRequestNum {
    70  		return nil, errors.New("out of range")
    71  	}
    72  
    73  	rre := c.reqRespErrs[*req]
    74  
    75  	return rre.resp, rre.err
    76  }