Skip to content

Commit

Permalink
chore: add tests, fix warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
Grodien committed Oct 29, 2024
1 parent 89206fb commit 9f9b211
Show file tree
Hide file tree
Showing 10 changed files with 237 additions and 23 deletions.
8 changes: 4 additions & 4 deletions das_client/integration_test/app_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';

import 'di.dart';
import 'test/fahrbild_test.dart' as FahrbildTests;
import 'test/navigation_test.dart' as NavigationTests;
import 'test/fahrbild_test.dart' as fahrbild_tests;
import 'test/navigation_test.dart' as navigation_tests;

AppLocalizations l10n = AppLocalizationsDe();

void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
Fimber.plantTree(DebugTree());

FahrbildTests.main();
NavigationTests.main();
fahrbild_tests.main();
navigation_tests.main();
}

Future<void> prepareAndStartApp(WidgetTester tester) async {
Expand Down
13 changes: 0 additions & 13 deletions das_client/lib/di.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,6 @@ class DI {
param2: param2,
);
}

static Future<T> readyGet<T extends Object>({
String? instanceName,
dynamic param1,
dynamic param2,
}) async {
await GetIt.I.isReady<T>();
return GetIt.I.get<T>(
instanceName: instanceName,
param1: param1,
param2: param2,
);
}
}

// Internal
Expand Down
3 changes: 2 additions & 1 deletion das_client/lib/logging/src/log_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,9 @@ class LogService {
Iterable iterable = json.decode(content);
List<LogEntry> logEntries = List<LogEntry>.from(iterable.map((json) => LogEntry.fromJson(json)));

final backendService = await DI.readyGet<BackendService>();
final backendService = DI.get<BackendService>();
if (await backendService.sendLogs(logEntries)) {
Fimber.d('Deleting ${file.path}');
file.deleteSync();
}
}
Expand Down
6 changes: 5 additions & 1 deletion das_client/lib/service/sfera/sfera_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ class SferaService {
final SferaRepository _sferaRepository;

StreamSubscription? _mqttStreamSubscription;
StreamSubscription? _journeySubscription;
final List<SferaMessageHandler> _messageHandlers = [];

final _stateSubject = BehaviorSubject.seeded(SferaServiceState.disconnected);
Expand Down Expand Up @@ -159,4 +158,9 @@ class SferaService {
static String sferaTrain(String trainNumber, DateTime date) {
return "${trainNumber}_${Format.sferaDate(date)}";
}

void dispose() {
_mqttStreamSubscription?.cancel();
_mqttStreamSubscription = null;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import 'package:das_client/model/sfera/b2g_request.dart';
import 'package:das_client/model/sfera/journey_profile.dart';
import 'package:das_client/model/sfera/jp_request.dart';
import 'package:das_client/model/sfera/otn_id.dart';
import 'package:das_client/model/sfera/segment_profile.dart';
import 'package:das_client/model/sfera/segment_profile_list.dart';
Expand Down
4 changes: 2 additions & 2 deletions das_client/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,7 @@ packages:
source: hosted
version: "2.2.1"
path_provider_platform_interface:
dependency: transitive
dependency: "direct dev"
description:
name: path_provider_platform_interface
sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
Expand Down Expand Up @@ -750,7 +750,7 @@ packages:
source: hosted
version: "3.1.5"
plugin_platform_interface:
dependency: transitive
dependency: "direct dev"
description:
name: plugin_platform_interface
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
Expand Down
2 changes: 2 additions & 0 deletions das_client/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ dev_dependencies:
auto_route_generator: ^9.0.0
mockito: ^5.4.4

path_provider_platform_interface: any
plugin_platform_interface: any
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
Expand Down
170 changes: 170 additions & 0 deletions das_client/test/logging/logging_service_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import 'dart:convert';
import 'dart:io';

import 'package:das_client/logging/src/log_entry.dart';
import 'package:das_client/logging/src/log_level.dart';
import 'package:das_client/logging/src/log_service.dart';
import 'package:das_client/service/backend_service.dart';
import 'package:fimber/fimber.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get_it/get_it.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';

import '../mocks/path_provider_mock.dart';
import 'logging_service_test.mocks.dart';

@GenerateNiceMocks([
MockSpec<BackendService>(),
])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late Directory logDirectory;
late MockBackendService mockBackendService = MockBackendService();
GetIt.I.registerSingleton<BackendService>(mockBackendService);

setUp(() async {
Fimber.plantTree(DebugTree());
PathProviderPlatform.instance = MockPathProviderPlatform();
logDirectory = Directory("${(await getApplicationSupportDirectory()).path}/logs");
logDirectory.listSync().forEach((element) {
element.deleteSync();
});
await GetIt.I.allReady();
});

test('Test writes logs to new file in directory', () async {
LogService loggingService = LogService();

var files = logDirectory.listSync();
expect(files, hasLength(0));

var logEntry = LogEntry("Test message", LogLevel.info, {});
loggingService.save(logEntry);
await Future.delayed(const Duration(milliseconds: 30));

files = logDirectory.listSync();
expect(files, hasLength(1));
});

test('Test writes appends comma after writing log', () async {
LogService loggingService = LogService();

var files = logDirectory.listSync();
expect(files, hasLength(0));

var logEntry = LogEntry("Test message", LogLevel.fatal, {});
loggingService.save(logEntry);
await Future.delayed(const Duration(milliseconds: 30));

files = logDirectory.listSync();
expect(files, hasLength(1));
expect((files[0] as File).readAsStringSync(), "${jsonEncode(logEntry)},");
});

test('Test writes multiple logs to same file', () async {
LogService loggingService = LogService();

var files = logDirectory.listSync();
expect(files, hasLength(0));

loggingService.save(LogEntry("Test message", LogLevel.info, {}));
loggingService.save(LogEntry("Test message 2", LogLevel.error, {}));
loggingService.save(LogEntry("Test message 3", LogLevel.warning, {}));
loggingService.save(LogEntry("Test message 4", LogLevel.debug, {}));
await Future.delayed(const Duration(milliseconds: 30));

files = logDirectory.listSync();
expect(files, hasLength(1));
});

test('Test log entry json encode & decode', () async {
final logEntry = LogEntry("Test message", LogLevel.info, {'version': "0.1", 'systemName': "unitTests"});
final logEntryDecoded = LogEntry.fromJson(jsonDecode(jsonEncode(logEntry)));

expect(logEntryDecoded.message, logEntry.message);
expect(logEntryDecoded.level, logEntry.level);
expect(logEntryDecoded.time, logEntry.time);
expect(logEntryDecoded.source, logEntry.source);
expect(logEntryDecoded.metadata, logEntry.metadata);
});

test('Test rolls over files after size limit reached', () async {
LogService loggingService = LogService();
when(mockBackendService.sendLogs(any)).thenAnswer((input) => Future.value(false));

var files = logDirectory.listSync();
expect(files, hasLength(0));
final logEntry = LogEntry("Test message", LogLevel.info, {'version': "0.1", 'systemName': "unitTests"});
loggingService.save(logEntry);

await Future.delayed(const Duration(milliseconds: 20));

files = logDirectory.listSync();
expect(files, hasLength(1));

for (var i = 0; i < 400; i++) {
loggingService.save(logEntry);
}

await Future.delayed(const Duration(milliseconds: 20));

files = logDirectory.listSync();
expect(files, hasLength(2));

await Future.delayed(const Duration(milliseconds: 20));
});

test('Test send logs after rolling over file', () async {
LogService loggingService = LogService();
when(mockBackendService.sendLogs(any)).thenAnswer((input) => Future.value(false));

var files = logDirectory.listSync();
expect(files, hasLength(0));
final logEntry = LogEntry("Test message", LogLevel.info, {'version': "0.1", 'systemName': "unitTests"});
loggingService.save(logEntry);

await Future.delayed(const Duration(milliseconds: 20));

files = logDirectory.listSync();
expect(files, hasLength(1));

for (var i = 0; i < 400; i++) {
loggingService.save(logEntry);
}

await Future.delayed(const Duration(milliseconds: 20));

files = logDirectory.listSync();
expect(files, hasLength(2));

verify(mockBackendService.sendLogs(any)).called(1);
});

test('Test file deletion after successful backend request', () async {
LogService loggingService = LogService();
when(mockBackendService.sendLogs(any)).thenAnswer((input) => Future.value(true));

var files = logDirectory.listSync();
expect(files, hasLength(0));
final logEntry = LogEntry("Test message", LogLevel.info, {'version': "0.1", 'systemName': "unitTests"});
loggingService.save(logEntry);

await Future.delayed(const Duration(milliseconds: 20));

files = logDirectory.listSync();
expect(files, hasLength(1));

for (var i = 0; i < 400; i++) {
loggingService.save(logEntry);
}

await Future.delayed(const Duration(milliseconds: 20));

files = logDirectory.listSync();
expect(files, hasLength(1));
verify(mockBackendService.sendLogs(any)).called(1);
});
}
52 changes: 52 additions & 0 deletions das_client/test/mocks/path_provider_mock.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import 'package:mockito/mockito.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';

const String temporaryPath = 'temporaryPath';
const String applicationSupportPath = 'applicationSupportPath';
const String downloadsPath = 'downloadsPath';
const String libraryPath = 'libraryPath';
const String applicationDocumentsPath = 'applicationDocumentsPath';
const String externalCachePath = 'externalCachePath';
const String externalStoragePath = 'externalStoragePath';

class MockPathProviderPlatform extends Mock
with MockPlatformInterfaceMixin
implements PathProviderPlatform {

@override
Future<String> getTemporaryPath() async {
return temporaryPath;
}

@override
Future<String> getApplicationSupportPath() async {
return applicationSupportPath;
}

@override
Future<String> getLibraryPath() async {
return libraryPath;
}

@override
Future<String> getApplicationDocumentsPath() async {
return applicationDocumentsPath;
}

@override
Future<String> getExternalStoragePath() async {
return externalStoragePath;
}

@override
Future<List<String>> getExternalCachePaths() async {
return <String>[externalCachePath];
}

@override
Future<String> getDownloadsPath() async {
return downloadsPath;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import 'package:das_client/model/sfera/sfera_g2b_reply_message.dart';
import 'package:das_client/model/sfera/sfera_reply_parser.dart';
import 'package:das_client/repo/sfera_repository.dart';
import 'package:das_client/service/mqtt/mqtt_service.dart';
import 'package:das_client/service/sfera/task/handshake_task.dart';
import 'package:das_client/service/sfera/task/request_journey_profile_task.dart';
import 'package:das_client/util/error_code.dart';
import 'package:fimber/fimber.dart';
Expand Down

0 comments on commit 9f9b211

Please sign in to comment.