mock

package
v1.230.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 22, 2022 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func OpenFileMock

func OpenFileMock(name string, tokens map[string]string) (io.ReadCloser, error)

Types

type DockerExecConfig

type DockerExecConfig struct {
	// Image is the fully qualified docker image name that is passed to docker for this tool.
	Image string
	// Workspace is the (optional) directory to which the current working directory is mapped
	// within the docker container.
	Workspace string
}

DockerExecConfig is the configuration for an individual tool that shall be executed in docker.

type DockerExecRunner

type DockerExecRunner struct {
	// Runner is the ExecRunner to which all executions are forwarded in the end.
	Runner baseRunner
	// contains filtered or unexported fields
}

DockerExecRunner can be used "in place" of another ExecRunner in order to transparently execute commands within a docker container. One use-case is to test locally with tools that are not available on the current platform. When entering the run*() function of a step implementation, a DockerExecRunner can be wrapped around a command.Command{} an be configured to run certain executables within docker.

func (*DockerExecRunner) AddExecConfig

func (d *DockerExecRunner) AddExecConfig(executable string, config DockerExecConfig) error

AddExecConfig needs to be called to store a configuration for a specific executable, in order to run this executable within docker.

func (*DockerExecRunner) RunExecutable

func (d *DockerExecRunner) RunExecutable(executable string, parameters ...string) error

RunExecutable runs the provided executable within docker, if a DockerExecConfig has been previously associated with this executable via AddExecConfig(). Otherwise runs it directly. The BaseRunner is used for execution in any case.

Example
package main

import (
	"bytes"
	"fmt"
	"github.com/SAP/jenkins-library/pkg/command"
	"github.com/SAP/jenkins-library/pkg/mock"
	"io"
	"strings"
)

type ExecRunner interface {
	SetDir(d string)
	SetEnv(e []string)
	Stdout(out io.Writer)
	Stderr(err io.Writer)
	RunExecutable(e string, p ...string) error
}

func getMavenVersion(runner ExecRunner) (string, error) {
	output := bytes.Buffer{}
	runner.Stdout(&output)
	err := runner.RunExecutable("mvn", "--version")
	if err != nil {
		return "", fmt.Errorf("failed to run maven: %w", err)
	}
	logLines := strings.Split(output.String(), "\n")
	if len(logLines) < 1 {
		return "", fmt.Errorf("failed to obtain maven output")
	}
	return logLines[0], nil
}

func main() {
	// getMavenVersion(runner ExecRunner) executes the command "mvn --version"
	// and returns the command output as string
	runner := command.Command{}
	localMavenVersion, _ := getMavenVersion(&runner)

	dockerRunner := mock.DockerExecRunner{Runner: &runner}
	_ = dockerRunner.AddExecConfig("mvn", mock.DockerExecConfig{
		Image: "maven:3.6.1-jdk-8",
	})

	dockerMavenVersion, _ := getMavenVersion(&dockerRunner)

	fmt.Printf("Your local mvn version is %v, while the version in docker is %v", localMavenVersion, dockerMavenVersion)
}
Output:

func (*DockerExecRunner) SetDir

func (d *DockerExecRunner) SetDir(dir string)

SetDir directly forwards to the provided BaseRunner.

func (*DockerExecRunner) SetEnv

func (d *DockerExecRunner) SetEnv(env []string)

SetEnv directly forwards to the provided BaseRunner.

func (*DockerExecRunner) Stderr

func (d *DockerExecRunner) Stderr(err io.Writer)

Stderr directly forwards to the provided BaseRunner.

func (*DockerExecRunner) Stdout

func (d *DockerExecRunner) Stdout(out io.Writer)

Stdout directly forwards to the provided BaseRunner.

type DownloadMock

type DownloadMock struct {
	FilePath       string
	ImageRef       string
	RemoteImageRef string
	RegistryURL    string

	ReturnImage     v1.Image
	RemoteImageInfo v1.Image
	ReturnError     string

	Stub func(imageRef, targetDir string) (v1.Image, error)
}

DownloadMock .

func (*DownloadMock) DownloadImage

func (c *DownloadMock) DownloadImage(imageRef, targetDir string) (v1.Image, error)

DownloadImage .

func (*DownloadMock) DownloadImageContent

func (c *DownloadMock) DownloadImageContent(imageRef, targetFile string) (v1.Image, error)

DownloadImageContent .

func (*DownloadMock) GetRemoteImageInfo

func (c *DownloadMock) GetRemoteImageInfo(imageRef string) (v1.Image, error)

GetRemoteImageInfo .

type ExecCall

type ExecCall struct {
	Execution *Execution
	Async     bool
	Exec      string
	Params    []string
}

type ExecMockRunner

type ExecMockRunner struct {
	Dir      []string
	Env      []string
	ExitCode int
	Calls    []ExecCall

	Stub                func(call string, stdoutReturn map[string]string, shouldFailOnCommand map[string]error, stdout io.Writer) error
	StdoutReturn        map[string]string
	ShouldFailOnCommand map[string]error
	// contains filtered or unexported fields
}

func (*ExecMockRunner) AppendEnv

func (m *ExecMockRunner) AppendEnv(e []string)

func (*ExecMockRunner) GetExitCode

func (m *ExecMockRunner) GetExitCode() int

func (*ExecMockRunner) GetStderr

func (m *ExecMockRunner) GetStderr() io.Writer

func (*ExecMockRunner) GetStdout

func (m *ExecMockRunner) GetStdout() io.Writer

func (*ExecMockRunner) RunExecutable

func (m *ExecMockRunner) RunExecutable(e string, p ...string) error

func (*ExecMockRunner) RunExecutableInBackground

func (m *ExecMockRunner) RunExecutableInBackground(e string, p ...string) (command.Execution, error)

func (*ExecMockRunner) SetDir

func (m *ExecMockRunner) SetDir(d string)

func (*ExecMockRunner) SetEnv

func (m *ExecMockRunner) SetEnv(e []string)

func (*ExecMockRunner) Stderr

func (m *ExecMockRunner) Stderr(err io.Writer)

func (*ExecMockRunner) Stdin

func (m *ExecMockRunner) Stdin(in io.Reader)

func (*ExecMockRunner) Stdout

func (m *ExecMockRunner) Stdout(out io.Writer)

type Execution

type Execution struct {
	Killed bool
}

func (*Execution) Kill

func (e *Execution) Kill() error

func (*Execution) Wait

func (e *Execution) Wait() error

type FileMock

type FileMock struct {
	// contains filtered or unexported fields
}

FileMock can be used in places where a io.Closer, io.StringWriter or io.Writer is expected. It is the concrete type returned from FilesMock.OpenFile()

func (*FileMock) Close

func (f *FileMock) Close() error

Close mocks freeing the associated OS resources.

func (*FileMock) Read

func (f *FileMock) Read(b []byte) (n int, err error)

Reads the content of the mock

func (*FileMock) Write

func (f *FileMock) Write(p []byte) (n int, err error)

Write appends the provided byte array to the end of the current virtual file contents. It fails if the FileMock has been closed already, but it does not fail in case the path has already been removed from the FilesMock instance that created this FileMock. In this situation, the written contents will not become visible in the FilesMock.

func (*FileMock) WriteString

func (f *FileMock) WriteString(s string) (n int, err error)

WriteString converts the passed string to a byte array and forwards to Write().

type FilesMock

type FilesMock struct {
	CurrentDir       string
	Separator        string
	FileExistsErrors map[string]error
	FileReadErrors   map[string]error
	FileWriteError   error
	FileWriteErrors  map[string]error
	// contains filtered or unexported fields
}

FilesMock implements the functions from piperutils.Files with an in-memory file system.

func (*FilesMock) Abs

func (f *FilesMock) Abs(path string) (string, error)

func (*FilesMock) AddDir

func (f *FilesMock) AddDir(path string)

AddDir establishes the existence of a virtual directory. The directory is add with default mode 755.

func (*FilesMock) AddDirWithMode

func (f *FilesMock) AddDirWithMode(path string, mode os.FileMode)

AddDirWithMode establishes the existence of a virtual directory.

func (*FilesMock) AddFile

func (f *FilesMock) AddFile(path string, contents []byte)

AddFile establishes the existence of a virtual file. The file is added with mode 644.

func (*FilesMock) AddFileWithMode

func (f *FilesMock) AddFileWithMode(path string, contents []byte, mode os.FileMode)

AddFileWithMode establishes the existence of a virtual file.

func (*FilesMock) Chdir

func (f *FilesMock) Chdir(path string) error

Chdir changes virtually into the given directory. The directory needs to exist according to the files and directories via AddFile() and AddDirectory(). The implementation does not support relative path components such as "..".

func (*FilesMock) Chmod

func (f *FilesMock) Chmod(path string, mode os.FileMode) error

Chmod changes the file mode for the entry at the given path

func (*FilesMock) Copy

func (f *FilesMock) Copy(src, dst string) (int64, error)

Copy checks if content has been associated with the given src path, and if so copies it under the given path dst.

func (*FilesMock) Create

func (f *FilesMock) Create(name string) (io.ReadWriteCloser, error)

func (*FilesMock) CurrentTime

func (f *FilesMock) CurrentTime(format string) string

CurrentTime returns the current time as a fixed value

func (*FilesMock) DirExists

func (f *FilesMock) DirExists(path string) (bool, error)

DirExists returns true, if the given path is a previously added directory, or a parent directory for any of the previously added files.

func (*FilesMock) FileExists

func (f *FilesMock) FileExists(path string) (bool, error)

FileExists returns true if file content has been associated with the given path, false otherwise. Only relative paths are supported.

func (*FilesMock) FileRead

func (f *FilesMock) FileRead(path string) ([]byte, error)

FileRead returns the content previously associated with the given path via AddFile(), or an error if no content has been associated.

func (*FilesMock) FileRemove

func (f *FilesMock) FileRemove(path string) error

FileRemove deletes the association of the given path with any content and records the removal of the file. If the path has not been registered before, it returns an error.

func (*FilesMock) FileRename

func (f *FilesMock) FileRename(oldPath, newPath string) error

FileRename changes the path under which content is associated in the virtual file system. Only leaf-entries are supported as of yet.

func (*FilesMock) FileWrite

func (f *FilesMock) FileWrite(path string, content []byte, mode os.FileMode) error

FileWrite just forwards to AddFile(), i.e. the content is associated with the given path.

func (*FilesMock) Getwd

func (f *FilesMock) Getwd() (string, error)

Getwd returns the rooted current virtual working directory

func (*FilesMock) Glob

func (f *FilesMock) Glob(pattern string) ([]string, error)

Glob returns an array of path strings which match the given glob-pattern. Double star matching is supported.

func (*FilesMock) HasCopiedFile

func (f *FilesMock) HasCopiedFile(src string, dest string) bool

HasCopiedFile returns true if the virtual file system at one point contained an entry for the given source and destination, and it was written via CopyFile().

func (f *FilesMock) HasCreatedSymlink(oldname, newname string) bool

HasCreatedSymlink returns true if the virtual file system has a symlink with a specific target.

func (*FilesMock) HasFile

func (f *FilesMock) HasFile(path string) bool

HasFile returns true if the virtual file system contains an entry for the given path.

func (*FilesMock) HasRemovedFile

func (f *FilesMock) HasRemovedFile(path string) bool

HasRemovedFile returns true if the virtual file system at one point contained an entry for the given path, and it was removed via FileRemove().

func (*FilesMock) HasWrittenFile

func (f *FilesMock) HasWrittenFile(path string) bool

HasWrittenFile returns true if the virtual file system at one point contained an entry for the given path, and it was written via FileWrite().

func (*FilesMock) MkdirAll

func (f *FilesMock) MkdirAll(path string, mode os.FileMode) error

MkdirAll creates a directory in the in-memory file system, so that this path is established to exist.

func (*FilesMock) Move

func (f *FilesMock) Move(src, dst string) error

Move moves a file to the given destination

func (*FilesMock) Open

func (f *FilesMock) Open(name string) (io.ReadWriteCloser, error)

func (*FilesMock) OpenFile

func (f *FilesMock) OpenFile(path string, flag int, perm os.FileMode) (*FileMock, error)

OpenFile mimics the behavior os.OpenFile(), but it cannot return an instance of the os.File struct. Instead, it returns a pointer to a FileMock instance, which implements a number of the same methods as os.File. The flag parameter is checked for os.O_CREATE and os.O_APPEND and behaves accordingly.

func (*FilesMock) RemoveAll

func (f *FilesMock) RemoveAll(path string) error

RemoveAll is a proxy for FileRemove

func (*FilesMock) SHA256

func (f *FilesMock) SHA256(path string) (string, error)

SHA256 returns a random SHA256

func (*FilesMock) Stat

func (f *FilesMock) Stat(path string) (os.FileInfo, error)

Stat returns an approximated os.FileInfo. For files, it returns properties that have been associated via the setup methods. For directories it depends. If a directory exists only implicitly, because it is the parent of an added file, default values will be reflected in the file info.

func (f *FilesMock) Symlink(oldname, newname string) error

func (*FilesMock) TempDir

func (f *FilesMock) TempDir(baseDir string, pattern string) (string, error)

TempDir create a temp-styled directory in the in-memory, so that this path is established to exist.

type HttpClientMock

type HttpClientMock struct {
	ClientOptions          []piperhttp.ClientOptions // set by mock
	FileUploads            map[string]string         // set by mock
	ReturnFileUploadStatus int                       // expected to be set upfront
	ReturnFileUploadError  error                     // expected to be set upfront
}

HttpClientMock mock struct

func (*HttpClientMock) DownloadFile

func (utils *HttpClientMock) DownloadFile(url, filename string, header http.Header, cookies []*http.Cookie) error

DownloadFile mock

func (*HttpClientMock) SendRequest

func (utils *HttpClientMock) SendRequest(method string, url string, r io.Reader, header http.Header, cookies []*http.Cookie) (*http.Response, error)

SendRequest mock

func (*HttpClientMock) SetOptions

func (utils *HttpClientMock) SetOptions(options piperhttp.ClientOptions)

SetOptions mock

func (*HttpClientMock) Upload

func (utils *HttpClientMock) Upload(data piperhttp.UploadRequestData) (*http.Response, error)

Upload mock

func (*HttpClientMock) UploadFile

func (utils *HttpClientMock) UploadFile(url, file, fieldName string, header http.Header, cookies []*http.Cookie, uploadType string) (*http.Response, error)

UploadFile mock

func (*HttpClientMock) UploadRequest

func (utils *HttpClientMock) UploadRequest(method, url, file, fieldName string, header http.Header, cookies []*http.Cookie, uploadType string) (*http.Response, error)

UploadRequest mock

type ShellMockRunner

type ShellMockRunner struct {
	Dir      string
	Env      []string
	ExitCode int
	Calls    []string
	Shell    []string

	StdoutReturn        map[string]string
	ShouldFailOnCommand map[string]error
	// contains filtered or unexported fields
}

func (*ShellMockRunner) AppendEnv

func (m *ShellMockRunner) AppendEnv(e []string)

func (*ShellMockRunner) GetExitCode

func (m *ShellMockRunner) GetExitCode() int

func (*ShellMockRunner) GetStderr

func (m *ShellMockRunner) GetStderr() io.Writer

func (*ShellMockRunner) GetStdout

func (m *ShellMockRunner) GetStdout() io.Writer

func (*ShellMockRunner) RunShell

func (m *ShellMockRunner) RunShell(s string, c string) error

func (*ShellMockRunner) SetDir

func (m *ShellMockRunner) SetDir(d string)

func (*ShellMockRunner) SetEnv

func (m *ShellMockRunner) SetEnv(e []string)

func (*ShellMockRunner) Stderr

func (m *ShellMockRunner) Stderr(err io.Writer)

func (*ShellMockRunner) Stdin

func (m *ShellMockRunner) Stdin(in io.Reader)

func (*ShellMockRunner) Stdout

func (m *ShellMockRunner) Stdout(out io.Writer)

type StepOptions

type StepOptions struct {
	TestParam string `json:"testParam,omitempty"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL