github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/pkg/curl/mock_schemes.go (about)

     1  // Copyright 2017-2018 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package curl
     6  
     7  import (
     8  	"errors"
     9  	"io"
    10  	"net/url"
    11  	"path"
    12  	"strings"
    13  )
    14  
    15  // MockScheme is a Scheme mock for testing.
    16  type MockScheme struct {
    17  	// scheme is the scheme name.
    18  	Scheme string
    19  
    20  	// hosts is a map of host -> relative filename to host -> file contents.
    21  	hosts map[string]map[string]string
    22  
    23  	// numCalled is a map of URL string -> number of times Fetch has been
    24  	// called on that URL.
    25  	numCalled map[string]uint
    26  }
    27  
    28  // NewMockScheme creates a new MockScheme with the given scheme name.
    29  func NewMockScheme(scheme string) *MockScheme {
    30  	return &MockScheme{
    31  		Scheme:    scheme,
    32  		hosts:     make(map[string]map[string]string),
    33  		numCalled: make(map[string]uint),
    34  	}
    35  }
    36  
    37  // Add adds a file to the MockScheme
    38  func (m *MockScheme) Add(host string, p string, content string) {
    39  	_, ok := m.hosts[host]
    40  	if !ok {
    41  		m.hosts[host] = make(map[string]string)
    42  	}
    43  
    44  	m.hosts[host][path.Clean(p)] = content
    45  }
    46  
    47  // NumCalled returns how many times a url has been looked up.
    48  func (m *MockScheme) NumCalled(u *url.URL) uint {
    49  	url := u.String()
    50  	if c, ok := m.numCalled[url]; ok {
    51  		return c
    52  	}
    53  	return 0
    54  }
    55  
    56  var (
    57  	// ErrWrongScheme means the wrong mocked scheme was used.
    58  	ErrWrongScheme = errors.New("wrong scheme")
    59  	// ErrNoSuchHost means there is no host record in the mock.
    60  	ErrNoSuchHost = errors.New("no such host exists")
    61  	// ErrNoSuchFile means there is no file record in the mock.
    62  	ErrNoSuchFile = errors.New("no such file exists on this host")
    63  )
    64  
    65  // Fetch implements FileScheme.Fetch.
    66  func (m *MockScheme) Fetch(u *url.URL) (io.ReaderAt, error) {
    67  	url := u.String()
    68  	m.numCalled[url]++
    69  
    70  	if u.Scheme != m.Scheme {
    71  		return nil, ErrWrongScheme
    72  	}
    73  
    74  	files, ok := m.hosts[u.Host]
    75  	if !ok {
    76  		return nil, ErrNoSuchHost
    77  	}
    78  
    79  	content, ok := files[path.Clean(u.Path)]
    80  	if !ok {
    81  		return nil, ErrNoSuchFile
    82  	}
    83  	return strings.NewReader(content), nil
    84  }