|
| 1 | +# The basics |
| 2 | + |
| 3 | +## Using `sessionBuilder` to set up a test scenario |
| 4 | + |
| 5 | +The `withServerpod` helper provides a `session` object that helps with setting up different scenarios for tests. It looks like the following: |
| 6 | + |
| 7 | +```dart |
| 8 | +/// A test specific builder to create a [Session] that for instance can be used to call database methods. |
| 9 | +/// The builder can also be passed to endpoint calls. The builder will create a new session for each call. |
| 10 | +abstract class TestSessionBuilder { |
| 11 | + /// Given the properties set on the session through the `copyWith` method, |
| 12 | + /// this returns a serverpod [Session] that has the configured state. |
| 13 | + Session build(); |
| 14 | +
|
| 15 | + /// Creates a new unique session with the provided properties. |
| 16 | + /// This is useful for setting up different session states in the tests |
| 17 | + /// or simulating multiple users. |
| 18 | + TestSessionBuilder copyWith({ |
| 19 | + AuthenticationOverride? authentication, |
| 20 | + bool? enableLogging, |
| 21 | + }); |
| 22 | +} |
| 23 | +``` |
| 24 | + |
| 25 | +To create a new state, simply call `copyWith` with the new properties and use the new session builder in the endpoint call. |
| 26 | + |
| 27 | +Below follows examples of some common scenarios. |
| 28 | + |
| 29 | +### Setting authenticated state |
| 30 | + |
| 31 | +```dart |
| 32 | +withServerpod('Given AuthenticatedExample endpoint', |
| 33 | + (sessionBuilder, endpoints) { |
| 34 | + // Corresponds to an actual user id |
| 35 | + const int userId = 1234; |
| 36 | +
|
| 37 | + group('when authenticated', () { |
| 38 | + var authenticatedSessionBuilder = sessionBuilder.copyWith( |
| 39 | + authentication: |
| 40 | + AuthenticationOverride.authenticationInfo(userId, {Scope('user')}), |
| 41 | + ); |
| 42 | +
|
| 43 | + test('then calling `hello` should return greeting', () async { |
| 44 | + final greeting = await endpoints.authenticatedExample |
| 45 | + .hello(authenticatedSessionBuilder, 'Michael'); |
| 46 | + expect(greeting, 'Hello, Michael!'); |
| 47 | + }); |
| 48 | + }); |
| 49 | +
|
| 50 | + group('when unauthenticated', () { |
| 51 | + var unauthenticatedSessionBuilder = sessionBuilder.copyWith( |
| 52 | + authentication: AuthenticationOverride.unauthenticated(), |
| 53 | + ); |
| 54 | +
|
| 55 | + test( |
| 56 | + 'then calling `hello` should throw `ServerpodUnauthenticatedException`', |
| 57 | + () async { |
| 58 | + final future = endpoints.authenticatedExample |
| 59 | + .hello(unauthenticatedSessionBuilder, 'Michael'); |
| 60 | + await expectLater( |
| 61 | + future, throwsA(isA<ServerpodUnauthenticatedException>())); |
| 62 | + }); |
| 63 | + }); |
| 64 | +}); |
| 65 | +``` |
| 66 | + |
| 67 | +### Seeding the database |
| 68 | + |
| 69 | +To seed the database before tests, simply `build` a `session` and pass to the database call exactly the same as in production code. |
| 70 | + |
| 71 | +:::info |
| 72 | + |
| 73 | +By default `withServerpod` does all database operations inside a transaction that is rolled back after each `test` case. See the [rollback database configuration](#rollback-database-configuration) for how to configure this behavior. |
| 74 | + |
| 75 | +::: |
| 76 | + |
| 77 | +```dart |
| 78 | +withServerpod('Given Products endpoint when authenticated', |
| 79 | + (sessionBuilder, endpoints) { |
| 80 | + const int userId = 1234; |
| 81 | + var authenticatedSession = sessionBuilder |
| 82 | + .copyWith( |
| 83 | + authentication: AuthenticationOverride.authenticationInfo( |
| 84 | + userId, |
| 85 | + {Scope('user')}, |
| 86 | + ), |
| 87 | + ) |
| 88 | + .build(); |
| 89 | +
|
| 90 | + setUp(() async { |
| 91 | + await Product.db.insert(authenticatedSession, [ |
| 92 | + Product(name: 'Apple', price: 10), |
| 93 | + Product(name: 'Banana', price: 10) |
| 94 | + ]); |
| 95 | + }); |
| 96 | +
|
| 97 | + test('then calling `all` should return all products', () async { |
| 98 | + final products = await endpoints.products.all(authenticatedSession); |
| 99 | + expect(products, hasLength(2)); |
| 100 | + expect(products.map((p) => p.name), contains(['Apple', 'Banana'])); |
| 101 | + }); |
| 102 | +}); |
| 103 | +``` |
| 104 | + |
| 105 | +## Environment |
| 106 | + |
| 107 | +By default `withServerpod` uses the `test` run mode and the database settings will be read from `config/test.yaml`. |
| 108 | + |
| 109 | +It is possible to override the default run mode by setting the `runMode` setting: |
| 110 | + |
| 111 | +```dart |
| 112 | +withServerpod( |
| 113 | + 'Given Products endpoint when authenticated', |
| 114 | + (sessionBuilder, endpoints) { |
| 115 | + /* test code */ |
| 116 | + }, |
| 117 | + runMode: ServerpodRunMode.development, |
| 118 | +); |
| 119 | +``` |
| 120 | + |
| 121 | +## Configuration |
| 122 | + |
| 123 | +The following optional configuration options are available to pass as a second argument to `withServerpod`: |
| 124 | + |
| 125 | +```dart |
| 126 | +{ |
| 127 | + RollbackDatabase? rollbackDatabase = RollbackDatabase.afterEach, |
| 128 | + String? runMode = ServerpodRunmode.test, |
| 129 | + bool? enableSessionLogging = false, |
| 130 | + bool? applyMigrations = true, |
| 131 | +} |
| 132 | +``` |
| 133 | + |
| 134 | +### `rollbackDatabase` {#rollback-database-configuration} |
| 135 | + |
| 136 | +By default `withServerpod` does all database operations inside a transaction that is rolled back after each `test` case. Just like the following enum describes, the behavior of the automatic rollbacks can be configured: |
| 137 | + |
| 138 | +```dart |
| 139 | +/// Options for when to rollback the database during the test lifecycle. |
| 140 | +enum RollbackDatabase { |
| 141 | + /// After each test. This is the default. |
| 142 | + afterEach, |
| 143 | +
|
| 144 | + /// After all tests. |
| 145 | + afterAll, |
| 146 | +
|
| 147 | + /// Disable rolling back the database. |
| 148 | + disabled, |
| 149 | +} |
| 150 | +``` |
| 151 | + |
| 152 | +There are two main reasons to change the default setting: |
| 153 | + |
| 154 | +1. **Scenario tests**: when consecutive `test` cases depend on each other. While generally considered an anti-pattern, it can be useful when the set up for the test group is very expensive. In this case `rollbackDatabase` can be set to `RollbackDatabase.afterAll` to ensure that the database state persists between `test` cases. At the end of the `withServerpod` scope, all database changes will be rolled back. |
| 155 | + |
| 156 | +2. **Concurrent transactions in endpoints**: when concurrent calls are made to `session.db.transaction` inside an endpoint, it is no longer possible for the Serverpod test tools to do these operations as part of a top level transaction. In this case this feature should be disabled by passing `RollbackDatabase.disabled`. |
| 157 | + |
| 158 | +```dart |
| 159 | +Future<void> concurrentTransactionCalls( |
| 160 | + Session session, |
| 161 | +) async { |
| 162 | + await Future.wait([ |
| 163 | + session.db.transaction((tx) => /*...*/), |
| 164 | + // Will throw `InvalidConfigurationException` if `rollbackDatabase` |
| 165 | + // is not set to `RollbackDatabase.disabled` in `withServerpod` |
| 166 | + session.db.transaction((tx) => /*...*/), |
| 167 | + ]); |
| 168 | +} |
| 169 | +``` |
| 170 | + |
| 171 | +When setting `rollbackDatabase.disabled` to be able to test `concurrentTransactionCalls`, remember that the database has to be manually cleaned up to not leak data: |
| 172 | + |
| 173 | +```dart |
| 174 | +withServerpod( |
| 175 | + 'Given ProductsEndpoint when calling concurrentTransactionCalls', |
| 176 | + (sessionBuilder, endpoints) { |
| 177 | + tearDownAll(() async { |
| 178 | + var session = sessionBuilder.build(); |
| 179 | + // If something was saved to the database in the endpoint, |
| 180 | + // for example a `Product`, then it has to be cleaned up! |
| 181 | + await Product.db.deleteWhere( |
| 182 | + session, |
| 183 | + where: (_) => Constant.bool(true), |
| 184 | + ); |
| 185 | + }); |
| 186 | +
|
| 187 | + test('then should execute and commit all transactions', () async { |
| 188 | + var result = |
| 189 | + await endpoints.products.concurrentTransactionCalls(sessionBuilder); |
| 190 | + // ... |
| 191 | + }); |
| 192 | + }, |
| 193 | + rollbackDatabase: RollbackDatabase.disabled, |
| 194 | +); |
| 195 | +``` |
| 196 | + |
| 197 | +### `runMode` |
| 198 | + |
| 199 | +The run mode that Serverpod should be running in. Defaults to `test`. |
| 200 | + |
| 201 | +### `enableSessionLogging` |
| 202 | + |
| 203 | +Wether session logging should be enabled. Defaults to `false`. |
| 204 | + |
| 205 | +### `applyMigrations` |
| 206 | + |
| 207 | +Wether pending migrations should be applied when starting Serverpod. Defaults to `true`. |
0 commit comments