Database-BI

 view release on metacpan or  search on metacpan

t/function.t  view on Meta::CPAN

};

# ---------------------------------------------------------------------------
# Subtest: _new_from_url -- invalid URL scheme is rejected
# ---------------------------------------------------------------------------
subtest 'DataSource::_new_from_url -- invalid URL scheme croaks' => sub {
	throws_ok { $DS->new(url => 'ftp://example.com/data.csv') }
		qr/must begin with http/i,
		'croaks for ftp:// URL';

	throws_ok { $DS->new(url => 'file:///etc/passwd') }
		qr/must begin with http/i,
		'croaks for file:// URL';

	throws_ok { $DS->new(url => 'javascript:alert(1)') }
		qr/must begin with http/i,
		'croaks for javascript: pseudo-URL';
};

# ============================================================================
# PART 2: Database::BI::Controller::Dashboard -- pure-function helpers
#
# These subs are not :Private and survive stash cleanup, so they can be
# called as plain functions without a Mojolicious controller context.
# ============================================================================

my $D = 'Database::BI::Controller::Dashboard';

# ---------------------------------------------------------------------------
# Subtest: _is_safe_url -- SSRF guard
#
# Each blocked range has a representative, a boundary, and a just-safe IP.
# Non-IP hostnames must always pass (firewall handles those).
# ---------------------------------------------------------------------------
subtest '_is_safe_url -- loopback aliases are blocked' => sub {
	my $fn = \&Database::BI::Controller::Dashboard::_is_safe_url;

	ok !$fn->('http://localhost/'),           'localhost blocked';
	ok !$fn->('http://localhost:8080/path'),  'localhost with port blocked';
	ok !$fn->('https://localhost/'),          'https://localhost blocked';
	ok !$fn->('http://127.0.0.1/'),           '127.0.0.1 blocked';
	ok !$fn->('http://127.255.255.255/'),     '127.255.255.255 blocked (127/8)';
	ok !$fn->('http://0.0.0.0/'),             '0.0.0.0 blocked';
	ok !$fn->('http://[::1]/'),               'IPv6 ::1 blocked';
};

subtest '_is_safe_url -- RFC 1918 private ranges are blocked' => sub {
	my $fn = \&Database::BI::Controller::Dashboard::_is_safe_url;

	ok !$fn->('http://10.0.0.1/'),            '10.0.0.1 blocked (10/8)';
	ok !$fn->('http://10.255.255.255/'),      '10.255.255.255 blocked (10/8 boundary)';
	ok !$fn->('http://172.16.0.1/'),          '172.16.0.1 blocked (172.16/12)';
	ok !$fn->('http://172.31.255.255/'),      '172.31.255.255 blocked (172.16/12 boundary)';
	ok !$fn->('http://192.168.0.1/'),         '192.168.0.1 blocked (192.168/16)';
	ok !$fn->('http://192.168.255.255/'),     '192.168.255.255 blocked (192.168/16 boundary)';
};

subtest '_is_safe_url -- link-local and CGNAT ranges are blocked' => sub {
	my $fn = \&Database::BI::Controller::Dashboard::_is_safe_url;

	ok !$fn->('http://169.254.169.254/'),     'AWS metadata endpoint blocked (169.254/16)';
	ok !$fn->('http://169.254.0.1/'),         '169.254.0.1 blocked (link-local)';
	ok !$fn->('http://100.64.0.1/'),          '100.64.0.1 blocked (CGNAT 100.64/10)';
	ok !$fn->('http://100.127.255.255/'),     '100.127.255.255 blocked (CGNAT boundary)';
};

subtest '_is_safe_url -- public addresses are allowed' => sub {
	my $fn = \&Database::BI::Controller::Dashboard::_is_safe_url;

	ok $fn->('http://8.8.8.8/'),              '8.8.8.8 (Google DNS) allowed';
	ok $fn->('http://1.1.1.1/'),              '1.1.1.1 (Cloudflare) allowed';
	ok $fn->('https://example.com/data'),     'example.com hostname allowed';
	ok $fn->('http://internal.corp.example/'), 'internal hostname allowed (firewall handles it)';

	# Just outside blocked ranges
	ok $fn->('http://11.0.0.1/'),             '11.0.0.1 allowed (outside 10/8)';
	ok $fn->('http://172.32.0.1/'),           '172.32.0.1 allowed (outside 172.16/12)';
	ok $fn->('http://192.169.0.1/'),          '192.169.0.1 allowed (outside 192.168/16)';
	ok $fn->('http://100.128.0.1/'),          '100.128.0.1 allowed (outside 100.64/10)';
};

subtest '_is_safe_url -- non-http scheme returns 0' => sub {
	my $fn = \&Database::BI::Controller::Dashboard::_is_safe_url;

	ok !$fn->('ftp://example.com/'),          'ftp:// returns 0 (no http/https match)';
	ok !$fn->('file:///etc/passwd'),           'file:// returns 0';
	ok !$fn->(''),                             'empty string returns 0';
};

# ---------------------------------------------------------------------------
# Subtest: _get_columns -- column ordering logic
#
# For CSV/PSV the source stores the original file-header order.
# For SQLite/XML (columns() returns undef), the fallback puts id_column first
# then alphabetical order.
# ---------------------------------------------------------------------------
subtest '_get_columns -- returns file-header order for CSV source' => sub {
	my $fn = \&Database::BI::Controller::Dashboard::_get_columns;

	# Mock a DataSource that has an ordered column list (CSV case).
	my $mock_src = bless {}, 'FakeDS_CSV';
	{
		no strict 'refs';
		*{'FakeDS_CSV::columns'}   = sub { [qw(id product region amount)] };
		*{'FakeDS_CSV::id_column'} = sub { 'id' };
	}

	my @cols = $fn->($mock_src, [{ id => 1, product => 'x' }]);
	is_deeply \@cols, [qw(id product region amount)],
		'preserves file-header order from columns()';
};

subtest '_get_columns -- fallback alphabetical order when columns() is undef' => sub {
	my $fn = \&Database::BI::Controller::Dashboard::_get_columns;

	# Mock a DataSource where columns() returns undef (SQLite/XML case).
	my $mock_src = bless {}, 'FakeDS_SQLite';
	{
		no strict 'refs';
		*{'FakeDS_SQLite::columns'}   = sub { undef };
		*{'FakeDS_SQLite::id_column'} = sub { 'id' };

t/function.t  view on Meta::CPAN

		'wrong separator (hyphens) fails %d/%m/%Y regex (returns undef)';
};

subtest 'Calc::date_normalise -- %d-%b-%Y DD-Mon-YYYY format' => sub {
	is Database::BI::Calc::date_normalise('15-Jan-2026', '%d-%b-%Y'), '2026-01-15',
		'converts DD-Mon-YYYY with mixed-case abbreviation';
	is Database::BI::Calc::date_normalise('01-DEC-1999', '%d-%b-%Y'), '1999-12-01',
		'case-insensitive month abbreviation (DEC)';
	is Database::BI::Calc::date_normalise('7-oct-2024',  '%d-%b-%Y'), '2024-10-07',
		'lowercase month abbreviation accepted';

	# Invalid month abbreviation must return undef, not crash.
	is Database::BI::Calc::date_normalise('15-Xxx-2026', '%d-%b-%Y'), undef,
		'unknown month abbreviation returns undef';
	# Slash separator does not match hyphen-based pattern.
	is Database::BI::Calc::date_normalise('15/Jan/2026', '%d-%b-%Y'), undef,
		'slash-separated date does not match %d-%b-%Y';
};

subtest 'Calc::date_normalise -- undef / empty / unknown pattern edge cases' => sub {
	# Guard clauses: undef or empty inputs must return undef safely.
	is Database::BI::Calc::date_normalise(undef, '%m/%d/%Y'), undef,
		'undef value returns undef';
	is Database::BI::Calc::date_normalise('',    '%m/%d/%Y'), undef,
		'empty string returns undef';
	is Database::BI::Calc::date_normalise('01/15/2026', undef), undef,
		'undef pattern returns undef';
	# An unsupported pattern silently returns undef (no croak).
	is Database::BI::Calc::date_normalise('01/15/2026', '%Y-%m-%d'), undef,
		'unsupported pattern returns undef (does not croak)';
};

subtest 'Calc::evaluate -- returns undef when object has a compile error (_code is undef)' => sub {
	# When new() fails to parse, _code stays undef.  evaluate() must not croak;
	# it must return undef so callers can treat runtime errors uniformly.
	my $bad = Database::BI::Calc->new(expr => 'qty % 2', columns => ['qty']);
	ok $bad->has_error, 'compile error set on bad expression';
	is $bad->evaluate({ qty => 10 }), undef,
		'evaluate() returns undef on object with compile error (no croak)';
};

subtest 'Calc::evaluate -- runtime division by zero returns undef, does not croak' => sub {
	my $c = Database::BI::Calc->new(expr => 'amount / qty', columns => ['amount', 'qty']);
	ok !$c->has_error, 'expression compiles cleanly';
	is $c->evaluate({ amount => 100, qty => 0 }), undef,
		'division by zero yields undef at runtime';
};

subtest 'Calc -- memory cycle check on compiled object' => sub {
	# Ensure the closure tree created by new() does not form a reference cycle
	# that would prevent garbage collection.
	my $c = Database::BI::Calc->new(
		expr    => 'if(amount > 0, round(amount * 1.1, 2), 0)',
		columns => ['amount'],
	);
	ok !$c->has_error, 'expression compiles for memory-cycle check';
	memory_cycle_ok($c, 'no reference cycles in compiled Calc object');
};

# ============================================================================
# PART 4: new chart-view endpoints (scatter / stacked / combo / treemap / histogram)
# ============================================================================
# All tests use the $t Test::Mojo instance and data/sales.csv (6 rows:
# product, region, amount, date) as the data source.  Only the error-path
# tests and basic smoke tests are included here; full pipeline tests live in
# t/integration.t.  The primary goal is 60%+ negative coverage.

{
	use Mojo::Util qw(url_escape);
	Readonly my $SALES_SPEC => url_escape('table:sales');

# ---------------------------------------------------------------------------
# scatter_view
# ---------------------------------------------------------------------------

subtest 'scatter_view -- missing x= returns 400' => sub {
	$t->get_ok("/scatter?l=$SALES_SPEC&y=amount")
	  ->status_is(400)
	  ->content_like(qr/Missing x=/i,
		'missing x= produces 400 with descriptive message');
};

subtest 'scatter_view -- missing y= returns 400' => sub {
	$t->get_ok("/scatter?l=$SALES_SPEC&x=amount")
	  ->status_is(400)
	  ->content_like(qr/Missing y=/i,
		'missing y= produces 400 with descriptive message');
};

subtest 'scatter_view -- unknown x column returns 400' => sub {
	SKIP: {
		skip 'data/sales.csv not found', 2 unless -f 'data/sales.csv';
		$t->get_ok("/scatter?l=$SALES_SPEC&x=no_such_col&y=amount")
		  ->status_is(400)
		  ->content_like(qr/Column not found.*no_such_col/i,
			'unknown x column yields 400');
	}
};

subtest 'scatter_view -- unknown colour scheme with series= returns 400' => sub {
	SKIP: {
		skip 'data/sales.csv not found', 2 unless -f 'data/sales.csv';
		$t->get_ok("/scatter?l=$SALES_SPEC&x=amount&y=amount&series=region&scheme=bogus")
		  ->status_is(400)
		  ->content_like(qr/Unknown colour scheme/i,
			'unrecognised scheme with series= yields 400');
	}
};

subtest 'scatter_view -- valid render returns 200 with SVG' => sub {
	SKIP: {
		skip 'data/sales.csv not found', 2 unless -f 'data/sales.csv';
		$t->get_ok("/scatter?l=$SALES_SPEC&x=amount&y=amount")
		  ->status_is(200)
		  ->content_like(qr/<svg/i,
			'valid scatter request renders an SVG element');
	}
};

# ---------------------------------------------------------------------------
# stacked_view

t/function.t  view on Meta::CPAN

		skip 'data/sales.csv not found', 2 unless -f 'data/sales.csv';
		$t->get_ok("/treemap?l=$SALES_SPEC&group=region&size=amount")
		  ->status_is(200)
		  ->content_like(qr/<svg/i,
			'valid treemap request renders an SVG element');
	}
};

# ---------------------------------------------------------------------------
# histogram_view
# ---------------------------------------------------------------------------

subtest 'histogram_view -- missing col= returns 400' => sub {
	$t->get_ok("/histogram?l=$SALES_SPEC")
	  ->status_is(400)
	  ->content_like(qr/Missing col=/i,
		'missing col= yields 400');
};

subtest 'histogram_view -- unknown col returns 400' => sub {
	SKIP: {
		skip 'data/sales.csv not found', 2 unless -f 'data/sales.csv';
		$t->get_ok("/histogram?l=$SALES_SPEC&col=no_such_col")
		  ->status_is(400)
		  ->content_like(qr/Column not found/i,
			'unknown col yields 400');
	}
};

subtest 'histogram_view -- bins clamped to 200 maximum (does not crash)' => sub {
	SKIP: {
		skip 'data/sales.csv not found', 2 unless -f 'data/sales.csv';
		# bins=99999 must be clamped to 200 internally; the response must be 200
		# or the "No plottable data" message, never a 500 or crash.
		$t->get_ok("/histogram?l=$SALES_SPEC&col=amount&bins=99999")
		  ->status_is(200, 'bins=99999 clamped to 200, no server error');
	}
};

subtest 'histogram_view -- bins clamped to 1 minimum (does not crash)' => sub {
	SKIP: {
		skip 'data/sales.csv not found', 2 unless -f 'data/sales.csv';
		$t->get_ok("/histogram?l=$SALES_SPEC&col=amount&bins=0")
		  ->status_is(200, 'bins=0 clamped to 1, no server error');
	}
};

subtest 'histogram_view -- valid render returns 200 with SVG' => sub {
	SKIP: {
		skip 'data/sales.csv not found', 2 unless -f 'data/sales.csv';
		$t->get_ok("/histogram?l=$SALES_SPEC&col=amount&bins=5")
		  ->status_is(200)
		  ->content_like(qr/<svg/i,
			'valid histogram request renders an SVG element');
	}
};

} # end url_escape scope

# ============================================================================
# PART 5: calc / groups / dates CRUD endpoints
# ============================================================================
# Isolate the model store in a fresh tempdir so these tests never touch
# .bi/models.json in the working directory.

{
	my $MODEL_DIR = tempdir(CLEANUP => 1);
	$t->app->config->{model_dir} = $MODEL_DIR;

	Readonly my $TEST_SPEC => 'table:sales';

# ---------------------------------------------------------------------------
# calc_list / calc_save / calc_delete
# ---------------------------------------------------------------------------

subtest 'calc_list -- l= required, returns 400 when absent' => sub {
	$t->get_ok('/calc/list')
	  ->status_is(400)
	  ->json_is('/error', 'l= required',
		'GET /calc/list without l= returns 400 with error message');
};

subtest 'calc_save -- l= required, returns 400 when absent' => sub {
	$t->post_ok('/calc/save', form => { name => 'profit', expr => 'amount * 2' })
	  ->status_is(400)
	  ->json_is('/error', 'l= required',
		'POST /calc/save without l= returns 400');
};

subtest 'calc_save -- invalid name (spaces) returns 400' => sub {
	$t->post_ok('/calc/save',
		form => { l => $TEST_SPEC, name => 'bad name', expr => 'amount * 2' })
	  ->status_is(400)
	  ->json_like('/error', qr/not a valid identifier/i,
		'calc name with spaces is rejected with 400');
};

subtest 'calc_save -- name with leading digit returns 400' => sub {
	$t->post_ok('/calc/save',
		form => { l => $TEST_SPEC, name => '1profit', expr => 'amount * 2' })
	  ->status_is(400)
	  ->json_like('/error', qr/not a valid identifier/i,
		'calc name starting with digit is rejected with 400');
};

subtest 'calc_save -- expr= required, returns 400 when absent' => sub {
	$t->post_ok('/calc/save', form => { l => $TEST_SPEC, name => 'profit' })
	  ->status_is(400)
	  ->json_is('/error', 'expr= required',
		'POST /calc/save without expr= returns 400');
};

subtest 'calc_save / calc_list / calc_delete -- full roundtrip' => sub {
	# Store two calc fields, retrieve them, then delete one and verify.

	$t->post_ok('/calc/save',
		form => { l => $TEST_SPEC, name => 'double', expr => 'amount * 2' })
	  ->status_is(200)
	  ->json_is('/ok', 1, 'first calc field saved');

	$t->post_ok('/calc/save',



( run in 0.849 second using v1.01-cache-2.11-cpan-eb134014566 )