Files
Cactiplugin_thold/tests/Unit/TholdCalculateExpressionTest.php
TheWitnessandCopilot 9b217e0e3a INFO: set compat to 1.2.29 (#838)
* INFO: set compat to 1.2.32

* docs: update Copilot instructions Cacti baseline to 1.2.32 (matches INFO compat)

* INFO: back off compat to 1.2.29

* Add manifest.json + upgrade-time file pruning

* Prune phpunit.xml on upgrade and ignore markdown-lint configs

phpunit.xml ships in the repo for CI but is a dev-only test artifact, so it
is removed from manifest.json 'expected', pruned from installs on upgrade
(like tests/), and excluded from the manifest drift check.

The retired markdown-lint configs (.mdlrc, .md_style.rb) are deleted, and
.md* is now ignored like .git*: protected from pruning and excluded from
drift if it reappears.

* Move thold_functions.php and thold_webapi.php into includes/; flatten css

The main threshold library becomes includes/functions.php and the web API
helper becomes includes/webapi.php; every caller (setup.php, includes/*, the
CLI/poller/notify entry points and the test suite) loads them from includes/.
Each per-theme stylesheet css/<theme>/main.css becomes css/<theme>.css so users
can drop their own css/<theme>.css into the css base, and the page_head hook
looks there. Old paths are tombstoned so existing installs drop the stale
copies on upgrade.

* Regenerate cacti.pot for the includes/ file relocations

Moving the plugin's library files into includes/ changed the source-reference
lines in the translation template; regenerate it so the 'Verify translation
template' CI check passes.

* Harden the hook-include test and make RPN integer ops explicit

The HookFunctionsIncludeTest invokes real hooks with placeholder input purely
to execute their relocated include_once lines; it now swallows engine
notices/warnings/deprecations during those calls (and restores the error
handler and config afterward) so it cannot trip the suite's failOnDeprecation
or leak state into other tests. The RPN % and ^ operators now cast their
operands to int explicitly, matching their long-standing integer-truncation
behaviour while silencing the implicit float-to-int conversion deprecation.

* Harden prune against tampered-manifest path traversal

The upgrade-time prune now rejects any tombstone containing '.'/'..' segments
(which could escape the plugin directory or resolve to its root) and treats
ancestors of whitelist entries as protected, so a tombstone on a parent
directory can no longer delete a whitelisted file beneath it.

* docs: update and align the Project Structure block

Point the structure tree at the relocated files (libraries now under
includes/, data files under docs/, stylesheets under css/) and align the
trailing '# ...' comments to a single column so they no longer drift right.

* docs/tests: standardize test header and correct manifest-contract notes

- Use the full license header (from the plugin's own setup.php) in
  tests/Unit/PruneFilesTest.php instead of the abbreviated copyright banner.
- Document that the manifest drift check and the upgrade-time prune also
  handle phpunit.xml and .md* files, matching the implemented behavior.

* refactor: rename prune helpers to the plugin-slug function prefix

The repository naming contract reserves the plugin_<name>_ prefix for plugin
lifecycle / hook-registration functions; all other functions use the plain
<name>_ prefix. Rename the internal upgrade helpers accordingly:

  plugin_<name>_prune_files() -> <name>_prune_files()
  plugin_<name>_rmtree()      -> <name>_rmtree()

The call site, unit tests, and the copilot-instructions.md references are
updated to match. No behavioral change.

* chore: set the Cacti compatibility floor to 1.2.29

Align the compat metadata (and the contributor-guide references) with the
team decision to standardize the minimum supported Cacti version at 1.2.29;
the previously proposed 1.2.32 floor was not adopted.

---------

Co-authored-by: Copilot <copilot@users.noreply.github.com>
2026-10-01 01:40:00 -05:00

184 lines
5.8 KiB
PHP

<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
/**
* thold_calculate_expression() evaluates a whole RPN expression and returns
* the single value the threshold is compared against.
*/
final class TholdCalculateExpressionTest extends TestCase {
/**
* @return void
*/
public static function setUpBeforeClass(): void {
self::loadPluginSource('includes/functions.php');
}
/**
* @param string $expression
*
* @return mixed
*/
private function evaluate($expression) {
$thold = [
'id' => 1,
'name' => 'CPU',
'local_data_id' => 4,
'local_graph_id' => 7,
'expression' => $expression,
];
$reindexed = [];
$time_reindexed = [];
return thold_calculate_expression($thold, 0, $reindexed, $time_reindexed);
}
/**
* @return array<string, array{0: string, 1: float|int}>
*/
public static function expressionProvider() {
return [
'addition' => ['2,3,+', 5],
'subtraction' => ['8,2,-', 6],
'multiplication' => ['4,3,*', 12],
'nested' => ['2,3,+,4,*', 20],
'single value' => ['7', 7],
];
}
/**
* @dataProvider expressionProvider
*
* @param string $expression
* @param float|int $expected
*
* @return void
*/
public function testExpressionsReduceToTheTopOfTheStack($expression, $expected): void {
$this->assertEqualsWithDelta($expected, $this->evaluate($expression), 1.0e-9);
}
/**
* An expression that leaves more than one value is an authoring error. It
* used to return the first operand pushed, which looks like a plausible
* reading and is compared against the bounds as though it were one.
*
* @return void
*/
public function testUnbalancedExpressionIsRejectedRatherThanReturningAnOperand(): void {
// '' (not numeric 0) is this function's unavailable-sample sentinel:
// polling.php's fail-closed guard only catches non-numeric values, so
// a manufactured 0 here would be persisted/alerted on as a real reading.
$this->assertSame('', $this->evaluate('1,2,3,+'));
$this->assertTrue($GLOBALS['rpn_error']);
}
/**
* @return void
*/
public function testUnsupportedTokenFailsTheExpression(): void {
$this->assertSame('', $this->evaluate('2,NOSUCHOP'));
$this->assertTrue($GLOBALS['rpn_error']);
}
/**
* Division/modulo by zero (with a non-zero numerator) is flagged by
* thold_expression_math_rpn() as an rpn_error. The whole-expression
* evaluator must fail closed with '' rather than a manufactured 0.
*
* @return array<string, array{0: string}>
*/
public static function zeroDivisorProvider() {
return [
'division by zero' => ['5,0,/'],
'modulo by zero' => ['5,0,%'],
];
}
/**
* @dataProvider zeroDivisorProvider
*
* @param string $expression
*
* @return void
*/
public function testZeroDivisorFailsClosedRatherThanReturningZero($expression): void {
$this->assertSame('', $this->evaluate($expression));
$this->assertTrue($GLOBALS['rpn_error']);
}
/**
* A |pipe| token thold_expand_string() cannot resolve returns ''.
* Converting that to '0' would let a manufactured zero flow through the
* RPN stack as a valid operand instead of failing the expression closed.
*
* @return void
*/
public function testUnresolvedPipeTokenFailsClosedRatherThanReturningZero(): void {
$graph = ['id' => 7, 'host_id' => 2, 'snmp_query_id' => '0', 'snmp_index' => ''];
// thold_calculate_expression() and thold_expand_string() each look up
// graph_local independently.
CactiStubs::willReturn('db_fetch_row_prepared', $graph);
CactiStubs::willReturn('db_fetch_row_prepared', $graph);
CactiStubs::willReturn('expand_title', '');
$this->assertSame('', $this->evaluate('|query_ifName|'));
$this->assertTrue($GLOBALS['rpn_error']);
}
/**
* @return array<string, array{0: string}>
*/
public static function specialTokenProvider() {
return [
'graph maximum' => ['CURRENT_GRAPH_MAXIMUM_VALUE'],
'graph minimum' => ['CURRENT_GRAPH_MINIMUM_VALUE'],
];
}
/**
* CURRENT_GRAPH_MAXIMUM_VALUE was missing from the dispatch list even
* though the evaluator handles it, so every expression using it failed as
* an unsupported field and returned zero.
*
* Reaching the handler is the whole assertion: what it then reads out of
* the RRD needs a live rrdtool and is not this test's concern.
*
* @dataProvider specialTokenProvider
*
* @param string $token
*
* @return void
*/
public function testSpecialGraphTokensReachTheirHandler($token): void {
// The handler reads the step off the data source before asking rrdtool.
CactiStubs::willReturnFor('db_fetch_row_prepared', 'FROM data_template_data', ['rrd_step' => 300]);
try {
$this->evaluate($token);
} catch (Throwable $reached_the_rrd_layer) {
// Expected: the handler runs and asks rrdtool for a value.
}
$unsupported = array_filter(CactiStubs::$log, static function ($message) {
return strpos($message, 'Unsupported Field') !== false;
});
$this->assertSame([], array_values($unsupported));
}
}