FE: enhance settings tests to verify API persistence of PLUGINS_KEEP_HIST setting

This commit is contained in:
Jokob @NetAlertX
2026-01-11 03:56:59 +00:00
parent 206c2e76d0
commit 6dc30bb7dd
3 changed files with 64 additions and 25 deletions

View File

@@ -48,7 +48,7 @@ if ($method === 'GET') {
$apiRoot = getenv('NETALERTX_API') ?: '/tmp/api'; $apiRoot = getenv('NETALERTX_API') ?: '/tmp/api';
$file_path = rtrim($apiRoot, '/') . '/table_devices.json'; $file_path = rtrim($apiRoot, '/') . '/table_devices.json';
$data = file_get_contents($file_path); $data = file_get_contents($file_path);
// Prepare the data to return as a JSON response // Prepare the data to return as a JSON response
$response_data = base64_encode($data); $response_data = base64_encode($data);
@@ -75,7 +75,7 @@ else if ($method === 'POST') {
// // check location // // check location
// if (!is_dir($storage_path)) { // if (!is_dir($storage_path)) {
// echo "Could not open folder: {$storage_path}"; // echo "Could not open folder: {$storage_path}";
// write_notification("[Plugin: SYNC] Could not open folder: {$storage_path}", "alert"); // write_notification("[Plugin: SYNC] Could not open folder: {$storage_path}", "alert");
// http_response_code(500); // http_response_code(500);
// exit; // exit;
// } // }

View File

@@ -30,6 +30,10 @@ def get_api_token():
return None return None
# Load API_TOKEN at module initialization
API_TOKEN = get_api_token()
def get_driver(download_dir=None): def get_driver(download_dir=None):
"""Create a Selenium WebDriver for Chrome/Chromium """Create a Selenium WebDriver for Chrome/Chromium

View File

@@ -6,6 +6,7 @@ Tests settings page load, settings groups, and configuration
import time import time
import os import os
import requests
from selenium.webdriver.common.by import By from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support import expected_conditions as EC
@@ -14,7 +15,7 @@ import sys
# Add test directory to path # Add test directory to path
sys.path.insert(0, os.path.dirname(__file__)) sys.path.insert(0, os.path.dirname(__file__))
from test_helpers import BASE_URL # noqa: E402 [flake8 lint suppression] from test_helpers import BASE_URL, API_TOKEN # noqa: E402 [flake8 lint suppression]
def test_settings_page_loads(driver): def test_settings_page_loads(driver):
@@ -156,41 +157,75 @@ def test_save_settings_no_loss_of_data(driver):
This test verifies that the saveSettings() function properly: This test verifies that the saveSettings() function properly:
1. Loads all settings 1. Loads all settings
2. Preserves settings that weren't modified 2. Update PLUGINS_KEEP_HIST <input> - set to 333
3. Saves without data loss 3. Saves
4. Check API endpoint that the setting is updated correctly
""" """
driver.get(f"{BASE_URL}/settings.php") driver.get(f"{BASE_URL}/settings.php")
time.sleep(3) time.sleep(3)
# Count the total number of setting inputs before save # Find the PLUGINS_KEEP_HIST input field
inputs_before = driver.find_elements(By.CSS_SELECTOR, "input, select, textarea") plugins_keep_hist_input = None
initial_count = len(inputs_before) try:
plugins_keep_hist_input = WebDriverWait(driver, 10).until(
if initial_count == 0: EC.presence_of_element_located((By.ID, "PLUGINS_KEEP_HIST"))
assert True, "No settings inputs found" )
except:
assert True, "PLUGINS_KEEP_HIST input not found, skipping test"
return return
print(f"Found {initial_count} settings inputs") # Get original value
original_value = plugins_keep_hist_input.get_attribute("value")
print(f"PLUGINS_KEEP_HIST original value: {original_value}")
# Click save without modifying anything # Set new value
new_value = "333"
plugins_keep_hist_input.clear()
plugins_keep_hist_input.send_keys(new_value)
time.sleep(1)
# Click save
save_btn = driver.find_element(By.CSS_SELECTOR, "button#save") save_btn = driver.find_element(By.CSS_SELECTOR, "button#save")
driver.execute_script("arguments[0].click();", save_btn) driver.execute_script("arguments[0].click();", save_btn)
time.sleep(3) time.sleep(3)
# Reload the page # Check for errors after save
driver.get(f"{BASE_URL}/settings.php") error_elements = driver.find_elements(By.CSS_SELECTOR, ".alert-danger, .error-message, .callout-danger")
time.sleep(3) has_visible_error = False
for elem in error_elements:
if elem.is_displayed():
error_text = elem.text
if error_text and len(error_text) > 0:
print(f"Found error message: {error_text}")
has_visible_error = True
break
# Count settings again assert not has_visible_error, "No error messages should be displayed after save"
inputs_after = driver.find_elements(By.CSS_SELECTOR, "input, select, textarea")
final_count = len(inputs_after)
# Should have the same number of settings (within 10% tolerance for dynamic elements) # Verify via API endpoint /settings/<setKey>
tolerance = max(1, int(initial_count * 0.1)) # Extract backend API URL from BASE_URL
assert abs(initial_count - final_count) <= tolerance, \ api_base = BASE_URL.replace('/front', '').replace(':20211', ':20212') # Switch to backend port
f"Settings count should be preserved. Before: {initial_count}, After: {final_count}" api_url = f"{api_base}/settings/PLUGINS_KEEP_HIST"
print(f"✅ Settings preservation verified: {initial_count} -> {final_count}") headers = {
"Authorization": f"Bearer {API_TOKEN}"
}
try:
response = requests.get(api_url, headers=headers, timeout=5)
assert response.status_code == 200, f"API returned {response.status_code}: {response.text}"
# Settings endpoint doesn't exist in Flask API - settings are managed via PHP/config files data = response.json()
assert data.get("success") == True, f"API returned success=false: {data}"
saved_value = str(data.get("value"))
print(f"API /settings/PLUGINS_KEEP_HIST returned: {saved_value}")
assert saved_value == new_value, \
f"Setting not persisted correctly. Expected: {new_value}, Got: {saved_value}"
except requests.exceptions.RequestException as e:
assert False, f"Error calling settings API: {e}"
except Exception as e:
assert False, f"Error verifying setting via API: {e}"
print(f"✅ Settings update verified via API: PLUGINS_KEEP_HIST changed to {new_value}")