Database-BI

 view release on metacpan or  search on metacpan

t/unit.t  view on Meta::CPAN

	'Util.urlencode.unreserved' => 'urlencode passes through RFC 3986 unreserved characters unchanged',
	'Util.urlencode.colon'      => 'urlencode(":") returns "%3A"',
	'Util.urlencode.space'      => 'urlencode(" ") returns "%20" (not "+")',
	'Util.urlencode.slash'      => 'urlencode("/") returns "%2F"',
	'Util.urlencode.uppercase'  => 'hex digits in percent-encoding are uppercase',

	# Database::BI::Ask -- infer_column_types() public API
	'Ask.infer_column_types.empty'   => 'infer_column_types([], []) returns []',
	'Ask.infer_column_types.numeric' => 'majority-numeric column inferred as type=number',
	'Ask.infer_column_types.date'    => 'majority-ISO-date column inferred as type=date',
	'Ask.infer_column_types.string'  => 'non-numeric, non-date column inferred as type=string',

	# Database::BI::Ask -- ask() public API (all documented error codes + success)
	'Ask.ask.no_question'    => 'ask(question=>"") returns {error=>"ask_no_question"}',
	'Ask.ask.no_api_key'     => 'ask() without api_key returns {error=>"ask_unavailable"}',
	'Ask.ask.provider_error' => 'ask() with failing LLM HTTP call returns {error=>"ask_provider_error"}',
	'Ask.ask.unparseable'    => 'ask() with non-JSON LLM reply returns {error=>"ask_unparseable"}',
	'Ask.ask.invalid_spec'   => 'ask() with unknown encode column returns {error=>"ask_invalid_spec:<col>"}',
	'Ask.ask.success'        => 'ask() with mocked LLM returns {spec,url,valid=>1}',

	# Database::BI::Insights -- compute() and method_note() public API
	'Insights.compute.empty'        => 'compute() with empty records returns []',
	'Insights.compute.outlier'      => 'compute() returns insight of kind=outlier when outlier present',
	'Insights.compute.period_delta' => 'compute() returns kind=period_delta with date+numeric data',
	'Insights.compute.seasonality'  => 'compute() returns kind=seasonality with 8+ distinct month-periods',
	'Insights.method_note.known'    => 'method_note(known key) returns a description string',
	'Insights.method_note.unknown'  => 'method_note(unknown key) returns the key itself',

	# Database::BI::Summary -- generate() public API (all documented source paths)
	'Summary.generate.template'      => 'generate() without use_ai returns source=template',
	'Summary.generate.no_insights'   => 'generate() with no insights includes "No significant patterns"',
	'Summary.generate.cached'        => 'generate() second call with same fingerprint returns cached=1',
	'Summary.generate.use_ai_no_key' => 'generate(use_ai=>1, no api_key) silently uses template path',
	'Summary.generate.llm_fallback'  => 'generate(use_ai=>1) LLM error -> source=template_fallback',
	'Summary.generate.llm_success'   => 'generate(use_ai=>1) mocked LLM -> source=llm',

	# HTTP: scatter / stacked / combo / treemap / histogram chart views
	'GET./scatter.200'                => 'GET /scatter?l=...&x=...&y=... -> 200 HTML',
	'GET./scatter.400.missing_param'  => 'GET /scatter missing x= or y= -> 400',
	'GET./scatter.404.no_source'      => 'GET /scatter with x=/y= but invalid l= -> 404',
	'GET./stacked.200'                => 'GET /stacked?l=...&cat=...&series=... -> 200 HTML',
	'GET./stacked.400.missing_param'  => 'GET /stacked missing cat= or series= -> 400',
	'GET./stacked.404.no_source'      => 'GET /stacked with cat=/series= but invalid l= -> 404',
	'GET./combo.200'                  => 'GET /combo?l=...&cat=...&bar_val=...&line_val=... -> 200 HTML',
	'GET./combo.400.missing_param'    => 'GET /combo missing cat= or bar_val= or line_val= -> 400',
	'GET./combo.404.no_source'        => 'GET /combo with required params but invalid l= -> 404',
	'GET./treemap.200'                => 'GET /treemap?l=...&group=... -> 200 HTML',
	'GET./treemap.400.missing_param'  => 'GET /treemap missing group= -> 400',
	'GET./treemap.404.no_source'      => 'GET /treemap with group= but invalid l= -> 404',
	'GET./histogram.200'              => 'GET /histogram?l=...&col=<numeric> -> 200 HTML',
	'GET./histogram.400.missing_param'=> 'GET /histogram missing col= -> 400',
	'GET./histogram.404.no_source'    => 'GET /histogram with col= but invalid l= -> 404',

	# HTTP: pivot / stats views
	'GET./pivot.200'           => 'GET /pivot?l=...&rows=...&m=col:sum:total -> 200 HTML',
	'GET./pivot.400.no_rows'   => 'GET /pivot without rows= -> 400',
	'GET./pivot.400.no_source' => 'GET /pivot no l= -> 400',
	'GET./stats.200'           => 'GET /stats?l=... -> 200 HTML',
	'GET./stats.400.no_source' => 'GET /stats no l= -> 400',

	# HTTP: Phase 5 endpoints
	'GET./insights.200'          => 'GET /insights?l=... -> 200 HTML insights page',
	'GET./insights.400.no_l'     => 'GET /insights without l= -> 400',
	'POST./api_summary.200'      => 'POST /api/summary?l=... -> 200 JSON {text,source,cached}',
	'POST./api_summary.400.no_l' => 'POST /api/summary without l= -> 400',
	'POST./api_ask.503.no_key'   => 'POST /api/ask without ai_api_key configured -> 503 JSON {error}',
	'POST./api_ask.400.no_l'     => 'POST /api/ask missing l= -> 400 JSON {error}',
	'POST./api_ask.400.no_q'     => 'POST /api/ask missing q= -> 400 JSON {error}',
	'POST./api_ask.200'          => 'POST /api/ask with mocked LLM -> 200 JSON {spec,url,valid}',
);

# ---------------------------------------------------------------------------
# The ledger also holds every message the modules can raise, read from their own
# dictionaries, so that a message added later fails this file until it is tested.
# A key that no code refers to cannot be raised, and is left out by the same
# reading, so it joins the ledger the moment something starts to use it.
# ---------------------------------------------------------------------------
Readonly my %MESSAGE_FILES => (
	Dashboard  => 'lib/Database/BI/Controller/Dashboard.pm',
	DataSource => 'lib/Database/BI/Model/DataSource.pm',
	Geocode    => 'lib/Database/BI/Model/Geocode.pm',
	Password   => 'lib/Database/BI/Password.pm',
	PasswordCommand => 'lib/Database/BI/Command/password.pm',
);
my %DICTIONARY;
for my $module (sort keys %MESSAGE_FILES) {
	# A Windows checkout has CRLF line ends, which would leave the POD in below.
	(my $source = Mojo::File->new($MESSAGE_FILES{$module})->slurp) =~ s/\r\n/\n/g;
	my ($block) = $source =~ /%MESSAGES => \((.*?)^\);/ms or BAIL_OUT("no %MESSAGES in $module");
	my %messages = eval "($block)";	## no critic (ProhibitStringyEval): the module's own constant data
	$source =~ s/%MESSAGES => \(.*?^\);//ms;
	$source =~ s/^=\w.*?^=cut\n//msg;
	$DICTIONARY{$module} = \%messages;
	for my $key (grep { $source =~ /\b$_\b/ } keys %messages) {
		$ledger{"msg.$module.$key"} = "$module raises $key";
	}
}

# Those the POD documents that are not messages.
$ledger{"api.$_"} = "documented behaviour: $_" for qw(
	Util.parse_number Util.iso_datetime Util.minute_stamp Util.iso8601_utc Calc.new Calc.error Calc.has_error Calc.evaluate Calc.span_interval Calc.date_normalise Calc.compile_pattern Calc.capture_of
	Extract.new Extract.path Extract.get Extract.put Extract.evict
	Tutorial.intro Tutorial.chapters Tutorial.faq Tutorial.glossary Tutorial.parts
	Tutorial.covered_routes Tutorial.exempt_routes Tutorial.chapter_for_action
	DataSource.sqlite_tables DataSource.dbi_source DataSource.aggregate DataSource.updated DataSource.schema DataSource.count DataSource.json_lists
	Geocode.shared_cache_from_models Geocode.models_with_shared_cache
	BI.startup Globals
	analyses.list analyses.create analyses.get analyses.update analyses.patch analyses.delete
	analyses.add_visual analyses.update_visual analyses.export analyses.import analyses.storage_503 analyses.unknown_keys
	share.share share.embed share.visual_download
	crud.calc crud.groups crud.dates crud.lookups crud.extract crud.geo
	accel.accelerate accel.unaccelerate accel.specs DataSource.column_order
	route.range route.tables route.wordcloud route.catalog route.tutorial route.index route.stats_percentile
);

# The public functions of the smaller modules, each tested from its POD alone.
$ledger{"api.$_"} = "documented behaviour: $_" for qw(
	Password.is_password_hash
	Boundary.check_ranks Boundary.rank_for Boundary.name_for Boundary.level_name Boundary.levels Boundary.point_key
	SafeUA.new SafeUA.send_request SafeUA.private_host_allowed SafeUA.blocked_address SafeUA.numeric_host
	I18N.languages I18N.choose I18N.lingua_choice I18N.language I18N.from_locale

t/unit.t  view on Meta::CPAN

	};

	subtest 'GET /histogram -- missing col= returns 400' => sub {
		$t->get_ok('/histogram?l=table:sales')
		  ->status_is(400, '400 when col= absent');
		delete $ledger{'GET./histogram.400.missing_param'};
	};

	subtest 'GET /histogram -- col= given but bad l= returns 404' => sub {
		$t->get_ok('/histogram?col=amount&l=path:/no/such/file.csv')
		  ->status_is(404, '404 when l= points to non-existent file');
		delete $ledger{'GET./histogram.404.no_source'};
	};

	subtest 'GET /histogram -- valid numeric col= returns 200 HTML histogram' => sub {
		$t->get_ok('/histogram?l=table:sales&col=amount')
		  ->status_is(200, '200 for valid histogram col=amount')
		  ->content_type_like(qr{text/html}, 'response is HTML');
		delete $ledger{'GET./histogram.200'};
	};
}

# ---------------------------------------------------------------------------
# HTTP: pivot and stats views
# ---------------------------------------------------------------------------
{
	subtest 'GET /pivot -- no l= returns 400' => sub {
		$t->get_ok('/pivot')
		  ->status_is(400, '400 when no l= given to pivot');
		delete $ledger{'GET./pivot.400.no_source'};
	};

	subtest 'GET /pivot -- no rows= returns 400' => sub {
		$t->get_ok('/pivot?l=table:sales&m=amount:sum:total')
		  ->status_is(400, '400 when rows= absent from pivot');
		delete $ledger{'GET./pivot.400.no_rows'};
	};

	subtest 'GET /pivot -- valid params return 200 HTML pivot table' => sub {
		$t->get_ok('/pivot?l=table:sales&rows=region&m=amount:sum:total')
		  ->status_is(200, '200 for valid pivot params')
		  ->content_type_like(qr{text/html}, 'response is HTML');
		delete $ledger{'GET./pivot.200'};
	};

	subtest 'GET /stats -- no l= returns 400' => sub {
		$t->get_ok('/stats')
		  ->status_is(400, '400 when no l= given to stats');
		delete $ledger{'GET./stats.400.no_source'};
	};

	subtest 'GET /stats -- valid l= returns 200 HTML stats page' => sub {
		$t->get_ok('/stats?l=table:sales')
		  ->status_is(200, '200 for valid stats l=')
		  ->content_type_like(qr{text/html}, 'response is HTML');
		delete $ledger{'GET./stats.200'};
	};
}

# ---------------------------------------------------------------------------
# HTTP: Phase 5 endpoints (/insights, /api/summary, /api/ask)
# ---------------------------------------------------------------------------
{
	subtest 'GET /insights -- no l= returns 400' => sub {
		$t->get_ok('/insights')
		  ->status_is(400, '400 when l= absent from /insights');
		delete $ledger{'GET./insights.400.no_l'};
	};

	subtest 'GET /insights -- valid l= returns 200 HTML insights page' => sub {
		$t->get_ok('/insights?l=table:sales')
		  ->status_is(200, '200 for /insights with valid l=')
		  ->content_type_like(qr{text/html}, 'response is HTML');
		delete $ledger{'GET./insights.200'};
	};

	subtest 'POST /api/summary -- no l= returns 400' => sub {
		$t->post_ok('/api/summary')
		  ->status_is(400, '400 when l= absent from /api/summary');
		delete $ledger{'POST./api_summary.400.no_l'};
	};

	subtest 'POST /api/summary -- valid l= returns 200 JSON {text,source,cached}' => sub {
		$t->post_ok('/api/summary?l=table:sales')
		  ->status_is(200, '200 for /api/summary with valid l=')
		  ->json_has('/text',   'response has text key')
		  ->json_has('/source', 'response has source key')
		  ->json_has('/cached', 'response has cached key');
		delete $ledger{'POST./api_summary.200'};
	};

	subtest 'POST /api/ask -- without ai_api_key returns 503' => sub {
		# The test app has no ai_api_key configured; expect 503.
		$t->post_ok('/api/ask', form => { l => 'table:sales', q => 'show a chart' })
		  ->status_is(503, '503 when ai_api_key not configured')
		  ->json_has('/error', 'error key present in 503 response');
		delete $ledger{'POST./api_ask.503.no_key'};
	};

	subtest 'POST /api/ask -- missing l= returns 400' => sub {
		# Temporarily inject a dummy api_key so the key guard passes.
		$t->app->config->{ai_api_key} = 'test-dummy-key';
		$t->post_ok('/api/ask', form => { q => 'show a chart' })
		  ->status_is(400, '400 when l= absent')
		  ->json_has('/error', 'error key present in 400 response');
		delete $t->app->config->{ai_api_key};
		delete $ledger{'POST./api_ask.400.no_l'};
	};

	subtest 'POST /api/ask -- missing q= returns 400' => sub {
		$t->app->config->{ai_api_key} = 'test-dummy-key';
		$t->post_ok('/api/ask', form => { l => 'table:sales' })
		  ->status_is(400, '400 when q= absent')
		  ->json_has('/error', 'error key present in 400 response');
		delete $t->app->config->{ai_api_key};
		delete $ledger{'POST./api_ask.400.no_q'};
	};

	subtest 'POST /api/ask -- valid request with mocked LLM returns 200 JSON {spec,url,valid}' => sub {
		require HTTP::Response;
		require JSON::PP;



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