Skip to content

Commit 725da65

Browse files
committed
lint: misc
1 parent 321b0f8 commit 725da65

13 files changed

+582
-449
lines changed

analysis_options.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ analyzer:
66
no_default_cases: ignore
77
avoid_catches_without_on_clauses: ignore
88
lines_longer_than_80_chars: ignore
9+
avoid_dynamic_calls: ignore
910
exclude:
1011
- build/**
1112
linter:

lib/src/services/jwt_auth_token_service.dart

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ class JwtAuthTokenService implements AuthTokenService {
7575
print('Error generating JWT for user ${user.id}: $e');
7676
// Map to a standard exception
7777
throw OperationFailedException(
78-
'Failed to generate authentication token: ${e.toString()}',
78+
'Failed to generate authentication token: $e',
7979
);
8080
}
8181
}
@@ -91,7 +91,8 @@ class JwtAuthTokenService implements AuthTokenService {
9191
if (userId == null) {
9292
print('Token validation failed: Missing "sub" claim.');
9393
// Throw specific exception for malformed token
94-
throw const BadRequestException('Malformed token: Missing subject claim.');
94+
throw const BadRequestException(
95+
'Malformed token: Missing subject claim.',);
9596
}
9697

9798
// Fetch the full user object from the repository
@@ -107,7 +108,8 @@ class JwtAuthTokenService implements AuthTokenService {
107108
print('Token validation failed: Invalid token. Reason: ${e.message}');
108109
// Throw specific exception for invalid token signature/format
109110
throw UnauthorizedException('Invalid token: ${e.message}');
110-
} on JWTException catch (e) { // Use JWTException as the general catch-all
111+
} on JWTException catch (e) {
112+
// Use JWTException as the general catch-all
111113
print('Token validation failed: JWT Exception. Reason: ${e.message}');
112114
// Treat other JWT exceptions as invalid tokens
113115
throw UnauthorizedException('Invalid token: ${e.message}');
@@ -121,7 +123,7 @@ class JwtAuthTokenService implements AuthTokenService {
121123
print('Unexpected error during token validation: $e');
122124
// Wrap unexpected errors in a standard exception type
123125
throw OperationFailedException(
124-
'Token validation failed unexpectedly: ${e.toString()}',
126+
'Token validation failed unexpectedly: $e',
125127
);
126128
}
127129
}

routes/_middleware.dart

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,6 @@ import 'package:dart_frog/dart_frog.dart';
99
import 'package:ht_api/src/middlewares/authentication_middleware.dart';
1010
import 'package:ht_api/src/middlewares/error_handler.dart';
1111
import 'package:ht_api/src/registry/model_registry.dart';
12-
import 'package:ht_api/src/middlewares/authentication_middleware.dart';
13-
import 'package:ht_api/src/middlewares/error_handler.dart';
14-
import 'package:ht_api/src/registry/model_registry.dart';
1512
import 'package:ht_api/src/services/auth_service.dart';
1613
import 'package:ht_api/src/services/auth_token_service.dart';
1714
// Import the new JWT service

test/helpers/create_mock_request_context.dart

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import 'package:dart_frog/dart_frog.dart';
2-
import 'package:ht_api/src/registry/model_registry.dart'; // For RequestId
2+
// For RequestId
33
import 'package:ht_api/src/services/auth_service.dart'; // Import necessary types
44
import 'package:ht_data_repository/ht_data_repository.dart'; // For HtDataRepository
55
import 'package:ht_shared/ht_shared.dart'; // For User
66
import 'package:mocktail/mocktail.dart';
7-
import 'package:test/test.dart'; // Import for TypeMatcher and isA
7+
// Import for TypeMatcher and isA
88

99
import '../../routes/_middleware.dart'; // Import for RequestId
1010
import 'mock_classes.dart'; // Import your mock classes
@@ -28,7 +28,8 @@ RequestContext createMockRequestContext({
2828
dependencies.forEach((type, instance) {
2929
// Add specific stubs for known types. Extend this list as needed.
3030
if (type == AuthService) {
31-
when(() => context.read<AuthService>()).thenReturn(instance as AuthService);
31+
when(() => context.read<AuthService>())
32+
.thenReturn(instance as AuthService);
3233
} else if (type == HtDataRepository<User>) {
3334
when(() => context.read<HtDataRepository<User>>())
3435
.thenReturn(instance as HtDataRepository<User>);
@@ -52,12 +53,12 @@ RequestContext createMockRequestContext({
5253
// This generic stub might not always work as expected.
5354
// Use a specific type if possible, otherwise fallback carefully.
5455
try {
55-
// Stubbing read<dynamic>() can be tricky. Prefer specific types.
56-
// If absolutely needed, ensure the call signature matches.
57-
// Mocktail's `any` matcher doesn't take arguments for `read`.
58-
when(() => context.read<dynamic>()).thenReturn(instance);
56+
// Stubbing read<dynamic>() can be tricky. Prefer specific types.
57+
// If absolutely needed, ensure the call signature matches.
58+
// Mocktail's `any` matcher doesn't take arguments for `read`.
59+
when(() => context.read<dynamic>()).thenReturn(instance);
5960
} catch (e) {
60-
print('Failed to setup generic read stub for $type: $e');
61+
print('Failed to setup generic read stub for $type: $e');
6162
}
6263
}
6364
});
@@ -77,7 +78,8 @@ RequestContext createMockRequestContext({
7778
// to allow chaining, which is typical for provider middleware.
7879
// Corrected: provide takes one argument (the provider function).
7980
// Use `any<T>()` with explicit type argument for the function.
80-
when(() => context.provide<dynamic>(any<dynamic Function()>())).thenReturn(context);
81+
when(() => context.provide<dynamic>(any<dynamic Function()>()))
82+
.thenReturn(context);
8183

8284
return context;
8385
}

test/helpers/mock_classes.dart

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,25 +11,38 @@ import 'package:uuid/uuid.dart';
1111

1212
// Core Dart Frog Mocks
1313
class MockRequestContext extends Mock implements RequestContext {}
14+
1415
class MockRequest extends Mock implements Request {}
16+
1517
class MockResponse extends Mock implements Response {}
18+
1619
class MockUri extends Mock implements Uri {}
1720

1821
// Service Mocks
1922
class MockAuthService extends Mock implements AuthService {}
23+
2024
class MockAuthTokenService extends Mock implements AuthTokenService {}
25+
2126
class MockVerificationCodeStorageService extends Mock
2227
implements VerificationCodeStorageService {}
2328

2429
// Repository Mocks
2530
class MockHtDataRepository<T> extends Mock implements HtDataRepository<T> {}
31+
2632
class MockUserRepository extends MockHtDataRepository<User> {}
33+
2734
class MockHeadlineRepository extends MockHtDataRepository<Headline> {}
35+
2836
class MockCategoryRepository extends MockHtDataRepository<Category> {}
37+
2938
class MockSourceRepository extends MockHtDataRepository<Source> {}
39+
3040
class MockCountryRepository extends MockHtDataRepository<Country> {}
41+
3142
// Corrected: Use 'extends Mock implements' for concrete classes
32-
class MockAppSettingsRepository extends Mock implements HtAppSettingsRepository {}
43+
class MockAppSettingsRepository extends Mock
44+
implements HtAppSettingsRepository {}
45+
3346
class MockEmailRepository extends Mock implements HtEmailRepository {}
3447

3548
// Utility Mocks

test/routes/api/v1/auth/anonymous_test.dart

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,23 @@ import 'package:ht_shared/ht_shared.dart';
77
import 'package:mocktail/mocktail.dart';
88
import 'package:test/test.dart';
99

10-
import '../../../../helpers/create_mock_request_context.dart';
11-
import '../../../../helpers/mock_classes.dart';
1210
// Import the actual route handler
1311
import '../../../../../routes/api/v1/auth/anonymous.dart' as route;
12+
import '../../../../helpers/create_mock_request_context.dart';
13+
import '../../../../helpers/mock_classes.dart';
1414

1515
void main() {
1616
group('POST /api/v1/auth/anonymous', () {
1717
late MockAuthService mockAuthService;
1818
late MockRequest mockRequest;
1919

2020
// Define a sample user and token for success cases
21-
final testUser = User(id: 'anon-123', isAnonymous: true);
21+
const testUser = User(id: 'anon-123', isAnonymous: true);
2222
const testToken = 'test-auth-token';
23-
final authResult = (user: testUser, token: testToken);
23+
const authResult = (user: testUser, token: testToken);
2424

2525
// Expected success response payload
26-
final successPayload = SuccessApiResponse<AuthSuccessResponse>(
26+
const successPayload = SuccessApiResponse<AuthSuccessResponse>(
2727
data: AuthSuccessResponse(user: testUser, token: testToken),
2828
);
2929
final expectedSuccessBody = jsonEncode(
@@ -40,7 +40,8 @@ void main() {
4040
when(() => mockRequest.headers).thenReturn({});
4141
// Default stub for body (can be overridden)
4242
when(() => mockRequest.body()).thenAnswer((_) async => '');
43-
when(() => mockRequest.json()).thenAnswer((_) async => <String, dynamic>{});
43+
when(() => mockRequest.json())
44+
.thenAnswer((_) async => <String, dynamic>{});
4445
});
4546

4647
test('returns 200 OK with user and token on successful anonymous sign-in',
@@ -90,7 +91,8 @@ void main() {
9091
verifyNever(() => mockAuthService.performAnonymousSignIn());
9192
});
9293

93-
test('returns 500 Internal Server Error when AuthService throws OperationFailedException',
94+
test(
95+
'returns 500 Internal Server Error when AuthService throws OperationFailedException',
9496
() async {
9597
// Arrange
9698
const exception = OperationFailedException('Database connection failed');
@@ -114,7 +116,7 @@ void main() {
114116
// The final 500 response format is tested in the error handler middleware tests.
115117
});
116118

117-
test('returns 500 Internal Server Error for unexpected errors', () async {
119+
test('returns 500 Internal Server Error for unexpected errors', () async {
118120
// Arrange
119121
final exception = Exception('Something unexpected went wrong');
120122
when(() => mockAuthService.performAnonymousSignIn()).thenThrow(exception);
@@ -130,11 +132,13 @@ void main() {
130132
// The handler catches generic exceptions and throws OperationFailedException
131133
expect(
132134
() => route.onRequest(context),
133-
throwsA(isA<OperationFailedException>().having(
134-
(e) => e.message,
135-
'message',
136-
'An unexpected error occurred during anonymous sign-in.',
137-
)),
135+
throwsA(
136+
isA<OperationFailedException>().having(
137+
(e) => e.message,
138+
'message',
139+
'An unexpected error occurred during anonymous sign-in.',
140+
),
141+
),
138142
);
139143
verify(() => mockAuthService.performAnonymousSignIn()).called(1);
140144
});

test/routes/api/v1/auth/me_test.dart

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,19 @@ import 'package:ht_shared/ht_shared.dart';
66
import 'package:mocktail/mocktail.dart';
77
import 'package:test/test.dart';
88

9-
import '../../../../helpers/create_mock_request_context.dart';
10-
import '../../../../helpers/mock_classes.dart';
11-
// Import the actual route handler
12-
import '../../../../../routes/api/v1/auth/me.dart' as route;
139
// Import RequestId definition from middleware file
1410
import '../../../../../routes/_middleware.dart' show RequestId;
15-
11+
// Import the actual route handler
12+
import '../../../../../routes/api/v1/auth/me.dart' as route;
13+
import '../../../../helpers/create_mock_request_context.dart';
14+
import '../../../../helpers/mock_classes.dart';
1615

1716
void main() {
1817
group('GET /api/v1/auth/me', () {
1918
late MockRequest mockRequest;
2019

2120
// Define a sample authenticated user
22-
final testUser = User(
21+
const testUser = User(
2322
id: 'user-123',
2423
2524
isAnonymous: false,
@@ -38,11 +37,10 @@ void main() {
3837
test('returns 200 OK with user data for authenticated user', () async {
3938
// Arrange
4039
// Expected success response payload (metadata timestamp will vary)
41-
final expectedPayload = SuccessApiResponse<User>(data: testUser);
40+
const expectedPayload = SuccessApiResponse<User>(data: testUser);
4241
final expectedBody = jsonEncode(
4342
// We ignore metadata for direct comparison as timestamp varies
44-
expectedPayload.toJson((user) => user.toJson())
45-
..remove('metadata'),
43+
expectedPayload.toJson((user) => user.toJson())..remove('metadata'),
4644
);
4745

4846
final context = createMockRequestContext(
@@ -70,18 +68,19 @@ void main() {
7068
);
7169
// Check metadata structure and requestId presence
7270
expect(decodedBody['metadata'], isA<Map<String, dynamic>>());
73-
expect(decodedBody['metadata']?['request_id'], equals(testRequestIdValue));
71+
expect(
72+
decodedBody['metadata']?['request_id'], equals(testRequestIdValue),);
7473
expect(decodedBody['metadata']?['timestamp'], isNotNull);
7574
});
7675

77-
test('returns 200 OK with user data when RequestId is not in context', () async {
76+
test('returns 200 OK with user data when RequestId is not in context',
77+
() async {
7878
// Arrange
7979
// Expected success response payload (metadata timestamp will vary)
80-
final expectedPayload = SuccessApiResponse<User>(data: testUser);
80+
const expectedPayload = SuccessApiResponse<User>(data: testUser);
8181
final expectedBody = jsonEncode(
8282
// We ignore metadata for direct comparison as timestamp varies
83-
expectedPayload.toJson((user) => user.toJson())
84-
..remove('metadata'),
83+
expectedPayload.toJson((user) => user.toJson())..remove('metadata'),
8584
);
8685

8786
final context = createMockRequestContext(
@@ -112,7 +111,6 @@ void main() {
112111
expect(decodedBody['metadata']?['timestamp'], isNotNull);
113112
});
114113

115-
116114
test('returns 405 Method Not Allowed for non-GET requests', () async {
117115
// Arrange
118116
when(() => mockRequest.method).thenReturn(HttpMethod.post); // Test POST

0 commit comments

Comments
 (0)