testrig

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2024 License: AGPL-3.0 Imports: 60 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigureTemplatesWithGin added in v0.2.0

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

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

func CreateGinTestContext added in v0.3.8

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(fieldName string, fileName string, extraFields map[string][]string) (bytes.Buffer, *multipart.Writer, error)

CreateMultipartFormData is a handy function for taking a fieldname and a filename, and creating a multipart form bytes buffer with the file contents set in the given fieldname. The extraFields param can be used to add extra FormFields to the request, as necessary. 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 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 added in v0.8.0

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

func InitTestConfig added in v0.2.0

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 added in v0.2.0

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 added in v0.3.1

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 added in v0.3.3

func NewAPNote(
	noteID *url.URL,
	noteURL *url.URL,
	noteCreatedAt time.Time,
	noteContent string,
	noteSummary string,
	noteAttributedTo *url.URL,
	noteTo []*url.URL,
	noteCC []*url.URL,
	noteSensitive bool,
	noteMentions []vocab.ActivityStreamsMention,
	noteTags []vocab.TootHashtag,
	noteAttachments []vocab.ActivityStreamsImage,
) vocab.ActivityStreamsNote

NewAPNote returns a new activity streams note for 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 added in v0.3.7

func NewInMemoryStorage() *gtsstorage.Driver

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

func NewTestAccountNotes added in v0.11.0

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

NewTestAccountNotes returns some account notes for use in testing.

func NewTestAccountSettings added in v0.15.0

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 added in v0.7.0

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

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

func NewTestClients

func NewTestClients() map[string]*gtsmodel.Client

NewTestClients returns a map of Clients keyed according to which account they are used by.

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 added in v0.6.0

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 added in v0.5.0

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 added in v0.3.5

func NewTestFediServices() map[string]vocab.ActivityStreamsService

func NewTestFediStatuses

func NewTestFediStatuses() map[string]vocab.ActivityStreamsNote

func NewTestFilterKeywords added in v0.15.0

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

func NewTestFilterStatuses added in v0.15.0

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

func NewTestFilters added in v0.15.0

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

func NewTestFollows

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

NewTestFollows returns some follows for use in testing.

func NewTestInstances added in v0.3.7

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

func NewTestListEntries added in v0.10.0

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

func NewTestLists added in v0.10.0

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

func NewTestMarkers added in v0.11.0

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

func NewTestMediaManager added in v0.2.0

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(db db.DB) oauth.Server

NewTestOauthServer returns an oauth server with the given db

func NewTestPollVotes added in v0.13.0

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

func NewTestPolls added in v0.13.0

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

func NewTestProcessor

func NewTestProcessor(state *state.State, federator *federation.Federator, emailSender email.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 added in v0.7.0

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 added in v0.12.0

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

func NewTestStatusToEmojis added in v0.6.0

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

func NewTestStatusToTags added in v0.6.0

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 NewTestThreadToStatus added in v0.13.0

func NewTestThreadToStatus() []*gtsmodel.ThreadToStatus

func NewTestThreads added in v0.13.0

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 added in v0.6.0

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 NewTestUsers

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

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

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 added in v0.13.0

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 StartTimelines added in v0.10.0

func StartTimelines(state *state.State, filter *visibility.Filter, converter *typeutils.Converter)

func StartWorkers added in v0.8.0

func StartWorkers(state *state.State, wProcessor *wprocessor.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 added in v0.8.0

func StopWorkers(state *state.State)

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 added in v0.5.0

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 added in v0.3.5

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

func WrapAPNoteInCreate added in v0.3.3

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

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 MockHTTPClient added in v0.3.5

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 ...vocab.ActivityStreamsPerson) *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 added in v0.3.5

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

func (*MockHTTPClient) DoSigned added in v0.9.0

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

type RemoteAttachmentFile

type RemoteAttachmentFile struct {
	Data        []byte
	ContentType string
}

RemoteAttachmentFile mimics a remote (federated) attachment

Jump to

Keyboard shortcuts

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