Skip to content

Commit 89f9ed1

Browse files
committed
feat: add tests to additions
1 parent d7ae175 commit 89f9ed1

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed

packages/dart_frog_auth/test/src/dart_frog_auth_test.dart

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,4 +456,95 @@ void main() {
456456
});
457457
});
458458
});
459+
460+
group('$cookieAuthentication', () {
461+
late RequestContext context;
462+
late Request request;
463+
_User? user;
464+
465+
setUp(() {
466+
context = _MockRequestContext();
467+
request = _MockRequest();
468+
when(() => context.provide<_User>(any())).thenReturn(context);
469+
when(() => request.headers).thenReturn({});
470+
when(() => context.request).thenReturn(request);
471+
});
472+
473+
test('returns 401 when Cookie header is not present', () async {
474+
final middleware = cookieAuthentication<_User>(
475+
authenticator: (_, __) async => user,
476+
);
477+
expect(
478+
await middleware((_) async => Response())(context),
479+
isA<Response>().having(
480+
(r) => r.statusCode,
481+
'statusCode',
482+
HttpStatus.unauthorized,
483+
),
484+
);
485+
});
486+
487+
test(
488+
'returns 401 when Cookie header is present but no user is returned',
489+
() async {
490+
when(() => request.headers).thenReturn({'Cookie': 'session=abc123'});
491+
final middleware = cookieAuthentication<_User>(
492+
authenticator: (_, __) async => null,
493+
);
494+
expect(
495+
await middleware((_) async => Response())(context),
496+
isA<Response>().having(
497+
(r) => r.statusCode,
498+
'statusCode',
499+
HttpStatus.unauthorized,
500+
),
501+
);
502+
},
503+
);
504+
505+
test(
506+
'sets the user when everything is valid',
507+
() async {
508+
user = _User('');
509+
when(() => request.headers).thenReturn({
510+
'Cookie': 'session=abc123',
511+
});
512+
final middleware = cookieAuthentication<_User>(
513+
authenticator: (_, __) async => user,
514+
);
515+
expect(
516+
await middleware((_) async => Response())(context),
517+
isA<Response>().having(
518+
(r) => r.statusCode,
519+
'statusCode',
520+
HttpStatus.ok,
521+
),
522+
);
523+
final captured = verify(() => context.provide<_User>(captureAny()))
524+
.captured
525+
.single;
526+
expect(
527+
(captured as _User Function()).call(),
528+
equals(user),
529+
);
530+
},
531+
);
532+
533+
test("skips routes that doesn't match the custom predicate", () async {
534+
var called = false;
535+
536+
final middleware = cookieAuthentication<_User>(
537+
authenticator: (_, __) async {
538+
called = true;
539+
return null;
540+
},
541+
applies: (_) async => false,
542+
);
543+
544+
final response = await middleware((_) async => Response())(context);
545+
546+
expect(called, isFalse);
547+
expect(response.statusCode, equals(HttpStatus.ok));
548+
});
549+
});
459550
}

0 commit comments

Comments
 (0)