withMockUsersAtOnce<T> function

Future<Map<String, List<T>>> withMockUsersAtOnce<T>(
  1. Iterable<String> usernames,
  2. FutureOr<T> body(
    1. String username
    ), {
  3. int rounds = 10,
  4. List<String> roles = const ['USER'],
})

Runs body as each of usernames at the same time, rounds times each, and returns what every call gave, by user, in the order of the rounds.

It is the test of "one user never sees another's": every call must give what its own user may see, whatever the other calls do meanwhile. The calls start a few turns of the event loop apart, in a pattern that changes from call to call, so they overtake each other at their awaits the way requests of a busy server do. What it finds: a bean that remembers the user in a field, a cache whose key has no user in it, a result shared between callers, an authentication set outside every scope.

test('everybody gets their own orders', () async {
  final found = await withMockUsersAtOnce(
    ['ada', 'bob', 'eve'],
    (username) => orders.mine(),
  );
  for (final MapEntry(key: username, value: results) in found.entries) {
    for (final orders in results) {
      expect(orders.map((o) => o.owner).toSet(), {username});
    }
  }
  expect(programWideAuthentication(), isNull);
});

Each call runs as withMockUser runs it, with roles. A call that fails fails the whole: the error of the first one is thrown once all have ended.

Differs from Spring: spring-security-test has nothing like it; a thread per request hides the mistakes a single event loop shows.

Implementation

Future<Map<String, List<T>>> withMockUsersAtOnce<T>(
  Iterable<String> usernames,
  FutureOr<T> Function(String username) body, {
  int rounds = 10,
  List<String> roles = const ['USER'],
}) async {
  final users = usernames.toList();
  if (users.toSet().length != users.length) {
    throw ArgumentError.value(usernames, 'usernames', 'A name twice');
  }
  final calls = <String, List<Future<T>>>{for (final user in users) user: []};
  var started = 0;
  for (var round = 0; round < rounds; round++) {
    for (final user in users) {
      // 0 to 3 turns of the event loop before the call, differently in
      // every round.
      final turns = (started++ * 7 + round) % 4;
      calls[user]!.add(() async {
        for (var turn = 0; turn < turns; turn++) {
          await Future<void>.delayed(Duration.zero);
        }
        return await withMockUser(
          () => body(user),
          username: user,
          roles: roles,
        );
      }());
    }
  }
  // All of them end before the first error is thrown: none is left
  // running into the next test.
  final all = [for (final list in calls.values) ...list];
  await Future.wait([
    for (final call in all) call.then<void>((_) {}, onError: (Object _) {}),
  ]);
  return {
    for (final MapEntry(key: user, value: list) in calls.entries)
      user: [for (final call in list) await call],
  };
}