#!perl

use Test::More tests => 5;

BEGIN {
    use_ok( 'PDL::Graphics::Gnuplot', qw(plot) ) || print "Bail out!\n";
}


use File::Temp qw(tempfile);
use PDL;
my $x = sequence(5);

# I want to test 2 things:
# 1. basic plotting generates output
# 2. error detection works
#
# The reasoning for this is that since the plots themselves aren't generated by
# me (but by gnuplot), as far as I'm concerned complicated plots are as likely
# to succeed as simple ones. So if simple plots work, I assume complicated ones
# do too. Also, I have no good simple way of evaluating whether a plot was
# generated correctly.
#
# Further, the error detection works by looking at the STDERR output from the
# gnuplot process. The code that does this is tricky and is the one most likely
# to have portability issues


{
  # test basic plotting
  my (undef, $testoutput) = tempfile('pdl_graphics_gnuplot_test_XXXXXXX');
  print STDERR "testfile: $testoutput\n";


  eval{ plot ( terminal => 'dumb 79 24', output => $testoutput, $x); };
  ok(! $@,           'basic plotting succeeded without error' )
    or diag "plot() died with '$@'";
  ok(-e $testoutput, 'basic plotting created an output file' )
    or diag "plot() didn't create an output file";

  # call the output good if it's at least 80% of the nominal size
  my @filestats = stat $testoutput;
  ok($filestats[7] > 79*24*0.8, 'basic plotting created a reasonably-sized file')
    or diag "resulting output file should be ascii 79x24, but only contains $filestats[7] bytes";

  unlink $testoutput;
}

{
  # purposely fail. make sure error message is as expected. This means the gnuplot
  # process STDERR is read and parsed correctly

  my (undef, $testoutput) = tempfile('pdl_graphics_gnuplot_test_XXXXXXX');
  eval{ plot ( terminal => 'dumb 79 24', output => $testoutput, with => 'bogus', $x); };
  ok($@ && $@ =~ /gnuplot>.*bogus.*expecting/s,  'error detection works' )
    or diag "plot() produced no error";

  unlink $testoutput;
}

diag( "Testing PDL::Graphics::Gnuplot $PDL::Graphics::Gnuplot::VERSION, Perl $], $^X" );
