Files
cacti/tests/Unit/Database/DbTimeoutTest.php
Sean Mancini 96033267cb refactor(tests): reorganize unit tests into domain category folders (#7733)
* refactor(tests): reorganize unit tests into domain category folders

- Consolidate per-advisory GHSA regression tests into Security/ subfolders by vuln class
- Group all 186 test files into domain folders: DataCollection/, Ui/, Core/,
  Database/, Installer/, Scripts/, Security/, Plugin/
- Strip GitHub issue/GHSA numbers from filenames; keep IDs in test descriptions
- Fix all __DIR__ relative paths to match new folder nesting depth
- Update CI workflow path triggers and phpunit XML configs for new file locations
- Update .github/copilot-instructions.md with unit test organization guidelines
- Add tests/vendor/ to .gitignore

* add gaurds

* fix up guard for unit tests

* fix redeclaration of cacti_log in tests

* fix updates to unit tests

* fix test patjhs

* fix: update test __DIR__ paths for reorganized test structure

* fix: conditionally define read_user_setting to prevent redeclaration in tests

* fix: conditionally define functions to prevent redeclaration in tests

- Wrap clean_up_lines, raise_message, cacti_debug_backtrace, and get_debug_prefix
  with function_exists() checks to prevent conflicts when test stubs are loaded
  before lib/functions.php in the same PHP process

* fix: add unit test bootstrap to prevent function redeclaration errors

- Create tests/bootstrap-unit.php to load core libraries before tests
- Ensures lib/functions.php loads before test stubs define stub functions
- Test stubs use function_exists() checks, so they detect pre-loaded functions
- Update phpunit.xml to use bootstrap-unit.php for Unit testsuite
- Fixes 'Cannot redeclare read_user_setting()' errors when tests run in same process

* fix: load test stubs before global.php in unit test bootstrap

- Reorder bootstrap to load CactiStubs.php and UnitStubs.php first
- Ensures stub functions like __() are available when global.php loads
- global.php calls get_cacti_version_text() which needs __() for translations
- Fixes 'Call to undefined function __()' error during bootstrap

* fix: remove function conflicts from test stubs

- Remove stub definitions for functions already in lib/functions.php:
  cacti_sizeof, cacti_log, cacti_strtolower, read_config_option,
  read_user_setting, cacti_count
- Keep translation function stubs (__(), __esc()) needed by global.php
- Update bootstrap to load lib/functions.php after stubs
- This prevents function redeclaration errors while maintaining test isolation

* fix: prevent constant and variable redeclaration in bootstrap

- Remove explicit PHP_TESTING and CACTI_TEST_BOOTSTRAP defines from bootstrap
  (CactiStubs.php now handles this with guards)
- Add guards to CactiStubs.php to prevent redefinition of PHP_TESTING
- Only set CACTI_TEST_BOOTSTRAP env vars if not already set
- Fixes PHP warnings about 'Constant X already defined'

* fix: remove redundant lib/functions.php load from bootstrap

include/global.php already loads lib/functions.php at lines 287-288.
The bootstrap was trying to load it again after global.php, but global.php
needs format_cacti_version() to be available on lines 293-294 to define
CACTI_VERSION and CACTI_VERSION_FULL constants.

Solution: Let global.php handle loading lib/functions.php itself, and don't
load it separately in the bootstrap.

* fix: remove more conflicting function stubs from test helpers

- Remove stubs for functions also defined in lib/functions.php:
  raise_message, clean_up_lines, cacti_debug_backtrace, get_debug_prefix
- Remove POLLER_ID constant stub (defined unconditionally by global.php)
- Keep only translation functions and test-specific helpers
- This prevents function/constant redeclaration errors

* fix: minimize test stubs to only translation functions

Remove ALL helper functions and constants from UnitStubs.php that are:
- Defined in lib/functions.php (raise_message, clean_up_lines, etc.)
- Defined in lib/html_utility.php (srv, set_request_var)
- Defined in global_constants.php (POLLER_VERBOSITY_*, MESSAGE_LEVEL_*)
- Defined in global.php (POLLER_ID)

Keep ONLY translation functions (__(), __esc()) that are:
- Called by global.php during initialization
- Not defined elsewhere
- Required for proper bootstrap sequence

This eliminates all constant and function redeclaration errors.

* fix: remove __esc stub - already defined in global_languages.php

Keep only __() translation function stub, which is needed by global.php
and not defined elsewhere in Cacti core.

* fix: handle no-arg case in __() translation stub

The __() function may be called with just a string and no format arguments.
Previously, vsprintf() would fail with 'arguments array must contain 2 items'.
Now, if no args are provided, return the text as-is.
2026-08-16 19:23:31 -07:00

160 lines
7.2 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 |
+-------------------------------------------------------------------------+
*/
require_once dirname(__DIR__, 2) . '/Helpers/UnitStubs.php';
require_once dirname(__DIR__, 3) . '/include/vendor/autoload.php';
require_once dirname(__DIR__, 3) . '/lib/database.php';
test('MariaDB wraps with SET STATEMENT for an integer timeout', function () {
expect(db_sql_apply_timeout('SELECT 1', 5, 'MariaDB', '10.6.12'))
->toBe('SET STATEMENT MAX_STATEMENT_TIME=5 FOR SELECT 1');
});
test('MariaDB keeps decimal seconds', function () {
expect(db_sql_apply_timeout('SELECT 1', 2.5, 'MariaDB', '10.6.12'))
->toBe('SET STATEMENT MAX_STATEMENT_TIME=2.5 FOR SELECT 1');
});
test('MariaDB trims trailing zeros on whole-number decimals', function () {
expect(db_sql_apply_timeout('SELECT 1', 5.0, 'MariaDB', '10.6.12'))
->toBe('SET STATEMENT MAX_STATEMENT_TIME=5 FOR SELECT 1');
});
test('MariaDB applies to non-SELECT statements', function () {
expect(db_sql_apply_timeout('DELETE FROM host WHERE id = 1', 3, 'MariaDB', '10.6.12'))
->toBe('SET STATEMENT MAX_STATEMENT_TIME=3 FOR DELETE FROM host WHERE id = 1');
});
test('MySQL injects the MAX_EXECUTION_TIME hint after SELECT', function () {
expect(db_sql_apply_timeout('SELECT 1', 2, 'MySQL', '8.0.30'))
->toBe('SELECT /*+ MAX_EXECUTION_TIME(2000) */ 1');
});
test('MySQL converts fractional seconds to milliseconds', function () {
expect(db_sql_apply_timeout('SELECT id FROM host', 0.25, 'MySQL', '8.0.30'))
->toBe('SELECT /*+ MAX_EXECUTION_TIME(250) */ id FROM host');
});
test('MySQL clamps sub-millisecond timeouts to at least 1ms', function () {
expect(db_sql_apply_timeout('SELECT 1', 0.0001, 'MySQL', '8.0.30'))
->toBe('SELECT /*+ MAX_EXECUTION_TIME(1) */ 1');
});
test('MySQL does not touch the SELECT keyword inside a larger word', function () {
expect(db_sql_apply_timeout('SELECTED FROM x', 2, 'MySQL', '8.0.30'))
->toBe('SELECTED FROM x');
});
test('MySQL leaves non-SELECT statements unchanged', function () {
expect(db_sql_apply_timeout('UPDATE host SET disabled = 1', 2, 'MySQL', '8.0.30'))
->toBe('UPDATE host SET disabled = 1');
});
test('MySQL leaves leading-WITH (CTE) statements unchanged', function () {
expect(db_sql_apply_timeout('WITH cte AS (SELECT 1) SELECT * FROM cte', 2, 'MySQL', '8.0.30'))
->toBe('WITH cte AS (SELECT 1) SELECT * FROM cte');
});
test('zero timeout is a no-op', function () {
expect(db_sql_apply_timeout('SELECT 1', 0, 'MariaDB', '10.6.12'))->toBe('SELECT 1');
});
test('negative timeout is a no-op', function () {
expect(db_sql_apply_timeout('SELECT 1', -1, 'MariaDB', '10.6.12'))->toBe('SELECT 1');
});
test('MariaDB below 10.1 passes through', function () {
expect(db_sql_apply_timeout('SELECT 1', 5, 'MariaDB', '10.0.38'))->toBe('SELECT 1');
});
test('MySQL below 5.7.8 passes through', function () {
expect(db_sql_apply_timeout('SELECT 1', 5, 'MySQL', '5.6.51'))->toBe('SELECT 1');
});
test('unknown engine passes through', function () {
expect(db_sql_apply_timeout('SELECT 1', 5, '', ''))->toBe('SELECT 1');
});
test('MariaDB clamps sub-millisecond timeout to a 1ms floor instead of disabling the limit', function () {
// MAX_STATEMENT_TIME=0 means "no limit" in MariaDB, so a positive timeout
// must never format to 0.
expect(db_sql_apply_timeout('SELECT 1', 0.0001, 'MariaDB', '10.6.12'))
->toBe('SET STATEMENT MAX_STATEMENT_TIME=0.001 FOR SELECT 1');
});
test('non-finite timeouts pass through (MariaDB)', function () {
expect(db_sql_apply_timeout('SELECT 1', INF, 'MariaDB', '10.6.12'))->toBe('SELECT 1');
expect(db_sql_apply_timeout('SELECT 1', NAN, 'MariaDB', '10.6.12'))->toBe('SELECT 1');
});
test('non-finite timeouts pass through (MySQL)', function () {
expect(db_sql_apply_timeout('SELECT 1', INF, 'MySQL', '8.0.30'))->toBe('SELECT 1');
expect(db_sql_apply_timeout('SELECT 1', NAN, 'MySQL', '8.0.30'))->toBe('SELECT 1');
});
test('MySQL does not double-inject when a hint block already follows SELECT', function () {
expect(db_sql_apply_timeout('SELECT /*+ BNL(t1) */ * FROM t1', 2, 'MySQL', '8.0.30'))
->toBe('SELECT /*+ BNL(t1) */ * FROM t1');
});
test('db_execute_prepared accepts a trailing timeout argument', function () {
$conn = new PDO('sqlite::memory:');
$conn->exec('CREATE TABLE host (id INTEGER PRIMARY KEY AUTOINCREMENT, hostname TEXT NOT NULL)');
$result = db_execute_prepared(
'INSERT INTO host (hostname) VALUES (?)',
['h1'], true, $conn, 'Exec', true, 'no_return_function', [], 5
);
expect($result)->toBeTruthy()
->and($conn->query('SELECT hostname FROM host WHERE id = 1')->fetchColumn())->toBe('h1');
});
test('every public wrapper accepts a trailing timeout argument', function () {
$conn = new PDO('sqlite::memory:');
$conn->exec('CREATE TABLE host (id INTEGER PRIMARY KEY AUTOINCREMENT, hostname TEXT NOT NULL)');
expect(db_execute("INSERT INTO host (hostname) VALUES ('h1')", true, $conn, 5))->toBeTruthy();
expect(db_fetch_cell('SELECT hostname FROM host WHERE id = 1', '', true, $conn, 5))->toBe('h1');
expect(db_fetch_cell_prepared('SELECT hostname FROM host WHERE id = ?', [1], '', true, $conn, 5))->toBe('h1');
expect(db_fetch_row('SELECT * FROM host WHERE id = 1', true, $conn, 5)['hostname'])->toBe('h1');
expect(db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', [1], true, $conn, 5)['hostname'])->toBe('h1');
expect(db_fetch_assoc('SELECT hostname FROM host', true, $conn, 5)[0]['hostname'])->toBe('h1');
expect(db_fetch_assoc_prepared('SELECT hostname FROM host WHERE id = ?', [1], true, $conn, 5)[0]['hostname'])->toBe('h1');
});
test('MariaDB version string with a distro/build suffix still applies the timeout', function () {
// db_connect_real stores the raw server version (SHOW VARIABLES 'version').
// version_compare decides on the leading numeric components, so build suffixes
// do not defeat the >= gate.
expect(db_sql_apply_timeout('SELECT 1', 5, 'MariaDB', '10.11.18-ubu2204'))
->toBe('SET STATEMENT MAX_STATEMENT_TIME=5 FOR SELECT 1');
});
test('MySQL version string with a distro/build suffix still applies the hint', function () {
expect(db_sql_apply_timeout('SELECT 1', 2, 'MySQL', '8.0.46-0ubuntu0.22.04.1'))
->toBe('SELECT /*+ MAX_EXECUTION_TIME(2000) */ 1');
});
test('MySQL SELECT preceded by a comment block is left untimed', function () {
// The hint must attach to the leading SELECT token; rather than risk placing it
// before a comment, a comment-prefixed statement runs untimed. MariaDB is
// unaffected because SET STATEMENT wraps the whole statement.
expect(db_sql_apply_timeout('/* app */ SELECT 1', 2, 'MySQL', '8.0.30'))
->toBe('/* app */ SELECT 1');
});