courgette/internal/driver/mock_container_driver.go

98 lines
2.6 KiB
Go

package driver
import (
"fmt"
"strings"
)
type MockCall struct {
Fname string
Args []string
}
type MockDriver struct {
Calls map[string][]MockCall
MockedCalls map[string]map[string]CommandResult
}
func NewMockDriver() MockDriver {
return MockDriver{
Calls: map[string][]MockCall{},
MockedCalls: map[string]map[string]CommandResult{},
}
}
func (d *MockDriver) Pull(uri string) error {
if _, init := d.Calls["Pull"]; !init {
d.Calls["Pull"] = []MockCall{}
}
d.Calls["Pull"] = append(d.Calls["Pull"], MockCall{Fname: "Pull", Args: []string{uri}})
return nil
}
func (d *MockDriver) Start(uri string, containerName string, cacheRoot string) error {
if _, init := d.Calls["Start"]; !init {
d.Calls["Start"] = []MockCall{}
}
d.Calls["Start"] = append(d.Calls["Start"], MockCall{Fname: "Start", Args: []string{uri, containerName}})
return nil
}
func (d *MockDriver) Stop(uri string) error {
if _, init := d.Calls["Stop"]; !init {
d.Calls["Stop"] = []MockCall{}
}
d.Calls["Stop"] = append(d.Calls["Stop"], MockCall{Fname: "Stop", Args: []string{uri}})
return nil
}
func (d *MockDriver) Exec(containerName string, command string, options CommandOptions) CommandResult {
if _, init := d.Calls["Exec"]; !init {
d.Calls["Exec"] = []MockCall{}
}
args := []string{containerName, command, options.Cwd, fmt.Sprintf("%#v", options.Env)}
d.Calls["Exec"] = append(d.Calls["Exec"], MockCall{Fname: "Exec", Args: args})
mockKeys := []string{
fmt.Sprintf("nthcall::%d", len(d.Calls["Exec"])),
fmt.Sprintf("withargs::%s", strings.Join(args, " ")),
}
for _, mockKey := range mockKeys {
if _, mocked := d.MockedCalls["Exec"][mockKey]; mocked {
return d.MockedCalls["Exec"][mockKey]
}
}
return CommandResult{}
}
// Mocks a call to <fn> with arguments <args> to return <returnValue>.
//
// The mocked call is reused as long as it's defined within the mock driver.
func (d *MockDriver) WithMockedCall(fn string, returnValue CommandResult, args ...string) {
mockKey := fmt.Sprintf("withargs::%s", strings.Join(args, " "))
if _, initialized := d.MockedCalls[fn]; !initialized {
d.MockedCalls[fn] = map[string]CommandResult{}
}
d.MockedCalls[fn][mockKey] = returnValue
}
// Mocks the nth call to <fn> to return <returnValue>.
//
// The mocked call is reused as long as it's defined within the mock driver.
func (d *MockDriver) WithNthMockedCall(fn string, callIndex int, returnValue CommandResult) {
mockKey := fmt.Sprintf("nthcall::%d", callIndex)
if _, initialized := d.MockedCalls[fn]; !initialized {
d.MockedCalls[fn] = map[string]CommandResult{}
}
d.MockedCalls[fn][mockKey] = returnValue
}