Skip to content

RFC: Testing framework (server-side) #2494

Closed

Description

@vlidholt

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.

testing

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? authenticated
    • Caches? caches
    • MessageCentral? messages
    • Storage? storage
    • Map<String,String>? passwords
    • dynamic 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 testSession like with withTestOverrides above (maybe copyWith is 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

  • Future calls: special helpers should be created to make testing Future calls 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)

  1. Harmonize code paths for authentication between endpoints and streams (refactor: Break out endpoint's business logic #2676)
  2. Implement code generation and implement TestServerpod and TestSession classes. Should be possible to create a simple demo test of the ExampleEndpoint that comes with a fresh serverpod project (feat: Add Serverpod test tools #2713)
  3. Implement transactions and rollback for each test (feat: Add Serverpod test tools #2713)

Follow-up checklist:

Activity

  1. added
    enhancement
    rfc
    on Jul 16, 2024
  2. SandPod commented on Aug 21, 2024

    @SandPod
    Contributor

    Duplicate issue: #1008
    Discussion from the duplicate issue: #1007

  3. self-assigned this
    on Aug 21, 2024
  4. SandPod commented on Aug 21, 2024

    @SandPod
    Contributor

    Requirements for seeding the database and masquerading as different users.
    Duplicate issue: #1009

  5. added
    area: test framework
    on Oct 9, 2024
  6. moved this from Now 🔥 to Done 🚀 in Serverpod Frameworkson Nov 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: test frameworkenhancementrfc

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions