testrig

package
v0.5.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2022 License: AGPL-3.0 Imports: 52 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 FalseBool added in v0.4.0

func FalseBool() *bool

FalseBool just returns a pointer to boolean false.

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 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,
	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.Local

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

func NewS3Storage added in v0.3.7

func NewS3Storage() gtsstorage.Driver

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 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() 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 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(db db.DB, fedWorker *concurrency.WorkerPool[messages.FromFederator]) federatingdb.DB

NewTestFederatingDB returns a federating DB with the underlying db

func NewTestFederator

func NewTestFederator(db db.DB, tc transport.Controller, storage storage.Driver, mediaManager media.Manager, fedWorker *concurrency.WorkerPool[messages.FromFederator]) federation.Federator

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

func NewTestFediAttachments

func NewTestFediAttachments(relativePath string) map[string]RemoteAttachmentFile

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

func NewTestMediaManager(db db.DB, storage storage.Driver) 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 NewTestProcessor

func NewTestProcessor(db db.DB, storage storage.Driver, federator federation.Federator, emailSender email.Sender, mediaManager media.Manager, clientWorker *concurrency.WorkerPool[messages.FromClientAPI], fedWorker *concurrency.WorkerPool[messages.FromFederator]) processing.Processor

NewTestProcessor returns a Processor suitable for testing purposes

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 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 NewTestTokens

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

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

func NewTestTransportController

func NewTestTransportController(client pub.HttpClient, db db.DB, fedWorker *concurrency.WorkerPool[messages.FromFederator]) 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 NewTestTypeConverter

func NewTestTypeConverter(db db.DB) typeutils.TypeConverter

NewTestTypeConverter returned a type converter with the given db and the default test config

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(s gtsstorage.Driver, relativePath string)

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

func StandardStorageTeardown

func StandardStorageTeardown(s gtsstorage.Driver)

StandardStorageTeardown deletes everything in storage so that it's clean for the next test nolint:gocritic // complains about the type switch, but it's the cleanest solution

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

func TrueBool() *bool

TrueBool just returns a pointer to boolean true.

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 {
	SentMessages sync.Map
	// contains filtered or unexported fields
}

func NewMockHTTPClient

func NewMockHTTPClient(do func(req *http.Request) (*http.Response, error), relativeMediaPath string) *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)

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