loggers.t 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. use strict;
  2. use warnings;
  3. use Test2::V0;
  4. use Test2::Plugin::NoWarnings;
  5. use Cwd qw{abs_path};
  6. use File::Path qw{make_path};
  7. use File::Temp qw{tempdir};
  8. use File::Basename qw{dirname};
  9. use lib dirname( abs_path(__FILE__) ) . '/../lib';
  10. use TPSGI;
  11. # A logger named in the configuration is a class that nothing has loaded yet.
  12. # An application ships it beside its router, and TPSGI logs its first line
  13. # while it is still loading that router.
  14. my $dir = tempdir( CLEANUP => 1 );
  15. my $lib = "$dir/lib";
  16. make_path("$lib/Test/Logger");
  17. open( my $fh, '>', "$lib/Test/Logger/Capture.pm" ) or die "Cannot write the test logger: $!";
  18. print $fh <<'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. close($fh);
  40. push( @INC, $lib );
  41. my $tpsgi = bless(
  42. {
  43. log_name => "$dir/tpsgi.log",
  44. log_dir => $dir,
  45. verbose => 0,
  46. loggers => ['Test::Logger::Capture'],
  47. ip => '0.0.0.0',
  48. },
  49. 'TPSGI'
  50. );
  51. ok( lives { $tpsgi->log }, 'a logger class that nothing loaded is loaded by name' ) or note $@;
  52. no warnings 'once';
  53. is( $Test::Logger::Capture::given{log_dir}, $dir, 'it is handed the log directory' );
  54. is( $Test::Logger::Capture::given{min_level}, 'info', 'and the level' );
  55. like( \@Test::Logger::Capture::lines, [qr/Opening Log/], 'and it receives the lines that the file gets' );
  56. # The name becomes a path to load, so only a module name is one.
  57. my $refusing = bless( { %$tpsgi, loggers => ['../../etc/passwd'] }, 'TPSGI' );
  58. like( dies { TPSGI::_build_log($refusing) }, qr/not a module name/, 'a logger that is not a module name is refused' );
  59. done_testing();