Trog-Log-DBI.t 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. use strict;
  2. use warnings;
  3. use Test::More;
  4. use Test::Fatal qw{exception};
  5. use Capture::Tiny qw{capture_stderr};
  6. use File::Temp qw{tempdir};
  7. use FindBin;
  8. use lib "$FindBin::Bin/../lib";
  9. use Trog::SQLite;
  10. require_ok('Trog::Log::DBI') or BAIL_OUT("Can't find SUT");
  11. # The metrics database the way Trog::Log opens it, in a directory of its own.
  12. my $dir = tempdir( CLEANUP => 1 );
  13. my $dbh = Trog::SQLite::dbh( "$FindBin::Bin/../schema/log.schema", "$dir/log.db" );
  14. my $output = Trog::Log::DBI->new( name => 'dbi', min_level => 'info', dbh => $dbh );
  15. my $line = "2026-09-29T12:00:00Z [INFO]: RequestId r-1 From 192.0.2.1 |nobody| GET 200 512 /posts\n";
  16. subtest 'a request line is a row' => sub {
  17. ok( $output->log_message( message => $line ), 'the write reports success' );
  18. my ($count) = $dbh->selectrow_array("SELECT count(*) FROM all_requests WHERE uuid='r-1'");
  19. is( $count, 1, 'and the request is in all_requests' );
  20. };
  21. # The handle raises on every error, and log_message runs inside every log
  22. # call, so a refused write must not take the caller down with it.
  23. subtest 'a write the database refuses is a warning, not a die' => sub {
  24. $dbh->do("CREATE TEMP TRIGGER refuse_request BEFORE INSERT ON requests BEGIN SELECT RAISE(ABORT, 'refused for the test'); END");
  25. my ( $res, $died );
  26. my $stderr = capture_stderr {
  27. $died = exception { $res = $output->log_message( message => $line =~ s/r-1/r-2/r ) };
  28. };
  29. $dbh->do("DROP TRIGGER temp.refuse_request");
  30. is( $died, undef, 'the caller of the log does not die' );
  31. is( $res, undef, 'the write reports that it failed' );
  32. like( $stderr, qr/Could not record request r-2 in the metrics database: .*refused for the test/, 'and says why on stderr' );
  33. };
  34. done_testing();