testrig

package
v0.20.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2025 License: AGPL-3.0 Imports: 69 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigureTemplatesWithGin

func ConfigureTemplatesWithGin(engine *gin.Engine, templatePath string)

ConfigureTemplatesWithGin will panic on any errors related to template loading during tests

func CreateGinTestContext

func CreateGinTestContext(rw http.ResponseWriter, r *http.Request) (*gin.Context, *gin.Engine)

CreateGinTextContext creates a new gin.Context suitable for a test, with an instantiated gin.Engine.

func CreateMultipartFormData

func CreateMultipartFormData(
	dataF DataF,
	extraFields map[string][]string,
) (bytes.Buffer, *multipart.Writer, error)

CreateMultipartFormData is a handy function for creating a multipart form bytes buffer with data.

If data function is not nil, it should return the fieldName for the data in the form (eg., "data"), the fileName (eg., "data.csv"), a readcloser for getting the data, or an error if something goes wrong.

The extraFields param can be used to add extra FormFields to the request, as necessary.

Data function can be nil if only FormFields and string values are required.

The returned bytes.Buffer b can be used like so:

httptest.NewRequest(http.MethodPost, "https://example.org/whateverpath", bytes.NewReader(b.Bytes()))

The returned *multipart.Writer w can be used to set the content type of the request, like so:

req.Header.Set("Content-Type", w.FormDataContentType())

func CreateTestTables

func CreateTestTables(db db.DB)

CreateTestTables creates prerequisite test tables in the database, but doesn't populate them.

func DomainPermissionSubscriptionResponse

func DomainPermissionSubscriptionResponse(req *http.Request) (
	responseCode int,
	responseBytes []byte,
	responseContentType string,
	responseContentLength int,
	extraHeaders map[string]string,
)

func EqualRequestURIs

func EqualRequestURIs(u1, u2 any) bool

EqualRequestURIs checks whether inputs have equal request URIs, handling cases of url.URL{}, *url.URL{}, string, *string.

func GetSignatureForActivity

func GetSignatureForActivity(activity pub.Activity, pubKeyID string, privkey *rsa.PrivateKey, destination *url.URL) (signatureHeader string, digestHeader string, dateHeader string)

GetSignatureForActivity prepares a mock HTTP request as if it were going to deliver activity to destination signed for privkey and pubKeyID, signs the request and returns the header values.

func GetSignatureForDereference

func GetSignatureForDereference(pubKeyID string, privkey *rsa.PrivateKey, destination *url.URL) (signatureHeader string, digestHeader string, dateHeader string)

GetSignatureForDereference prepares a mock HTTP request as if it were going to dereference destination signed for privkey and pubKeyID, signs the request and returns the header values.

func HostMetaResponse

func HostMetaResponse(req *http.Request) (
	responseCode int,
	responseBytes []byte,
	responseContentType string,
	responseContentLength int,
	extraHeaders map[string]string,
)

func InitTestConfig

func InitTestConfig()

InitTestConfig initializes viper configuration with test defaults.

func InitTestLog

func InitTestLog()

InitTestLog sets the global logger to trace level for logging

func InitTestSyslog

func InitTestSyslog() (*syslog.Server, chan format.LogParts, error)

InitTestSyslog returns a test syslog running on port 42069 and a channel for reading messages sent to the server, or an error if something goes wrong.

Callers of this function should call Kill() on the server when they're finished with it!

func InitTestSyslogUnixgram

func InitTestSyslogUnixgram(address string) (*syslog.Server, chan format.LogParts, error)

InitTestSyslog returns a test syslog running on a unix socket, and a channel for reading messages sent to the server, or an error if something goes wrong.

Callers of this function should call Kill() on the server when they're finished with it!

func NewAPNote

NewAPNote is a utility function that returns a new activity streams note using the given parameters.

func NewEmailSender

func NewEmailSender(templateBaseDir string, sentEmails map[string]string) email.Sender

NewEmailSender returns a noop email sender that won't make any remote calls.

If sentEmails is not nil, the noop callback function will place sent emails in the map, with email address of the recipient as the key, and the value as the parsed email message as it would have been sent.

func NewInMemoryStorage

func NewInMemoryStorage() *gtsstorage.Driver

NewInMemoryStorage returns a new in memory storage with the default test config

func NewNoopWebPushSender

func NewNoopWebPushSender() webpush.Sender

NewNoopWebPushSender creates a no-op sender that does nothing.

func NewTestAccountNotes

func NewTestAccountNotes() map[string]*gtsmodel.AccountNote

NewTestAccountNotes returns some account notes for use in testing.

func NewTestAccountSettings

func NewTestAccountSettings() map[string]*gtsmodel.AccountSettings

func NewTestAccounts

func NewTestAccounts() map[string]*gtsmodel.Account

NewTestAccounts returns a map of accounts keyed by what type of account they are.

func NewTestActivities

func NewTestActivities(accounts map[string]*gtsmodel.Account) map[string]ActivityWithSignature

NewTestActivities returns a bunch of pub.Activity types for use in testing the federation protocols. A struct of accounts needs to be passed in because the activities will also be bundled along with their requesting signatures.

func NewTestApplications

func NewTestApplications() map[string]*gtsmodel.Application

NewTestApplications returns a map of applications keyed to which number application they are.

func NewTestAttachments

func NewTestAttachments() map[string]*gtsmodel.MediaAttachment

NewTestAttachments returns a map of attachments keyed according to which account and status they belong to, and which attachment number of that status they are.

func NewTestBlocks

func NewTestBlocks() map[string]*gtsmodel.Block

func NewTestBookmarks

func NewTestBookmarks() map[string]*gtsmodel.StatusBookmark

NewTestBookmarks returns a map of gts model bookmarks, keyed in the format [bookmarking_account]_[target_status]

func NewTestDB

func NewTestDB(state *state.State) db.DB

NewTestDB returns a new initialized, empty database for testing.

If the environment variable GTS_DB_ADDRESS is set, it will take that value as the database address instead.

If the environment variable GTS_DB_TYPE is set, it will take that value as the database type instead.

If the environment variable GTS_DB_PORT is set, it will take that value as the port instead.

func NewTestDereferenceRequests

func NewTestDereferenceRequests(accounts map[string]*gtsmodel.Account) map[string]ActivityWithSignature

NewTestDereferenceRequests returns a map of incoming dereference requests, with their signatures.

func NewTestDomainBlocks

func NewTestDomainBlocks() map[string]*gtsmodel.DomainBlock

func NewTestEmojiCategories

func NewTestEmojiCategories() map[string]*gtsmodel.EmojiCategory

func NewTestEmojis

func NewTestEmojis() map[string]*gtsmodel.Emoji

NewTestEmojis returns a map of gts emojis, keyed by the emoji shortcode

func NewTestFaves

func NewTestFaves() map[string]*gtsmodel.StatusFave

NewTestFaves returns a map of gts model faves, keyed in the format [faving_account]_[target_status]

func NewTestFederatingDB

func NewTestFederatingDB(state *state.State) *federatingdb.DB

NewTestFederatingDB returns a federating DB with the underlying db

func NewTestFederator

func NewTestFederator(state *state.State, tc transport.Controller, mediaManager *media.Manager) *federation.Federator

NewTestFederator returns a federator with the given database and (mock!!) transport controller.

func NewTestFediAttachments

func NewTestFediAttachments(relativePath string) map[string]RemoteAttachmentFile

func NewTestFediEmojis

func NewTestFediEmojis() map[string]vocab.TootEmoji

func NewTestFediGroups

func NewTestFediGroups() map[string]vocab.ActivityStreamsGroup

func NewTestFediPeople

func NewTestFediPeople() map[string]vocab.ActivityStreamsPerson

NewTestFediPeople returns a bunch of activity pub Person representations for testing converters and so on.

func NewTestFediServices

func NewTestFediServices() map[string]vocab.ActivityStreamsService

func NewTestFediStatuses

func NewTestFediStatuses() map[string]vocab.ActivityStreamsNote

func NewTestFilterKeywords

func NewTestFilterKeywords() map[string]*gtsmodel.FilterKeyword

func NewTestFilterStatuses

func NewTestFilterStatuses() map[string]*gtsmodel.FilterStatus

func NewTestFilters

func NewTestFilters() map[string]*gtsmodel.Filter

func NewTestFollows

func NewTestFollows() map[string]*gtsmodel.Follow

NewTestFollows returns some follows for use in testing.

func NewTestInstances

func NewTestInstances() map[string]*gtsmodel.Instance

func NewTestInteractionRequests

func NewTestInteractionRequests() map[string]*gtsmodel.InteractionRequest

func NewTestListEntries

func NewTestListEntries() map[string]*gtsmodel.ListEntry

func NewTestLists

func NewTestLists() map[string]*gtsmodel.List

func NewTestMarkers

func NewTestMarkers() map[string]*gtsmodel.Marker

func NewTestMediaManager

func NewTestMediaManager(state *state.State) *media.Manager

NewTestMediaManager returns a media handler with the default test config, and the given db and storage.

func NewTestMentions

func NewTestMentions() map[string]*gtsmodel.Mention

NewTestMentions returns a map of gts model mentions keyed by their name.

func NewTestNotifications

func NewTestNotifications() map[string]*gtsmodel.Notification

NewTestNotifications returns some notifications for use in testing.

func NewTestOauthServer

func NewTestOauthServer(state *state.State) oauth.Server

NewTestOauthServer returns an oauth server with the given db

func NewTestPollVotes

func NewTestPollVotes() map[string]*gtsmodel.PollVote

func NewTestPolls

func NewTestPolls() map[string]*gtsmodel.Poll

func NewTestProcessor

func NewTestProcessor(
	state *state.State,
	federator *federation.Federator,
	emailSender email.Sender,
	webPushSender webpush.Sender,
	mediaManager *media.Manager,
) *processing.Processor

NewTestProcessor returns a Processor suitable for testing purposes. The passed in state will have its worker functions set appropriately, but the state will not be initialized.

func NewTestReports

func NewTestReports() map[string]*gtsmodel.Report

func NewTestRouter

func NewTestRouter(db db.DB) *router.Router

NewTestRouter returns a Router suitable for testing

If the environment variable GTS_WEB_TEMPLATE_BASE_DIR set, it will take that value as the template base directory instead.

func NewTestRules

func NewTestRules() map[string]*gtsmodel.Rule

func NewTestScheduledStatuses added in v0.20.0

func NewTestScheduledStatuses() map[string]*gtsmodel.ScheduledStatus

func NewTestStatusEdits

func NewTestStatusEdits() map[string]*gtsmodel.StatusEdit

func NewTestStatusToEmojis

func NewTestStatusToEmojis() map[string]*gtsmodel.StatusToEmoji

func NewTestStatusToTags

func NewTestStatusToTags() map[string]*gtsmodel.StatusToTag

func NewTestStatuses

func NewTestStatuses() map[string]*gtsmodel.Status

NewTestStatuses returns a map of statuses keyed according to which account and status they are.

func NewTestTags

func NewTestTags() map[string]*gtsmodel.Tag

NewTestTags returns a map of gts model tags keyed by their name

func NewTestThreads

func NewTestThreads() map[string]*gtsmodel.Thread

func NewTestTokens

func NewTestTokens() map[string]*gtsmodel.Token

NewTestTokens returns a map of tokens keyed according to which account the token belongs to.

func NewTestTombstones

func NewTestTombstones() map[string]*gtsmodel.Tombstone

func NewTestTransportController

func NewTestTransportController(state *state.State, client pub.HttpClient) transport.Controller

NewTestTransportController returns a test transport controller with the given http client.

Obviously for testing purposes you should not be making actual http calls to other servers. To obviate this, use the function NewMockHTTPClient in this package to return a mock http client that doesn't make any remote calls but just returns whatever you tell it to.

Unlike the other test interfaces provided in this package, you'll probably want to call this function PER TEST rather than per suite, so that the do function can be set on a test by test (or even more granular) basis.

func NewTestUserMutes

func NewTestUserMutes() map[string]*gtsmodel.UserMute

func NewTestUsers

func NewTestUsers() map[string]*gtsmodel.User

NewTestUsers returns a map of Users keyed by which account belongs to them.

func NewTestWebPushSubscriptions

func NewTestWebPushSubscriptions() map[string]*gtsmodel.WebPushSubscription

func NodeInfoResponse

func NodeInfoResponse(req *http.Request) (
	responseCode int,
	responseBytes []byte,
	responseContentType string,
	responseContentLength int,
	extraHeaders map[string]string,
)

func RobotsTxtResponse

func RobotsTxtResponse(req *http.Request) (
	responseCode int,
	responseBytes []byte,
	responseContentType string,
	responseContentLength int,
	extraHeaders map[string]string,
)

func StandardDBSetup

func StandardDBSetup(db db.DB, accounts map[string]*gtsmodel.Account)

StandardDBSetup populates a given db with all the necessary tables/models for perfoming tests.

The accounts parameter is provided in case the db should be populated with a certain set of accounts. If accounts is nil, then the standard test accounts will be used.

When testing http signatures, you should pass into this function the same accounts map that you generated signatures with, otherwise this function will randomly generate new keys for accounts and signature verification will fail.

func StandardDBTeardown

func StandardDBTeardown(db db.DB)

StandardDBTeardown drops all the standard testing tables/models from the database to ensure it's clean for the next test.

func StandardStorageSetup

func StandardStorageSetup(storage *gtsstorage.Driver, relativePath string)

StandardStorageSetup populates the storage with standard test entries from the given directory.

func StandardStorageTeardown

func StandardStorageTeardown(storage *gtsstorage.Driver)

StandardStorageTeardown deletes everything in storage so that it's clean for the next test.

func StartNoopWorkers

func StartNoopWorkers(state *state.State)

Starts workers on the provided state using noop processing functions. Useful when you *don't* want to trigger side effects in a test.

func StartWorkers

func StartWorkers(state *state.State, processor *workers.Processor)

Starts workers on the provided state using processing functions from the given workers processor. Useful when you *do* want to trigger side effects in a test.

func StopWorkers

func StopWorkers(state *state.State)

func TearDownTestStructs

func TearDownTestStructs(testStructs *TestStructs)

func TimeMustParse

func TimeMustParse(timeString string) time.Time

TimeMustParse tries to parse the given time as RFC3339, and panics if it can't. Should only be used in tests.

func URLMustParse

func URLMustParse(stringURL string) *url.URL

URLMustParse tries to parse the given URL and panics if it can't. Should only be used in tests.

func WaitFor

func WaitFor(condition func() bool) bool

WaitFor calls condition every 200ms, returning true when condition() returns true, or false after 5s.

It's useful for when you're waiting for something to happen, but you don't know exactly how long it will take, and you want to fail if the thing doesn't happen within 5s.

func WebfingerResponse

func WebfingerResponse(req *http.Request) (
	responseCode int,
	responseBytes []byte,
	responseContentType string,
	responseContentLength int,
	extraHeaders map[string]string,
)

func WellKnownNodeInfoResponse

func WellKnownNodeInfoResponse(req *http.Request) (
	responseCode int,
	responseBytes []byte,
	responseContentType string,
	responseContentLength int,
	extraHeaders map[string]string,
)

func WrapAPNoteInCreate

func WrapAPNoteInCreate(createID *url.URL, createActor *url.URL, createPublished time.Time, createNote vocab.ActivityStreamsNote) vocab.ActivityStreamsCreate

WrapAPNoteInCreate wraps the given activity streams note in a Create activity streams action

func WrapAPNoteInUpdate

func WrapAPNoteInUpdate(
	updateID *url.URL,
	updateTarget *url.URL,
	updateActor *url.URL,
	updatePublished time.Time,
	updateNote vocab.ActivityStreamsNote,
) vocab.ActivityStreamsUpdate

Types

type ActivityWithSignature

type ActivityWithSignature struct {
	Activity        pub.Activity
	SignatureHeader string
	DigestHeader    string
	DateHeader      string
}

ActivityWithSignature wraps a pub.Activity along with its signature headers, for testing.

type DataF

type DataF func() (
	fieldName string,
	fileName string,
	rc io.ReadCloser,
	err error,
)

func FileToDataF

func FileToDataF(fieldName string, filePath string) DataF

FileToDataF is a convenience function for opening a file at the given filePath, and packaging it into a DataF for use in CreateMultipartFormData.

func StringToDataF

func StringToDataF(fieldName string, fileName string, data string) DataF

StringToDataF is a convenience function for wrapping the given data into a DataF for use in CreateMultipartFormData.

type MockHTTPClient

type MockHTTPClient struct {
	TestRemoteStatuses    map[string]vocab.ActivityStreamsNote
	TestRemotePeople      map[string]vocab.ActivityStreamsPerson
	TestRemoteGroups      map[string]vocab.ActivityStreamsGroup
	TestRemoteServices    map[string]vocab.ActivityStreamsService
	TestRemoteAttachments map[string]RemoteAttachmentFile
	TestRemoteEmojis      map[string]vocab.TootEmoji
	TestTombstones        map[string]*gtsmodel.Tombstone

	SentMessages sync.Map
	// contains filtered or unexported fields
}

func NewMockHTTPClient

func NewMockHTTPClient(do func(req *http.Request) (*http.Response, error), relativeMediaPath string, extraPeople ...ap.Accountable) *MockHTTPClient

NewMockHTTPClient returns a client that conforms to the pub.HttpClient interface.

If do is nil, then a standard response set will be mocked out, which includes models stored in the testrig, and webfinger responses as well.

If do is not nil, then the given do function will always be used, which allows callers to customize how the client is mocked.

Note that you should never ever make ACTUAL http calls with this thing.

func (*MockHTTPClient) Do

func (m *MockHTTPClient) Do(req *http.Request) (*http.Response, error)

func (*MockHTTPClient) DoSigned

func (m *MockHTTPClient) DoSigned(req *http.Request, sign httpclient.SignFunc) (*http.Response, error)

type NewAPNoteParams added in v0.20.0

type NewAPNoteParams struct {
	ID                 *url.URL
	URL                *url.URL
	CreatedAt          time.Time
	Content            string
	Summary            string
	AttributedTo       *url.URL
	To                 []*url.URL
	CC                 []*url.URL
	Sensitive          bool
	Mentions           []vocab.ActivityStreamsMention
	Tags               []vocab.TootHashtag
	Attachments        []vocab.ActivityStreamsImage
	InReplyTo          *url.URL
	ApprovedBy         *url.URL
	ReplyAuthorization *url.URL
}

type RemoteAttachmentFile

type RemoteAttachmentFile struct {
	Data        []byte
	ContentType string
}

RemoteAttachmentFile mimics a remote (federated) attachment

type TestStructs

type TestStructs struct {
	State               *state.State
	Common              *common.Processor
	Processor           *processing.Processor
	HTTPClient          *MockHTTPClient
	TypeConverter       *typeutils.Converter
	EmailSender         email.Sender
	WebPushSender       *WebPushMockSender
	TransportController transport.Controller
	InteractionFilter   *interaction.Filter
	StatusFilter        *status.Filter
}

TestStructs encapsulates structs needed to run one test independently. Each test should call SetupTestStructs to get a new TestStructs, and defer TearDownTestStructs to close it when the test is complete. The reason for doing things this way here is to prevent the tests in a package from overwriting one another's processors and worker queues, which was causing issues when running all tests at once.

func SetupTestStructs

func SetupTestStructs(
	rMediaPath string,
	rTemplatePath string,
) *TestStructs

type WebPushMockSender

type WebPushMockSender struct {
	Sent map[string][]*gtsmodel.Notification
}

WebPushMockSender collects a map of notifications sent to each account ID.

func NewWebPushMockSender

func NewWebPushMockSender() *WebPushMockSender

NewWebPushMockSender creates a mock sender that can record sent Web Push notifications for test expectations.

func (*WebPushMockSender) Send

func (m *WebPushMockSender) Send(
	ctx context.Context,
	notif *gtsmodel.Notification,
	apiNotif *apimodel.Notification,
) error

Jump to

Keyboard shortcuts

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