Documentation
¶
Overview ¶
Package testutils provides utility functions and behaviors for testing.
Index ¶
- Constants
- Variables
- func AppendCovEnv(env []string) []string
- func ArtifactsDir(t *testing.T) string
- func AuthctlGoBuildArgs(outputPath string) []string
- func AuthdGoBuildArgs(outputPath string) []string
- func BrokerCompletionSignalFilename(username string) string
- func BrokerCompletionSignalWaitingFilename(username string) string
- func BrokerCompletionSignalsDir(socketPath string) string
- func BubbleWrapCommand(t *testing.T, env []string) *exec.Cmd
- func BuildAuthctl() (binaryPath string, cleanup func(), err error)
- func BuildAuthdWithExampleBroker() (execPath string, cleanup func(), err error)
- func BuildRustNSSLib(t *testing.T, disableCoverage bool, features ...string) (libPath string, rustCovEnv []string)
- func CanRunRustTests(coverageWanted bool) (err error)
- func CheckCommand(t *testing.T, cmd *exec.Cmd, expectedExitCode int)
- func CleanupLXDContainers()
- func CoverDirEnv() string
- func CoverDirForTests() string
- func CreateBrokerCompletionSignal(t *testing.T, socketPath, username string) string
- func CurrentDir() string
- func GenerateEncryptionKey(brokerName string) string
- func GenerateSessionID(username string) string
- func GetSystemBusConnection(t *testing.T) (*dbus.Conn, error)
- func GoBuildFlags() []string
- func IsAsan() bool
- func IsRace() bool
- func LXCExecFromDir(t *testing.T, containerName, dir string, args ...string)
- func LXCExecFromDirAsUser(t *testing.T, containerName, dir string, userID, groupID int, args ...string)
- func MakeReadOnly(t *testing.T, dest string)
- func MaybeSaveBufferAsArtifactOnCleanup(t *testing.T, buf *SyncBuffer, filename string)
- func MaybeSaveBytesAsArtifactOnCleanup(t *testing.T, content []byte, filename string)
- func MaybeSaveFilesAsArtifactsOnCleanup(t *testing.T, artifacts ...string)
- func MultipliedSleepDuration(in time.Duration) time.Duration
- func ProjectRoot() string
- func RegisterLXDProvisionHook(fn func(t *testing.T, containerName string))
- func RequireBubblewrap(t *testing.T)
- func RunTestAsRoot(t *testing.T, args ...string)
- func RunTestInBubbleWrap(t *testing.T, args ...string)
- func RunTestInLXD(t *testing.T, ubuntuVersion string) bool
- func RunningAsRoot() bool
- func RunningInBubblewrap() bool
- func RunningInLXD() bool
- func RustNSSBuildArgs(targetDir string, extraFeatures ...string) []string
- func SkipIfCannotRunAsRoot(t *testing.T)
- func SleepMultiplier() float64
- func StartAuthd(t *testing.T, execPath string, args ...DaemonOption) (socketPath string)
- func StartAuthdWithCancel(t *testing.T, execPath string, args ...DaemonOption) (socketPath string, cancelFunc func())
- func StartBusBrokerMock(cfgDir string, brokerName string) (string, func(), error)
- func StartBusMock() (string, func(), error)
- func StartSystemBusMock() (func(), error)
- func TempDir(t *testing.T) string
- func TestFamilyPath(t *testing.T) string
- func TestVerbosity() int
- type BrokerBusMock
- func (b *BrokerBusMock) CancelIsAuthenticated(sessionID string) (dbusErr *dbus.Error)
- func (b *BrokerBusMock) DeleteUser(username, providerID string) (dbusErr *dbus.Error)
- func (b *BrokerBusMock) EndSession(sessionID string) (dbusErr *dbus.Error)
- func (b *BrokerBusMock) GetAuthenticationModes(sessionID string, supportedUILayouts []map[string]string) (authenticationModes []map[string]string, dbusErr *dbus.Error)
- func (b *BrokerBusMock) IsAuthenticated(sessionID, authenticationData string) (access, data string, dbusErr *dbus.Error)
- func (b *BrokerBusMock) NewSession(username, lang, mode, providerID string) (sessionID, encryptionKey string, dbusErr *dbus.Error)
- func (b *BrokerBusMock) SelectAuthenticationMode(sessionID, authenticationModeName string) (uiLayoutInfo map[string]string, dbusErr *dbus.Error)
- func (b *BrokerBusMock) UserPreCheck(username string) (userinfo string, dbusErr *dbus.Error)
- type DaemonOption
- func WithDBPath(path string) DaemonOption
- func WithEnvironment(env ...string) DaemonOption
- func WithGroupFile(groupFile string) DaemonOption
- func WithGroupFileOutput(groupFile string) DaemonOption
- func WithHomeBaseDir(baseDir string) DaemonOption
- func WithOutputAsTestArtifact() DaemonOption
- func WithPidFile(pidFile string) DaemonOption
- func WithPreviousDBState(db string) DaemonOption
- func WithSharedDaemon(shared bool) DaemonOption
- func WithSocketPath(path string) DaemonOption
- type SyncBuffer
Constants ¶
const ( // UseLXDEnvVar enables running version-specific tests in LXD containers. // When set, tests targeting a different Ubuntu version than the host will // be executed inside an LXD container with the correct Ubuntu version. UseLXDEnvVar = "AUTHD_TESTS_USE_LXD" // LXDUbuntuUserID is Ubuntu's default non-root user/group inside cloud images. LXDUbuntuUserID = 1000 )
const (
// IDSeparator is the value used to append values to the sessionID in the broker mock.
IDSeparator = "_separator_"
)
const LXDRustTargetDir = "/home/ubuntu/.cache/authd-test/rust-build-artifacts"
LXDRustTargetDir is the persistent directory used for Rust build artifacts inside LXD test containers. It is under the ubuntu user's home so both the LXD test runner and warmup hook (which run as UID/GID 1000) can reuse it. It must match the path used by BuildRustNSSLib when RunningInLXD() is true.
const MinimalPathEnv = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
MinimalPathEnv is the minimal PATH environment variable used to run tests.
Variables ¶
var IsAutoPkgTest = sync.OnceValue(func() bool { _, ok := os.LookupEnv("AUTOPKGTEST_TEST_ARCH") return ok })
IsAutoPkgTest returns true if the tests are running in an autopkgtest environment.
var IsCI = sync.OnceValue(func() bool { _, ok := os.LookupEnv("GITHUB_ACTIONS") return ok })
IsCI returns whether the test is running in CI environment.
var IsDebianPackageBuild = sync.OnceValue(func() bool { _, ok := os.LookupEnv("DEB_BUILD_ARCH") return ok })
IsDebianPackageBuild returns true if the tests are running in a Debian package build environment.
Functions ¶
func AppendCovEnv ¶
AppendCovEnv returns the env needed to enable coverage when running a go binary, if coverage is enabled.
func ArtifactsDir ¶
ArtifactsDir returns the path to the directory where artifacts are stored.
func AuthctlGoBuildArgs ¶ added in v0.7.0
AuthctlGoBuildArgs returns the `go build` arguments (run from ProjectRoot) used to build the authctl binary into outputPath. It is the single source of truth shared by BuildAuthctl and the LXD build-cache warmup, so their build (and thus cache) keys stay in sync.
func AuthdGoBuildArgs ¶ added in v0.7.0
AuthdGoBuildArgs returns the `go build` arguments (run from ProjectRoot) used to build the authd daemon with the example broker into outputPath. It is the single source of truth shared by BuildAuthdWithExampleBroker and the LXD build-cache warmup, so their build (and thus cache) keys stay in sync.
func BrokerCompletionSignalFilename ¶ added in v0.7.0
BrokerCompletionSignalFilename returns the file name used for broker completion signals.
func BrokerCompletionSignalWaitingFilename ¶ added in v0.7.0
BrokerCompletionSignalWaitingFilename returns the file name used for broker completion signals as marker that we're currently waiting.
func BrokerCompletionSignalsDir ¶ added in v0.7.0
BrokerCompletionSignalsDir returns the directory where broker completion signals are stored for a daemon started with the given socket path. This follows the convention established by StartAuthdWithCancel which creates the signals dir at $dir(socketPath)/broker-signals.
func BubbleWrapCommand ¶
BubbleWrapCommand returns a command that runs in bubblewrap.
func BuildAuthctl ¶
BuildAuthctl builds the authctl binary in a temporary directory for testing purposes.
func BuildAuthdWithExampleBroker ¶
BuildAuthdWithExampleBroker builds the authd executable and returns the binary path.
func BuildRustNSSLib ¶
func BuildRustNSSLib(t *testing.T, disableCoverage bool, features ...string) (libPath string, rustCovEnv []string)
BuildRustNSSLib builds the NSS library and links the compiled file to libPath.
func CanRunRustTests ¶
CanRunRustTests returns if we can run rust tests via cargo on this machine. It checks for code coverage report if supported.
func CheckCommand ¶
CheckCommand runs the given command and: * Checks that it exits with the expected exit code. * Checks that the output matches the golden file.
func CleanupLXDContainers ¶ added in v0.7.0
func CleanupLXDContainers()
CleanupLXDContainers stops all LXD containers that were used during this test run. Containers are kept (not deleted) so they can be reused on the next run; their provisioned build cache persists across restarts. Call this from TestMain after m.Run().
func CoverDirEnv ¶
func CoverDirEnv() string
CoverDirEnv returns the cover dir env variable to run a go binary, if coverage is enabled.
func CoverDirForTests ¶
func CoverDirForTests() string
CoverDirForTests parses the test arguments and return the cover profile directory, if coverage is enabled.
func CreateBrokerCompletionSignal ¶ added in v0.7.0
CreateBrokerCompletionSignal creates a signal file that tells the broker to complete authentication for the given username. The broker polls for this file and deletes it when found.
func GenerateEncryptionKey ¶
GenerateEncryptionKey returns an encryption key that can be used in tests.
func GenerateSessionID ¶
GenerateSessionID returns a sessionID that can be used in tests.
func GetSystemBusConnection ¶
GetSystemBusConnection returns a connection to the system bus with a safety check to avoid mistakenly connecting to the actual system bus.
func GoBuildFlags ¶
func GoBuildFlags() []string
GoBuildFlags returns the Go build flags that should be used when building binaries in tests. It includes flags for coverage, address sanitizer, and race detection if they are enabled in the current test environment.
Note: The flags returned by this function must be the first arguments to the `go build` command, because -cover is a "positional flag".
func IsAsan ¶
func IsAsan() bool
IsAsan returns whether the tests are running with address sanitizer.
func IsRace ¶
func IsRace() bool
IsRace returns whether the tests are running with thread sanitizer.
func LXCExecFromDir ¶ added in v0.7.0
LXCExecFromDir runs a command inside an LXD container with a specific working directory.
func LXCExecFromDirAsUser ¶ added in v0.7.0
func LXCExecFromDirAsUser(t *testing.T, containerName, dir string, userID, groupID int, args ...string)
LXCExecFromDirAsUser runs a command inside an LXD container with a specific working directory and UID/GID.
func MakeReadOnly ¶
MakeReadOnly makes dest read only and restore permission on cleanup.
func MaybeSaveBufferAsArtifactOnCleanup ¶
func MaybeSaveBufferAsArtifactOnCleanup(t *testing.T, buf *SyncBuffer, filename string)
MaybeSaveBufferAsArtifactOnCleanup saves the specified buffer to a temporary directory if the test failed or if the AUTHD_TESTS_ARTIFACTS_ALWAYS_SAVE environment variable is set.
func MaybeSaveBytesAsArtifactOnCleanup ¶
MaybeSaveBytesAsArtifactOnCleanup saves the specified bytes to a temporary directory if the test failed or if the AUTHD_TESTS_ARTIFACTS_ALWAYS_SAVE environment variable is set.
func MaybeSaveFilesAsArtifactsOnCleanup ¶
MaybeSaveFilesAsArtifactsOnCleanup saves the specified artifacts to a temporary directory if the test failed or if the AUTHD_TESTS_ARTIFACTS_ALWAYS_SAVE environment variable is set.
func MultipliedSleepDuration ¶
MultipliedSleepDuration returns a duration multiplied by the sleep multiplier provided by MultipliedSleepDuration.
func ProjectRoot ¶
func ProjectRoot() string
ProjectRoot returns the absolute path to the project root.
func RegisterLXDProvisionHook ¶ added in v0.7.0
RegisterLXDProvisionHook registers a function to run during container provisioning, after system packages are installed but before the provisioning marker is written. Use this to pre-warm build caches or perform any other one-time test-specific setup.
Hooks registered after provisioning has already run for a given container will not execute for that container.
func RequireBubblewrap ¶
RequireBubblewrap ensures that bubblewrap is available and usable for running tests. It skips or fails the test if bubblewrap cannot be used in the current environment.
func RunTestAsRoot ¶
RunTestAsRoot runs the given test as root.
func RunTestInBubbleWrap ¶
RunTestInBubbleWrap runs the given test in bubblewrap.
func RunTestInLXD ¶ added in v0.7.0
RunTestInLXD re-runs the current test inside an LXD container with the specified Ubuntu version if the host version doesn't match.
The caller MUST return immediately when this function returns true:
if testutils.RunTestInLXD(t, "24.04") {
return
}
Behavior:
- If already inside LXD (AUTHD_LXD_TEST=1): returns false (caller proceeds normally)
- If host Ubuntu version matches: returns false (caller proceeds normally)
- If TESTS_UPDATE_GOLDEN or AUTHD_TESTS_USE_LXD is set: runs test in LXD, returns true
- Otherwise: skips the test, returns true
func RunningAsRoot ¶
func RunningAsRoot() bool
RunningAsRoot returns true if the current process is running as root.
func RunningInBubblewrap ¶
func RunningInBubblewrap() bool
RunningInBubblewrap returns true if the test is being run in bubblewrap.
func RunningInLXD ¶ added in v0.7.0
func RunningInLXD() bool
RunningInLXD returns true if the test is being run inside an LXD container spawned by RunTestInLXD.
func RustNSSBuildArgs ¶ added in v0.7.0
RustNSSBuildArgs returns the `cargo` arguments (run from ProjectRoot) used to build the NSS library into targetDir with the given extra features. The integration_tests and custom_socket features are always included. It is the single source of truth shared by BuildRustNSSLib and the LXD build-cache warmup, so their features and target dir (and thus cache keys) stay in sync.
func SkipIfCannotRunAsRoot ¶
SkipIfCannotRunAsRoot checks whether we can run tests as root or skip the tests otherwise.
func SleepMultiplier ¶
func SleepMultiplier() float64
SleepMultiplier returns the sleep multiplier to be used in tests.
func StartAuthd ¶
func StartAuthd(t *testing.T, execPath string, args ...DaemonOption) (socketPath string)
StartAuthd starts authd in a separate process and returns the socket path.
func StartAuthdWithCancel ¶
func StartAuthdWithCancel(t *testing.T, execPath string, args ...DaemonOption) (socketPath string, cancelFunc func())
StartAuthdWithCancel starts authd in a separate process and returns the socket path and a cancel function.
func StartBusBrokerMock ¶
StartBusBrokerMock starts the D-Bus service and exports it on the system bus. It returns the configuration file path for the exported broker.
func StartBusMock ¶
StartBusMock starts a mock dbus daemon and returns its address and a cancel function to stop it.
func StartSystemBusMock ¶
func StartSystemBusMock() (func(), error)
StartSystemBusMock starts a mock dbus daemon and returns a cancel function to stop it.
This function uses t.Setenv to set the DBUS_SYSTEM_BUS_ADDRESS environment, so it shouldn't be used in parallel tests that rely on the mentioned variable.
func TempDir ¶
TempDir returns a temporary directory for the test. If the SKIP_CLEANUP environment variable is set, it creates a temp dir that is not automatically removed after the test.
func TestFamilyPath ¶
TestFamilyPath returns the path of the dir for storing fixtures and other files related to the test.
func TestVerbosity ¶
func TestVerbosity() int
TestVerbosity returns the verbosity level that should be used in tests.
Types ¶
type BrokerBusMock ¶
type BrokerBusMock struct {
// contains filtered or unexported fields
}
BrokerBusMock is the D-Bus object that will answer calls for the broker mock.
func (*BrokerBusMock) CancelIsAuthenticated ¶
func (b *BrokerBusMock) CancelIsAuthenticated(sessionID string) (dbusErr *dbus.Error)
CancelIsAuthenticated cancels an ongoing IsAuthenticated call if it exists.
func (*BrokerBusMock) DeleteUser ¶ added in v0.7.0
func (b *BrokerBusMock) DeleteUser(username, providerID string) (dbusErr *dbus.Error)
DeleteUser removes broker side user data or returns an error if requested.
func (*BrokerBusMock) EndSession ¶
func (b *BrokerBusMock) EndSession(sessionID string) (dbusErr *dbus.Error)
EndSession returns default values to be used in tests or an error if requested.
func (*BrokerBusMock) GetAuthenticationModes ¶
func (b *BrokerBusMock) GetAuthenticationModes(sessionID string, supportedUILayouts []map[string]string) (authenticationModes []map[string]string, dbusErr *dbus.Error)
GetAuthenticationModes returns default values to be used in tests or an error if requested.
func (*BrokerBusMock) IsAuthenticated ¶
func (b *BrokerBusMock) IsAuthenticated(sessionID, authenticationData string) (access, data string, dbusErr *dbus.Error)
IsAuthenticated returns default values to be used in tests or an error if requested.
func (*BrokerBusMock) NewSession ¶
func (b *BrokerBusMock) NewSession(username, lang, mode, providerID string) (sessionID, encryptionKey string, dbusErr *dbus.Error)
NewSession returns default values to be used in tests or an error if requested.
func (*BrokerBusMock) SelectAuthenticationMode ¶
func (b *BrokerBusMock) SelectAuthenticationMode(sessionID, authenticationModeName string) (uiLayoutInfo map[string]string, dbusErr *dbus.Error)
SelectAuthenticationMode returns default values to be used in tests or an error if requested.
func (*BrokerBusMock) UserPreCheck ¶
func (b *BrokerBusMock) UserPreCheck(username string) (userinfo string, dbusErr *dbus.Error)
UserPreCheck returns default values to be used in tests or an error if requested.
type DaemonOption ¶
type DaemonOption func(*daemonOptions)
DaemonOption represents an optional function that can be used to override some of the daemon default values.
var WithCurrentUserAsRoot DaemonOption = func(o *daemonOptions) { o.env = append(o.env, "AUTHD_INTEGRATIONTESTS_CURRENT_USER_AS_ROOT=1") }
WithCurrentUserAsRoot configures authd to accept the current user as root when checking permissions. This is useful for integration tests where the current user is not root, but we want to test the behavior as if it were root.
func WithDBPath ¶
func WithDBPath(path string) DaemonOption
WithDBPath overrides the default database path of the daemon.
func WithEnvironment ¶
func WithEnvironment(env ...string) DaemonOption
WithEnvironment overrides the default environment of the daemon.
func WithGroupFile ¶
func WithGroupFile(groupFile string) DaemonOption
WithGroupFile sets the group file.
func WithGroupFileOutput ¶
func WithGroupFileOutput(groupFile string) DaemonOption
WithGroupFileOutput sets the group output file.
func WithHomeBaseDir ¶
func WithHomeBaseDir(baseDir string) DaemonOption
WithHomeBaseDir sets the base path for the user home directories.
func WithOutputAsTestArtifact ¶
func WithOutputAsTestArtifact() DaemonOption
WithOutputAsTestArtifact saves the daemon output to a test artifact.
func WithPidFile ¶
func WithPidFile(pidFile string) DaemonOption
WithPidFile sets the path where the process pid will be saved while running. The pidFile is also special because when it gets removed, authd is stopped.
func WithPreviousDBState ¶
func WithPreviousDBState(db string) DaemonOption
WithPreviousDBState initializes the database of the daemon with a preexistent database.
func WithSharedDaemon ¶
func WithSharedDaemon(shared bool) DaemonOption
WithSharedDaemon sets whether the daemon is shared between tests.
func WithSocketPath ¶
func WithSocketPath(path string) DaemonOption
WithSocketPath overrides the default socket path of the daemon.
type SyncBuffer ¶
type SyncBuffer struct {
// contains filtered or unexported fields
}
SyncBuffer is a mutex-protected buffer to avoid data races.
func (*SyncBuffer) String ¶
func (s *SyncBuffer) String() string
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package golden provides utilities to compare and update golden files in tests.
|
Package golden provides utilities to compare and update golden files in tests. |
|
Package ptytest provides a PTY-based test harness for interactive terminal testing.
|
Package ptytest provides a PTY-based test harness for interactive terminal testing. |
|
launcher
command
package main is a helper binary for ptytest tests that launches a child process.
|
package main is a helper binary for ptytest tests that launches a child process. |