testutil

package
v0.0.0-...-263a040 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2024 License: GPL-3.0 Imports: 25 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	FileInfoFile    = &fakeFileInfo{}
	FileInfoDir     = &fakeFileInfo{mode: os.ModeDir}
	FileInfoSymlink = &fakeFileInfo{mode: os.ModeSymlink}
)

Convenient FakeFileInfo objects for InsertLstatResult

View Source
var Contains check.Checker = &containsChecker{
	&check.CheckerInfo{Name: "Contains", Params: []string{"container", "elem"}},
}

Contains is a Checker that looks for a elem in a container. The elem can be any object. The container can be an array, slice or string.

View Source
var ContainsPadded = &paddedChecker{
	CheckerInfo: &check.CheckerInfo{Name: "ContainsPadded", Params: []string{"padded", "expected"}},
	isPartial:   true,
	isLine:      true,
}

ContainsPadded is a Checker that looks for an expected string in another that might have been padded out to align with something else (so arbitrary amounts of horizontal whitespace is ok between non-whitespace bits).

View Source
var ContainsWrapped = &paddedChecker{
	CheckerInfo: &check.CheckerInfo{Name: "EqualsWrapped", Params: []string{"wrapped", "expected"}},
	isRegexp:    false,
	isPartial:   true,
}

ContainsWrapped is a Checker that looks for an expected string in another that might have been padded out and wrapped (so arbitrary amounts of whitespace is ok between non-whitespace bits).

View Source
var DeepContains check.Checker = &deepContainsChecker{
	&check.CheckerInfo{Name: "DeepContains", Params: []string{"container", "elem"}},
}

DeepContains is a Checker that looks for a elem in a container using DeepEqual. The elem can be any object. The container can be an array, slice or string.

View Source
var DeepUnsortedMatches check.Checker = &deepUnsortedMatchChecker{
	&check.CheckerInfo{Name: "DeepUnsortedMatches", Params: []string{"container1", "container2"}},
}

DeepUnsortedMatches checks if two containers contain the same elements in the same number (but possibly different order) using DeepEqual. The container can be an array, a slice or a map.

View Source
var EqualsPadded = &paddedChecker{
	CheckerInfo: &check.CheckerInfo{Name: "EqualsPadded", Params: []string{"padded", "expected"}},
	isLine:      true,
}

EqualsPadded is a Checker that looks for an expected string to be equal to another except that the other might have been padded out to align with something else (so arbitrary amounts of horizontal whitespace is ok at the ends, and between non-whitespace bits).

View Source
var EqualsWrapped = &paddedChecker{
	CheckerInfo: &check.CheckerInfo{Name: "EqualsWrapped", Params: []string{"wrapped", "expected"}},
}

EqualsWrapped is a Checker that looks for an expected string to be equal to another except that the other might have been padded out and wrapped (so arbitrary amounts of whitespace is ok at the ends, and between non-whitespace bits).

View Source
var ErrorIs = &errorIsChecker{
	&check.CheckerInfo{Name: "ErrorIs", Params: []string{"error", "target"}},
}

ErrorIs calls errors.Is with the provided arguments.

View Source
var FileAbsent check.Checker = &filePresenceChecker{
	CheckerInfo: &check.CheckerInfo{Name: "FileAbsent", Params: []string{"filename"}},
	present:     false,
}

FileAbsent verifies that the given file does not exist.

View Source
var FileContains check.Checker = &fileContentChecker{
	CheckerInfo: &check.CheckerInfo{Name: "FileContains", Params: []string{"filename", "contents"}},
}

FileContains verifies that the given file's content contains the string (or fmt.Stringer) or []byte provided.

View Source
var FileEquals check.Checker = &fileContentChecker{
	CheckerInfo: &check.CheckerInfo{Name: "FileEquals", Params: []string{"filename", "contents"}},
	exact:       true,
}

FileEquals verifies that the given file's content is equal to the string (or fmt.Stringer), []byte provided, or the contents referred by a FileContentRef.

View Source
var FileMatches check.Checker = &fileContentChecker{
	CheckerInfo: &check.CheckerInfo{Name: "FileMatches", Params: []string{"filename", "regex"}},
}

FileMatches verifies that the given file's content matches the string provided.

View Source
var FilePresent check.Checker = &filePresenceChecker{
	CheckerInfo: &check.CheckerInfo{Name: "FilePresent", Params: []string{"filename"}},
	present:     true,
}

FilePresent verifies that the given file exists.

View Source
var IntEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntEqual", Params: []string{"a", "b"}}, rel: "=="}

IntEqual checker verifies that one integer is equal to other integer.

For example:

c.Assert(1, IntEqual, 1)
View Source
var IntGreaterEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntGreaterEqual", Params: []string{"a", "b"}}, rel: ">="}

IntGreaterEqual checker verifies that one integer is greater than or equal to other integer.

For example:

c.Assert(1, IntGreaterEqual, 2)
View Source
var IntGreaterThan = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntGreaterThan", Params: []string{"a", "b"}}, rel: ">"}

IntGreaterThan checker verifies that one integer is greater than other integer.

For example:

c.Assert(2, IntGreaterThan, 1)
View Source
var IntLessEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntLessEqual", Params: []string{"a", "b"}}, rel: "<="}

IntLessEqual checker verifies that one integer is less than or equal to other integer.

For example:

c.Assert(1, IntLessEqual, 1)
View Source
var IntLessThan = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntLessThan", Params: []string{"a", "b"}}, rel: "<"}

IntLessThan checker verifies that one integer is less than other integer.

For example:

c.Assert(1, IntLessThan, 2)
View Source
var IntNotEqual = &intChecker{CheckerInfo: &check.CheckerInfo{Name: "IntNotEqual", Params: []string{"a", "b"}}, rel: "!="}

IntNotEqual checker verifies that one integer is not equal to other integer.

For example:

c.Assert(1, IntNotEqual, 2)
View Source
var IsInterfaceNil = &interfaceNilChecker{
	&check.CheckerInfo{Name: "IsInterfaceNil", Params: []string{"value"}},
}

IsInterfaceNil checks that the value is a nil interface value (<nil>).

View Source
var JsonEquals check.Checker = &jsonEqualChecker{
	&check.CheckerInfo{Name: "JsonEqual", Params: []string{"obtained", "expected"}},
}

JsonEquals compares the obtained and expected values after having serialized them to JSON and deserialized to a generic interface{} type. This avoids trouble comparing types with unexported fields that otherwise would be problematic to set in external packages.

View Source
var MatchesPadded = &paddedChecker{
	CheckerInfo: &check.CheckerInfo{Name: "MatchesPadded", Params: []string{"padded", "expected"}},
	isRegexp:    true,
	isLine:      true,
}

MatchesPadded is a Checker that looks for an expected regexp in a string that might have been padded out to align with something else (so whitespace in the regexp is changed to [ \t]+, and ^[ \t]* is added to the beginning, and [ \t]*$ to the end of it).

View Source
var MatchesWrapped = &paddedChecker{
	CheckerInfo: &check.CheckerInfo{Name: "MatchesWrapped", Params: []string{"wrapped", "expected"}},
	isRegexp:    true,
}

MatchesWrapped is a Checker that looks for an expected regexp in a string that might have been padded and wrapped (so whitespace in the regexp is changed to \s+, and (?s)^\s* is added to the beginning, and \s*$ to the end of it).

View Source
var SymlinkTargetContains check.Checker = &symlinkTargetChecker{
	CheckerInfo: &check.CheckerInfo{Name: "SymlinkTargetContains", Params: []string{"filename", "target"}},
}

SymlinkTargetContains verifies that the given file is a symbolic link whose target contains the provided text.

View Source
var SymlinkTargetEquals check.Checker = &symlinkTargetChecker{
	CheckerInfo: &check.CheckerInfo{Name: "SymlinkTargetEquals", Params: []string{"filename", "target"}},
	exact:       true,
}

SymlinkTargetEquals verifies that the given file is a symbolic link with the given target.

View Source
var SymlinkTargetMatches check.Checker = &symlinkTargetChecker{
	CheckerInfo: &check.CheckerInfo{Name: "SymlinkTargetMatches", Params: []string{"filename", "regex"}},
}

SymlinkTargetMatches verifies that the given file is a symbolic link whose target matches the provided regular expression.

View Source
var SyscallsEqual check.Checker = &syscallsEqualChecker{
	CheckerInfo: &check.CheckerInfo{Name: "SyscallsEqual", Params: []string{"actualList", "expectedList"}},
}

SyscallsEqual checks that one sequence of system calls is equal to another.

Functions

func AppArmorParseAndHashHelper

func AppArmorParseAndHashHelper(profile string) (string, error)

func Backup

func Backup[T any](mockable *T) (restore func())

Backup a single element before further mocking.

Example (MockingMultiple)
mockableFunc := func() {
	fmt.Println("Original function")
}
mockableNumber := 17.53
mockableString := "Original string"
mockableStruct := struct {
	first  string
	second string
}{
	first:  "Original",
	second: "struct",
}

// Mock
restore := testutil.BackupMany(&mockableFunc, &mockableNumber, &mockableString, &mockableStruct)
mockableFunc = func() {
	fmt.Println("Mock")
}
mockableNumber = 37
mockableString = "Mock"
mockableStruct.first, mockableStruct.second = "mocked", "value"

// Restore
restore()

mockableFunc()
fmt.Println(mockableNumber, mockableString, mockableStruct)
Output:

Original function
17.53 Original string {Original struct}
Example (MockingSimple)
mockable := func() {
	fmt.Println("Original")
}

// Mock
restore := testutil.Backup(&mockable)
mockable = func() {
	fmt.Println("Mock")
}

// Restore
restore()

mockable()
Output:

Original

func BackupMany

func BackupMany(mockablesByPtr ...interface{}) (restore func())

Backup the specified list of elements before further mocking.

func DBusGetConnectionUnixProcessID

func DBusGetConnectionUnixProcessID(conn *dbus.Conn, name string) (pid int, err error)

func FakeDirEntry

func FakeDirEntry(name string, mode os.FileMode) fs.DirEntry

FakeDirEntry returns a fake object implementing fs.DirEntry

func FakeFileInfo

func FakeFileInfo(name string, mode os.FileMode) os.FileInfo

FakeFileInfo returns a fake object implementing os.FileInfo

func HostScaledTimeout

func HostScaledTimeout(t time.Duration) time.Duration

HostScaledTimeout returns a timeout for tests that is adjusted for the slowness of certain systems.

This should only be used in tests and is a bit of a guess.

func Mock

func Mock[T any](mockable *T, newVal T) (restore func())

Mock provides a type safe way of mocking a single thing.

Types

type BaseTest

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

BaseTest is a structure used as a base test suite for all the snappy tests.

func (*BaseTest) AddCleanup

func (s *BaseTest) AddCleanup(f func())

AddCleanup adds a new cleanup function to the test.

func (*BaseTest) SetUpTest

func (s *BaseTest) SetUpTest(c *check.C)

SetUpTest prepares the cleanup.

func (*BaseTest) TearDownTest

func (s *BaseTest) TearDownTest(c *check.C)

TearDownTest cleans up the channel.ini files in case they were changed by the test. It also runs the cleanup handlers

type CallResultError

type CallResultError struct {
	C string
	R interface{}
	E error
}

CallResultError describes a system call and the corresponding result or error.

The field names stand for Call, Result and Error respectively. They are abbreviated due to the nature of their use (in large quantity).

type DBusTest

type DBusTest struct {

	// the dbus.Conn to the session bus that tests can use
	SessionBus *dbus.Conn
	// contains filtered or unexported fields
}

DBusTest provides a separate dbus session bus for running tests

func (*DBusTest) SetUpSuite

func (s *DBusTest) SetUpSuite(c *C)

func (*DBusTest) SetUpTest

func (s *DBusTest) SetUpTest(c *C)

func (*DBusTest) TearDownSuite

func (s *DBusTest) TearDownSuite(c *C)

func (*DBusTest) TearDownTest

func (s *DBusTest) TearDownTest(c *C)

type FileContentRef

type FileContentRef string

FileContentRef refers to the content of file by its name, to use in conjunction with FileEquals.

type MockCmd

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

MockCmd allows mocking commands for testing.

func MockCommand

func MockCommand(c *check.C, basename, script string) *MockCmd

MockCommand adds a mocked command. If the basename argument is a command it is added to PATH. If it is an absolute path it is just created there, along with the full prefix. The caller is responsible for the cleanup in this case.

The command logs all invocations to a dedicated log file. If script is non-empty then it is used as is and the caller is responsible for how the script behaves (exit code and any extra behavior). If script is empty then the command exits successfully without any other side-effect.

func MockLockedCommand

func MockLockedCommand(c *check.C, basename, script string) *MockCmd

MockLockedCommand is the same as MockCommand(), but the script uses flock to enforce exclusive locking, preventing the call tracking from being corrupted. Thus it is safe to be called in parallel.

func (*MockCmd) Also

func (cmd *MockCmd) Also(basename, script string) *MockCmd

Also mock this command, using the same bindir and log. Useful when you want to check the ordering of things.

func (*MockCmd) BinDir

func (cmd *MockCmd) BinDir() string

BinDir returns the location of the directory holding overridden commands.

func (*MockCmd) Calls

func (cmd *MockCmd) Calls() [][]string

Calls returns a list of calls that were made to the mock command. of the form:

[][]string{
    {"cmd", "arg1", "arg2"}, // first invocation of "cmd"
    {"cmd", "arg1", "arg2"}, // second invocation of "cmd"
}

func (*MockCmd) Exe

func (cmd *MockCmd) Exe() string

Exe return the full path of the mock binary

func (*MockCmd) ForgetCalls

func (cmd *MockCmd) ForgetCalls()

ForgetCalls purges the list of calls made so far

func (*MockCmd) Restore

func (cmd *MockCmd) Restore()

Restore removes the mocked command from PATH

type SyscallRecorder

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

SyscallRecorder stores which system calls were invoked.

The recorder supports a small set of features useful for testing: injecting failures, returning pre-arranged test data, allocation, tracking and verification of file descriptors.

func (*SyscallRecorder) Calls

func (sys *SyscallRecorder) Calls() []string

Calls returns the sequence of mocked calls that have been made.

func (*SyscallRecorder) CheckForStrayDescriptors

func (sys *SyscallRecorder) CheckForStrayDescriptors(c *check.C)

CheckForStrayDescriptors ensures that all fake file descriptors are closed.

func (*SyscallRecorder) Close

func (sys *SyscallRecorder) Close(fd int) error

Close is a fake implementation of syscall.Close

func (*SyscallRecorder) Fchdir

func (sys *SyscallRecorder) Fchdir(fd int) error

Fchdir is a fake implementation of syscall.Fchdir

func (*SyscallRecorder) Fchown

func (sys *SyscallRecorder) Fchown(fd int, uid sys.UserID, gid sys.GroupID) error

Fchown is a fake implementation of syscall.Fchown

func (*SyscallRecorder) Fstat

func (sys *SyscallRecorder) Fstat(fd int, buf *syscall.Stat_t) error

Fstat is a fake implementation of syscall.Fstat

func (*SyscallRecorder) Fstatfs

func (sys *SyscallRecorder) Fstatfs(fd int, buf *syscall.Statfs_t) error

Fstatfs is a fake implementation of syscall.Fstatfs

func (*SyscallRecorder) InsertFault

func (sys *SyscallRecorder) InsertFault(call string, errors ...error)

InsertFault makes given subsequent call to return the specified error.

If one error is provided then the call will reliably fail that way. If multiple errors are given then they will be used on subsequent calls until the errors finally run out and the call succeeds.

func (*SyscallRecorder) InsertFaultFunc

func (sys *SyscallRecorder) InsertFaultFunc(call string, fn func() error)

InsertFaultFunc arranges given function to be called whenever given call is made.

The main purpose is to allow to vary the behavior of a given system call over time. The provided function can return an error or nil to indicate success.

func (*SyscallRecorder) InsertFstatResult

func (sys *SyscallRecorder) InsertFstatResult(call string, buf syscall.Stat_t)

InsertFstatResult makes given subsequent call fstat return the specified stat buffer.

func (*SyscallRecorder) InsertFstatfsResult

func (sys *SyscallRecorder) InsertFstatfsResult(call string, bufs ...syscall.Statfs_t)

InsertFstatfsResult makes given subsequent call fstatfs return the specified stat buffer.

func (*SyscallRecorder) InsertOsLstatResult

func (sys *SyscallRecorder) InsertOsLstatResult(call string, fi os.FileInfo)

InsertOsLstatResult makes given subsequent call to OsLstat return the specified fake file info.

func (*SyscallRecorder) InsertReadDirResult

func (sys *SyscallRecorder) InsertReadDirResult(call string, infos []fs.DirEntry)

InsertReadDirResult makes given subsequent call readdir return the specified fake file infos.

func (*SyscallRecorder) InsertReadlinkatResult

func (sys *SyscallRecorder) InsertReadlinkatResult(call, oldname string)

InsertReadlinkatResult makes given subsequent call to readlinkat return the specified oldname.

func (*SyscallRecorder) InsertSysLstatResult

func (sys *SyscallRecorder) InsertSysLstatResult(call string, sb syscall.Stat_t)

InsertSysLstatResult makes given subsequent call to SysLstat return the specified fake file info.

func (*SyscallRecorder) Mkdirat

func (sys *SyscallRecorder) Mkdirat(dirfd int, path string, mode uint32) error

Mkdirat is a fake implementation of syscall.Mkdirat

func (*SyscallRecorder) Mount

func (sys *SyscallRecorder) Mount(source string, target string, fstype string, flags uintptr, data string) error

Mount is a fake implementation of syscall.Mount

func (*SyscallRecorder) Open

func (sys *SyscallRecorder) Open(path string, flags int, mode uint32) (int, error)

Open is a fake implementation of syscall.Open

func (*SyscallRecorder) Openat

func (sys *SyscallRecorder) Openat(dirfd int, path string, flags int, mode uint32) (int, error)

Openat is a fake implementation of syscall.Openat

func (*SyscallRecorder) OsLstat

func (sys *SyscallRecorder) OsLstat(name string) (os.FileInfo, error)

OsLstat is a fake implementation of os.Lstat

func (*SyscallRecorder) RCalls

func (sys *SyscallRecorder) RCalls() []CallResultError

RCalls returns the sequence of mocked calls that have been made along with their results.

func (*SyscallRecorder) ReadDir

func (sys *SyscallRecorder) ReadDir(dirname string) ([]fs.DirEntry, error)

ReadDir is a fake implementation of os.ReadDir

func (*SyscallRecorder) Readlinkat

func (sys *SyscallRecorder) Readlinkat(dirfd int, path string, buf []byte) (int, error)

Readlinkat is a fake implementation of osutil.Readlinkat (syscall.Readlinkat is not exposed)

func (*SyscallRecorder) Remove

func (sys *SyscallRecorder) Remove(name string) error

Remove is a fake implementation of os.Remove

func (*SyscallRecorder) StrayDescriptorsError

func (sys *SyscallRecorder) StrayDescriptorsError() error

StrayDescriptorsError returns an error if any descriptor is left unclosed.

func (sys *SyscallRecorder) Symlink(oldname, newname string) error

Symlink is a fake implementation of syscall.Symlink

func (*SyscallRecorder) Symlinkat

func (sys *SyscallRecorder) Symlinkat(oldname string, dirfd int, newname string) error

Symlinkat is a fake implementation of osutil.Symlinkat (syscall.Symlinkat is not exposed)

func (*SyscallRecorder) SysLstat

func (sys *SyscallRecorder) SysLstat(name string, sb *syscall.Stat_t) error

SysLstat is a fake implementation of syscall.Lstat

func (*SyscallRecorder) Unmount

func (sys *SyscallRecorder) Unmount(target string, flags int) error

Unmount is a fake implementation of syscall.Unmount

Jump to

Keyboard shortcuts

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