ormedTest function
void
ormedTest(})
Runs a test with database isolation.
Automatically sets up and tears down database state for each test. The DataSource is passed to the test body.
If called inside an ormedGroup, this uses the group's DataSource and follows the group's isolation strategy. If called standalone, this creates a fresh database for this specific test.
ormedTest('creates a user', (db) async {
final user = User(name: 'John');
await user.save(db);
expect(user.id, isNotNull);
});
Implementation
void ormedTest(
String description,
FutureOr<void> Function(DataSource dataSource) body, {
String? testOn,
Timeout? timeout,
dynamic skip,
dynamic tags,
Map<String, dynamic>? onPlatform,
int? retry,
}) {
test(
description,
() async {
final context = _currentGroupContext;
// Resolve manager from context/config or fail
final manager =
context?.manager ??
_currentZoneConfig?.manager ??
_lastRegisteredConfig?.manager ??
(_managers.isEmpty ? null : _managers.values.first);
if (manager == null) {
throw StateError(
'Ormed test environment not initialized. '
'ormedTest must be called within an ormedGroup, or call setUpOrmed() first.',
);
}
DataSource dataSource;
bool isStandalone = context == null;
if (isStandalone) {
// Standalone test: create fresh DB
final testId = 'test_${_generateGroupId()}';
dataSource = await manager.createDatabase(testId);
// Optional: begin transaction for consistency, though we drop DB anyway
await dataSource.beginTransaction();
dataSource.setAsDefault();
} else {
// Group test: use context's datasource
if (context.dataSource == null) {
throw StateError(
'Group DataSource not initialized. Check ormedGroup strategy.',
);
}
dataSource = context.dataSource!;
}
try {
await body(dataSource);
} finally {
if (isStandalone) {
await dataSource.rollback();
await manager.dropDatabase(dataSource);
}
}
},
testOn: testOn,
timeout: timeout,
skip: skip,
tags: tags,
onPlatform: onPlatform,
retry: retry,
);
}