package main;
use Evo::Base -strict;
use Test::More;
use Railway::Builder;
use Test::Fatal;

my $fired = 0;
{

  package MyTrain;
  use Evo::Base 'Railway::Train';
  sub cleanup { my $self = shift; $fired++; $self->SUPER::cleanup(@_) }
}

my $bldr = Railway::Builder->new;
my $tr;
$bldr->train_class('MyTrain');

# normal
$tr = $bldr->build_train;
$tr->way->add(sub { });
$tr->start();

# in way
like exception {
  $tr = $bldr->build_train;
  $tr->way->add(sub { die "FooE" });
  $tr->start();
},
  qr/FooE/;

# in cb
like exception {
  $tr = $bldr->build_train;
  $tr->way->add(sub { });
  $tr->start(sub    { die "FooE" });
}, qr/FooE/;

is $fired, 3, 'right count';

isa_ok $tr = $bldr->build_train->cargo([])->done(sub { })->index(1)->power(1),
  'Railway::Train';
ok $tr->{done} && $tr->{way} && $tr->{cargo};

$tr->cleanup;
is $tr->{done},  undef, 'cleared';
is $tr->{way},   undef, 'cleared';
is $tr->{cargo}, undef, 'cleared';
is $tr->{index}, undef, 'cleared';
is $tr->{power}, undef, 'cleared';


done_testing;
