package Test::Perinci::CmdLine;

our $DATE = '2015-08-01'; # DATE
our $VERSION = '1.21'; # VERSION

use 5.010001;
use strict;
use warnings;
use Devel::Confess;

use Capture::Tiny qw(capture);
use Data::Dumper;
use File::Path qw(remove_tree);
use File::Slurper qw(read_text write_text);
use File::Temp qw(tempdir tempfile);
use IPC::System::Options qw(system);

use Test::More 0.98;

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(pericmd_ok);

our %SPEC;

sub _dump {
    local $Data::Dumper::Deparse = 1;
    local $Data::Dumper::Terse   = 1;
    local $Data::Dumper::Indent  = 0;
    Data::Dumper::Dumper($_[0]);
}

$SPEC{pericmd_ok} = {
    v => 1.1,
    summary => 'Common test suite for Perinci::CmdLine::{Lite,Classic,Inline}',
    args => {
        class => {
            summary => 'Which class are we testing',
            schema => ['str*', in=>[
                'Perinci::CmdLine::Lite',
                'Perinci::CmdLine::Classic',
                'Perinci::CmdLine::Inline',
            ]],
            req => 1,
        },
    },
};
sub pericmd_ok {
    my %suite_args = @_;

    my $class   = $suite_args{class};
    my $tempdir = tempdir();

    my $test_run = sub {
        use experimental 'smartmatch';
        no strict 'refs';
        no warnings 'redefine';

        my %test_args = @_;

        my $name = "run: " .
            ($test_args{name} // join(" ", @{$test_args{argv} // []}));

        subtest $name => sub {
            my $tags = $test_args{tags} // [];
            if ($class eq 'Perinci::CmdLine::Inline' && (
                'subcommand' ~~ @$tags)) {
                plan skip_all => "Not yet supported by pericmd-inline";
                return;
            }

            my %cli_args = %{
                # use class-specific args if defined
                ($class eq 'Perinci::CmdLine::Inline' ?
                     $test_args{args_inline} :
                     $class eq 'Perinci::CmdLine::Lite' ?
                     $test_args{args_lite} :
                     $test_args{args_classic}
                 )
                    // $test_args{args} // {}
                };
            $cli_args{read_config} //= 0;

            # construct the cli script
            my @script;
            if ($class eq 'Perinci::CmdLine::Inline') {
                require Perinci::CmdLine::Inline;
                $cli_args{include} = $test_args{inline_include}
                    if $test_args{inline_include};
                my $res = Perinci::CmdLine::Inline::gen_inline_pericmd_script(
                    %cli_args);
                die "Can't generate Perinci::CmdLine::Inline script: ".
                    "$res->[0] - $res->[1]" unless $res->[0] == 200;
                @script = ($res->[2]);
            } else {
                push @script, "use 5.010; use strict; use warnings;\n";
                push @script, "use $class;\n";
                push @script, "my \$cli = $class->new(\@{",
                    _dump([%cli_args]), '});', "\n";
                push @script, "\$cli->run;\n";
            }

            # write cli script to tempfile
            my ($fh, $filename) = tempfile('cliXXXXXXXX', DIR=>$tempdir);
            write_text($filename, join("", @script));
            note "Generated CLI script at $filename";

            my $stdout;
            my $stderr;
            my $res;
            system(
                {shell=>0, die=>0, log=>1,
                 capture_stdout=>\$stdout, capture_stderr=>\$stderr, lang=>'C'},
                $^X,
                # pericmd-inline script must work with only core modules
                ($class eq 'Perinci::CmdLine::Inline' ?
                     ("-Mlib::filter=allow_noncore,0".
                      ($test_args{inline_allow} ? ",allow=".
                       join(";",@{$test_args{inline_allow}}) : "")) : ()),
                $filename,
                @{ $test_args{argv} // []},
            );
            note "Script's stdout: <$stdout>";
            note "Script's stderr: <$stderr>";
            my $exit_code = $? >> 8;

            if (defined $test_args{exit_code}) {
                is($exit_code, $test_args{exit_code}, "exit_code") or do {
                    diag "Script's stdout: <$stdout>";
                    diag "Script's stderr: <$stderr>";
                };
            }
            if ($test_args{stdout_like}) {
                like($stdout, $test_args{stdout_like}, "stdout_like");
            }
            if ($test_args{stdout_unlike}) {
                unlike($stdout, $test_args{stdout_unlike}, "stdout_unlike");
            }
            if ($test_args{stderr_like}) {
                like($stderr, $test_args{stderr_like}, "stderr_like");
            }
            if ($test_args{stderr_unlike}) {
                unlike($stderr, $test_args{stderr_unlike}, "stderr_unlike");
            }
            if ($test_args{posttest}) {
                $test_args{posttest}->($exit_code, $stdout, $stderr);
            }
        }; # subtest
    }; # test_run

    subtest 'pericmd_ok test suite' => sub {
        subtest 'help action' => sub {
            $test_run->(
                args        => {url => '/Perinci/Examples/Tiny/noop'},
                argv        => [qw/--help/],
                exit_code   => 0,
                stdout_like => qr/^Usage.+^([^\n]*)Options/ims,
                inline_include => [qw/Perinci::Examples::Tiny/],
            );
            $test_run->(
                tags        => [qw/subcommand/],
                name        => 'help for cli with subcommands',
                args        => {
                    url => '/Perinci/Examples/Tiny/',
                    subcommands => {
                        sc1 => {url=>'/Perinci/Examples/Tiny/noop'},
                    },
                },
                argv        => [qw/--help/],
                exit_code   => 0,
                stdout_like => qr/^Subcommands.+\bsc1\b/ms,
                #inline_include => [qw/Perinci::Examples::Tiny/],
            );
            $test_run->(
                tags          => [qw/subcommand/],
                name          => 'help on a subcommand',
                args          => {
                    url => '/Perinci/Examples/Tiny/',
                    subcommands => {
                        sc1 => {url=>'/Perinci/Examples/Tiny/noop'},
                    },
                },
                argv          => [qw/sc1 --help/],
                exit_code     => 0,
                stdout_like   => qr/Do nothing.+^Usage/ms,
                stdout_unlike => qr/^Subcommands.+\bsc1\b/ms,
                #inline_include => [qw/Perinci::Examples::Tiny/],
            );
        };
    };

    if (!Test::More->builder->is_passing) {
        diag "there are failing tests, not deleting tempdir $tempdir";
    } elsif ($ENV{DEBUG}) {
        diag "DEBUG is true, not deleting tempdir $tempdir";
    } else {
        note "all tests successful, deleting tempdir $tempdir";
        remove_tree($tempdir);
    }
}

1;
# ABSTRACT: Common test suite for Perinci::CmdLine::{Lite,Classic,Inline}

__END__

=pod

=encoding UTF-8

=head1 NAME

Test::Perinci::CmdLine - Common test suite for Perinci::CmdLine::{Lite,Classic,Inline}

=head1 VERSION

This document describes version 1.21 of Test::Perinci::CmdLine (from Perl distribution Test-Perinci-CmdLine), released on 2015-08-01.

=head1 SEE ALSO

Supported Perinci::CmdLine backends: L<Perinci::CmdLine::Inline>,
L<Perinci::CmdLine::Lite>, L<Perinci::CmdLine::Classic>.

=head1 ENVIRONMENT

=head2 DEBUG => bool

If set to 1, then temporary files (e.g. generated scripts for testing) will not
be cleaned up, so you can inspect them.

=head1 FUNCTIONS


=head2 pericmd_ok(%args) -> [status, msg, result, meta]

Common test suite for Perinci::CmdLine::{Lite,Classic,Inline}.

Arguments ('*' denotes required arguments):

=over 4

=item * B<class>* => I<str>

Which class are we testing.

=back

Returns an enveloped result (an array).

First element (status) is an integer containing HTTP status code
(200 means OK, 4xx caller error, 5xx function error). Second element
(msg) is a string containing error message, or 'OK' if status is
200. Third element (result) is optional, the actual result. Fourth
element (meta) is called result metadata and is optional, a hash
that contains extra information.

Return value:  (any)

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/Test-Perinci-CmdLine>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-Test-Perinci-CmdLine>.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=Test-Perinci-CmdLine>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by perlancar@cpan.org.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
