drift/drift_dev/test/utils/test_backend.dart

83 lines
2.0 KiB
Dart
Raw Normal View History

import 'dart:async';
import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:build_test/build_test.dart';
2021-10-08 09:10:48 -07:00
import 'package:drift_dev/src/backends/backend.dart';
import 'package:logging/logging.dart';
class TestBackend extends Backend {
2019-09-02 11:28:57 -07:00
final Map<AssetId, String> fakeContent;
2021-07-26 10:48:26 -07:00
late Resolver _resolver;
final Completer _initCompleter = Completer();
final Completer _finish = Completer();
/// Future that completes when this backend is ready, which happens when all
/// input files have been parsed and analyzed by the Dart analyzer.
Future get _ready => _initCompleter.future;
TestBackend(this.fakeContent, {bool enableDartAnalyzer = true}) {
2020-02-25 12:54:12 -08:00
if (enableDartAnalyzer) {
_init();
} else {
_initCompleter.complete();
}
}
void _init() {
2019-09-02 11:28:57 -07:00
resolveSources(fakeContent.map((k, v) => MapEntry(k.toString(), v)), (r) {
_resolver = r;
_initCompleter.complete();
return _finish.future;
});
}
2019-09-02 11:28:57 -07:00
BackendTask startTask(Uri uri) {
return _TestBackendTask(this, uri);
}
void finish() {
_finish.complete();
}
@override
Uri resolve(Uri base, String import) {
2021-03-16 01:47:09 -07:00
final from = AssetId.resolve(base);
return AssetId.resolve(Uri.parse(import), from: from).uri;
}
}
class _TestBackendTask extends BackendTask {
final TestBackend backend;
@override
2019-09-02 11:28:57 -07:00
final Uri entrypoint;
@override
2021-07-26 10:48:26 -07:00
Logger get log => Logger.root;
_TestBackendTask(this.backend, this.entrypoint);
@override
2019-09-02 11:28:57 -07:00
Future<String> readMoor(Uri path) async {
await backend._ready;
2021-07-26 10:48:26 -07:00
return backend.fakeContent[AssetId.resolve(path)]!;
}
@override
2019-09-02 11:28:57 -07:00
Future<LibraryElement> resolveDart(Uri path) async {
await backend._ready;
try {
return await backend._resolver.libraryFor(AssetId.resolve(path));
} on NonLibraryAssetException catch (_) {
throw NotALibraryException(path);
}
}
@override
Future<bool> exists(Uri uri) async {
2021-03-16 01:47:09 -07:00
return backend.fakeContent.containsKey(AssetId.resolve(uri));
}
}