Search code examples
databasedartaqueduct

Running Dart tests on the real database in Aqueduct


I'm creating a read only PostgreSQL database. Since it won't be modified after I populate it, I'd like to run some tests to make sure the data is good. The TestHarness with the ORM mixin creates an empty database for each test. Can I access the real database from the tests?

I'm moving a Q&A from the Aqueduct Slack channel for public reference.


Solution

  • Answer from Reductions:

    You can start a server and get its mangedContext.:

    final app = Application<YourChannel>() 
      ..options.configurationFilePath = theConfigString 
      ..options.port = somePort;
    await app.startOnCurrentIsolate();
    final context = app.channel.context; 
    // Now you can use the context to access the data base
    

    And this is how I implemented it in context:

    import "package:test/test.dart";
    import 'package:my_server/model/text_line.dart';
    import '../harness/app.dart';
    
    Future main() async {
    
      // setup
      final app = Application<MyServerChannel>()
        ..options.configurationFilePath = 'config.yaml';
      await app.startOnCurrentIsolate();
      final context = app.channel.context;
    
      test('Database has the right number of rows', () async {
        final query = Query<TextLine>(context);
        final numRows = await query.reduce.count();
        expect(numRows, 43845);
      });
    
    }