Files
cacti/tests/Unit/DataCollection/DataQuery/UpdateDataQueryCacheBatchingStructureTest.php
T
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

159 lines
5.3 KiB
PHP

<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
+-------------------------------------------------------------------------+
*/
/*
* Regression test for issue #7531 (update_data_query_cache() commits
* poller-cache writes per-row instead of batching).
*
* Before the fix, every changed row called update_poller_cache($data_source,
* true) -- $commit = true made it flush immediately via
* poller_update_poller_cache_from_buffer() on every iteration. The fix
* accumulates changed rows and calls update_poller_cache(..., false, ...)
* (no immediate commit) inside the loop, flushing once via
* poller_update_poller_cache_from_buffer() after the loop.
*
* The loop body is pulled directly out of lib/data_query.php and wrapped in
* a namespaced, throwaway function so the test exercises the shipped code
* rather than a re-typed copy of it (same extract-and-eval pattern as
* SsNimbleAlletraVolumesWordAssemblyTest.php). The namespace holds spies for
* update_data_source_data_query_cache(), update_poller_cache(),
* poller_update_poller_cache_from_buffer() and db_fetch_cell_prepared() so
* the test observes call counts/arguments without touching a real DB --
* see UpdateDataQueryCacheBatchingIntegrationTest.php for the companion
* test that proves the real poller_update_poller_cache_from_buffer()
* issues fewer SQL statements when batched this way.
*/
require_once dirname(__DIR__, 3) . '/Helpers/UnitStubs.php'; // provides the global cacti_sizeof() the extracted block falls back to
$source = file_get_contents(dirname(__DIR__, 4) . '/lib/data_query.php');
preg_match('/\tif \(cacti_sizeof\(\$data_sources\) > 0\) \{.*?\n\t\}\n/s', $source, $block);
test('the batched update_data_query_cache() loop body is present in lib/data_query.php', function () use ($block) {
expect($block)->not->toBeEmpty();
});
$namespace = 'CactiTest\\UpdateDataQueryCacheBatching';
// eval() here only wraps PHP regex-extracted from this repo's own
// lib/data_query.php (not external/user input) into a throwaway, namespaced
// function. Test-only. Guarded by function_exists() so re-running this file
// within the same process is safe.
if (!function_exists($namespace . '\\run')) {
eval("
namespace $namespace;
function db_fetch_cell_prepared(\$sql, \$params = []) {
return 5; // the poller_id every data_source in this scenario shares
}
function update_data_source_data_query_cache(\$id, \$host_id, \$data_query_id, \$index) {
\$GLOBALS['__changed_check_calls'][] = \$id;
return in_array(\$id, \$GLOBALS['__changed_ids'], true);
}
function update_poller_cache(\$data_source, \$commit, \$poller_id) {
\$GLOBALS['__update_poller_cache_calls'][] = [\$data_source['id'], \$commit, \$poller_id];
return [\"tuple_{\$data_source['id']}\"];
}
function poller_update_poller_cache_from_buffer(\$ids, \$items, \$poller_id) {
\$GLOBALS['__flush_calls'][] = [\$ids, \$items, \$poller_id];
}
function run(int \$host_id, int \$data_query_id, array \$data_sources) {
{$block[0]}
}
");
}
$run = $namespace . '\\run';
beforeEach(function () {
$GLOBALS['__changed_check_calls'] = [];
$GLOBALS['__update_poller_cache_calls'] = [];
$GLOBALS['__flush_calls'] = [];
});
test('every changed row calls update_poller_cache() with commit=false, not commit=true', function () use ($run) {
$GLOBALS['__changed_ids'] = [1, 2, 3];
$dataSources = [
['id' => 1, 'snmp_index' => '1'],
['id' => 2, 'snmp_index' => '2'],
['id' => 3, 'snmp_index' => '3'],
];
$run(10, 20, $dataSources);
expect($GLOBALS['__update_poller_cache_calls'])->toHaveCount(3);
foreach ($GLOBALS['__update_poller_cache_calls'] as $call) {
[, $commit, $poller_id] = $call;
expect($commit)->toBeFalse()
->and($poller_id)->toBe(5);
}
});
test('poller_update_poller_cache_from_buffer() is called exactly once for all changed rows, not once per row', function () use ($run) {
$GLOBALS['__changed_ids'] = [1, 2, 3];
$dataSources = [
['id' => 1, 'snmp_index' => '1'],
['id' => 2, 'snmp_index' => '2'],
['id' => 3, 'snmp_index' => '3'],
];
$run(10, 20, $dataSources);
expect($GLOBALS['__flush_calls'])->toHaveCount(1);
[$ids, $items, $poller_id] = $GLOBALS['__flush_calls'][0];
expect($ids)->toBe([1, 2, 3])
->and($items)->toBe(['tuple_1', 'tuple_2', 'tuple_3'])
->and($poller_id)->toBe(5);
});
test('unchanged rows are excluded from both the poller_items buffer and the flush id list', function () use ($run) {
$GLOBALS['__changed_ids'] = [2];
$dataSources = [
['id' => 1, 'snmp_index' => '1'],
['id' => 2, 'snmp_index' => '2'],
['id' => 3, 'snmp_index' => '3'],
];
$run(10, 20, $dataSources);
// update_data_source_data_query_cache() is still called for every row
// (that check is unrelated to batching), but only row 2 changed
expect($GLOBALS['__changed_check_calls'])->toBe([1, 2, 3])
->and($GLOBALS['__update_poller_cache_calls'])->toHaveCount(1);
[$ids, $items] = $GLOBALS['__flush_calls'][0];
expect($ids)->toBe([2])
->and($items)->toBe(['tuple_2']);
});
test('no rows changed means no flush at all', function () use ($run) {
$GLOBALS['__changed_ids'] = [];
$dataSources = [
['id' => 1, 'snmp_index' => '1'],
];
$run(10, 20, $dataSources);
expect($GLOBALS['__update_poller_cache_calls'])->toBe([])
->and($GLOBALS['__flush_calls'])->toBe([]);
});