Repository navigation
Description
Serverpod would benefit from including a framework that makes testing easier. Currently, to test endpoint methods, the user must either mock the Session class or set up end-to-end tests. A better solution would be to provide a way to call endpoint methods through a testing API.
Goals
It should be easy and intuitive to:
- Test endpoints
- Test relic endpoints
- Seed database state and corresponding clean-up
- Mock/override the following properties of
Session:AuthenticationInfo? authenticatedCaches? cachesMessageCentral? messagesStorage? storageMap<String,String>? passwordsdynamic userObject
Testing interface
Due to the way the Dart test framework works, it seems best and most idiomatic to create a HOC that provides the needed test objects and that can take care of set up and clean up that should be hidden to the end user.
Below follows a code example in which two objects, TestServerpod and TestSession, are provided to meet the requirements of the outlined goals:
withServerpod('Example Endpoint', (endpoints, session) {
test('Hello', () async {
final response =
await endpoints.example.hello(session, 'Michael');
expect(response, 'Hello, Michael!');
});
test('Hello with authenticated user', () async {
AuthenticationInfo authInfo =
AuthenticationInfo(12345, Set.of([Scope('admin')]));
var session = session.withTestOverrides(
userObject: 'data', authenticated: authInfo);
final response =
await endpoints.example.hello(session, 'Michael');
expect(response, 'Hello, Michael!');
});
// TODO: Add missing stream endpoint example
});
withRelic('Example Endpoint', (client, session) {
test('Create user', () {
var headers = {
'Content-Type': 'application/json'
};
var body = {'name': 'Michael'};
final response =
client.post(session, '/users', body, headers);
expect(response.body['id'], isA<String>);
expect(response.status, equals(201));
});
});The names of properties and functions here are up for debate, but conceptually it makes sense to:
- Have a zero-conf way to start doing an endpoint test
- Some way to extend the baseline
testSessionlike withwithTestOverridesabove (maybecopyWithis more idiomatic?) - Relic is a bit speculative at this point since a lot of work will be done there. But conceptually it should be possible to create a testing interface that is similar to the Serverpod endpoints.
Seeding the database
Seeding the database before a test or group is done by simply using the ORM as usual. However, to facilitate a clean state after each test all operations in a test are done in a transaction. After the test the transaction will be rolled-back.
withServerpod('Example Endpoint', (testServer, testSession) {
test('Get all todos', () async {
// Will be automatically cleaned up due to being performed as a transaction
// that will be rolled back in the `tearDown` callback inside `withServerpod`
TodoItem.db.insert(
testSession, [TodoItem(description: 'Buy milk', isCompleted: false)]);
final todoItem = await testServer.endpoints.todo.getAll(testSession);
expect(todoItem.first.description, 'Buy milk');
expect(todoItem.first.isCompleted, false);
});
});Test overrides/Mocking
As mentioned under Goals, a number of Session properties should be possible to mock or override. It could be worth considering using a mocking library such as dart-lang/mockito to help with this. That could enable writing code along these lines:
when(caches.local.get("User-1")).thenAnswer((_) async => User(name: "Anna"));It is also an option to create test versions of all those properties:
TestContext({
TestAuthenticationInfo? authenticated,
TestCaches? caches,
TestMessageCentral? messages,
TestStorage? storage,
Map<String,String>? passwords,
dynamic userObject,
});
TestAuthenticationInfo({
Set<Scope>? scopes,
int? userId,
});TestCaches and TestMessageCentral, can likely just extend the Caches and MessageCentral classes, as they can be populated or listened to with their current functionality. The TestMessageCentral can also be used to post messages into a long-running endpoint method (e.g., a stream). The TestCaches can be inspected after a method has been tested.
Configuration (WIP)
In-test configuration
There are potentially many things that should be configurable besides mocking/overriding the TestSession. It therefore makes sense to pass a configuration object to withServerpod.
Serverpod configuration
Support for a test.yaml inside <myapp>_server/config should be added.
Escape hatch (WIP)
There should be a way to skip using the withServerpod HOC and set things up oneself, should one not want all the set up that comes with it. Conceptually it would mean creating a TestServerpod and TestSession manually (similar to the original RFC)
Non-goals/out of scope
Futurecalls: special helpers should be created to make testingFuturecalls easier. But since these might be reworked they will be out of scope for the moment.- Will not start working on Relic's test helpers until after all the upcoming big changes to Relic are made
Roadmap (WIP)
- Harmonize code paths for authentication between endpoints and streams (refactor: Break out endpoint's business logic #2676)
- Implement code generation and implement
TestServerpodandTestSessionclasses. Should be possible to create a simple demo test of theExampleEndpointthat comes with a fresh serverpod project (feat: Add Serverpod test tools #2713) - Implement transactions and rollback for each test (feat: Add Serverpod test tools #2713)
Follow-up checklist:
- Throw
ExitExceptioninServerpod.startinstead of exiting process #2725 - Move revoked authentication logic to endpoint dispatch for method streams. #2739
- Support Serverpod Mini in Serverpod test tools #2740
- Update template files for Serverpod test tools #2734
- To discuss: "Global" setUpAll/tearDownAll
- To discuss: Enhance stack trace for errors thrown in tests (seems difficult)
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone 🚀

Activity
SandPod commentedon Aug 21, 2024
Duplicate issue: #1008
Discussion from the duplicate issue: #1007
SandPod commentedon Aug 21, 2024
Requirements for seeding the database and masquerading as different users.
Duplicate issue: #1009