Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(shorebird_cli): auth tests should use temporary directory #294

Merged
merged 1 commit into from
Apr 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions packages/shorebird_cli/lib/src/auth/auth.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import 'dart:convert';
import 'dart:io';

import 'package:cli_util/cli_util.dart';
import 'package:googleapis_auth/auth_io.dart' as oauth2;
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
import 'package:shorebird_cli/src/auth/jwt.dart';
import 'package:shorebird_cli/src/config/config.dart';
import 'package:shorebird_cli/src/command_runner.dart';

final _clientId = oauth2.ClientId(
/// Shorebird CLI's OAuth 2.0 identifier.
Expand Down Expand Up @@ -77,18 +78,23 @@ class AuthenticatedClient extends http.BaseClient {
class Auth {
Auth({
http.Client? httpClient,
String? credentialsDir,
ObtainAccessCredentials? obtainAccessCredentials,
}) : _httpClient = httpClient ?? http.Client(),
_credentialsDir =
credentialsDir ?? applicationConfigHome(executableName),
_obtainAccessCredentials = obtainAccessCredentials ??
oauth2.obtainAccessCredentialsViaUserConsent {
_loadCredentials();
}

static const _credentialsFileName = 'credentials.json';

final http.Client _httpClient;
final String _credentialsDir;
final ObtainAccessCredentials _obtainAccessCredentials;
final credentialsFilePath = p.join(shorebirdConfigDir, _credentialsFileName);

String get credentialsFilePath {
return p.join(_credentialsDir, 'credentials.json');
}

http.Client get client {
final credentials = _credentials;
Expand Down
1 change: 0 additions & 1 deletion packages/shorebird_cli/lib/src/config/config.dart
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export 'shorebird_config_dir.dart';
export 'shorebird_yaml.dart';
13 changes: 0 additions & 13 deletions packages/shorebird_cli/lib/src/config/shorebird_config_dir.dart

This file was deleted.

89 changes: 48 additions & 41 deletions packages/shorebird_cli/test/src/auth/auth_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,41 +10,48 @@ class _FakeBaseRequest extends Fake implements http.BaseRequest {}

class _MockHttpClient extends Mock implements http.Client {}

class _MockAccessCredentials extends Mock implements AccessCredentials {}

void main() {
group('Auth', () {
const idToken =
'''eyJhbGciOiJSUzI1NiIsImN0eSI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAZW1haWwuY29tIn0.pD47BhF3MBLyIpfsgWCzP9twzC1HJxGukpcR36DqT6yfiOMHTLcjDbCjRLAnklWEHiT0BQTKTfhs8IousU90Fm5bVKObudfKu8pP5iZZ6Ls4ohDjTrXky9j3eZpZjwv8CnttBVgRfMJG-7YASTFRYFcOLUpnb4Zm5R6QdoCDUYg''';
const email = 'test@email.com';
final validCredentials = AccessCredentials(
AccessToken(
'Bearer',
'accessToken',
DateTime.now().add(const Duration(minutes: 10)).toUtc(),
),
'',
[],
const refreshToken = '';
const scopes = <String>[];
final accessToken = AccessToken(
'Bearer',
'accessToken',
DateTime.now().add(const Duration(minutes: 10)).toUtc(),
);

final accessCredentials = AccessCredentials(
accessToken,
refreshToken,
scopes,
idToken: idToken,
);

late String credentialsDir;
late http.Client httpClient;
late AccessCredentials accessCredentials;
late Auth auth;

setUpAll(() {
registerFallbackValue(_FakeBaseRequest());
});

setUp(() {
httpClient = _MockHttpClient();
accessCredentials = _MockAccessCredentials();
auth = Auth(
Auth buildAuth({AccessCredentials? credentials}) {
return Auth(
credentialsDir: credentialsDir,
httpClient: httpClient,
obtainAccessCredentials: (clientId, scopes, client, userPrompt) async {
return validCredentials;
return credentials ?? accessCredentials;
},
)..logout();
);
}

setUp(() {
credentialsDir = Directory.systemTemp.createTempSync().path;
httpClient = _MockHttpClient();
auth = buildAuth();
});

group('AuthenticatedClient', () {
Expand Down Expand Up @@ -74,7 +81,7 @@ void main() {
httpClient: httpClient,
onRefreshCredentials: onRefreshCredentialsCalls.add,
refreshCredentials: (clientId, credentials, client) async =>
validCredentials,
accessCredentials,
);

await client.get(Uri.parse('https://example.com'));
Expand All @@ -100,7 +107,7 @@ void main() {
);
final onRefreshCredentialsCalls = <AccessCredentials>[];
final client = AuthenticatedClient(
credentials: validCredentials,
credentials: accessCredentials,
httpClient: httpClient,
onRefreshCredentials: onRefreshCredentialsCalls.add,
);
Expand Down Expand Up @@ -149,21 +156,20 @@ void main() {

group('login', () {
test('should set the user when claims are valid', () async {
when(() => accessCredentials.idToken).thenReturn(idToken);
await auth.login((_) {});
expect(auth.email, email);
expect(auth.isAuthenticated, isTrue);
expect(Auth().email, email);
expect(Auth().isAuthenticated, isTrue);
expect(buildAuth().email, email);
expect(buildAuth().isAuthenticated, isTrue);
});

test('should not set the user when token is null', () async {
when(() => accessCredentials.idToken).thenReturn(null);
auth = Auth(
httpClient: httpClient,
obtainAccessCredentials:
(clientId, scopes, client, userPrompt) async => accessCredentials,
final credentialsWithNoIdToken = AccessCredentials(
accessToken,
refreshToken,
scopes,
);
auth = buildAuth(credentials: credentialsWithNoIdToken);
await expectLater(
auth.login((_) {}),
throwsA(
Expand All @@ -179,12 +185,13 @@ void main() {
});

test('should not set the user when token is empty', () async {
when(() => accessCredentials.idToken).thenReturn('');
auth = Auth(
httpClient: httpClient,
obtainAccessCredentials:
(clientId, scopes, client, userPrompt) async => accessCredentials,
final credentialsWithEmptyIdToken = AccessCredentials(
accessToken,
refreshToken,
scopes,
idToken: '',
);
auth = buildAuth(credentials: credentialsWithEmptyIdToken);
await expectLater(
auth.login((_) {}),
throwsA(
Expand All @@ -200,14 +207,14 @@ void main() {
});

test('should not set the user when token claims are malformed', () async {
when(() => accessCredentials.idToken).thenReturn(
'''eyJhbGciOiJSUzI1NiIsImN0eSI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.LaR0JfOiDrS1AuABC38kzxpSjRLJ_OtfOkZ8hL6I1GPya-cJYwsmqhi5eMBwEbpYHcJhguG5l56XM6dW8xjdK7JbUN6_53gHBosSnL-Ccf29oW71Ado9sxO17YFQyihyMofJ_v78BPVy2H5O10hNjRn_M0JnnAe0Fvd2VrInlIE''',
);
auth = Auth(
httpClient: httpClient,
obtainAccessCredentials:
(clientId, scopes, client, userPrompt) async => accessCredentials,
final credentialsWithMalformedIdToken = AccessCredentials(
accessToken,
refreshToken,
scopes,
idToken:
'''eyJhbGciOiJSUzI1NiIsImN0eSI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.LaR0JfOiDrS1AuABC38kzxpSjRLJ_OtfOkZ8hL6I1GPya-cJYwsmqhi5eMBwEbpYHcJhguG5l56XM6dW8xjdK7JbUN6_53gHBosSnL-Ccf29oW71Ado9sxO17YFQyihyMofJ_v78BPVy2H5O10hNjRn_M0JnnAe0Fvd2VrInlIE''',
);
auth = buildAuth(credentials: credentialsWithMalformedIdToken);
await expectLater(
auth.login((_) {}),
throwsA(
Expand All @@ -232,8 +239,8 @@ void main() {
auth.logout();
expect(auth.email, isNull);
expect(auth.isAuthenticated, isFalse);
expect(Auth().email, isNull);
expect(Auth().isAuthenticated, isFalse);
expect(buildAuth().email, isNull);
expect(buildAuth().isAuthenticated, isFalse);
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import 'package:mason_logger/mason_logger.dart';
import 'package:mocktail/mocktail.dart';
import 'package:shorebird_cli/src/auth/auth.dart';
import 'package:shorebird_cli/src/commands/build_command.dart';
import 'package:shorebird_cli/src/config/config.dart';
import 'package:shorebird_cli/src/validators/validators.dart';
import 'package:shorebird_code_push_client/shorebird_code_push_client.dart';
import 'package:test/test.dart';
Expand All @@ -31,7 +30,6 @@ class _MockShorebirdFlutterValidator extends Mock
void main() {
group('build', () {
late ArgResults argResults;
late Directory applicationConfigHome;
late http.Client httpClient;
late Auth auth;
late CodePushClient codePushClient;
Expand All @@ -41,7 +39,6 @@ void main() {
late ShorebirdFlutterValidator flutterValidator;

setUp(() {
applicationConfigHome = Directory.systemTemp.createTempSync();
argResults = _MockArgResults();
httpClient = _MockHttpClient();
auth = _MockAuth();
Expand Down Expand Up @@ -70,7 +67,6 @@ void main() {
},
validators: [flutterValidator],
)..testArgResults = argResults;
testApplicationConfigHome = (_) => applicationConfigHome.path;

when(() => argResults.rest).thenReturn([]);
when(() => auth.isAuthenticated).thenReturn(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import 'package:mocktail/mocktail.dart';
import 'package:path/path.dart' as p;
import 'package:shorebird_cli/src/auth/auth.dart';
import 'package:shorebird_cli/src/commands/login_command.dart';
import 'package:shorebird_cli/src/config/config.dart';
import 'package:test/test.dart';

class _MockAuth extends Mock implements Auth {}
Expand All @@ -27,8 +26,6 @@ void main() {
auth = _MockAuth();
loginCommand = LoginCommand(auth: auth, logger: logger);

testApplicationConfigHome = (_) => applicationConfigHome.path;

when(() => auth.credentialsFilePath).thenReturn(
p.join(applicationConfigHome.path, 'credentials.json'),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import 'package:path/path.dart' as p;
import 'package:shorebird_cli/src/auth/auth.dart';
import 'package:shorebird_cli/src/cache.dart' show Cache;
import 'package:shorebird_cli/src/commands/patch_command.dart';
import 'package:shorebird_cli/src/config/config.dart';
import 'package:shorebird_cli/src/shorebird_build_mixin.dart';
import 'package:shorebird_cli/src/validators/validators.dart';
import 'package:shorebird_code_push_client/shorebird_code_push_client.dart';
Expand Down Expand Up @@ -81,7 +80,6 @@ flutter:
- shorebird.yaml''';

late ArgResults argResults;
late Directory applicationConfigHome;
late Auth auth;
late Progress progress;
late Logger logger;
Expand Down Expand Up @@ -129,7 +127,6 @@ flutter:

setUp(() {
argResults = _MockArgResults();
applicationConfigHome = Directory.systemTemp.createTempSync();
auth = _MockAuth();
progress = _MockProgress();
logger = _MockLogger();
Expand Down Expand Up @@ -165,7 +162,6 @@ flutter:
httpClient: httpClient,
validators: [flutterValidator],
)..testArgResults = argResults;
testApplicationConfigHome = (_) => applicationConfigHome.path;

when(() => argResults.rest).thenReturn([]);
when(() => argResults['arch']).thenReturn(arch);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import 'package:mocktail/mocktail.dart';
import 'package:path/path.dart' as p;
import 'package:shorebird_cli/src/auth/auth.dart';
import 'package:shorebird_cli/src/commands/commands.dart';
import 'package:shorebird_cli/src/config/config.dart';
import 'package:shorebird_cli/src/shorebird_build_mixin.dart';
import 'package:shorebird_cli/src/validators/validators.dart';
import 'package:shorebird_code_push_client/shorebird_code_push_client.dart';
Expand Down Expand Up @@ -65,7 +64,6 @@ flutter:
- shorebird.yaml''';

late ArgResults argResults;
late Directory applicationConfigHome;
late http.Client httpClient;
late Auth auth;
late Progress progress;
Expand Down Expand Up @@ -107,7 +105,6 @@ flutter:

setUp(() {
argResults = _MockArgResults();
applicationConfigHome = Directory.systemTemp.createTempSync();
httpClient = _MockHttpClient();
auth = _MockAuth();
progress = _MockProgress();
Expand Down Expand Up @@ -137,7 +134,6 @@ flutter:
logger: logger,
validators: [flutterValidator],
)..testArgResults = argResults;
testApplicationConfigHome = (_) => applicationConfigHome.path;

when(() => argResults.rest).thenReturn([]);
when(() => argResults['arch']).thenReturn(arch);
Expand Down
10 changes: 3 additions & 7 deletions packages/shorebird_cli/test/src/commands/run_command_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import 'package:mason_logger/mason_logger.dart';
import 'package:mocktail/mocktail.dart';
import 'package:shorebird_cli/src/auth/auth.dart';
import 'package:shorebird_cli/src/commands/run_command.dart';
import 'package:shorebird_cli/src/config/config.dart';
import 'package:shorebird_cli/src/validators/validators.dart';
import 'package:shorebird_code_push_client/shorebird_code_push_client.dart';
import 'package:test/test.dart';
Expand Down Expand Up @@ -36,7 +35,6 @@ class _MockShorebirdFlutterValidator extends Mock
void main() {
group('run', () {
late ArgResults argResults;
late Directory applicationConfigHome;
late http.Client httpClient;
late Auth auth;
late Logger logger;
Expand All @@ -48,7 +46,6 @@ void main() {

setUp(() {
argResults = _MockArgResults();
applicationConfigHome = Directory.systemTemp.createTempSync();
httpClient = _MockHttpClient();
auth = _MockAuth();
logger = _MockLogger();
Expand All @@ -75,14 +72,13 @@ void main() {
],
)..testArgResults = argResults;

testApplicationConfigHome = (_) => applicationConfigHome.path;

when(() => argResults.rest).thenReturn([]);
when(() => auth.isAuthenticated).thenReturn(true);
when(() => auth.client).thenReturn(httpClient);
when(() => logger.progress(any())).thenReturn(_MockProgress());
when(() => androidInternetPermissionValidator.validate())
.thenAnswer((_) async => []);
when(
() => androidInternetPermissionValidator.validate(),
).thenAnswer((_) async => []);
when(() => flutterValidator.validate()).thenAnswer((_) async => []);
});

Expand Down