<?php
use PHPUnit\Framework\TestCase;
use SHServ\Middleware\ControlScripts;
class ControlScriptsRegularTest extends TestCase {
protected $tb;
protected function setUp(): void {
$this -> tb = app() -> thin_builder;
$this -> tb -> query("CREATE TABLE scripts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
area_id INTEGER DEFAULT 0,
uniq_name TEXT,
type TEXT,
state TEXT,
create_at TEXT,
update_at TEXT
)");
ControlScripts::flush_statics();
}
protected function tearDown(): void {
$this -> tb -> query("DROP TABLE IF EXISTS scripts");
ControlScripts::flush_statics();
}
public function test_run_regular_script_returns_false_when_alias_missing(): void {
$this -> assertFalse(ControlScripts::run_regular_script('nonexistent'));
}
public function test_run_regular_script_returns_false_when_disabled(): void {
$ref = new \ReflectionClass(ControlScripts::class);
$prop = $ref -> getProperty('regular_scripts');
$prop -> setAccessible(true);
$prop -> setValue(null, [
'disabled' => [
'attributes' => ['alias' => 'disabled'],
'code' => '',
'script' => function() {}
]
]);
$this -> tb -> insert('scripts', [
'uniq_name' => 'disabled',
'type' => 'regular',
'state' => 'disabled',
'create_at' => date('Y-m-d H:i:s'),
]);
$this -> assertFalse(ControlScripts::run_regular_script('disabled'));
}
public function test_run_regular_script_catches_exception(): void {
$ref = new \ReflectionClass(ControlScripts::class);
$prop = $ref -> getProperty('regular_scripts');
$prop -> setAccessible(true);
$prop -> setValue(null, [
'fail' => [
'attributes' => ['alias' => 'fail'],
'code' => '',
'script' => function() { throw new \Exception('boom'); }
]
]);
$this -> tb -> insert('scripts', [
'uniq_name' => 'fail',
'type' => 'regular',
'state' => 'enabled',
'create_at' => date('Y-m-d H:i:s'),
]);
$this -> assertFalse(ControlScripts::run_regular_script('fail'));
}
public function test_run_regular_script_returns_true_on_success(): void {
$ref = new \ReflectionClass(ControlScripts::class);
$prop = $ref -> getProperty('regular_scripts');
$prop -> setAccessible(true);
$prop -> setValue(null, [
'ok' => [
'attributes' => ['alias' => 'ok'],
'code' => '',
'script' => function() { return true; }
]
]);
$this -> tb -> insert('scripts', [
'uniq_name' => 'ok',
'type' => 'regular',
'state' => 'enabled',
'create_at' => date('Y-m-d H:i:s'),
]);
$this -> assertTrue(ControlScripts::run_regular_script('ok'));
}
}