add better generate

Signed-off-by: Jess Frazelle <acidburn@microsoft.com>
This commit is contained in:
Jess Frazelle 2018-03-20 01:33:56 -04:00
parent 3fc6abf56b
commit cdd93563f5
5655 changed files with 1187011 additions and 392 deletions

View file

@ -0,0 +1,68 @@
package builders
import (
"time"
"github.com/docker/docker/api/types/swarm"
)
// Config creates a config with default values.
// Any number of config builder functions can be passed to augment it.
func Config(builders ...func(config *swarm.Config)) *swarm.Config {
config := &swarm.Config{}
for _, builder := range builders {
builder(config)
}
return config
}
// ConfigLabels sets the config's labels
func ConfigLabels(labels map[string]string) func(config *swarm.Config) {
return func(config *swarm.Config) {
config.Spec.Labels = labels
}
}
// ConfigName sets the config's name
func ConfigName(name string) func(config *swarm.Config) {
return func(config *swarm.Config) {
config.Spec.Name = name
}
}
// ConfigID sets the config's ID
func ConfigID(ID string) func(config *swarm.Config) {
return func(config *swarm.Config) {
config.ID = ID
}
}
// ConfigVersion sets the version for the config
func ConfigVersion(v swarm.Version) func(*swarm.Config) {
return func(config *swarm.Config) {
config.Version = v
}
}
// ConfigCreatedAt sets the creation time for the config
func ConfigCreatedAt(t time.Time) func(*swarm.Config) {
return func(config *swarm.Config) {
config.CreatedAt = t
}
}
// ConfigUpdatedAt sets the update time for the config
func ConfigUpdatedAt(t time.Time) func(*swarm.Config) {
return func(config *swarm.Config) {
config.UpdatedAt = t
}
}
// ConfigData sets the config payload.
func ConfigData(data []byte) func(*swarm.Config) {
return func(config *swarm.Config) {
config.Spec.Data = data
}
}

View file

@ -0,0 +1,79 @@
package builders
import (
"time"
"github.com/docker/docker/api/types"
)
// Container creates a container with default values.
// Any number of container function builder can be passed to augment it.
func Container(name string, builders ...func(container *types.Container)) *types.Container {
// now := time.Now()
// onehourago := now.Add(-120 * time.Minute)
container := &types.Container{
ID: "container_id",
Names: []string{"/" + name},
Command: "top",
Image: "busybox:latest",
Status: "Up 1 second",
Created: time.Now().UnixNano(),
}
for _, builder := range builders {
builder(container)
}
return container
}
// WithLabel adds a label to the container
func WithLabel(key, value string) func(*types.Container) {
return func(c *types.Container) {
if c.Labels == nil {
c.Labels = map[string]string{}
}
c.Labels[key] = value
}
}
// WithName adds a name to the container
func WithName(name string) func(*types.Container) {
return func(c *types.Container) {
c.Names = append(c.Names, "/"+name)
}
}
// WithPort adds a port mapping to the container
func WithPort(privateport, publicport uint16, builders ...func(*types.Port)) func(*types.Container) {
return func(c *types.Container) {
if c.Ports == nil {
c.Ports = []types.Port{}
}
port := &types.Port{
PrivatePort: privateport,
PublicPort: publicport,
}
for _, builder := range builders {
builder(port)
}
c.Ports = append(c.Ports, *port)
}
}
// IP sets the ip of the port
func IP(ip string) func(*types.Port) {
return func(p *types.Port) {
p.IP = ip
}
}
// TCP sets the port to tcp
func TCP(p *types.Port) {
p.Type = "tcp"
}
// UDP sets the port to udp
func UDP(p *types.Port) {
p.Type = "udp"
}

View file

@ -0,0 +1,3 @@
// Package builders helps you create struct for your unit test while keeping them expressive.
//
package builders

View file

@ -0,0 +1,45 @@
package builders
import (
"github.com/docker/docker/api/types"
)
// NetworkResource creates a network resource with default values.
// Any number of networkResource function builder can be pass to modify the existing value.
// feel free to add another builder func if you need to override another value
func NetworkResource(builders ...func(resource *types.NetworkResource)) *types.NetworkResource {
resource := &types.NetworkResource{}
for _, builder := range builders {
builder(resource)
}
return resource
}
// NetworkResourceName sets the name of the resource network
func NetworkResourceName(name string) func(networkResource *types.NetworkResource) {
return func(networkResource *types.NetworkResource) {
networkResource.Name = name
}
}
// NetworkResourceID sets the ID of the resource network
func NetworkResourceID(id string) func(networkResource *types.NetworkResource) {
return func(networkResource *types.NetworkResource) {
networkResource.ID = id
}
}
// NetworkResourceDriver sets the driver of the resource network
func NetworkResourceDriver(name string) func(networkResource *types.NetworkResource) {
return func(networkResource *types.NetworkResource) {
networkResource.Driver = name
}
}
// NetworkResourceScope sets the Scope of the resource network
func NetworkResourceScope(scope string) func(networkResource *types.NetworkResource) {
return func(networkResource *types.NetworkResource) {
networkResource.Scope = scope
}
}

View file

@ -0,0 +1,134 @@
package builders
import (
"time"
"github.com/docker/docker/api/types/swarm"
)
// Node creates a node with default values.
// Any number of node function builder can be pass to augment it.
//
// n1 := Node() // Returns a default node
// n2 := Node(NodeID("foo"), NodeHostname("bar"), Leader())
func Node(builders ...func(*swarm.Node)) *swarm.Node {
t1 := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
node := &swarm.Node{
ID: "nodeID",
Meta: swarm.Meta{
CreatedAt: t1,
},
Description: swarm.NodeDescription{
Hostname: "defaultNodeHostname",
Platform: swarm.Platform{
Architecture: "x86_64",
OS: "linux",
},
Resources: swarm.Resources{
NanoCPUs: 4,
MemoryBytes: 20 * 1024 * 1024,
},
Engine: swarm.EngineDescription{
EngineVersion: "1.13.0",
Labels: map[string]string{
"engine": "label",
},
Plugins: []swarm.PluginDescription{
{
Type: "Volume",
Name: "local",
},
{
Type: "Network",
Name: "bridge",
},
{
Type: "Network",
Name: "overlay",
},
},
},
},
Status: swarm.NodeStatus{
State: swarm.NodeStateReady,
Addr: "127.0.0.1",
},
Spec: swarm.NodeSpec{
Annotations: swarm.Annotations{
Name: "defaultNodeName",
},
Role: swarm.NodeRoleWorker,
Availability: swarm.NodeAvailabilityActive,
},
}
for _, builder := range builders {
builder(node)
}
return node
}
// NodeID sets the node id
func NodeID(id string) func(*swarm.Node) {
return func(node *swarm.Node) {
node.ID = id
}
}
// NodeName sets the node name
func NodeName(name string) func(*swarm.Node) {
return func(node *swarm.Node) {
node.Spec.Annotations.Name = name
}
}
// NodeLabels sets the node labels
func NodeLabels(labels map[string]string) func(*swarm.Node) {
return func(node *swarm.Node) {
node.Spec.Labels = labels
}
}
// Hostname sets the node hostname
func Hostname(hostname string) func(*swarm.Node) {
return func(node *swarm.Node) {
node.Description.Hostname = hostname
}
}
// Leader sets the current node as a leader
func Leader() func(*swarm.ManagerStatus) {
return func(managerStatus *swarm.ManagerStatus) {
managerStatus.Leader = true
}
}
// Manager set the current node as a manager
func Manager(managerStatusBuilders ...func(*swarm.ManagerStatus)) func(*swarm.Node) {
return func(node *swarm.Node) {
node.Spec.Role = swarm.NodeRoleManager
node.ManagerStatus = ManagerStatus(managerStatusBuilders...)
}
}
// ManagerStatus create a ManageStatus with default values.
func ManagerStatus(managerStatusBuilders ...func(*swarm.ManagerStatus)) *swarm.ManagerStatus {
managerStatus := &swarm.ManagerStatus{
Reachability: swarm.ReachabilityReachable,
Addr: "127.0.0.1",
}
for _, builder := range managerStatusBuilders {
builder(managerStatus)
}
return managerStatus
}
// EngineVersion sets the node's engine version
func EngineVersion(version string) func(*swarm.Node) {
return func(node *swarm.Node) {
node.Description.Engine.EngineVersion = version
}
}

View file

@ -0,0 +1,70 @@
package builders
import (
"time"
"github.com/docker/docker/api/types/swarm"
)
// Secret creates a secret with default values.
// Any number of secret builder functions can be passed to augment it.
func Secret(builders ...func(secret *swarm.Secret)) *swarm.Secret {
secret := &swarm.Secret{}
for _, builder := range builders {
builder(secret)
}
return secret
}
// SecretLabels sets the secret's labels
func SecretLabels(labels map[string]string) func(secret *swarm.Secret) {
return func(secret *swarm.Secret) {
secret.Spec.Labels = labels
}
}
// SecretName sets the secret's name
func SecretName(name string) func(secret *swarm.Secret) {
return func(secret *swarm.Secret) {
secret.Spec.Name = name
}
}
// SecretDriver sets the secret's driver name
func SecretDriver(driver string) func(secret *swarm.Secret) {
return func(secret *swarm.Secret) {
secret.Spec.Driver = &swarm.Driver{
Name: driver,
}
}
}
// SecretID sets the secret's ID
func SecretID(ID string) func(secret *swarm.Secret) {
return func(secret *swarm.Secret) {
secret.ID = ID
}
}
// SecretVersion sets the version for the secret
func SecretVersion(v swarm.Version) func(*swarm.Secret) {
return func(secret *swarm.Secret) {
secret.Version = v
}
}
// SecretCreatedAt sets the creation time for the secret
func SecretCreatedAt(t time.Time) func(*swarm.Secret) {
return func(secret *swarm.Secret) {
secret.CreatedAt = t
}
}
// SecretUpdatedAt sets the update time for the secret
func SecretUpdatedAt(t time.Time) func(*swarm.Secret) {
return func(secret *swarm.Secret) {
secret.UpdatedAt = t
}
}

View file

@ -0,0 +1,74 @@
package builders
import (
"github.com/docker/docker/api/types/swarm"
)
// Service creates a service with default values.
// Any number of service builder functions can be passed to augment it.
// Currently, only ServiceName is implemented
func Service(builders ...func(*swarm.Service)) *swarm.Service {
service := &swarm.Service{
ID: "serviceID",
Spec: swarm.ServiceSpec{
Annotations: swarm.Annotations{
Name: "defaultServiceName",
},
EndpointSpec: &swarm.EndpointSpec{},
},
}
for _, builder := range builders {
builder(service)
}
return service
}
// ServiceID sets the service ID
func ServiceID(ID string) func(*swarm.Service) {
return func(service *swarm.Service) {
service.ID = ID
}
}
// ServiceName sets the service name
func ServiceName(name string) func(*swarm.Service) {
return func(service *swarm.Service) {
service.Spec.Annotations.Name = name
}
}
// ServiceLabels sets the service's labels
func ServiceLabels(labels map[string]string) func(*swarm.Service) {
return func(service *swarm.Service) {
service.Spec.Annotations.Labels = labels
}
}
// ReplicatedService sets the number of replicas for the service
func ReplicatedService(replicas uint64) func(*swarm.Service) {
return func(service *swarm.Service) {
service.Spec.Mode = swarm.ServiceMode{Replicated: &swarm.ReplicatedService{Replicas: &replicas}}
}
}
// ServiceImage sets the service's image
func ServiceImage(image string) func(*swarm.Service) {
return func(service *swarm.Service) {
service.Spec.TaskTemplate = swarm.TaskSpec{ContainerSpec: &swarm.ContainerSpec{Image: image}}
}
}
// ServicePort sets the service's port
func ServicePort(port swarm.PortConfig) func(*swarm.Service) {
return func(service *swarm.Service) {
service.Spec.EndpointSpec.Ports = append(service.Spec.EndpointSpec.Ports, port)
assignedPort := port
if assignedPort.PublishedPort == 0 {
assignedPort.PublishedPort = 30000
}
service.Endpoint.Ports = append(service.Endpoint.Ports, assignedPort)
}
}

View file

@ -0,0 +1,39 @@
package builders
import (
"time"
"github.com/docker/docker/api/types/swarm"
)
// Swarm creates a swarm with default values.
// Any number of swarm function builder can be pass to augment it.
func Swarm(swarmBuilders ...func(*swarm.Swarm)) *swarm.Swarm {
t1 := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
swarm := &swarm.Swarm{
ClusterInfo: swarm.ClusterInfo{
ID: "swarm",
Meta: swarm.Meta{
CreatedAt: t1,
},
Spec: swarm.Spec{},
},
JoinTokens: swarm.JoinTokens{
Worker: "worker-join-token",
Manager: "manager-join-token",
},
}
for _, builder := range swarmBuilders {
builder(swarm)
}
return swarm
}
// Autolock set the swarm into autolock mode
func Autolock() func(*swarm.Swarm) {
return func(swarm *swarm.Swarm) {
swarm.Spec.EncryptionConfig.AutoLockManagers = true
}
}

View file

@ -0,0 +1,160 @@
package builders
import (
"time"
"github.com/docker/docker/api/types/swarm"
)
var (
defaultTime = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
)
// Task creates a task with default values .
// Any number of task function builder can be pass to augment it.
func Task(taskBuilders ...func(*swarm.Task)) *swarm.Task {
task := &swarm.Task{
ID: "taskID",
Meta: swarm.Meta{
CreatedAt: defaultTime,
},
Annotations: swarm.Annotations{
Name: "defaultTaskName",
},
Spec: *TaskSpec(),
ServiceID: "rl02d5gwz6chzu7il5fhtb8be",
Slot: 1,
Status: *TaskStatus(),
DesiredState: swarm.TaskStateReady,
}
for _, builder := range taskBuilders {
builder(task)
}
return task
}
// TaskID sets the task ID
func TaskID(id string) func(*swarm.Task) {
return func(task *swarm.Task) {
task.ID = id
}
}
// TaskName sets the task name
func TaskName(name string) func(*swarm.Task) {
return func(task *swarm.Task) {
task.Annotations.Name = name
}
}
// TaskServiceID sets the task service's ID
func TaskServiceID(id string) func(*swarm.Task) {
return func(task *swarm.Task) {
task.ServiceID = id
}
}
// TaskNodeID sets the task's node id
func TaskNodeID(id string) func(*swarm.Task) {
return func(task *swarm.Task) {
task.NodeID = id
}
}
// TaskDesiredState sets the task's desired state
func TaskDesiredState(state swarm.TaskState) func(*swarm.Task) {
return func(task *swarm.Task) {
task.DesiredState = state
}
}
// TaskSlot sets the task's slot
func TaskSlot(slot int) func(*swarm.Task) {
return func(task *swarm.Task) {
task.Slot = slot
}
}
// WithStatus sets the task status
func WithStatus(statusBuilders ...func(*swarm.TaskStatus)) func(*swarm.Task) {
return func(task *swarm.Task) {
task.Status = *TaskStatus(statusBuilders...)
}
}
// TaskStatus creates a task status with default values .
// Any number of taskStatus function builder can be pass to augment it.
func TaskStatus(statusBuilders ...func(*swarm.TaskStatus)) *swarm.TaskStatus {
timestamp := defaultTime.Add(1 * time.Hour)
taskStatus := &swarm.TaskStatus{
State: swarm.TaskStateReady,
Timestamp: timestamp,
}
for _, builder := range statusBuilders {
builder(taskStatus)
}
return taskStatus
}
// Timestamp sets the task status timestamp
func Timestamp(t time.Time) func(*swarm.TaskStatus) {
return func(taskStatus *swarm.TaskStatus) {
taskStatus.Timestamp = t
}
}
// StatusErr sets the tasks status error
func StatusErr(err string) func(*swarm.TaskStatus) {
return func(taskStatus *swarm.TaskStatus) {
taskStatus.Err = err
}
}
// TaskState sets the task's current state
func TaskState(state swarm.TaskState) func(*swarm.TaskStatus) {
return func(taskStatus *swarm.TaskStatus) {
taskStatus.State = state
}
}
// PortStatus sets the tasks port config status
// FIXME(vdemeester) should be a sub builder 👼
func PortStatus(portConfigs []swarm.PortConfig) func(*swarm.TaskStatus) {
return func(taskStatus *swarm.TaskStatus) {
taskStatus.PortStatus.Ports = portConfigs
}
}
// WithTaskSpec sets the task spec
func WithTaskSpec(specBuilders ...func(*swarm.TaskSpec)) func(*swarm.Task) {
return func(task *swarm.Task) {
task.Spec = *TaskSpec(specBuilders...)
}
}
// TaskSpec creates a task spec with default values .
// Any number of taskSpec function builder can be pass to augment it.
func TaskSpec(specBuilders ...func(*swarm.TaskSpec)) *swarm.TaskSpec {
taskSpec := &swarm.TaskSpec{
ContainerSpec: &swarm.ContainerSpec{
Image: "myimage:mytag",
},
}
for _, builder := range specBuilders {
builder(taskSpec)
}
return taskSpec
}
// TaskImage sets the task's image
func TaskImage(image string) func(*swarm.TaskSpec) {
return func(taskSpec *swarm.TaskSpec) {
taskSpec.ContainerSpec.Image = image
}
}

View file

@ -0,0 +1,43 @@
package builders
import (
"github.com/docker/docker/api/types"
)
// Volume creates a volume with default values.
// Any number of volume function builder can be passed to augment it.
func Volume(builders ...func(volume *types.Volume)) *types.Volume {
volume := &types.Volume{
Name: "volume",
Driver: "local",
Mountpoint: "/data/volume",
Scope: "local",
}
for _, builder := range builders {
builder(volume)
}
return volume
}
// VolumeLabels sets the volume labels
func VolumeLabels(labels map[string]string) func(volume *types.Volume) {
return func(volume *types.Volume) {
volume.Labels = labels
}
}
// VolumeName sets the volume labels
func VolumeName(name string) func(volume *types.Volume) {
return func(volume *types.Volume) {
volume.Name = name
}
}
// VolumeDriver sets the volume driver
func VolumeDriver(name string) func(volume *types.Volume) {
return func(volume *types.Volume) {
volume.Driver = name
}
}

169
vendor/github.com/docker/cli/internal/test/cli.go generated vendored Normal file
View file

@ -0,0 +1,169 @@
package test
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"strings"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/config/configfile"
manifeststore "github.com/docker/cli/cli/manifest/store"
registryclient "github.com/docker/cli/cli/registry/client"
"github.com/docker/cli/cli/trust"
"github.com/docker/docker/client"
notaryclient "github.com/theupdateframework/notary/client"
)
// NotaryClientFuncType defines a function that returns a fake notary client
type NotaryClientFuncType func(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (notaryclient.Repository, error)
type clientInfoFuncType func() command.ClientInfo
// FakeCli emulates the default DockerCli
type FakeCli struct {
command.DockerCli
client client.APIClient
configfile *configfile.ConfigFile
out *command.OutStream
outBuffer *bytes.Buffer
err *bytes.Buffer
in *command.InStream
server command.ServerInfo
clientInfoFunc clientInfoFuncType
notaryClientFunc NotaryClientFuncType
manifestStore manifeststore.Store
registryClient registryclient.RegistryClient
contentTrust bool
}
// NewFakeCli returns a fake for the command.Cli interface
func NewFakeCli(client client.APIClient, opts ...func(*FakeCli)) *FakeCli {
outBuffer := new(bytes.Buffer)
errBuffer := new(bytes.Buffer)
c := &FakeCli{
client: client,
out: command.NewOutStream(outBuffer),
outBuffer: outBuffer,
err: errBuffer,
in: command.NewInStream(ioutil.NopCloser(strings.NewReader(""))),
// Use an empty string for filename so that tests don't create configfiles
// Set cli.ConfigFile().Filename to a tempfile to support Save.
configfile: configfile.New(""),
}
for _, opt := range opts {
opt(c)
}
return c
}
// SetIn sets the input of the cli to the specified ReadCloser
func (c *FakeCli) SetIn(in *command.InStream) {
c.in = in
}
// SetErr sets the stderr stream for the cli to the specified io.Writer
func (c *FakeCli) SetErr(err *bytes.Buffer) {
c.err = err
}
// SetConfigFile sets the "fake" config file
func (c *FakeCli) SetConfigFile(configfile *configfile.ConfigFile) {
c.configfile = configfile
}
// Client returns a docker API client
func (c *FakeCli) Client() client.APIClient {
return c.client
}
// Out returns the output stream (stdout) the cli should write on
func (c *FakeCli) Out() *command.OutStream {
return c.out
}
// Err returns the output stream (stderr) the cli should write on
func (c *FakeCli) Err() io.Writer {
return c.err
}
// In returns the input stream the cli will use
func (c *FakeCli) In() *command.InStream {
return c.in
}
// ConfigFile returns the cli configfile object (to get client configuration)
func (c *FakeCli) ConfigFile() *configfile.ConfigFile {
return c.configfile
}
// ServerInfo returns API server information for the server used by this client
func (c *FakeCli) ServerInfo() command.ServerInfo {
return c.server
}
// ClientInfo returns client information
func (c *FakeCli) ClientInfo() command.ClientInfo {
if c.clientInfoFunc != nil {
return c.clientInfoFunc()
}
return c.DockerCli.ClientInfo()
}
// SetClientInfo sets the internal getter for retrieving a ClientInfo
func (c *FakeCli) SetClientInfo(clientInfoFunc clientInfoFuncType) {
c.clientInfoFunc = clientInfoFunc
}
// OutBuffer returns the stdout buffer
func (c *FakeCli) OutBuffer() *bytes.Buffer {
return c.outBuffer
}
// ErrBuffer Buffer returns the stderr buffer
func (c *FakeCli) ErrBuffer() *bytes.Buffer {
return c.err
}
// SetNotaryClient sets the internal getter for retrieving a NotaryClient
func (c *FakeCli) SetNotaryClient(notaryClientFunc NotaryClientFuncType) {
c.notaryClientFunc = notaryClientFunc
}
// NotaryClient returns an err for testing unless defined
func (c *FakeCli) NotaryClient(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (notaryclient.Repository, error) {
if c.notaryClientFunc != nil {
return c.notaryClientFunc(imgRefAndAuth, actions)
}
return nil, fmt.Errorf("no notary client available unless defined")
}
// ManifestStore returns a fake store used for testing
func (c *FakeCli) ManifestStore() manifeststore.Store {
return c.manifestStore
}
// RegistryClient returns a fake client for testing
func (c *FakeCli) RegistryClient(insecure bool) registryclient.RegistryClient {
return c.registryClient
}
// SetManifestStore on the fake cli
func (c *FakeCli) SetManifestStore(store manifeststore.Store) {
c.manifestStore = store
}
// SetRegistryClient on the fake cli
func (c *FakeCli) SetRegistryClient(client registryclient.RegistryClient) {
c.registryClient = client
}
// ContentTrustEnabled on the fake cli
func (c *FakeCli) ContentTrustEnabled() bool {
return c.contentTrust
}
// EnableContentTrust on the fake cli
func EnableContentTrust(c *FakeCli) {
c.contentTrust = true
}

5
vendor/github.com/docker/cli/internal/test/doc.go generated vendored Normal file
View file

@ -0,0 +1,5 @@
// Package test is a test-only package that can be used by other cli package to write unit test.
//
// It as an internal package and cannot be used outside of github.com/docker/cli package.
//
package test

View file

@ -0,0 +1,21 @@
package environment
import (
"os"
"time"
"github.com/gotestyourself/gotestyourself/poll"
"github.com/pkg/errors"
)
// Setup a new environment
func Setup() error {
dockerHost := os.Getenv("TEST_DOCKER_HOST")
if dockerHost == "" {
return errors.New("$TEST_DOCKER_HOST must be set")
}
return os.Setenv("DOCKER_HOST", dockerHost)
}
// DefaultPollSettings used with gotestyourself/poll
var DefaultPollSettings = poll.WithDelay(100 * time.Millisecond)

View file

@ -0,0 +1,56 @@
package network
import (
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network"
"golang.org/x/net/context"
)
// FakeClient is a fake NetworkAPIClient
type FakeClient struct {
NetworkInspectFunc func(ctx context.Context, networkID string, options types.NetworkInspectOptions) (types.NetworkResource, error)
}
// NetworkConnect fakes connecting to a network
func (c *FakeClient) NetworkConnect(ctx context.Context, networkID, container string, config *network.EndpointSettings) error {
return nil
}
// NetworkCreate fakes creating a network
func (c *FakeClient) NetworkCreate(_ context.Context, _ string, options types.NetworkCreate) (types.NetworkCreateResponse, error) {
return types.NetworkCreateResponse{}, nil
}
// NetworkDisconnect fakes disconnecting from a network
func (c *FakeClient) NetworkDisconnect(ctx context.Context, networkID, container string, force bool) error {
return nil
}
// NetworkInspect fakes inspecting a network
func (c *FakeClient) NetworkInspect(ctx context.Context, networkID string, options types.NetworkInspectOptions) (types.NetworkResource, error) {
if c.NetworkInspectFunc != nil {
return c.NetworkInspectFunc(ctx, networkID, options)
}
return types.NetworkResource{}, nil
}
// NetworkInspectWithRaw fakes inspecting a network with a raw response
func (c *FakeClient) NetworkInspectWithRaw(_ context.Context, _ string, _ types.NetworkInspectOptions) (types.NetworkResource, []byte, error) {
return types.NetworkResource{}, nil, nil
}
// NetworkList fakes listing networks
func (c *FakeClient) NetworkList(_ context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) {
return nil, nil
}
// NetworkRemove fakes removing networks
func (c *FakeClient) NetworkRemove(ctx context.Context, networkID string) error {
return nil
}
// NetworksPrune fakes pruning networks
func (c *FakeClient) NetworksPrune(_ context.Context, pruneFilter filters.Args) (types.NetworksPruneReport, error) {
return types.NetworksPruneReport{}, nil
}

View file

@ -0,0 +1,543 @@
package notary
import (
"github.com/docker/cli/cli/trust"
"github.com/theupdateframework/notary/client"
"github.com/theupdateframework/notary/client/changelist"
"github.com/theupdateframework/notary/cryptoservice"
"github.com/theupdateframework/notary/passphrase"
"github.com/theupdateframework/notary/storage"
"github.com/theupdateframework/notary/trustmanager"
"github.com/theupdateframework/notary/tuf/data"
"github.com/theupdateframework/notary/tuf/signed"
)
// GetOfflineNotaryRepository returns a OfflineNotaryRepository
func GetOfflineNotaryRepository(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (client.Repository, error) {
return OfflineNotaryRepository{}, nil
}
// OfflineNotaryRepository is a mock Notary repository that is offline
type OfflineNotaryRepository struct{}
// Initialize creates a new repository by using rootKey as the root Key for the
// TUF repository.
func (o OfflineNotaryRepository) Initialize(rootKeyIDs []string, serverManagedRoles ...data.RoleName) error {
return storage.ErrOffline{}
}
// InitializeWithCertificate initializes the repository with root keys and their corresponding certificates
func (o OfflineNotaryRepository) InitializeWithCertificate(rootKeyIDs []string, rootCerts []data.PublicKey, serverManagedRoles ...data.RoleName) error {
return storage.ErrOffline{}
}
// Publish pushes the local changes in signed material to the remote notary-server
// Conceptually it performs an operation similar to a `git rebase`
func (o OfflineNotaryRepository) Publish() error {
return storage.ErrOffline{}
}
// AddTarget creates new changelist entries to add a target to the given roles
// in the repository when the changelist gets applied at publish time.
func (o OfflineNotaryRepository) AddTarget(target *client.Target, roles ...data.RoleName) error {
return nil
}
// RemoveTarget creates new changelist entries to remove a target from the given
// roles in the repository when the changelist gets applied at publish time.
func (o OfflineNotaryRepository) RemoveTarget(targetName string, roles ...data.RoleName) error {
return nil
}
// ListTargets lists all targets for the current repository. The list of
// roles should be passed in order from highest to lowest priority.
func (o OfflineNotaryRepository) ListTargets(roles ...data.RoleName) ([]*client.TargetWithRole, error) {
return nil, storage.ErrOffline{}
}
// GetTargetByName returns a target by the given name.
func (o OfflineNotaryRepository) GetTargetByName(name string, roles ...data.RoleName) (*client.TargetWithRole, error) {
return nil, storage.ErrOffline{}
}
// GetAllTargetMetadataByName searches the entire delegation role tree to find the specified target by name for all
// roles, and returns a list of TargetSignedStructs for each time it finds the specified target.
func (o OfflineNotaryRepository) GetAllTargetMetadataByName(name string) ([]client.TargetSignedStruct, error) {
return nil, storage.ErrOffline{}
}
// GetChangelist returns the list of the repository's unpublished changes
func (o OfflineNotaryRepository) GetChangelist() (changelist.Changelist, error) {
return changelist.NewMemChangelist(), nil
}
// ListRoles returns a list of RoleWithSignatures objects for this repo
func (o OfflineNotaryRepository) ListRoles() ([]client.RoleWithSignatures, error) {
return nil, storage.ErrOffline{}
}
// GetDelegationRoles returns the keys and roles of the repository's delegations
func (o OfflineNotaryRepository) GetDelegationRoles() ([]data.Role, error) {
return nil, storage.ErrOffline{}
}
// AddDelegation creates changelist entries to add provided delegation public keys and paths.
func (o OfflineNotaryRepository) AddDelegation(name data.RoleName, delegationKeys []data.PublicKey, paths []string) error {
return nil
}
// AddDelegationRoleAndKeys creates a changelist entry to add provided delegation public keys.
func (o OfflineNotaryRepository) AddDelegationRoleAndKeys(name data.RoleName, delegationKeys []data.PublicKey) error {
return nil
}
// AddDelegationPaths creates a changelist entry to add provided paths to an existing delegation.
func (o OfflineNotaryRepository) AddDelegationPaths(name data.RoleName, paths []string) error {
return nil
}
// RemoveDelegationKeysAndPaths creates changelist entries to remove provided delegation key IDs and paths.
func (o OfflineNotaryRepository) RemoveDelegationKeysAndPaths(name data.RoleName, keyIDs, paths []string) error {
return nil
}
// RemoveDelegationRole creates a changelist to remove all paths and keys from a role, and delete the role in its entirety.
func (o OfflineNotaryRepository) RemoveDelegationRole(name data.RoleName) error {
return nil
}
// RemoveDelegationPaths creates a changelist entry to remove provided paths from an existing delegation.
func (o OfflineNotaryRepository) RemoveDelegationPaths(name data.RoleName, paths []string) error {
return nil
}
// RemoveDelegationKeys creates a changelist entry to remove provided keys from an existing delegation.
func (o OfflineNotaryRepository) RemoveDelegationKeys(name data.RoleName, keyIDs []string) error {
return nil
}
// ClearDelegationPaths creates a changelist entry to remove all paths from an existing delegation.
func (o OfflineNotaryRepository) ClearDelegationPaths(name data.RoleName) error {
return nil
}
// Witness creates change objects to witness (i.e. re-sign) the given
// roles on the next publish. One change is created per role
func (o OfflineNotaryRepository) Witness(roles ...data.RoleName) ([]data.RoleName, error) {
return nil, nil
}
// RotateKey rotates a private key and returns the public component from the remote server
func (o OfflineNotaryRepository) RotateKey(role data.RoleName, serverManagesKey bool, keyList []string) error {
return storage.ErrOffline{}
}
// GetCryptoService is the getter for the repository's CryptoService
func (o OfflineNotaryRepository) GetCryptoService() signed.CryptoService {
return nil
}
// SetLegacyVersions allows the number of legacy versions of the root
// to be inspected for old signing keys to be configured.
func (o OfflineNotaryRepository) SetLegacyVersions(version int) {}
// GetGUN is a getter for the GUN object from a Repository
func (o OfflineNotaryRepository) GetGUN() data.GUN {
return data.GUN("gun")
}
// GetUninitializedNotaryRepository returns an UninitializedNotaryRepository
func GetUninitializedNotaryRepository(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (client.Repository, error) {
return UninitializedNotaryRepository{}, nil
}
// UninitializedNotaryRepository is a mock Notary repository that is uninintialized
// it builds on top of the OfflineNotaryRepository, instead returning ErrRepositoryNotExist
// for any online operation
type UninitializedNotaryRepository struct {
OfflineNotaryRepository
}
// Initialize creates a new repository by using rootKey as the root Key for the
// TUF repository.
func (u UninitializedNotaryRepository) Initialize(rootKeyIDs []string, serverManagedRoles ...data.RoleName) error {
return client.ErrRepositoryNotExist{}
}
// InitializeWithCertificate initializes the repository with root keys and their corresponding certificates
func (u UninitializedNotaryRepository) InitializeWithCertificate(rootKeyIDs []string, rootCerts []data.PublicKey, serverManagedRoles ...data.RoleName) error {
return client.ErrRepositoryNotExist{}
}
// Publish pushes the local changes in signed material to the remote notary-server
// Conceptually it performs an operation similar to a `git rebase`
func (u UninitializedNotaryRepository) Publish() error {
return client.ErrRepositoryNotExist{}
}
// ListTargets lists all targets for the current repository. The list of
// roles should be passed in order from highest to lowest priority.
func (u UninitializedNotaryRepository) ListTargets(roles ...data.RoleName) ([]*client.TargetWithRole, error) {
return nil, client.ErrRepositoryNotExist{}
}
// GetTargetByName returns a target by the given name.
func (u UninitializedNotaryRepository) GetTargetByName(name string, roles ...data.RoleName) (*client.TargetWithRole, error) {
return nil, client.ErrRepositoryNotExist{}
}
// GetAllTargetMetadataByName searches the entire delegation role tree to find the specified target by name for all
// roles, and returns a list of TargetSignedStructs for each time it finds the specified target.
func (u UninitializedNotaryRepository) GetAllTargetMetadataByName(name string) ([]client.TargetSignedStruct, error) {
return nil, client.ErrRepositoryNotExist{}
}
// ListRoles returns a list of RoleWithSignatures objects for this repo
func (u UninitializedNotaryRepository) ListRoles() ([]client.RoleWithSignatures, error) {
return nil, client.ErrRepositoryNotExist{}
}
// GetDelegationRoles returns the keys and roles of the repository's delegations
func (u UninitializedNotaryRepository) GetDelegationRoles() ([]data.Role, error) {
return nil, client.ErrRepositoryNotExist{}
}
// RotateKey rotates a private key and returns the public component from the remote server
func (u UninitializedNotaryRepository) RotateKey(role data.RoleName, serverManagesKey bool, keyList []string) error {
return client.ErrRepositoryNotExist{}
}
// GetEmptyTargetsNotaryRepository returns an EmptyTargetsNotaryRepository
func GetEmptyTargetsNotaryRepository(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (client.Repository, error) {
return EmptyTargetsNotaryRepository{}, nil
}
// EmptyTargetsNotaryRepository is a mock Notary repository that is initialized
// but does not have any signed targets
type EmptyTargetsNotaryRepository struct {
OfflineNotaryRepository
}
// Initialize creates a new repository by using rootKey as the root Key for the
// TUF repository.
func (e EmptyTargetsNotaryRepository) Initialize(rootKeyIDs []string, serverManagedRoles ...data.RoleName) error {
return nil
}
// InitializeWithCertificate initializes the repository with root keys and their corresponding certificates
func (e EmptyTargetsNotaryRepository) InitializeWithCertificate(rootKeyIDs []string, rootCerts []data.PublicKey, serverManagedRoles ...data.RoleName) error {
return nil
}
// Publish pushes the local changes in signed material to the remote notary-server
// Conceptually it performs an operation similar to a `git rebase`
func (e EmptyTargetsNotaryRepository) Publish() error {
return nil
}
// ListTargets lists all targets for the current repository. The list of
// roles should be passed in order from highest to lowest priority.
func (e EmptyTargetsNotaryRepository) ListTargets(roles ...data.RoleName) ([]*client.TargetWithRole, error) {
return []*client.TargetWithRole{}, nil
}
// GetTargetByName returns a target by the given name.
func (e EmptyTargetsNotaryRepository) GetTargetByName(name string, roles ...data.RoleName) (*client.TargetWithRole, error) {
return nil, client.ErrNoSuchTarget(name)
}
// GetAllTargetMetadataByName searches the entire delegation role tree to find the specified target by name for all
// roles, and returns a list of TargetSignedStructs for each time it finds the specified target.
func (e EmptyTargetsNotaryRepository) GetAllTargetMetadataByName(name string) ([]client.TargetSignedStruct, error) {
return nil, client.ErrNoSuchTarget(name)
}
// ListRoles returns a list of RoleWithSignatures objects for this repo
func (e EmptyTargetsNotaryRepository) ListRoles() ([]client.RoleWithSignatures, error) {
rootRole := data.Role{
RootRole: data.RootRole{
KeyIDs: []string{"rootID"},
Threshold: 1,
},
Name: data.CanonicalRootRole,
}
targetsRole := data.Role{
RootRole: data.RootRole{
KeyIDs: []string{"targetsID"},
Threshold: 1,
},
Name: data.CanonicalTargetsRole,
}
return []client.RoleWithSignatures{
{Role: rootRole},
{Role: targetsRole}}, nil
}
// GetDelegationRoles returns the keys and roles of the repository's delegations
func (e EmptyTargetsNotaryRepository) GetDelegationRoles() ([]data.Role, error) {
return []data.Role{}, nil
}
// RotateKey rotates a private key and returns the public component from the remote server
func (e EmptyTargetsNotaryRepository) RotateKey(role data.RoleName, serverManagesKey bool, keyList []string) error {
return nil
}
// GetLoadedNotaryRepository returns a LoadedNotaryRepository
func GetLoadedNotaryRepository(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (client.Repository, error) {
return LoadedNotaryRepository{}, nil
}
// LoadedNotaryRepository is a mock Notary repository that is loaded with targets, delegations, and keys
type LoadedNotaryRepository struct {
EmptyTargetsNotaryRepository
statefulCryptoService signed.CryptoService
}
// LoadedNotaryRepository has three delegations:
// - targets/releases: includes keys A and B
// - targets/alice: includes key A
// - targets/bob: includes key B
var loadedReleasesRole = data.DelegationRole{
BaseRole: data.BaseRole{
Name: "targets/releases",
Keys: map[string]data.PublicKey{"A": nil, "B": nil},
Threshold: 1,
},
}
var loadedAliceRole = data.DelegationRole{
BaseRole: data.BaseRole{
Name: "targets/alice",
Keys: map[string]data.PublicKey{"A": nil},
Threshold: 1,
},
}
var loadedBobRole = data.DelegationRole{
BaseRole: data.BaseRole{
Name: "targets/bob",
Keys: map[string]data.PublicKey{"B": nil},
Threshold: 1,
},
}
var loadedDelegationRoles = []data.Role{
{
Name: loadedReleasesRole.Name,
RootRole: data.RootRole{
KeyIDs: []string{"A", "B"},
Threshold: 1,
},
},
{
Name: loadedAliceRole.Name,
RootRole: data.RootRole{
KeyIDs: []string{"A"},
Threshold: 1,
},
},
{
Name: loadedBobRole.Name,
RootRole: data.RootRole{
KeyIDs: []string{"B"},
Threshold: 1,
},
},
}
var loadedTargetsRole = data.DelegationRole{
BaseRole: data.BaseRole{
Name: data.CanonicalTargetsRole,
Keys: map[string]data.PublicKey{"C": nil},
Threshold: 1,
},
}
// LoadedNotaryRepository has three targets:
// - red: signed by targets/releases, targets/alice, targets/bob
// - blue: signed by targets/releases, targets/alice
// - green: signed by targets/releases
var loadedRedTarget = client.Target{
Name: "red",
Hashes: data.Hashes{"sha256": []byte("red-digest")},
}
var loadedBlueTarget = client.Target{
Name: "blue",
Hashes: data.Hashes{"sha256": []byte("blue-digest")},
}
var loadedGreenTarget = client.Target{
Name: "green",
Hashes: data.Hashes{"sha256": []byte("green-digest")},
}
var loadedTargets = []client.TargetSignedStruct{
// red is signed by all three delegations
{Target: loadedRedTarget, Role: loadedReleasesRole},
{Target: loadedRedTarget, Role: loadedAliceRole},
{Target: loadedRedTarget, Role: loadedBobRole},
// blue is signed by targets/releases, targets/alice
{Target: loadedBlueTarget, Role: loadedReleasesRole},
{Target: loadedBlueTarget, Role: loadedAliceRole},
// green is signed by targets/releases
{Target: loadedGreenTarget, Role: loadedReleasesRole},
}
// ListRoles returns a list of RoleWithSignatures objects for this repo
func (l LoadedNotaryRepository) ListRoles() ([]client.RoleWithSignatures, error) {
rootRole := data.Role{
RootRole: data.RootRole{
KeyIDs: []string{"rootID"},
Threshold: 1,
},
Name: data.CanonicalRootRole,
}
targetsRole := data.Role{
RootRole: data.RootRole{
KeyIDs: []string{"targetsID"},
Threshold: 1,
},
Name: data.CanonicalTargetsRole,
}
aliceRole := data.Role{
RootRole: data.RootRole{
KeyIDs: []string{"A"},
Threshold: 1,
},
Name: data.RoleName("targets/alice"),
}
bobRole := data.Role{
RootRole: data.RootRole{
KeyIDs: []string{"B"},
Threshold: 1,
},
Name: data.RoleName("targets/bob"),
}
releasesRole := data.Role{
RootRole: data.RootRole{
KeyIDs: []string{"A", "B"},
Threshold: 1,
},
Name: data.RoleName("targets/releases"),
}
// have releases only signed off by Alice last
releasesSig := []data.Signature{{KeyID: "A"}}
return []client.RoleWithSignatures{
{Role: rootRole},
{Role: targetsRole},
{Role: aliceRole},
{Role: bobRole},
{Role: releasesRole, Signatures: releasesSig},
}, nil
}
// ListTargets lists all targets for the current repository. The list of
// roles should be passed in order from highest to lowest priority.
func (l LoadedNotaryRepository) ListTargets(roles ...data.RoleName) ([]*client.TargetWithRole, error) {
filteredTargets := []*client.TargetWithRole{}
for _, tgt := range loadedTargets {
if len(roles) == 0 || (len(roles) > 0 && roles[0] == tgt.Role.Name) {
filteredTargets = append(filteredTargets, &client.TargetWithRole{Target: tgt.Target, Role: tgt.Role.Name})
}
}
return filteredTargets, nil
}
// GetTargetByName returns a target by the given name.
func (l LoadedNotaryRepository) GetTargetByName(name string, roles ...data.RoleName) (*client.TargetWithRole, error) {
for _, tgt := range loadedTargets {
if name == tgt.Target.Name {
if len(roles) == 0 || (len(roles) > 0 && roles[0] == tgt.Role.Name) {
return &client.TargetWithRole{Target: tgt.Target, Role: tgt.Role.Name}, nil
}
}
}
return nil, client.ErrNoSuchTarget(name)
}
// GetAllTargetMetadataByName searches the entire delegation role tree to find the specified target by name for all
// roles, and returns a list of TargetSignedStructs for each time it finds the specified target.
func (l LoadedNotaryRepository) GetAllTargetMetadataByName(name string) ([]client.TargetSignedStruct, error) {
if name == "" {
return loadedTargets, nil
}
filteredTargets := []client.TargetSignedStruct{}
for _, tgt := range loadedTargets {
if name == tgt.Target.Name {
filteredTargets = append(filteredTargets, tgt)
}
}
if len(filteredTargets) == 0 {
return nil, client.ErrNoSuchTarget(name)
}
return filteredTargets, nil
}
// GetGUN is a getter for the GUN object from a Repository
func (l LoadedNotaryRepository) GetGUN() data.GUN {
return data.GUN("signed-repo")
}
// GetDelegationRoles returns the keys and roles of the repository's delegations
func (l LoadedNotaryRepository) GetDelegationRoles() ([]data.Role, error) {
return loadedDelegationRoles, nil
}
// GetCryptoService is the getter for the repository's CryptoService
func (l LoadedNotaryRepository) GetCryptoService() signed.CryptoService {
if l.statefulCryptoService == nil {
// give it an in-memory cryptoservice with a root key and targets key
l.statefulCryptoService = cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(passphrase.ConstantRetriever("password")))
l.statefulCryptoService.AddKey(data.CanonicalRootRole, l.GetGUN(), nil)
l.statefulCryptoService.AddKey(data.CanonicalTargetsRole, l.GetGUN(), nil)
}
return l.statefulCryptoService
}
// GetLoadedWithNoSignersNotaryRepository returns a LoadedWithNoSignersNotaryRepository
func GetLoadedWithNoSignersNotaryRepository(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (client.Repository, error) {
return LoadedWithNoSignersNotaryRepository{}, nil
}
// LoadedWithNoSignersNotaryRepository is a mock Notary repository that is loaded with targets but no delegations
// it only contains the green target
type LoadedWithNoSignersNotaryRepository struct {
LoadedNotaryRepository
}
// ListTargets lists all targets for the current repository. The list of
// roles should be passed in order from highest to lowest priority.
func (l LoadedWithNoSignersNotaryRepository) ListTargets(roles ...data.RoleName) ([]*client.TargetWithRole, error) {
filteredTargets := []*client.TargetWithRole{}
for _, tgt := range loadedTargets {
if len(roles) == 0 || (len(roles) > 0 && roles[0] == tgt.Role.Name) {
filteredTargets = append(filteredTargets, &client.TargetWithRole{Target: tgt.Target, Role: tgt.Role.Name})
}
}
return filteredTargets, nil
}
// GetTargetByName returns a target by the given name.
func (l LoadedWithNoSignersNotaryRepository) GetTargetByName(name string, roles ...data.RoleName) (*client.TargetWithRole, error) {
if name == "" || name == loadedGreenTarget.Name {
return &client.TargetWithRole{Target: loadedGreenTarget, Role: data.CanonicalTargetsRole}, nil
}
return nil, client.ErrNoSuchTarget(name)
}
// GetAllTargetMetadataByName searches the entire delegation role tree to find the specified target by name for all
// roles, and returns a list of TargetSignedStructs for each time it finds the specified target.
func (l LoadedWithNoSignersNotaryRepository) GetAllTargetMetadataByName(name string) ([]client.TargetSignedStruct, error) {
if name == "" || name == loadedGreenTarget.Name {
return []client.TargetSignedStruct{{Target: loadedGreenTarget, Role: loadedTargetsRole}}, nil
}
return nil, client.ErrNoSuchTarget(name)
}
// GetDelegationRoles returns the keys and roles of the repository's delegations
func (l LoadedWithNoSignersNotaryRepository) GetDelegationRoles() ([]data.Role, error) {
return []data.Role{}, nil
}

View file

@ -0,0 +1,44 @@
package output
import (
"strings"
"testing"
"github.com/pkg/errors"
)
// Assert checks wether the output contains the specified lines
func Assert(t *testing.T, actual string, expectedLines map[int]func(string) error) {
for i, line := range strings.Split(actual, "\n") {
cmp, ok := expectedLines[i]
if !ok {
continue
}
if err := cmp(line); err != nil {
t.Errorf("line %d: %s", i, err)
}
}
if t.Failed() {
t.Log(actual)
}
}
// Prefix returns whether if the line has the specified string as prefix
func Prefix(expected string) func(string) error {
return func(actual string) error {
if strings.HasPrefix(actual, expected) {
return nil
}
return errors.Errorf("expected %s to start with %s", actual, expected)
}
}
// Equals returns wether the line is the same as the specified string
func Equals(expected string) func(string) error {
return func(actual string) error {
if expected == actual {
return nil
}
return errors.Errorf("got %s, expected %s", actual, expected)
}
}

79
vendor/github.com/docker/cli/internal/test/store.go generated vendored Normal file
View file

@ -0,0 +1,79 @@
package test
import (
"github.com/docker/cli/cli/config/credentials"
"github.com/docker/docker/api/types"
)
// FakeStore implements a credentials.Store that only acts as an in memory map
type FakeStore struct {
store map[string]types.AuthConfig
eraseFunc func(serverAddress string) error
getFunc func(serverAddress string) (types.AuthConfig, error)
getAllFunc func() (map[string]types.AuthConfig, error)
storeFunc func(authConfig types.AuthConfig) error
}
// NewFakeStore creates a new file credentials store.
func NewFakeStore() credentials.Store {
return &FakeStore{store: map[string]types.AuthConfig{}}
}
// SetStore is used to overrides Set function
func (c *FakeStore) SetStore(store map[string]types.AuthConfig) {
c.store = store
}
// SetEraseFunc is used to overrides Erase function
func (c *FakeStore) SetEraseFunc(eraseFunc func(string) error) {
c.eraseFunc = eraseFunc
}
// SetGetFunc is used to overrides Get function
func (c *FakeStore) SetGetFunc(getFunc func(string) (types.AuthConfig, error)) {
c.getFunc = getFunc
}
// SetGetAllFunc is used to overrides GetAll function
func (c *FakeStore) SetGetAllFunc(getAllFunc func() (map[string]types.AuthConfig, error)) {
c.getAllFunc = getAllFunc
}
// SetStoreFunc is used to override Store function
func (c *FakeStore) SetStoreFunc(storeFunc func(types.AuthConfig) error) {
c.storeFunc = storeFunc
}
// Erase removes the given credentials from the map store
func (c *FakeStore) Erase(serverAddress string) error {
if c.eraseFunc != nil {
return c.eraseFunc(serverAddress)
}
delete(c.store, serverAddress)
return nil
}
// Get retrieves credentials for a specific server from the map store.
func (c *FakeStore) Get(serverAddress string) (types.AuthConfig, error) {
if c.getFunc != nil {
return c.getFunc(serverAddress)
}
return c.store[serverAddress], nil
}
// GetAll returns the key value pairs of ServerAddress => Username
func (c *FakeStore) GetAll() (map[string]types.AuthConfig, error) {
if c.getAllFunc != nil {
return c.getAllFunc()
}
return c.store, nil
}
// Store saves the given credentials in the map store.
func (c *FakeStore) Store(authConfig types.AuthConfig) error {
if c.storeFunc != nil {
return c.storeFunc(authConfig)
}
c.store[authConfig.ServerAddress] = authConfig
return nil
}