#!/usr/bin/perl

# t/11-bugfix.t

#
# Written by Sébastien Millet
# June 2016
#

#
# Test script for Text::AutoCSV: bug fixes
#

use strict;
use warnings;

use Test::More tests => 8;
#use Test::More qw(no_plan);

	# FIXME
	# If the below is zero, ignore this FIX ME entry
	# If the below is non zero, it'll use some hacks to ease development
my $DEVTIME = 0;

	# FIXME
	# Comment when not in dev
#use feature qw(say);
#use Data::Dumper;
#$Data::Dumper::Sortkeys = 1;

BEGIN {
	use_ok('Text::AutoCSV');
}

if ($DEVTIME) {
	note("");
	note("***");
	note("***");
	note("***  !! WARNING !!");
	note("***");
	note("***  SET \$DEVTIME TO 0 BEFORE RELEASING THIS CODE TO PRODUCTION");
	note("***  RIGHT NOW, \$DEVTIME IS EQUAL TO $DEVTIME");
	note("***");
	note("***");
	note("");
}

can_ok('Text::AutoCSV', ('new'));


# * **** *
# * bugs *
# * **** *

note("");
note("[BU]g fixes");

my $csv = Text::AutoCSV->new(in_file => 't/l01a.csv', croak_if_error => 0)
	->field_add_link('WHATEVER', 'A->B->NON_EXISTENT_FIELD', 't/l01b.csv');
my $eval_failed = 0;
my $msgs = '';
eval {
	local $SIG{__WARN__} = sub {
		$msgs .= "@_";
	};
	my $all = $csv->get_hr_all();
} or $eval_failed = 1;
$msgs .= "\n" . $@ if $eval_failed;
is($eval_failed, 1, "BU01 - check link to a non-existent field produces a croak");
like($msgs, qr/unknown field/i, "BU02 - check error message");
unlike($msgs, qr/in-memory CSV content discarded/i, "BU03 - check there is no buggy warning");

$csv = Text::AutoCSV->new(in_file => 't/l01a.csv')
	->field_add_link('S', 'Z->B->SITE', 't/l01b.csv');
$eval_failed = 0;
$msgs = '';
eval {
	local $SIG{__WARN__} = sub {
		$msgs .= "@_";
	};
	$csv->read();
} or $eval_failed = 1;
is($eval_failed, 1, "BU04 - check link from a non-existent field produces a croak");
like($@, qr/unknown field/i, "BU05 - check error message");
unlike($msgs, qr/uninitialized/i, "BU06 - check there was no warning about uninitialized value");


done_testing();

