Documentation
¶
Overview ¶
Package tests provides common helpers and mocks used in Base application tests.
Package tests provides test token helper functions.
Index ¶
- Constants
- func GetSuperuserAuthToken(app core.App, recordId string) (string, error)
- func GetUserAuthToken(app core.App, collectionNameOrId, recordId string) (string, error)
- func GetUserPasswordResetToken(app core.App, collectionNameOrId, recordId string) (string, error)
- func GetUserStaticAuthToken(app core.App, collectionNameOrId, recordId string) (string, error)
- func GetUserVerificationToken(app core.App, collectionNameOrId, recordId string) (string, error)
- func MockMultipartData(data map[string]string, fileFields ...string) (*bytes.Buffer, *multipart.Writer, error)
- func StubLogsData(app *TestApp) error
- func StubMFARecords(app core.App) error
- func StubOTPRecords(app core.App) error
- func TempDirClone(dirToClone string) (string, error)
- func TestValidationErrors(t *testing.T, rawErrors error, expectedErrors []string)
- type ApiScenario
- type TestApp
- type TestMailer
Constants ¶
const ( // Users collection (_users_auth_) TestUserID1 = "4q1xlclmfloku33" // test@example.com TestUserID2 = "oap640cot4yru2s" // test2@example.com TestUserID3 = "bgs820n361vj1qd" // test3@example.com // Clients collection (v851q4r790rhknl) TestClientID1 = "gk390qegs4y47wn" // test@example.com TestClientID2 = "o1y0dd0spd786md" // test2@example.com // Nologin collection (kpv709sk2lqbqk8) TestNologinID1 = "dc49k6jgejn40h3" // test@example.com TestNologinID2 = "phhq3wr65cap535" // test2@example.com TestNologinID3 = "oos036e9xvqeexy" // test3@example.com // Superusers collection (hbc_3142635823) TestSuperuserID1 = "sywbhecnh46rhm0" // test@example.com TestSuperuserID2 = "sbmbsdb40jyxf7h" // test2@example.com TestSuperuserID3 = "9q2trqumvlyr3bd" // test3@example.com TestSuperuserID4 = "q911776rrfy658l" // test4@example.com )
Common test record IDs (matching tests/data/data.db)
Variables ¶
This section is empty.
Functions ¶
func GetSuperuserAuthToken ¶ added in v0.29.4
GetSuperuserAuthToken returns a valid auth token for a test superuser.
func GetUserAuthToken ¶ added in v0.29.4
GetUserAuthToken returns a valid auth token for a test user in the given collection. This should be used in tests instead of hardcoded tokens.
func GetUserPasswordResetToken ¶ added in v0.29.4
GetUserPasswordResetToken returns a password reset token for testing.
func GetUserStaticAuthToken ¶ added in v0.29.4
GetUserStaticAuthToken returns a long-lived static auth token for testing.
func GetUserVerificationToken ¶ added in v0.29.4
GetUserVerificationToken returns a verification token for testing.
func MockMultipartData ¶
func MockMultipartData(data map[string]string, fileFields ...string) (*bytes.Buffer, *multipart.Writer, error)
MockMultipartData creates a mocked multipart/form-data payload.
Example
data, mp, err := tests.MockMultipartData(
map[string]string{"title": "new"},
"file1",
"file2",
...
)
func StubLogsData ¶
func StubMFARecords ¶
func StubOTPRecords ¶
func TempDirClone ¶
TempDirClone creates a new temporary directory copy from the provided directory path.
It is the caller's responsibility to call `os.RemoveAll(tempDir)` when the directory is no longer needed!
func TestValidationErrors ¶
TestValidationErrors checks whether the provided rawErrors are instance of validation.Errors and contains the expectedErrors keys.
Types ¶
type ApiScenario ¶
type ApiScenario struct {
// Name is the test name.
Name string
// Method is the HTTP method of the test request to use.
Method string
// URL is the url/path of the endpoint you want to test.
URL string
// Body specifies the body to send with the request.
//
// For example:
//
// strings.NewReader(`{"title":"abc"}`)
Body io.Reader
// Headers specifies the headers to send with the request (e.g. "Authorization": "abc")
Headers map[string]string
// Delay adds a delay before checking the expectations usually
// to ensure that all fired non-awaited go routines have finished
Delay time.Duration
// Timeout specifies how long to wait before cancelling the request context.
//
// A zero or negative value means that there will be no timeout.
Timeout time.Duration
// DisableTestAppCleanup disables the builtin TestApp cleanup at
// the end of the ApiScenario execution.
//
// This option works only when explicit TestAppFactory is specified
// and means that the developer is responsible to do the necessary
// after test cleanup on their own (e.g. by manually calling testApp.Cleanup()).
DisableTestAppCleanup bool
// ExpectedStatus specifies the expected response HTTP status code.
ExpectedStatus int
// List of keywords that MUST exist in the response body.
//
// Either ExpectedContent or NotExpectedContent must be set if the response body is non-empty.
// Leave both fields empty if you want to ensure that the response didn't have any body (e.g. 204).
ExpectedContent []string
// List of keywords that MUST NOT exist in the response body.
//
// Either ExpectedContent or NotExpectedContent must be set if the response body is non-empty.
// Leave both fields empty if you want to ensure that the response didn't have any body (e.g. 204).
NotExpectedContent []string
// List of hook events to check whether they were fired or not.
//
// You can use the wildcard "*" event key if you want to ensure
// that no other hook events except those listed have been fired.
//
// For example:
//
// map[string]int{ "*": 0 } // no hook events were fired
// map[string]int{ "*": 0, "EventA": 2 } // no hook events, except EventA were fired
// map[string]int{ "EventA": 2, "EventB": 0 } // ensures that EventA was fired exactly 2 times and EventB exactly 0 times.
ExpectedEvents map[string]int
TestAppFactory func(t testing.TB) *TestApp
BeforeTestFunc func(t testing.TB, app *TestApp, e *core.ServeEvent)
AfterTestFunc func(t testing.TB, app *TestApp, res *http.Response)
}
ApiScenario defines a single api request test case/scenario.
func (*ApiScenario) Benchmark ¶
func (scenario *ApiScenario) Benchmark(b *testing.B)
Benchmark benchmarks the test scenario.
Example:
func BenchmarkListExample(b *testing.B) {
scenario := tests.ApiScenario{
Name: "list example collection",
Method: http.MethodGet,
URL: "/api/collections/example/records",
ExpectedStatus: 200,
ExpectedContent: []string{
`"totalItems":3`,
`"id":"0yxhwia2amd8gec"`,
`"id":"achvryl401bhse3"`,
`"id":"llvuca81nly1qls"`,
},
ExpectedEvents: map[string]int{
"OnRecordsListRequest": 1,
"OnRecordEnrich": 3,
},
}
scenario.Benchmark(b)
}
func (*ApiScenario) Test ¶
func (scenario *ApiScenario) Test(t *testing.T)
Test executes the test scenario.
Example:
func TestListExample(t *testing.T) {
scenario := tests.ApiScenario{
Name: "list example collection",
Method: http.MethodGet,
URL: "/api/collections/example/records",
ExpectedStatus: 200,
ExpectedContent: []string{
`"totalItems":3`,
`"id":"0yxhwia2amd8gec"`,
`"id":"achvryl401bhse3"`,
`"id":"llvuca81nly1qls"`,
},
ExpectedEvents: map[string]int{
"OnRecordsListRequest": 1,
"OnRecordEnrich": 3,
},
}
scenario.Test(t)
}
type TestApp ¶
type TestApp struct {
*core.BaseApp
// EventCalls defines a map to inspect which app events
// (and how many times) were triggered.
EventCalls map[string]int
TestMailer *TestMailer
// contains filtered or unexported fields
}
TestApp is a wrapper app instance used for testing.
func NewTestApp ¶
NewTestApp creates and initializes a test application instance.
It is the caller's responsibility to call app.Cleanup() when the app is no longer needed.
func NewTestAppWithConfig ¶
func NewTestAppWithConfig(config core.BaseAppConfig) (*TestApp, error)
NewTestAppWithConfig creates and initializes a test application instance from the provided config.
If config.DataDir is not set it fallbacks to the default internal test data directory.
config.DataDir is cloned for each new test application instance.
It is the caller's responsibility to call app.Cleanup() when the app is no longer needed.
func (*TestApp) Cleanup ¶
func (t *TestApp) Cleanup()
Cleanup resets the test application state and removes the test app's dataDir from the filesystem.
After this call, the app instance shouldn't be used anymore.
func (*TestApp) ResetEventCalls ¶
func (t *TestApp) ResetEventCalls()
ResetEventCalls resets the EventCalls counter.
type TestMailer ¶
type TestMailer struct {
// contains filtered or unexported fields
}
TestMailer is a mock mailer.Mailer implementation.
func (*TestMailer) FirstMessage ¶
func (tm *TestMailer) FirstMessage() mailer.Message
FirstMessage returns a shallow copy of the first sent message.
Returns an empty mailer.Message struct if there are no sent messages.
func (*TestMailer) LastMessage ¶
func (tm *TestMailer) LastMessage() mailer.Message
LastMessage returns a shallow copy of the last sent message.
Returns an empty mailer.Message struct if there are no sent messages.
func (*TestMailer) Messages ¶
func (tm *TestMailer) Messages() []*mailer.Message
Messages returns a shallow copy of all of the collected test messages.
func (*TestMailer) Reset ¶
func (tm *TestMailer) Reset()
Reset clears any previously test collected data.
func (*TestMailer) Send ¶
func (tm *TestMailer) Send(m *mailer.Message) error
Send implements mailer.Mailer interface.
func (*TestMailer) TotalSend ¶
func (tm *TestMailer) TotalSend() int
TotalSend returns the total number of sent messages.