Database-BI
view release on metacpan or search on metacpan
t/function.t view on Meta::CPAN
# ============================================================================
{
my $fn = \&Database::BI::Util::urlencode;
# Strategy: the unreserved set must pass untouched, because over-encoding
# breaks the URLs Insights and Ask compare and link to.
subtest 'Util::urlencode -- unreserved characters pass through' => sub {
is $fn->('AZaz09-._~'), 'AZaz09-._~', 'the RFC 3986 unreserved set is left alone';
is $fn->(''), '', 'an empty string stays empty';
is $fn->('0'), '0', 'a false but defined value is not treated as missing';
returns_is $fn->('x'), { type => 'string' }, 'always a plain string';
};
# Strategy: everything that could end a value or start a parameter, a path or
# a script has to come out inert.
subtest 'Util::urlencode -- hostile input cannot escape the query value' => sub {
is $fn->(undef), '', 'undef becomes an empty string, not a warning';
is $fn->('a b&c=d'), 'a%20b%26c%3Dd', 'separators cannot start a new parameter';
is $fn->('%41'), '%2541', 'an encoded value is encoded again, never passed through';
is $fn->('../../etc'), '..%2F..%2Fetc', 'slashes cannot walk a path';
is $fn->(qq{"><script>}), '%22%3E%3Cscript%3E', 'markup cannot leave an attribute';
is $fn->("a\r\nb"), 'a%0D%0Ab', 'CRLF cannot split a header';
is $fn->("\0"), '%00', 'a NUL byte cannot truncate the value';
is $fn->('#frag?q'), '%23frag%3Fq', 'nor can a fragment or a query mark';
};
# Why: a decoded column name reaches this function from Insights. The code
# point 0x263A printed as "%263A" would decode to "&3A", a different value.
subtest 'Util::urlencode -- a wide character is encoded as its UTF-8 bytes' => sub {
is $fn->("\x{263A}"), '%E2%98%BA', 'three UTF-8 bytes, not one over-long escape';
is $fn->("a\x{263A}b"), 'a%E2%98%BAb', 'inside a longer value too';
is $fn->("\xC3\xA9"), '%C3%A9', 'bytes that are already UTF-8 are not encoded twice';
};
subtest 'Util::urlencode -- the caller keeps its value and its globals' => sub {
my $input = 'a b';
$fn->($input);
is $input, 'a b', 'the argument is not modified in place';
keeps_globals_ok('urlencode', sub { $fn->('a b') });
};
my $number = \&Database::BI::Util::parse_number;
subtest 'Util::parse_number -- the ways a number is dressed' => sub {
my %reads = (
'12' => 12, '-1.5' => -1.5, '0' => 0, '$1,234.56' => 1234.56, '(1,234.56)' => -1234.56,
'($5)' => -5, '50%' => 50, '1 234' => 1234, '1e3' => 1000, '2.5E-1' => 0.25,
'USD 100' => 100, '100 EUR' => 100, 'GBP100' => 100, '100GBP' => 100, '(USD 100)' => -100,
"\xC2\xA35" => 5, "\x{20AC}7" => 7, ' 7 ' => 7,
);
is $number->($_), $reads{$_}, "'$_' is read" for sort grep { !/[^\x00-\x7F]/ } keys %reads;
is $number->("\xC2\xA35"), 5, 'a pound sign as UTF-8 bytes';
is $number->("\x{20AC}7"), 7, 'a decoded euro sign';
};
# Why: this is the test of what a chart will total. A code column read as numbers
# is a meaningless measure, and an unknown code must not pass for a currency.
subtest 'Util::parse_number -- text that merely holds digits' => sub {
is $number->($_), undef, "'$_' is not a number" for
'', 'abc', 'SKU123', 'SKU 100', '100 SKU', 'A1', 'AB-100', 'R2D2', 'v1.2', '12/25/2025', '2026-05-20',
'10:30', '1.2.3', '--5', '-', '.', '()', 'USD', 'USD USD', 'Widget 2', '1e', 'e5', '0x10', 'Inf', 'NaN';
is $number->(undef), undef, 'nor is nothing';
is $number->('1e999'), undef, 'nor is what would be infinity';
is $number->('-1e999'), undef, 'in either direction';
is $number->('9' x 400), undef, 'however it is spelled';
# The limit is a double's, which is the browser's, on every perl. A perl
# built with -Duselongdouble or -Dusequadmath holds these as finite
# numbers, and passed them through until GitHub issue 6.
ok defined $number->('1.79e308'), 'the largest a double holds is a number';
is $number->('1.8e308'), undef, 'one past it is not, whatever this perl holds';
is $number->('-1.8e308'), undef, '... nor below';
is $number->('1e4000'), undef, '... nor far past it';
keeps_globals_ok('parse_number', sub { $number->('$5') });
};
}
# ============================================================================
# PART U2: Database::BI::Summary
#
# The cache is a lexical in the module, so each subtest uses its own label to
# start from a miss. LWP is replaced throughout: nothing here reaches a network.
# ============================================================================
{
Readonly my $SUM => 'Database::BI::Summary';
Readonly my $API_KEY => 'test-key';
Readonly my $SECRET => 'path:/private/secret-file.csv';
my $tmpl = \&Database::BI::Summary::_template_summary;
my $fp = \&Database::BI::Summary::_fingerprint;
my $llm = \&Database::BI::Summary::_llm_summary;
my $call = \&Database::BI::Summary::_call_anthropic;
my %outlier = (kind => 'outlier', headline => 'Odd value', detail => 'd1');
my %period = (kind => 'period_delta', headline => 'Up 5', detail => 'd2');
my %mover = (kind => 'top_mover', headline => 'North rose', detail => 'd3');
my %season = (kind => 'seasonality', headline => 'Repeats', detail => 'd4');
subtest 'Summary::_fingerprint -- every input that changes the text changes the key' => sub {
my $base = $fp->([ \%period ], 0, 'L', 1);
like $base, qr/\A[0-9a-f]{32}\z/, 'an md5 hex digest';
is $fp->([ \%period ], 0, 'L', 1), $base, 'the same input gives the same key';
isnt $fp->([ \%period ], 1, 'L', 1), $base, 'a polished summary is not a template one';
isnt $fp->([ \%period ], 0, 'M', 1), $base, 'nor another dataset';
isnt $fp->([ \%period ], 0, 'L', 2), $base, 'nor another row count';
isnt $fp->([ \%mover ], 0, 'L', 1), $base, 'nor another insight';
isnt $fp->([ { %period, headline => 'Up 6' } ], 0, 'L', 1), $base, 'nor another headline';
# Why: the summary prints the detail, and two period deltas can share a
# headline while their figures differ. A key without it serves one
# dataset's numbers to the other for an hour.
isnt $fp->([ { %period, detail => 'other figures' } ], 0, 'L', 1), $base,
'nor another detail, since the template prints it';
};
subtest 'Summary::_fingerprint -- text outside Latin-1 does not kill the request' => sub {
my $key;
lives_ok { $key = $fp->([ { %period, headline => "Up \x{20AC}5" } ], 0, "L\x{263A}", 1) }
'md5_hex is given bytes, so a wide character cannot make it croak';
like $key, qr/\A[0-9a-f]{32}\z/, 'and the key is still a digest';
lives_ok { $fp->([], 0, 'L', 0) } 'no insights at all is still a key';
};
t/function.t view on Meta::CPAN
# parameters that are parsed or reach a script; EXTENDED_TESTING tries them all.
Readonly my @RISKIEST_PARAMS => qw(bins topn minlen page per_page scheme range cs span tcol f c format);
# Each of these is a case nobody considered, whatever the page went on to do.
Readonly my $PERL_INTERNAL_WARNING => qr/uninitialized|isn't numeric|substr outside|Deep recursion|Odd number|Wide character|filename containing newline|masks earlier|Invalid \\0/;
no strict 'refs';
my %F = map { $_ => \&{"${DASH}::$_"} } qw(
_pagination _breadcrumb_trail _crumb_local _crumb_parent _crumb_label _crumb_spec_name
_crumb_view_suffix _crumb_chart_subject _template_languages _has_templates _data_dir_for
_tidy_error _schema_type_name _is_iso_date _to_iso_date _date_key _iso_day _iso_second
_midday _time_range_bounds _time_range_specs _time_range_preset _time_range_presets
_apply_time_range _trim _dedup_requested _filter_specs_to_criteria _measure _numeric_cell
_column_is_numeric _card_plan _cross_row_ui_state _cross_row_values _cross_row_cmp
_extend_row _canonical_path _inside_dir _chart_orientation _vis_cf_col _decode_cell
_percent_encode _word_tokens _wordcloud_option _wordcloud_link _map_popup _map_size_range
_map_radius _map_limit _parse_color _parse_color_rules _apply_color_rule _marker_icon
_color_hex _iso8601_utc _scope_card_scripts _wrap_card_script
);
use strict 'refs';
# A controller holding one request, for helpers that read their parameters.
sub dash_controller {
my ($app, $url) = @_;
my $tx = Mojo::Transaction::HTTP->new;
$tx->req->method('GET');
$tx->req->url->parse($url // '/');
$tx->req->url->base->parse('http://localhost:3000');
# A controller's hold on its transaction is weak, so something else must keep it.
our @LIVE_TX;
push @LIVE_TX, $tx;
return Database::BI::Controller::Dashboard->new(app => $app, tx => $tx);
}
# An application with its own stores, for a subtest that writes to them or
# changes what the configuration says.
sub isolated_app {
my $tm = Test::Mojo->new('Database::BI');
$tm->app->config->{model_dir} = tempdir(CLEANUP => 1);
$tm->app->config->{uploads_dir} = tempdir(CLEANUP => 1);
return $tm;
}
require Mojo::Transaction::HTTP;
require Mojo::Parameters;
require Mojo::URL;
require Mojo::Util;
my $app = $t->app;
subtest 'Dashboard::_pagination -- sane whatever is asked for' => sub {
is_deeply [ $F{_pagination}->(dash_controller($app, '/')) ], [ 1, $PER_PAGE, 0 ], 'the defaults';
is_deeply [ $F{_pagination}->(dash_controller($app, '/?page=3&per_page=10')) ], [ 3, 10, 20 ], 'as asked';
is_deeply [ $F{_pagination}->(dash_controller($app, '/?page=-5&per_page=-5')) ], [ 1, 1, 0 ], 'a negative is clamped up';
my ($p, $n) = $F{_pagination}->(dash_controller($app, '/?per_page=99999999'));
ok $n < 99999999, 'a huge page size is clamped down';
};
# Why: int('abc') warns and is 0, and a per_page of 0 is clamped to one row, so
# a stray parameter showed a single-row table. 1e400 is Inf, and an infinite
# OFFSET is not something a database can be asked for.
subtest 'Dashboard::_pagination -- input that is not a number' => sub {
for my $junk ('abc', '1x', '1e400', '9' x 400, 'Inf', 'NaN', '', '0x10', "1\n") {
(my $shown = substr($junk, 0, 8)) =~ s/\n/NL/;
my @got;
warnings_are {
@got = $F{_pagination}->(dash_controller($app, '/?page=' . Mojo::Util::url_escape($junk) . '&per_page=' . Mojo::Util::url_escape($junk)));
} [], "'$shown' raises no warning";
is_deeply \@got, [ 1, $PER_PAGE, 0 ], "and means the defaults, not one row";
}
};
subtest 'Dashboard::_crumb_spec_name' => sub {
is $F{_crumb_spec_name}->($SALES), 'sales', 'a table';
is $F{_crumb_spec_name}->('table:store/orders'), 'store: orders', 'an internal table';
is $F{_crumb_spec_name}->('path:/a/b/c.csv'), 'c.csv', 'a path shows only its file name';
is $F{_crumb_spec_name}->('url:http://example.com/x.html'), 'example.com', 'a web page its host';
is $F{_crumb_spec_name}->('URL:http://example.com/'), 'example.com', 'in any case';
is $F{_crumb_spec_name}->('redis://secret-host:6379/0'), 'Redis', 'a Redis URL is not shown';
is $F{_crumb_spec_name}->(undef), '', 'nothing';
is $F{_crumb_spec_name}->('junk'), 'junk', 'anything else as it is';
};
subtest 'Dashboard::_crumb_view_suffix' => sub {
my $q = sub { Mojo::Parameters->new($_[0]) };
is $F{_crumb_view_suffix}->($q->('')), '', 'no filters';
is $F{_crumb_view_suffix}->($q->('f=region:empty')), ' (region is empty)', 'a unary operator has no value'
if $F{_crumb_view_suffix}->($q->('f=region:empty')) =~ /is empty/;
like $F{_crumb_view_suffix}->($q->('f=region:eq:East')), qr/\A \(region .+ East\)\z/, 'a filter';
like $F{_crumb_view_suffix}->($q->('f=a:eq:1&f=b:eq:2&f=c:eq:3&f=d:eq:4')), qr/\+2 more\)\z/, 'more than two are counted';
like $F{_crumb_view_suffix}->($q->('range=last_30_days')), qr/\A \(last 30 days\)\z/i, 'a range';
is $F{_crumb_view_suffix}->($q->('range=nonsense')), '', 'an unknown range';
is $F{_crumb_view_suffix}->($q->('f=:eq:x&f=col')), '', 'malformed filters are left out';
is $F{_crumb_view_suffix}->($q->('f=' . Mojo::Util::url_escape('<b>:eq:x'))), '', 'markup in a column is not repeated';
is $F{_crumb_view_suffix}->($q->('f=' . Mojo::Util::url_escape('a:eq:<b>'))), '', 'nor in a value';
is $F{_crumb_view_suffix}->($q->('f=' . Mojo::Util::url_escape(('x' x 65) . ':eq:y'))), '', 'nor a value too long to be a label';
is $F{_crumb_view_suffix}->($q->('f=' . Mojo::Util::url_escape('place:in:["<b>","Rome"]'))), ' (place is one of 2 values)',
'a list is counted, never repeated';
is $F{_crumb_view_suffix}->($q->('f=' . Mojo::Util::url_escape('place:in:nonsense'))), ' (place is one of 0 values)',
'and a list that is not one counts nothing';
};
subtest 'Dashboard::_crumb_chart_subject' => sub {
my $s = sub { $F{_crumb_chart_subject}->($_[0], Mojo::Parameters->new($_[1])) };
is $s->('graph', 'x=when&y=amount'), 'amount by when', 'a line';
is $s->('scatter', 'x=a&y=b'), 'b by a', 'a scatter';
is $s->('heatmap', 'x=a&y=b'), 'a by b', 'a heatmap';
is $s->('stacked', 'cat=a&seg=b'), 'a by b', 'a stacked bar';
is $s->('pivot', 'rows=a,b'), 'a, b', 'a pivot';
is $s->('map', 'loc=town'), 'town', 'a map by place';
is $s->('map', 'lat=a&lon=b'), 'a, b', 'a map by position';
is $s->('map', ''), '', 'a map of nothing';
is $s->('bar', 'cat=region&val=amount'), 'amount by region', 'a bar';
is $s->('bar', 'cat=region'), 'Count by region', 'a bar with no measure counts';
is $s->('pie', 'cat=region&val=__count__'), 'Count by region', 'the count marker has a name';
is $s->('histogram', 'col=amount'), 'amount', 'a histogram';
is $s->('stats', ''), '', 'a page about the whole table has none';
is $s->('bar', 'cat=' . Mojo::Util::url_escape('<script>') . '&val=a'), '', 'markup is dropped, and a measure alone says nothing';
};
subtest 'Dashboard::_crumb_local -- a parent link has to be on this site' => sub {
my $c = dash_controller($app, '/bar');
is $F{_crumb_local}->($c, '/view/sales?x=1')->to_string, '/view/sales?x=1', 'a local link';
t/function.t view on Meta::CPAN
is $e->([ { %good, x => undef } ]), 'layout entry 1 is missing x', 'a missing field';
is $e->([ { %good, w => 'a' } ]), 'layout entry 1: w must be a whole number', 'text';
is $e->([ { %good, h => -1 } ]), 'layout entry 1: h must be a whole number', 'a negative';
is $e->([ { %good, h => 1.5 } ]), 'layout entry 1: h must be a whole number', 'a fraction';
is $e->([ { %good, x => [] } ]), 'layout entry 1: x must be a whole number', 'a list';
like $e->([ { %good, x => 0 } ]), qr/\Alayout entry 1: x must be between 1 and \d+\z/, 'x of 0';
like $e->([ { %good, x => 999 } ]), qr/\Alayout entry 1: x must be between/, 'x off the grid';
is $e->([ { %good, y => 0 } ]), 'layout entry 1: y must be at least 1', 'y of 0';
like $e->([ { %good, w => 0 } ]), qr/\Alayout entry 1: w must be between/, 'w of 0';
like $e->([ { %good, h => 0 } ]), qr/\Alayout entry 1: h must be between/, 'h of 0';
like $e->([ { %good, h => 99_999 } ]), qr/\Alayout entry 1: h must be between/, 'h too tall';
like $e->([ { %good, x => 12, w => 3 } ]), qr/\Alayout entry 1: x \+ w - 1 must not exceed/, 'off the right edge';
is $e->([ \%good, { %good, visual => 1, x => 2 } ]), 'layout entry 2 overlaps an earlier entry', 'an overlap';
is $e->([ \%good, \%good ]), 'layout entry 2 overlaps an earlier entry', 'the same cell twice';
};
subtest 'Dashboard::_validate_analysis -- every refusal is exact' => sub {
my $fn = \&Database::BI::Controller::Dashboard::_validate_analysis;
my $c = dash_controller($app, '/');
my %good = (name => 'n', datasets => [ { spec => $SALES } ]);
my $e = sub { $fn->($c, { %good, @_ }) };
is $e->(), undef, 'a minimal document';
is $e->(name => undef), 'Missing required field: name', 'no name';
is $e->(name => ''), 'Missing required field: name', 'an empty name';
is $e->(datasets => undef), 'Missing required field: datasets', 'no datasets';
is $e->(datasets => []), 'Missing required field: datasets', 'an empty list';
is $e->(datasets => 'x'), 'Missing required field: datasets', 'not a list';
is $e->(datasets => [ {} ]), 'Each dataset entry must have a spec field', 'no spec';
like $e->(datasets => [ { spec => 'ftp://x' } ]), qr/"ftp:\/\/x" is not a valid spec/, 'an unknown scheme';
like $e->(version => 2), qr/\AUnsupported analysis version 2/, 'a newer version';
like $e->(version => 'x'), qr/\AUnsupported analysis version x/, 'a version that is not one';
is $e->($_ => 'x'), "$_ must be an array", "$_ of the wrong kind" for qw(visuals joins measures combines bookmarks layout hierarchies);
is $e->(fields => []), 'fields must be a hash', 'fields';
is $e->(params => []), 'params must be a hash', 'params';
is $e->(layout => [ 'x' ]), 'layout entry 1 must be a hash', 'the layout is checked too';
};
# Why: this body is whatever a client POSTs. An element that is not a hash used
# to be a strict-refs crash, which is a 500 and a stack trace in the log for a
# request that deserves a 400.
subtest 'Dashboard::_validate_analysis -- hostile shapes are refused, not crashed on' => sub {
my $fn = \&Database::BI::Controller::Dashboard::_validate_analysis;
my $c = dash_controller($app, '/');
for my $ds ('x', 5, [ 1 ], undef) {
my $got;
lives_ok { $got = $fn->($c, { name => 'n', datasets => [ $ds ] }) } 'a dataset that is not a hash';
is $got, 'Each dataset entry must have a spec field', 'is refused';
}
is $fn->($c, { name => {}, datasets => [ { spec => $SALES } ] }), 'Missing required field: name', 'a name that is an object';
is $fn->($c, { name => [ 1 ], datasets => [ { spec => $SALES } ] }), 'Missing required field: name', 'or a list';
is $fn->($c, { name => 'n', datasets => [ { spec => [ 1 ] } ] }), 'Each dataset entry must have a spec field', 'a spec that is a list';
like $fn->($c, { name => 'n', version => [ 1 ], datasets => [ { spec => $SALES } ] }), qr/Unsupported analysis version/, 'a version that is a list';
};
subtest 'Dashboard::_whole_number' => sub {
my $fn = \&Database::BI::Controller::Dashboard::_whole_number;
is $fn->('12'), 12, 'digits';
is $fn->('-3'), -3, 'a negative';
is $fn->('0'), 0, 'zero';
is $fn->($_), undef, 'not a whole number' for undef, '', 'abc', '1x', '1.5', '1e3', "5\n", ' 5', '+5', '--5', 'Inf', 'NaN', '0x10', '9' x 16;
keeps_globals_ok('_whole_number', sub { $fn->('5') });
};
# Why: everything reads a stored document blindly, so this is what stands between
# a hand-edit and a 500. An index must survive it: a visual's place in the list is
# what the layout and /a/:id/visual/:n refer to.
subtest 'Dashboard::_tidy_analysis and _tidy_visual' => sub {
my $tidy = \&Database::BI::Controller::Dashboard::_tidy_analysis;
my %good = (
name => 'n',
updated => 5,
datasets => [ { spec => $SALES, filters => ['a:eq:1'] } ],
visuals => [ { kind => 'bar', title => 't', encode => { cat => 'a' }, options => { o => 1 }, filters => ['f'] } ],
joins => [ { right => 'r' } ],
layout => [ { visual => 0 } ],
fields => { f => 'x' },
params => { p => { type => 'number' } },
);
is_deeply $tidy->({ %good }), \%good, 'a good document is untouched';
is_deeply $tidy->({}), {}, 'an empty one gains nothing';
my $got = $tidy->({ map { $_ => 'x' } qw(datasets visuals joins measures combines bookmarks layout hierarchies fields params) });
is_deeply $got, {}, 'sections of the wrong shape are as if absent';
is_deeply $tidy->({ name => [ 1 ], updated => {} }), {}, 'as are a name and a time that are not values';
$got = $tidy->({ datasets => [ 'x', {}, { spec => [ 1 ] }, { spec => $SALES, filters => 'x' } ] });
is_deeply $got->{datasets}, [ { spec => $SALES } ], 'only a usable dataset is kept';
$got = $tidy->({ visuals => [ 'x', [ 1 ], { kind => 'bar' } ] });
is_deeply $got->{visuals}, [ {}, {}, { kind => 'bar' } ], 'a bad visual keeps its place, so the next keeps its index';
$got = $tidy->({ visuals => [ { kind => [ 1 ], title => {}, encode => 'x', options => [ 1 ], filters => 'x' } ] });
is_deeply $got->{visuals}, [ {} ], 'and its parts are checked';
is_deeply $tidy->({ joins => [ 'x', { right => 'r' } ], layout => [ 1 ] }), { joins => [ { right => 'r' } ], layout => [] }, 'joins and layout entries';
is_deeply $tidy->({ params => { a => 'oops', b => { type => 'number' } } })->{params}, { a => {}, b => { type => 'number' } }, 'a parameter is kept, with no definition';
memory_cycle_ok($got, 'no cycle');
};
# Why: the validators used to see only a whole document, so a PATCH could store
# what a PUT would refuse.
subtest 'Dashboard::_validate_analysis_parts -- only the keys that are present' => sub {
my $fn = \&Database::BI::Controller::Dashboard::_validate_analysis_parts;
my $c = dash_controller($app, '/');
is $fn->($c, {}), undef, 'nothing to judge';
is $fn->($c, { bookmarks => [] }), undef, 'a section alone';
is $fn->($c, { name => '' }), 'Missing required field: name', 'an empty name';
is $fn->($c, { datasets => [] }), 'Missing required field: datasets', 'no datasets';
is $fn->($c, { visuals => 'x' }), 'visuals must be an array', 'a section of the wrong shape';
is $fn->($c, { visuals => [ 'x' ] }), 'Each entry in visuals must be an object', 'a visual that is not one';
is $fn->($c, { joins => [ 1 ] }), 'Each entry in joins must be an object', 'a join that is not one';
is $fn->($c, { params => 'x' }), 'params must be a hash', 'params';
};
# Why: HTML::D3 writes a categorical name straight into its script, so this check
# is the only thing between scheme= and script on the page; and it dies on an
# unknown sequential name, which was a 500 for any bad link to a heatmap.
subtest 'Dashboard::_categorical_scheme and _sequential_scheme' => sub {
my $cat = \&Database::BI::Controller::Dashboard::_categorical_scheme;
my $seq = \&Database::BI::Controller::Dashboard::_sequential_scheme;
is $cat->('tableau10'), 'tableau10', 'a known palette';
is $seq->('Blues'), 'Blues', 'a known scale';
for my $evil (undef, '', 'nope', "'];alert(1);//", $XSS_PROBE, [ 1 ], 'constructor') {
t/function.t view on Meta::CPAN
is $fn->($c, {}), undef, 'no datasets';
is $fn->($c, { datasets => [ {} ] }), undef, 'a dataset with no spec';
is $fn->($c, { datasets => [ { spec => $SALES } ] }), '/join?l=table%3Asales', 'just the source';
my $url = $fn->($c, {
datasets => [ { spec => $SALES, alias => 'l', filters => ['a:eq:1'] }, { spec => 'table:b', alias => 'r' } ],
joins => [ { right => 'r', left_key => 'x', right_key => 'y' }, { right => 'nosuch' } ],
});
like $url, qr/&j=table%3Ab%7Cx%7Cy/, 'the join, encoded';
like $url, qr/&f=a%3Aeq%3A1\z/, 'the filter, encoded';
unlike $url, qr/nosuch/, 'and a join to nothing is left out';
like $fn->($c, { datasets => [ { spec => 'table:a&admin=1' } ] }), qr/\A\/join\?l=table%3Aa%26admin%3D1\z/, 'a hostile spec stays one value';
# A stored document can be anything; _validate_analysis does not look this deep.
for my $doc (
{ datasets => [ { spec => $SALES, filters => 'x' } ] },
{ datasets => [ { spec => $SALES } ], joins => [ 'x' ] },
) {
lives_ok { $fn->($c, $doc) } 'a document of the wrong shape does not crash';
}
};
subtest 'Dashboard::_chart_orientation and _vis_cf_col' => sub {
is $F{_chart_orientation}->({ orientation => $_ }), 'horizontal', "$_ is horizontal" for qw(h H horizontal);
is $F{_chart_orientation}->({ orient => 'h' }), 'horizontal', 'the older spelling';
is $F{_chart_orientation}->({ orientation => $_ }), 'vertical', "$_ is vertical" for qw(v vertical nonsense);
is $F{_chart_orientation}->({}), 'vertical', 'the default';
is $F{_vis_cf_col}->({ encode => { x => 'b', cat => 'a' } }), 'a', 'cat comes first';
is $F{_vis_cf_col}->({ encode => { x => 'b' } }), 'b', 'then x';
is $F{_vis_cf_col}->({ encode => { val => 'v' } }), undef, 'a measure is not a dimension';
is $F{_vis_cf_col}->({}), undef, 'no encoding';
is $F{_vis_cf_col}->({ encode => { cat => '', x => 'b' } }), 'b', 'an empty one is passed over';
};
subtest 'Dashboard::_bound_canvas_params' => sub {
my $fn = \&Database::BI::Controller::Dashboard::_bound_canvas_params;
my $c = dash_controller($app, '/');
my $none = sub { undef };
my ($b, $e) = $fn->($c, {}, $none);
is_deeply [ $b, $e ], [ {}, [] ], 'no parameters';
($b, $e) = $fn->($c, { params => { a => { type => 'number', default => 5 }, s => {} } }, $none);
is_deeply $b, { a => 5, s => '' }, 'the defaults';
($b, $e) = $fn->($c, { params => { a => { type => 'number' } } }, sub { '7' });
is $b->{a}, 7, 'a URL value is coerced';
($b, $e) = $fn->($c, { params => { s => { default => 'd' } } }, sub { '<x>' });
is $b->{s}, '<x>', 'a string is taken as it is';
($b, $e) = $fn->($c, { params => { a => { type => 'number' } } }, sub { 'x' });
is_deeply $e, ["Parameter 'a' must be a number"], 'text for a number';
ok !exists $b->{a}, 'is not bound';
($b, $e) = $fn->($c, { params => { a => { type => 'number', min => 1, max => 5 } } }, sub { 9 });
is_deeply $e, ["Parameter 'a' is out of range (min 1, max 5)"], 'over the top';
($b, $e) = $fn->($c, { params => { a => { type => 'number', min => 1 } } }, sub { 0 });
is_deeply $e, ["Parameter 'a' is out of range (min 1, max +inf)"], 'under the bottom, with no top';
($b, $e) = $fn->($c, { params => { a => { type => 'number', max => 1 } } }, sub { 2 });
is_deeply $e, ["Parameter 'a' is out of range (min -inf, max 1)"], 'over the top, with no bottom';
};
# Why: every comparison with NaN is false, so "nan" walked straight past min and
# max; looks_like_number says yes to all of these.
subtest 'Dashboard::_bound_canvas_params -- cannot be talked round' => sub {
my $fn = \&Database::BI::Controller::Dashboard::_bound_canvas_params;
my $c = dash_controller($app, '/');
for my $evil (qw(nan NaN inf -inf Infinity)) {
my ($b, $e) = $fn->($c, { params => { a => { type => 'number', min => 1, max => 5 } } }, sub { $evil });
ok !exists $b->{a}, "$evil is not bound";
is scalar @$e, 1, 'and is reported';
}
for my $bad ('oops', 5, [ 1 ]) {
my ($b, $e);
lives_ok { ($b, $e) = $fn->($c, { params => { a => $bad } }, sub { undef }) } 'a stored definition that is not a hash';
is $b->{a}, '', 'is a plain string parameter';
}
};
subtest 'Dashboard::_decode_cell and _percent_encode' => sub {
is $F{_decode_cell}->(undef), undef, 'nothing';
is $F{_decode_cell}->("caf\xC3\xA9"), "caf\x{e9}", 'UTF-8 bytes become a character';
is $F{_decode_cell}->("\xFF\xFE"), "\xFF\xFE", 'invalid UTF-8 is left, not lost';
is $F{_decode_cell}->("\x{263A}"), "\x{263A}", 'a decoded string is unchanged';
is $F{_percent_encode}->("a b&c"), 'a%20b%26c', 'separators';
is $F{_percent_encode}->("caf\x{e9}\x{263A}"), 'caf%C3%A9%E2%98%BA', 'characters as UTF-8';
is $F{_percent_encode}->(undef), '', 'nothing';
};
subtest 'Dashboard::_word_tokens' => sub {
is_deeply [ $F{_word_tokens}->('Hello, big World!', 2) ], [qw(hello big world)], 'lower-cased and split';
is_deeply [ $F{_word_tokens}->('a big one', 3) ], [qw(big one)], 'the shortest kept';
is_deeply [ $F{_word_tokens}->("O'Brien's 'quoted'", 2) ], [ "o'brien's", 'quoted' ], 'an apostrophe stays inside';
is_deeply [ $F{_word_tokens}->("caf\xC3\xA9 ole", 2) ], [ "caf\x{e9}", 'ole' ], 'bytes are decoded first';
is_deeply [ $F{_word_tokens}->('!!! ???', 1) ], [], 'punctuation is no word';
is_deeply [ $F{_word_tokens}->($_, 1) ], [], 'nothing' for undef, '';
keeps_globals_ok('_word_tokens', sub { $F{_word_tokens}->('a b', 1) });
};
subtest 'Dashboard::_wordcloud_option' => sub {
is $F{_wordcloud_option}->('50', 10, 1, 100), 50, 'in range';
is $F{_wordcloud_option}->('0', 10, 1, 100), 1, 'below';
is $F{_wordcloud_option}->('9999', 10, 1, 100), 100, 'above';
is $F{_wordcloud_option}->($_, 10, 1, 100), 10, 'unreadable means the default' for undef, '', 'x', '-5', '1.5', "5\n", [];
is $F{_wordcloud_option}->('9' x 400, 10, 1, 100), 100, 'an absurd count is held';
};
subtest 'Dashboard::_wordcloud_link' => sub {
is $F{_wordcloud_link}->('/view/sales', 'c', 'w', '/cloud'),
'/view/sales?f=c%3Acontains%3Aw&back2=%2Fcloud&back2_label=Back%20to%20word%20cloud', 'a drill-down';
like $F{_wordcloud_link}->('/open?path=x', 'c', 'w', '/cloud'), qr/\A\/open\?path=x&f=/, 'added to a query';
like $F{_wordcloud_link}->('/v', 'c', q{"><s&x=1}, '/cloud'), qr/f=c%3Acontains%3A%22%3E%3Cs%26x%3D1&/, 'a hostile word stays inert';
};
subtest 'Dashboard::_map_popup -- a place name is not markup' => sub {
is $F{_map_popup}->('Town', [ {} ], []), '<strong>Town</strong>', 'one row';
is $F{_map_popup}->('Town', [ {}, {}, {} ], []), '<strong>Town</strong><br>3 rows', 'several';
is $F{_map_popup}->(undef, undef, undef), '<strong></strong>', 'nothing';
is $F{_map_popup}->('T', [ { a => 'b', c => undef, d => '' } ], [ qw(a c d) ]), '<strong>T</strong><br>a: b', 'empty cells are left out';
my $html = $F{_map_popup}->('<script>x</script>', [ { '<img>' => q{"'&} } ], [ '<img>' ]);
unlike $html, qr/<script|<img/, 'markup is escaped everywhere';
like $html, qr/<script>/, 'and shown as text';
};
# A marker stands for every row at its place, so its popup lists them all:
# what they share once, what differs in a table that is capped and scrolls,
# so a place with hundreds of rows cannot cover the map.
t/function.t view on Meta::CPAN
alarm 0;
$r;
};
is $answer, 0, 'a round count past the limit is refused at once' or diag $@;
(my $few = $hash) =~ s/\$$MIN_ROUNDS\$/\$10001\$/;
is Database::BI::Password::verify_password('s3cret', $few), 0, 'a count that was not the one hashed with fails the check';
(my $weak = $hash) =~ s/\$$MIN_ROUNDS\$/\$9999\$/;
is Database::BI::Password::verify_password('s3cret', $weak), 0, 'a count under the minimum is refused';
keeps_globals_ok('verify_password', sub { Database::BI::Password::verify_password('s3cret', $hash) });
};
subtest 'Password::is_password_hash -- exactly the stored form, nothing near it' => sub {
my $good = Database::BI::Password::hash_password('pw', rounds => $MIN_ROUNDS, salt => $SALT);
is Database::BI::Password::is_password_hash($good), 1, 'a real one';
my ($scheme, $rounds, $salt, $key) = split /\$/, $good;
my %variants = (
'undef' => undef,
'empty' => '',
'a reference' => {},
'scheme in capitals' => join('$', uc $scheme, $rounds, $salt, $key),
'another scheme' => join('$', 'pbkdf2-sha1', $rounds, $salt, $key),
'rounds under limit' => join('$', $scheme, $MIN_ROUNDS - 1, $salt, $key),
'rounds over limit' => join('$', $scheme, $MAX_ROUNDS + 1, $salt, $key),
'four-digit rounds' => join('$', $scheme, '9999', $salt, $key),
'ten-digit rounds' => join('$', $scheme, '1000000000', $salt, $key),
'rounds with a sign' => join('$', $scheme, "+$rounds", $salt, $key),
'short salt' => join('$', $scheme, $rounds, substr($salt, 1), $key),
'long key' => join('$', $scheme, $rounds, $salt, "${key}A"),
'padded key' => join('$', $scheme, $rounds, $salt, "$key="),
'a fifth field' => "$good\$x",
'trailing newline' => "$good\n",
'leading space' => " $good",
'non-ASCII in the key'=> join('$', $scheme, $rounds, $salt, substr($key, 1) . "\x{e9}"),
);
for my $name (sort keys %variants) {
is Database::BI::Password::is_password_hash($variants{$name}), 0, "$name is not a hash";
}
is Database::BI::Password::is_password_hash(join('$', $scheme, $MAX_ROUNDS, $salt, $key)), 1, 'the upper limit itself is allowed';
};
}
# ----------------------------------------------------------------------------
# Database::BI::Model::Boundary: ranks, names, keys and geometry
# ----------------------------------------------------------------------------
{
require Database::BI::Model::Boundary;
my $B = 'Database::BI::Model::Boundary';
my @OUTSIDE_CASES;
subtest 'Boundary->point_key -- one key per point, nothing for a value that is not a point' => sub {
is $B->point_key('51.5074', '-0.1278'), '51.507,-0.128', 'rounded to three decimals';
is $B->point_key(51, 0), '51.000,0.000', 'whole numbers get their decimals';
is $B->point_key(90, 180), '90.000,180.000', 'the limits are points';
is $B->point_key(-90, -180), '-90.000,-180.000', 'so are the negative ones';
is $B->point_key('-0.0001', '-0.0004'), '0.000,0.000', 'a point just under zero has no "-0.000" twin';
is $B->point_key('51.5074', '-0.1278'), $B->point_key('51.50741', '-0.12779'), 'points a metre apart share a key';
for my $case (
[ undef, 1 ], [ 1, undef ], [ '', 1 ], [ 'abc', 1 ], [ 1, 'abc' ],
[ 90.001, 0 ], [ -90.001, 0 ], [ 0, 180.001 ], [ 0, -180.001 ],
[ '1e2', 1 ], [ "5\n", 1 ], [ '+5', 1 ], [ '5.', 1 ], [ '.5', 1 ], [ '1,5', 1 ],
[ "1' OR '1'='1", 1 ], [ [ 1 ], 1 ], [ 'NaN', 1 ], [ 'Inf', 1 ],
) {
my @got = $B->point_key(@{$case});
is_deeply \@got, [], 'refused: ' . join(',', map { !defined $_ ? 'undef' : ref $_ ? 'ref' : ($_ =~ s/\n/\\n/gr) } @{$case});
}
};
subtest 'Boundary->check_ranks -- a config the code cannot honour stops at startup' => sub {
my $ok = $B->check_ranks({ GB => 10, fr => '12', De => 8 });
is_deeply $ok, { gb => 10, fr => 12, de => 8 }, 'lower-cased codes, numeric ranks';
memory_cycle_ok($ok, 'the checked hash has no cycle');
is_deeply $B->check_ranks({}), {}, 'nothing configured is fine';
my $must = qr/the rank for '%s' must be one of 8, 10, 12/;
throws_ok { $B->check_ranks(undef) } qr/\ABoundary ranks must be a hash of country codes to place ranks/, 'undef';
throws_ok { $B->check_ranks([ gb => 10 ]) } qr/\ABoundary ranks must be a hash/, 'a list';
throws_ok { $B->check_ranks('gb') } qr/\ABoundary ranks must be a hash/, 'a string';
for my $code ('', 'g', 'gbr', 'g1', 'g b', "gb\n", 'g.', '../') {
throws_ok { $B->check_ranks({ $code => 10 }) } qr/\A'\Q$code\E' is not a two-letter country code/,
'code ' . ($code =~ s/\n/\\n/gr) . ' refused';
}
for my $rank (undef, '', 0, 7, 11, 13, -8, '8.0', '1e1', "10\n", '10 ', 'ten', [ 10 ], {}) {
throws_ok { $B->check_ranks({ gb => $rank }) } qr/\Athe rank for 'gb' must be one of 8, 10, 12/,
'rank ' . (!defined $rank ? 'undef' : ref $rank ? ref $rank : "'" . ($rank =~ s/\n/\\n/gr) . "'") . ' refused';
}
throws_ok { $B->check_ranks({ gb => 10, GB => 12 }) } qr/\A'(?:gb|GB)' is given twice/, 'the same country in two spellings';
};
subtest 'Boundary->name_for / level_name -- what a place is called' => sub {
is $B->name_for('in'), 'district', 'India has districts';
is $B->name_for('IN'), 'district', 'whatever the case';
is $B->name_for('fr'), 'department', 'France has departments';
is $B->name_for('us'), 'county', 'an unlisted country gets the level default';
for my $odd (undef, '', [ 'in' ], {}) {
is $B->name_for($odd), 'county', 'no usable country: ' . (ref $odd || (defined $odd ? 'empty' : 'undef'));
}
my $state = $B->new(level => 'state');
is $state->name_for('ca'), 'province', 'an instance names by its own level';
is $state->name_for('xx'), 'state', 'and falls back to it';
is $B->level_name('country'), 'country', 'a level names itself';
is $B->level_name('neighbourhood'), 'neighbourhood', 'every level does';
for my $bad (undef, '', 'nope', 'County', ' county', "county\n", [ 'county' ], {}) {
my @got = $B->level_name($bad);
is_deeply \@got, [], 'no name for ' . (ref $bad || (defined $bad ? "'" . ($bad =~ s/\n/\\n/gr) . "'" : 'undef'));
}
};
subtest 'Boundary->rank_for -- the rank a country is read at' => sub {
my $county = $B->new;
is $county->rank_for('us'), 12, 'the default county rank';
is $county->rank_for('in'), 10, 'a country the table knows';
is $county->rank_for('IN'), 10, 'whatever the case';
is $county->rank_for(undef), 12, 'no country: the default';
is $county->rank_for([ 'in' ]), 12, 'a reference is not a country';
is $B->new(ranks => { fr => 10 })->rank_for('fr'), 10, 'a configured rank beats the default';
is $B->new(ranks => { in => 12 })->rank_for('in'), 12, 'and the built-in one';
throws_ok { $B->new(ranks => { fr => 11 }) } qr/the rank for 'fr' must be one of/, 'a bad rank stops the object being built';
throws_ok { $B->new(level => 'galaxy') } qr/\AUnknown boundary level 'galaxy'/, 'an unknown level stops it too';
like $B->new(level => 'city')->rank_for('gb'), qr/\A\d+\z/, 'a level with plans answers with a rank';
memory_cycle_ok($county, 'a Boundary object has no cycle');
t/function.t view on Meta::CPAN
subtest 'Database::BI::_require_export_dirs_with_password -- a shared server needs folders of its own' => sub {
my $needs = qr/\Aexport_dirs: with password_hash set, other people can save exports, so keep them to folders of their own/;
for my $no_password (undef, '', {}, [ 'x' ]) {
lives_ok { $F{_require_export_dirs_with_password}->($no_password, undef) } 'no password to protect: ' . $show->($no_password);
}
lives_ok { $F{_require_export_dirs_with_password}->('hash', [ '/srv/x' ]) } 'a password and a folder';
lives_ok { $F{_require_export_dirs_with_password}->('hash', [ '/a', '/b' ]) } 'and several';
for my $bad (undef, [], '', '/srv/x', {}, 0) {
throws_ok { $F{_require_export_dirs_with_password}->('hash', $bad) } $needs, 'a password and export_dirs ' . $show->($bad);
}
};
}
# ----------------------------------------------------------------------------
# Dashboard::_gen_analysis_id and _filter_date_key
# ----------------------------------------------------------------------------
subtest 'Dashboard::_gen_analysis_id -- ids come from the system generator, whole' => sub {
my $c = dash_controller($t->app, '/');
my %seen;
for (1 .. 300) {
my $id = $c->_gen_analysis_id;
like $id, qr/\A[A-Za-z0-9]{10}\z/, 'ten URL-safe characters' or last;
$seen{$id}++;
}
is scalar(keys %seen), 300, 'and no repeats in 300 draws';
require Crypt::URandom;
# Known bytes in, known id out: proves the bytes (not perl's rand) choose
# the characters, and that the mapping wraps instead of running off the end.
Test::Mockingbird::mock('Crypt::URandom::urandom', sub { return pack 'C*', 0 .. 9 });
is $c->_gen_analysis_id, 'abcdefghij', 'byte n picks character n';
Test::Mockingbird::restore_all();
Test::Mockingbird::mock('Crypt::URandom::urandom', sub { return pack 'C*', (62, 63, 255, 254) x 2, 0, 1 });
is $c->_gen_analysis_id, 'abhg' . 'abhg' . 'ab', 'a byte past 61 wraps to a valid character';
Test::Mockingbird::restore_all();
# A generator that gives too little must stop the save, not name a canvas '' .
for my $short ('', 'abc', 'abcdefghi') {
Test::Mockingbird::mock('Crypt::URandom::urandom', sub { return $short });
throws_ok { $c->_gen_analysis_id } qr/\AThe system random generator gave too few bytes for an id/,
'a generator that gave ' . length($short) . ' bytes is not used';
Test::Mockingbird::restore_all();
}
Test::Mockingbird::mock('Crypt::URandom::urandom', sub { return undef });
throws_ok { $c->_gen_analysis_id } qr/too few bytes/, 'undef is too few';
Test::Mockingbird::restore_all();
keeps_globals_ok('_gen_analysis_id', sub { $c->_gen_analysis_id });
};
subtest 'Dashboard::_filter_date_key -- the key a date filter compares by' => sub {
my $key = \&Database::BI::Controller::Dashboard::_filter_date_key;
Readonly my $DAY => 10;
Readonly my $SECOND => 19;
is $key->('2026-01-05', $DAY), '2026-01-05', 'a day';
is $key->('2026-01-05T09:15:07', $SECOND), '2026-01-05T09:15:07', 'a timestamp at second precision';
is $key->('2026-01-05 09:15', $SECOND), '2026-01-05T09:15:00', 'missing seconds are zero';
is $key->('2026-01-05T09:15:07.9+05:30', $DAY), '2026-01-05', 'a zone and fraction are set aside; the day is as written';
is $key->('2026-01-05', $SECOND), '2026-01-05T00:00:00', 'a day at second precision is its start';
is $key->('1/5/2026', $DAY), '2026-01-05', 'M/D/YYYY is rewritten';
is $key->('01/05/2026', $DAY), '2026-01-05', 'with leading zeros too';
for my $text ('', 'x', '1/5/26', '1/5/20266', '1/5/2026 ', '2026-01-05 junk', "2026-01-05\n", '5/1', '--', 'NaN') {
is $key->($text, $DAY), $text, 'not a date, so its own key: ' . ($text =~ s/\n/\\n/gr);
}
my @warned;
local $SIG{__WARN__} = sub { push @warned, @_ };
is $key->(undef, $DAY), undef, 'undef stays undef';
my $ref = [ 1 ];
is $key->($ref, $DAY), $ref, 'a reference is returned untouched, never read as text';
is scalar(@warned), 0, 'and neither warns' or diag @warned;
keeps_globals_ok('_filter_date_key', sub { $key->('2026-01-05', $DAY) });
};
# ----------------------------------------------------------------------------
# Util::parse_number's plain-decimal fast path must keep the full path's answers
# ----------------------------------------------------------------------------
subtest 'Util::parse_number -- plain decimals take a short cut that must agree with the long way' => sub {
my $number = \&Database::BI::Util::parse_number;
Readonly my $EDGE => 300; # the longest integer part the short cut takes
is $number->('0'), 0, 'zero';
is $number->('-12.50'), -12.5, 'negative with decimals';
is $number->('007'), 7, 'leading zeros';
ok defined $number->('1' x $EDGE), 'at the edge';
ok defined $number->('1' x ($EDGE + 1)), 'one past the edge, by the long way';
is $number->('9' x 400), undef, 'past a double: not a number, whichever way';
for my $text ('1.', '.5', '1..2', '--1', '1e', '0x10', "\x{FF11}", 'NaN', 'Inf', '-', '.', '1/2') {
is $number->($text), undef, 'not a number: ' . ($text =~ s/[^\x20-\x7e]/?/gr);
}
is $number->("1\n"), 1, 'a trailing newline is stripped as it always was';
is $number->('1 000'), 1000, 'a space is a thousands separator';
is $number->("1\x{a0}000"), 1000, 'so is a non-breaking space';
is $number->('(5)'), -5, 'accounting negatives are still read';
is $number->('$1,000'), 1000, 'currency and separators are still read';
};
done_testing();
( run in 1.059 second using v1.01-cache-2.11-cpan-60884a8df76 )