loggers.t 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env perl
  2. use 5.040;
  3. use warnings FATAL => 'all';
  4. use re '/aasx';
  5. use Test2::V0;
  6. use Test2::Plugin::NoWarnings;
  7. use File::Path qw{make_path};
  8. use File::Temp qw{tempdir};
  9. use Mojo::File ();
  10. use FindBin::libs;
  11. ok( require TPSGI, 'TPSGI loads' ) or bail_out("Can't find SUT");
  12. # A logger named in the configuration is a class that nothing has loaded yet.
  13. # An application ships it beside its router, and TPSGI logs its first line
  14. # while it is still loading that router.
  15. my $dir = tempdir( CLEANUP => 1 );
  16. my $lib = "$dir/lib";
  17. make_path("$lib/Test/Logger");
  18. Mojo::File->new("$lib/Test/Logger/Capture.pm")->spew(<<'LOGGER');
  19. package Test::Logger::Capture;
  20. use strict;
  21. use warnings;
  22. use parent qw{Log::Dispatch::Output};
  23. our @lines;
  24. our %given;
  25. sub new {
  26. my ( $class, %p ) = @_;
  27. %given = %p;
  28. my $self = bless {}, $class;
  29. $self->_basic_init( name => 'capture', min_level => $p{min_level} );
  30. return $self;
  31. }
  32. sub log_message {
  33. my ( $self, %p ) = @_;
  34. push( @lines, $p{message} );
  35. return;
  36. }
  37. 1;
  38. LOGGER
  39. push( @INC, $lib );
  40. my $tpsgi = bless(
  41. {
  42. log_name => "$dir/tpsgi.log",
  43. log_dir => $dir,
  44. verbose => 0,
  45. loggers => ['Test::Logger::Capture'],
  46. ip => '0.0.0.0',
  47. },
  48. 'TPSGI'
  49. );
  50. ok( lives { $tpsgi->log }, 'a logger class that nothing loaded is loaded by name' ) or note $@;
  51. no warnings 'once';
  52. is( $Test::Logger::Capture::given{log_dir}, $dir, 'it is handed the log directory' );
  53. is( $Test::Logger::Capture::given{min_level}, 'info', 'and the level' );
  54. like( \@Test::Logger::Capture::lines, [qr/Opening[ ]Log/], 'and it receives the lines that the file gets' );
  55. # The name becomes a path to load, so only a module name is one.
  56. my $refusing = bless( { %$tpsgi, loggers => ['../../etc/passwd'] }, 'TPSGI' );
  57. like( dies { $refusing->build_log }, qr/not[ ]a[ ]module[ ]name/, 'a logger that is not a module name is refused' );
  58. done_testing();