testhelpers

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package testhelpers provides the shared test helpers, file helpers and generated mocks of this module.

Index

Constants

View Source
const FlagKeyNotStringResult = MissingFlagKeyResult

FlagKeyNotStringResult is the expected flag configuration for MongoFindResultFlagNoStr.

View Source
const MissingFlagKeyResult = `{"test-flag":{"variations":{"true_var":true,"false_var":false},"targeting":[{"query` +
	`":"key eq \"random-key\"","percentage":{"true_var":0,"false_var":100}}],"defaultRule":{"variation":"false_var"}` +
	`,"trackEvents":false}}`

MissingFlagKeyResult is the expected flag configuration for MongoMissingFlagKey.

View Source
const MongoFindResultFlagNoStr = `[{"flag":123456,"variations":{"true_var":true,"false_var":false},"targeting":[{` +
	`"query":"key eq \"random-key\"","percentage":{"true_var":0,"false_var":100}}],"defaultRule":{"variation":"false` +
	`_var"},"trackEvents":false},{"flag":"test-flag","variations":{"true_var":true,"false_var":false},"targeting":[{` +
	`"query":"key eq \"random-key\"","percentage":{"true_var":0,"false_var":100}}],"defaultRule":{"variation":"false` +
	`_var"},"trackEvents":false}]`

MongoFindResultFlagNoStr is a MongoDB find result in which a flag key is not a string.

View Source
const MongoFindResultString = `[{"flag":"test-flag","variations":{"true_var":true,"false_var":false},"targeting":` +
	`[{"query":"key eq \"random-key\"","percentage":{"true_var":0,"false_var":100}}],"defaultRule":{"variation":"fal` +
	`se_var"},"trackEvents":false},{"flag":"test-flag2","variations":{"true_var":true,"false_var":false},"targeting"` +
	`:[{"query":"key eq \"not-a-key\"","percentage":{"true_var":0,"false_var":100}}],"defaultRule":{"variation":"fal` +
	`se_var"},"trackEvents":false}]`

MongoFindResultString is a MongoDB find result with two flags.

View Source
const MongoMissingFlagKey = `[{"flag":"test-flag","variations":{"true_var":true,"false_var":false},"targeting":[{` +
	`"query":"key eq \"random-key\"","percentage":{"true_var":0,"false_var":100}}],"defaultRule":{"variation":"false` +
	`_var"},"trackEvents":false},{"variations":{"true_var":true,"false_var":false},"targeting":[{"query":"key eq \"n` +
	`ot-a-key\"","percentage":{"true_var":0,"false_var":100}}],"defaultRule":{"variation":"false_var"},"trackEvents"` +
	`:false}]`

MongoMissingFlagKey is a MongoDB find result in which one flag has no key.

View Source
const QueryResult = `{"test-flag":{"variations":{"true_var":true,"false_var":false},"targeting":[{"query":"key eq` +
	` \"random-key\"","percentage":{"true_var":0,"false_var":100}}],"defaultRule":{"variation":"false_var"},"trackEv` +
	`ents":false},"test-flag2":{"variations":{"true_var":true,"false_var":false},"targeting":[{"query":"key eq \"not` +
	`-a-key\"","percentage":{"true_var":0,"false_var":100}}],"defaultRule":{"variation":"false_var"},"trackEvents":false}}`

QueryResult is the expected flag configuration of the MongoDB query tests.

View Source
const RFC3339Regex = "" //nolint:lll // long literal that can not be wrapped

/* 161-byte string literal not displayed */

RFC3339Regex is a regular expression that matches RFC 3339 timestamps.

Variables

This section is empty.

Functions

func CopyContentToExistingTempFile

func CopyContentToExistingTempFile(t *testing.T, content string, file *os.File) *os.File

CopyContentToExistingTempFile writes content into file and returns it.

func CopyContentToNewTempFile

func CopyContentToNewTempFile(t *testing.T, content string) *os.File

CopyContentToNewTempFile writes content into a new temporary file and returns it.

func CopyFileToExistingTempFile

func CopyFileToExistingTempFile(t *testing.T, src string, file *os.File) *os.File

CopyFileToExistingTempFile copies the file src into file and returns it.

func CopyFileToNewTempFile

func CopyFileToNewTempFile(t *testing.T, src string) *os.File

CopyFileToNewTempFile copies the file src into a new temporary file and returns it.

func EncodedMd5Hash

func EncodedMd5Hash(content []byte) string

EncodedMd5Hash returns the base64-encoded MD5 hash of content.

func ListenLocal

func ListenLocal(t *testing.T) (net.Listener, int)

ListenLocal binds a TCP listener on a free loopback port and returns it with the port. The listener stays bound until the test ends, so no other test can take the port: hand it to the component under test (for example api.WithListener) instead of closing it and binding the port again later. The component that serves on it closes it; the test cleanup closing it a second time is harmless.

func ReplaceAndCopyFileToExistingFile

func ReplaceAndCopyFileToExistingFile(t *testing.T, src string, dstFile *os.File, old, newStr string) *os.File

ReplaceAndCopyFileToExistingFile copies src into dstFile, replacing old with newStr, and returns dstFile.

func ReplaceInFile

func ReplaceInFile(t *testing.T, file *os.File, old, newStr string)

ReplaceInFile replaces the text old with newStr in file.

Types

type ExportableMockEvent

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

ExportableMockEvent is an exportable evaluation event used in tests.

func NewExportableMockEvent

func NewExportableMockEvent(name string) ExportableMockEvent

NewExportableMockEvent returns an exportable event with the given name.

func (ExportableMockEvent) FormatInCSV

func (e ExportableMockEvent) FormatInCSV(_ *template.Template) ([]byte, error)

FormatInCSV returns the event formatted as a CSV line.

func (ExportableMockEvent) FormatInJSON

func (e ExportableMockEvent) FormatInJSON() ([]byte, error)

FormatInJSON returns the event formatted as JSON.

func (ExportableMockEvent) GetCreationDate

func (ExportableMockEvent) GetCreationDate() int64

GetCreationDate returns the creation date of the event as a Unix timestamp.

func (ExportableMockEvent) GetKey

func (e ExportableMockEvent) GetKey() string

GetKey returns the name of the event as its key.

func (ExportableMockEvent) GetUserKey

func (e ExportableMockEvent) GetUserKey() string

GetUserKey returns the name of the event as its user key.

type GCStorageReaderMock

type GCStorageReaderMock struct {
	FileToRead string

	ShouldFail bool
	// contains filtered or unexported fields
}

GCStorageReaderMock is a mock of a Google Cloud Storage object reader.

func (*GCStorageReaderMock) Close

func (*GCStorageReaderMock) Close() error

Close does nothing and always returns nil.

func (*GCStorageReaderMock) Read

func (r *GCStorageReaderMock) Read(buf []byte) (int, error)

type MockedStorage

type MockedStorage struct {
	Server *fakestorage.Server
}

MockedStorage is a fake Google Cloud Storage server used in tests.

func NewMockedGCS

func NewMockedGCS(t *testing.T) MockedStorage

NewMockedGCS starts a fake Google Cloud Storage server for the test.

func (MockedStorage) WithFiles

func (m MockedStorage) WithFiles(t *testing.T, bucketName string, files map[string]string)

WithFiles adds the files to the bucket bucketName of the fake server.

type Mockobject

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

Mockobject is a mock of object interface.

func NewMockobject

func NewMockobject(ctrl *gomock.Controller) *Mockobject

NewMockobject creates a new mock instance.

func (*Mockobject) Attrs

func (m *Mockobject) Attrs(ctx context.Context) (*storage.ObjectAttrs, error)

Attrs mocks base method.

func (*Mockobject) EXPECT

func (m *Mockobject) EXPECT() *MockobjectMockRecorder

EXPECT returns an object that allows the caller to indicate expected use.

func (*Mockobject) NewReader

func (m *Mockobject) NewReader(ctx context.Context) (*storage.Reader, error)

NewReader mocks base method.

type MockobjectMockRecorder

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

MockobjectMockRecorder is the mock recorder for Mockobject.

func (*MockobjectMockRecorder) Attrs

func (mr *MockobjectMockRecorder) Attrs(ctx any) *gomock.Call

Attrs indicates an expected call of Attrs.

func (*MockobjectMockRecorder) NewReader

func (mr *MockobjectMockRecorder) NewReader(ctx any) *gomock.Call

NewReader indicates an expected call of NewReader.

type S3ManagerV2Mock

type S3ManagerV2Mock struct {
	S3ManagerMockFileSystem map[string]string
	TestDataLocation        string
}

S3ManagerV2Mock is a mock of the S3 transfer manager that works on an in-memory file system.

func (*S3ManagerV2Mock) DownloadObject

DownloadObject reads the object from the mock file system.

func (*S3ManagerV2Mock) UploadObject

UploadObject stores the uploaded content in the mock file system.

type S3PrefixMock

type S3PrefixMock struct {
	// ListErr, if set, is returned by every ListObjectsV2 call.
	ListErr error
	// DownloadErr, if set, is returned by every DownloadObject call.
	DownloadErr error
	// BeforeDownload, if set, is called with the key at the start of every DownloadObject call,
	// without the mock lock held, so it can call Put and Delete to swap an object between the list
	// and the download.
	BeforeDownload func(key string)

	// PageSize is the max number of keys returned by one ListObjectsV2 call (default 1000).
	PageSize int

	// NoETag lists the objects with an empty ETag, like some S3 compatible stores do.
	NoETag bool
	// contains filtered or unexported fields
}

S3PrefixMock is an in-memory fake of a S3 bucket implementing both the lister and the downloader APIs used by the S3 retriever v2. It supports prefix/delimiter semantics, pagination, ETags and call counters.

func (*S3PrefixMock) Delete

func (m *S3PrefixMock) Delete(key string)

Delete removes an object.

func (*S3PrefixMock) DownloadCalls

func (m *S3PrefixMock) DownloadCalls(key string) int

DownloadCalls returns the number of times the key was downloaded.

func (*S3PrefixMock) DownloadObject

DownloadObject writes the content of the object in the WriterAt of the input.

func (*S3PrefixMock) ListCalls

func (m *S3PrefixMock) ListCalls() int

ListCalls returns the number of ListObjectsV2 calls.

func (*S3PrefixMock) ListObjectsV2

func (m *S3PrefixMock) ListObjectsV2(
	_ context.Context,
	params *s3.ListObjectsV2Input,
	_ ...func(*s3.Options),
) (*s3.ListObjectsV2Output, error)

ListObjectsV2 mimics the S3 API (prefix, delimiter, continuation token, max keys).

func (*S3PrefixMock) Put

func (m *S3PrefixMock) Put(key, content string)

Put creates or replaces an object. The ETag is derived from the content.

func (*S3PrefixMock) SetDownloadErrKey

func (m *S3PrefixMock) SetDownloadErrKey(key string, err error)

SetDownloadErrKey makes the download of one key fail with err, nil removes the failure.

func (*S3PrefixMock) TotalDownloadCalls

func (m *S3PrefixMock) TotalDownloadCalls() int

TotalDownloadCalls returns the number of downloads, all keys included.

Directories

Path Synopsis
Package apifake holds what the fakes of the repository APIs (githubfake, gitlabfake, bitbucketfake) share: the record of the requests a fake saw, the access token a private repository requires, and the answers of an exhausted request limit.
Package apifake holds what the fakes of the repository APIs (githubfake, gitlabfake, bitbucketfake) share: the record of the requests a fake saw, the access token a private repository requires, and the answers of an exhausted request limit.
Package bitbucketfake is a fake of the source API of Bitbucket Cloud for the tests of the bitbucket flag source: the files of one repository at a branch (a .json file as application/json, any other as text/plain), served at /2.0/repositories/<workspace>/<repo>/src/<ref>/<path> as the documentation of Bitbucket describes it (the ref is one path segment, a directory is answered with a JSON listing, a Bearer token is checked, an exhausted limit is a 429), and a record of what the relay sent.
Package bitbucketfake is a fake of the source API of Bitbucket Cloud for the tests of the bitbucket flag source: the files of one repository at a branch (a .json file as application/json, any other as text/plain), served at /2.0/repositories/<workspace>/<repo>/src/<ref>/<path> as the documentation of Bitbucket describes it (the ref is one path segment, a directory is answered with a JSON listing, a Bearer token is checked, an exhausted limit is a 429), and a record of what the relay sent.
Package cloudfake holds fakes of the two cloud object stores the control plane reads: the media download of the Google Cloud Storage JSON API and the Get Blob request of Azure Blob Storage.
Package cloudfake holds fakes of the two cloud object stores the control plane reads: the media download of the Google Cloud Storage JSON API and the Get Blob request of Azure Blob Storage.
Package dynamofake is a fake of the DynamoDB service for the tests of the DynamoDB flag source: an HTTP server on a loopback port that speaks the JSON protocol of the service and answers Scan from tables it keeps in memory, a page at a time.
Package dynamofake is a fake of the DynamoDB service for the tests of the DynamoDB flag source: an HTTP server on a loopback port that speaks the JSON protocol of the service and answers Scan from tables it keeps in memory, a page at a time.
Package fixture reads and checks the fixture files of a test package: the expected outputs and the sample documents under its testdata/fixtures directory.
Package fixture reads and checks the fixture files of a test package: the expected outputs and the sample documents under its testdata/fixtures directory.
Package fixtures holds the constants shared by the tests of more than one package: flag keys, user keys, variation names, rule names, API keys, fixture file paths and a few common literals.
Package fixtures holds the constants shared by the tests of more than one package: flag keys, user keys, variation names, rule names, API keys, fixture file paths and a few common literals.
Package githubfake is a fake of the contents API of GitHub for the tests of the github flag source: the files of one branch of one repository, answered with an ETag and 304, a 404 for a file that is away, a token the server requires, the answers of an exhausted request limit, a redirect, and a record of what the relay sent (path, ref, token and Accept).
Package githubfake is a fake of the contents API of GitHub for the tests of the github flag source: the files of one branch of one repository, answered with an ETag and 304, a 404 for a file that is away, a token the server requires, the answers of an exhausted request limit, a redirect, and a record of what the relay sent (path, ref, token and Accept).
Package gitlabfake is a fake of the repository files API of GitLab for the tests of the gitlab flag source: the raw files of one branch of one project, served as GitLab serves them (the project and the file path are each one path segment with "/" sent as %2F, a 404 for a file or a project that is not there, a 401 for a wrong token, a 404 for a private project without a token, the PRIVATE-TOKEN header, the rate limit answers with the RateLimit-* headers), and a record of what the relay sent.
Package gitlabfake is a fake of the repository files API of GitLab for the tests of the gitlab flag source: the raw files of one branch of one project, served as GitLab serves them (the project and the file path are each one path segment with "/" sent as %2F, a 404 for a file or a project that is not there, a 401 for a wrong token, a 404 for a private project without a token, the PRIVATE-TOKEN header, the rate limit answers with the RateLimit-* headers), and a record of what the relay sent.
Package gopherstack starts the gopherstack AWS emulator (https://github.com/blackbirdworks/gopherstack) in a Docker container, to run end-to-end tests of the AWS-backed components (S3, Kinesis, SQS).
Package gopherstack starts the gopherstack AWS emulator (https://github.com/blackbirdworks/gopherstack) in a Docker container, to run end-to-end tests of the AWS-backed components (S3, Kinesis, SQS).
Package httpfake is a file server for the tests of the http flag source: files by key, with the validators a test chooses (ETag, Last-Modified or none), conditional requests, a removed file answered 404, a redirect, a required header, a hang, and counters of what the relay asked.
Package httpfake is a file server for the tests of the http flag source: files by key, with the validators a test chooses (ETag, Last-Modified or none), conditional requests, a removed file answered 404, a redirect, a required header, a hang, and counters of what the relay asked.
Package httpsink is a local HTTP endpoint for tests: it answers every request with a fixed status and keeps what it received, so a test drives a component through its real HTTP client and checks the request it sent.
Package httpsink is a local HTTP endpoint for tests: it answers every request with a fixed status and keeps what it received, so a test drives a component through its real HTTP client and checks the request it sent.
Package kubefake is a fake of the Kubernetes API for the tests of the ConfigMap flag source: it serves GET /api/v1/namespaces/<namespace>/configmaps/<name> as the API server does (a ConfigMap document with its resourceVersion that moves on every write, a Status document for 401, 403, 404, 429 and 5xx), checks a bearer token, and records what the client sent.
Package kubefake is a fake of the Kubernetes API for the tests of the ConfigMap flag source: it serves GET /api/v1/namespaces/<namespace>/configmaps/<name> as the API server does (a ConfigMap document with its resourceVersion that moves on every write, a Status document for 401, 403, 404, 429 and 5xx), checks a bearer token, and records what the client sent.
Package mock provides mocks of the exporters, notifiers and services used in tests.
Package mock provides mocks of the exporters, notifiers and services used in tests.
mockretriever
Package mockretriever provides mock implementations of various retriever interfaces for testing purposes in the semaphore project.
Package mockretriever provides mock implementations of various retriever interfaces for testing purposes in the semaphore project.
Package mongofake is a fake of a MongoDB server for the tests of the MongoDB flag source: it speaks the wire protocol (OP_MSG, and the OP_QUERY of the first handshake) on a loopback port, and answers hello, ping, find (sorted by _id, in batches), getMore, killCursors, listCollections and endSessions from collections it keeps in memory.
Package mongofake is a fake of a MongoDB server for the tests of the MongoDB flag source: it speaks the wire protocol (OP_MSG, and the OP_QUERY of the first handshake) on a loopback port, and answers hello, ping, find (sorted by _id, in batches), getMore, killCursors, listCollections and endSessions from collections it keeps in memory.
Package pgfake is a PostgreSQL server fake for tests: it speaks the wire protocol (through the pgproto3 package of the driver) on a loopback port and answers the statement the PostgreSQL flag source sends: the name column and the config column of a table (the config is NULL, and a third column says so, when it is over the limit that the statement binds), with the rows of one flag set when the statement asks for them.
Package pgfake is a PostgreSQL server fake for tests: it speaks the wire protocol (through the pgproto3 package of the driver) on a loopback port and answers the statement the PostgreSQL flag source sends: the name column and the config column of a table (the config is NULL, and a third column says so, when it is over the limit that the statement binds), with the rows of one flag set when the statement asks for them.
Package slogutil provides slog helpers that capture log records in tests.
Package slogutil provides slog helpers that capture log records in tests.
Package testclient gives tests an HTTP client with a transport of its own.
Package testclient gives tests an HTTP client with a transport of its own.
Package tlstest makes the certificates of the TLS tests.
Package tlstest makes the certificates of the TLS tests.

Jump to

Keyboard shortcuts

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