доработки в рамках трейдингового бота и поднятие версии до 1.4.0
This commit is contained in:
1 parent
41a0c8878c
commit
f3bfef9788
30 files changed
+2082
-69
No files matched your search
@@ -0,0 +1,211 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Зависимости в конструкторе задач очереди и консольных команд: их подставляет
|
||||
* контейнер, а постановка в очередь и справка обходятся без сборки.
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Console\Application;
|
||||
use Rsgrinko\Proton\Console\Command;
|
||||
use Rsgrinko\Proton\Database\Connection;
|
||||
use Rsgrinko\Proton\Models\Setting;
|
||||
use Rsgrinko\Proton\Queue\Job;
|
||||
use Rsgrinko\Proton\Queue\Queue;
|
||||
use Rsgrinko\Proton\Queue\Worker;
|
||||
use Rsgrinko\Proton\Support\Container;
|
||||
|
||||
interface AutowireTestClock
|
||||
{
|
||||
public function now(): string;
|
||||
}
|
||||
|
||||
final class AutowireTestFrozenClock implements AutowireTestClock
|
||||
{
|
||||
public function now(): string
|
||||
{
|
||||
return '2026-01-01 00:00:00';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Задача с зависимостью по интерфейсу — как её напишет приложение.
|
||||
*/
|
||||
final class AutowireTestJob extends Job
|
||||
{
|
||||
public function __construct(private readonly AutowireTestClock $clock)
|
||||
{
|
||||
}
|
||||
|
||||
public function queue(): string
|
||||
{
|
||||
return 'часы';
|
||||
}
|
||||
|
||||
public function attempts(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function handle(array $payload): void
|
||||
{
|
||||
Setting::set('test:autowire:job', $this->clock->now());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function failed(array $payload, string $error): void
|
||||
{
|
||||
Setting::set('test:autowire:failed', $this->clock->now());
|
||||
}
|
||||
}
|
||||
|
||||
final class AutowireTestCommand extends Command
|
||||
{
|
||||
public function __construct(private readonly AutowireTestClock $clock)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'test:clock';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Печатает время из зависимости';
|
||||
}
|
||||
|
||||
public function run(): int
|
||||
{
|
||||
$this->line($this->clock->now());
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Свой контейнер с привязкой часов на время теста.
|
||||
*/
|
||||
function withClockBinding(callable $body): void
|
||||
{
|
||||
$previous = Container::instance();
|
||||
$container = new Container();
|
||||
$container->bind(AutowireTestClock::class, AutowireTestFrozenClock::class);
|
||||
|
||||
Container::setInstance($container);
|
||||
|
||||
try {
|
||||
$body();
|
||||
} finally {
|
||||
Container::setInstance($previous);
|
||||
}
|
||||
}
|
||||
|
||||
test('автовайринг: задача ставится в очередь без сборки зависимостей', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
// Привязки нет вовсе: собрать задачу нельзя, а поставить — можно
|
||||
$id = Queue::push(AutowireTestJob::class);
|
||||
$row = assertNotNull(Connection::instance()->selectOne('SELECT * FROM jobs WHERE id = :id', ['id' => $id]));
|
||||
|
||||
assertSame('часы', (string) $row['queue'], 'очередь взята у класса');
|
||||
assertSame(1, (int) $row['max_attempts']);
|
||||
});
|
||||
});
|
||||
|
||||
test('автовайринг: воркер собирает задачу контейнером', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
withClockBinding(static function (): void {
|
||||
Queue::push(AutowireTestJob::class);
|
||||
|
||||
$result = (new Worker('часы'))->run(true);
|
||||
|
||||
assertSame(1, $result['done']);
|
||||
assertSame('2026-01-01 00:00:00', Setting::get('test:autowire:job'));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('автовайринг: несобравшаяся задача падает как обычная, а не роняет воркер', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
$id = Queue::push(AutowireTestJob::class);
|
||||
|
||||
$result = (new Worker('часы'))->run(true);
|
||||
|
||||
assertSame(1, $result['failed']);
|
||||
|
||||
$row = assertNotNull(Connection::instance()->selectOne('SELECT * FROM jobs WHERE id = :id', ['id' => $id]));
|
||||
|
||||
assertContains('не собралась', (string) $row['error']);
|
||||
assertSame(Queue::DEAD, (string) $row['status'], 'попытка у задачи одна — она кончилась');
|
||||
});
|
||||
});
|
||||
|
||||
test('автовайринг: зависшая задача зовёт failed() уже собранной', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
withClockBinding(static function (): void {
|
||||
$id = Queue::push(AutowireTestJob::class);
|
||||
|
||||
// Воркер «пропал» посреди единственной попытки
|
||||
Connection::instance()->update('jobs', [
|
||||
'status' => Queue::RUNNING,
|
||||
'attempts' => 1,
|
||||
'reserved_at' => date('Y-m-d H:i:s', time() - 7200),
|
||||
], ['id' => $id]);
|
||||
|
||||
assertSame(1, Queue::releaseStuck(15));
|
||||
assertSame('2026-01-01 00:00:00', Setting::get('test:autowire:failed'));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('автовайринг: команда собирается контейнером, справке сборка не нужна', function (): void {
|
||||
// Без привязки команду не собрать, а имя и описание узнать можно
|
||||
$described = Application::describe(AutowireTestCommand::class);
|
||||
|
||||
assertSame('test:clock', $described->name());
|
||||
assertSame('Печатает время из зависимости', $described->description());
|
||||
|
||||
withClockBinding(static function (): void {
|
||||
$lines = [];
|
||||
|
||||
$status = Container::instance()->make(AutowireTestCommand::class)
|
||||
->withInput([], [], static function (string $line) use (&$lines): void {
|
||||
$lines[] = $line;
|
||||
})
|
||||
->run();
|
||||
|
||||
assertSame(0, $status);
|
||||
assertSame(['2026-01-01 00:00:00'], $lines);
|
||||
});
|
||||
});
|
||||
|
||||
test('автовайринг: справка и поиск команды по-прежнему работают', function (): void {
|
||||
ob_start();
|
||||
|
||||
try {
|
||||
$status = (new Application())->run(['proton', 'help']);
|
||||
} finally {
|
||||
$help = (string) ob_get_clean();
|
||||
}
|
||||
|
||||
assertSame(0, $status);
|
||||
assertContains('queue:status', $help);
|
||||
|
||||
ob_start();
|
||||
|
||||
try {
|
||||
$status = (new Application())->run(['proton', 'core:version']);
|
||||
} finally {
|
||||
$output = (string) ob_get_clean();
|
||||
}
|
||||
|
||||
assertSame(0, $status);
|
||||
assertContains(trim((string) file_get_contents(APP_ROOT . '/framework/VERSION')), $output);
|
||||
});
|
||||
@@ -0,0 +1,318 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* DaemonCommand: круги, остановка (сам, флагом, сигналом), один экземпляр,
|
||||
* упавший круг и свежие настройки.
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Console\Commands\DaemonStopCommand;
|
||||
use Rsgrinko\Proton\Console\DaemonCommand;
|
||||
use Rsgrinko\Proton\Database\Lock;
|
||||
use Rsgrinko\Proton\Models\Setting;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Settings;
|
||||
|
||||
/**
|
||||
* Демон, у которого круг — переданная функция. Функция получает сам демон
|
||||
* и номер круга.
|
||||
*/
|
||||
final class DaemonTestCommand extends DaemonCommand
|
||||
{
|
||||
public int $ticks = 0;
|
||||
|
||||
/** @var array<int, string> */
|
||||
public array $lines = [];
|
||||
|
||||
/**
|
||||
* @param Closure(self, int): void $body
|
||||
*/
|
||||
public function __construct(private readonly Closure $body, private readonly string $daemonName = 'test:daemon')
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return $this->daemonName;
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'демон для теста';
|
||||
}
|
||||
|
||||
protected function interval(): int
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected function errorPause(): int
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected function tick(): void
|
||||
{
|
||||
$this->ticks++;
|
||||
|
||||
($this->body)($this, $this->ticks);
|
||||
}
|
||||
|
||||
public function finish(): void
|
||||
{
|
||||
$this->stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $options
|
||||
*/
|
||||
public function start(array $options = []): int
|
||||
{
|
||||
return $this->withInput([], $options, function (string $line): void {
|
||||
$this->lines[] = $line;
|
||||
})->run();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Свой каталог флагов остановки на время теста.
|
||||
*/
|
||||
function withDaemonFlags(callable $body): void
|
||||
{
|
||||
$dir = sys_get_temp_dir() . '/proton-daemon-test-' . bin2hex(random_bytes(4));
|
||||
|
||||
try {
|
||||
withConfig(['paths.daemon' => $dir], static fn () => $body($dir));
|
||||
} finally {
|
||||
foreach (glob($dir . '/*') ?: [] as $file) {
|
||||
@unlink($file);
|
||||
}
|
||||
|
||||
@rmdir($dir);
|
||||
}
|
||||
}
|
||||
|
||||
test('демон: --once делает ровно один круг', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
$daemon = new DaemonTestCommand(static function (): void {});
|
||||
|
||||
assertSame(0, $daemon->start(['once' => '1']));
|
||||
assertSame(1, $daemon->ticks);
|
||||
});
|
||||
});
|
||||
|
||||
test('демон: крутит круги, пока его не остановят', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
$daemon = new DaemonTestCommand(static function (DaemonTestCommand $daemon, int $tick): void {
|
||||
if ($tick === 5) {
|
||||
$daemon->finish();
|
||||
}
|
||||
});
|
||||
|
||||
assertSame(0, $daemon->start());
|
||||
assertSame(5, $daemon->ticks);
|
||||
});
|
||||
});
|
||||
|
||||
test('демон: упавший круг не роняет демон', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
$daemon = new DaemonTestCommand(static function (DaemonTestCommand $daemon, int $tick): void {
|
||||
if ($tick === 3) {
|
||||
$daemon->finish();
|
||||
}
|
||||
|
||||
throw new RuntimeException('чужой сервис лежит');
|
||||
});
|
||||
|
||||
assertSame(0, $daemon->start());
|
||||
assertSame(3, $daemon->ticks, 'после ошибок круги продолжились');
|
||||
});
|
||||
});
|
||||
|
||||
test('демон: второй экземпляр с тем же именем не запускается', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
$held = new Lock(null, 'daemon:test:daemon');
|
||||
|
||||
assertTrue($held->acquire(0));
|
||||
|
||||
try {
|
||||
$daemon = new DaemonTestCommand(static function (): void {});
|
||||
|
||||
assertSame(1, $daemon->start());
|
||||
assertSame(0, $daemon->ticks, 'ни одного круга');
|
||||
assertContains('уже запущен', implode("\n", $daemon->lines));
|
||||
} finally {
|
||||
$held->release();
|
||||
}
|
||||
|
||||
// Блокировку демон за собой отпускает
|
||||
$daemon = new DaemonTestCommand(static function (): void {});
|
||||
|
||||
assertSame(0, $daemon->start(['once' => '1']));
|
||||
|
||||
$again = new Lock(null, 'daemon:test:daemon');
|
||||
|
||||
assertTrue($again->acquire(0), 'после выхода блокировка свободна');
|
||||
$again->release();
|
||||
});
|
||||
});
|
||||
|
||||
test('демон: выходит по флагу, а старый флаг нового не останавливает', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
withDaemonFlags(static function (): void {
|
||||
// Флаг остался от прошлого экземпляра — на новый он не действует
|
||||
DaemonCommand::requestStop('test:daemon');
|
||||
usleep(1000);
|
||||
|
||||
$daemon = new DaemonTestCommand(static function (DaemonTestCommand $daemon, int $tick): void {
|
||||
if ($tick === 3) {
|
||||
DaemonCommand::requestStop('test:daemon');
|
||||
}
|
||||
|
||||
if ($tick > 10) {
|
||||
$daemon->finish();
|
||||
}
|
||||
});
|
||||
|
||||
assertSame(0, $daemon->start());
|
||||
assertSame(3, $daemon->ticks, 'вышел сразу после круга, на котором попросили');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('демон: перед каждым кругом настройки свежие', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
withConfig(['ui.per_page' => 25], static function (): void {
|
||||
Settings::apply();
|
||||
|
||||
$seen = [];
|
||||
|
||||
$daemon = new DaemonTestCommand(static function (DaemonTestCommand $daemon, int $tick) use (&$seen): void {
|
||||
$seen[] = Config::get('ui.per_page');
|
||||
|
||||
// Панель поменяла значение, пока демон работает
|
||||
Setting::set(Settings::PREFIX . 'ui.per_page', (string) (40 + $tick));
|
||||
|
||||
if ($tick === 3) {
|
||||
$daemon->finish();
|
||||
}
|
||||
});
|
||||
|
||||
$daemon->start();
|
||||
|
||||
assertSame([25, 41, 42], $seen);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('демон: daemon:stop требует имя и ставит флаг', function (): void {
|
||||
withDaemonFlags(static function (string $dir): void {
|
||||
$lines = [];
|
||||
$out = static function (string $line) use (&$lines): void {
|
||||
$lines[] = $line;
|
||||
};
|
||||
|
||||
assertSame(1, (new DaemonStopCommand())->withInput([], [], $out)->run());
|
||||
assertSame(0, (new DaemonStopCommand())->withInput(['inbox:poll'], [], $out)->run());
|
||||
assertTrue(is_file($dir . '/inbox_poll.stop'), 'двоеточие в имени файла заменено');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Запускает tests/support/fake_daemon.php отдельным процессом и ждёт первых кругов.
|
||||
*
|
||||
* @return array{process: resource, pipes: array<int, resource>, report: string}
|
||||
*/
|
||||
function startFakeDaemon(string $name, string $flagsDir): array
|
||||
{
|
||||
$report = sys_get_temp_dir() . '/proton-daemon-report-' . bin2hex(random_bytes(4)) . '.json';
|
||||
|
||||
$process = proc_open(
|
||||
['php', APP_ROOT . '/tests/support/fake_daemon.php', $name, $flagsDir, $report],
|
||||
[1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
|
||||
$pipes
|
||||
);
|
||||
|
||||
$deadline = microtime(true) + 15;
|
||||
|
||||
while (microtime(true) < $deadline) {
|
||||
$state = json_decode((string) @file_get_contents($report), true);
|
||||
|
||||
if (is_array($state) && (int) ($state['ticks'] ?? 0) >= 2) {
|
||||
break;
|
||||
}
|
||||
|
||||
usleep(50000);
|
||||
}
|
||||
|
||||
return ['process' => $process, 'pipes' => $pipes, 'report' => $report];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ждёт выхода процесса. Возвращает отчёт демона или null, если не вышел.
|
||||
*
|
||||
* @param array{process: resource, pipes: array<int, resource>, report: string} $daemon
|
||||
*
|
||||
* @return array{ticks: int, exit: int|null}|null
|
||||
*/
|
||||
function waitFakeDaemon(array $daemon, float $seconds): ?array
|
||||
{
|
||||
$deadline = microtime(true) + $seconds;
|
||||
|
||||
while (microtime(true) < $deadline && proc_get_status($daemon['process'])['running']) {
|
||||
usleep(50000);
|
||||
}
|
||||
|
||||
$running = proc_get_status($daemon['process'])['running'];
|
||||
|
||||
foreach ($daemon['pipes'] as $pipe) {
|
||||
@fclose($pipe);
|
||||
}
|
||||
|
||||
if ($running) {
|
||||
proc_terminate($daemon['process'], 9);
|
||||
}
|
||||
|
||||
proc_close($daemon['process']);
|
||||
|
||||
$report = json_decode((string) @file_get_contents($daemon['report']), true);
|
||||
|
||||
@unlink($daemon['report']);
|
||||
|
||||
return $running || !is_array($report) ? null : $report;
|
||||
}
|
||||
|
||||
test('демон: отдельный процесс выходит по daemon:stop', function (): void {
|
||||
withDaemonFlags(static function (string $dir): void {
|
||||
$name = 'test:proc-' . bin2hex(random_bytes(3));
|
||||
$daemon = startFakeDaemon($name, $dir);
|
||||
|
||||
(new DaemonStopCommand())->withInput([$name], [], static function (): void {})->run();
|
||||
|
||||
$report = waitFakeDaemon($daemon, 10);
|
||||
|
||||
assertNotNull($report, 'процесс вышел сам, его не пришлось убивать');
|
||||
assertSame(0, $report['exit'], 'вышел по-хорошему, с кодом 0');
|
||||
assertTrue($report['ticks'] >= 2);
|
||||
});
|
||||
});
|
||||
|
||||
test('демон: отдельный процесс доделывает круг и выходит по SIGTERM', function (): void {
|
||||
if (!function_exists('pcntl_signal') || PHP_OS_FAMILY === 'Windows') {
|
||||
skipTest('PCNTL недоступен');
|
||||
}
|
||||
|
||||
withDaemonFlags(static function (string $dir): void {
|
||||
$daemon = startFakeDaemon('test:sig-' . bin2hex(random_bytes(3)), $dir);
|
||||
|
||||
// proc_terminate() по умолчанию шлёт именно SIGTERM — как systemd stop
|
||||
proc_terminate($daemon['process']);
|
||||
|
||||
$report = waitFakeDaemon($daemon, 10);
|
||||
|
||||
assertNotNull($report, 'процесс вышел сам');
|
||||
assertSame(0, $report['exit'], 'вышел по-хорошему, а не убит сигналом');
|
||||
});
|
||||
});
|
||||
@@ -169,3 +169,117 @@ test('база: знает о своих таблицах, колонках и
|
||||
assertFalse($db->hasColumn('users', 'колонки_такой_нет'));
|
||||
assertTrue($db->hasIndex('users', 'idx_users_login'));
|
||||
});
|
||||
|
||||
/**
|
||||
* Своя таблица на время теста: ключ-значение и записи с датами.
|
||||
*/
|
||||
function withScratchTables(callable $body): void
|
||||
{
|
||||
withOwnDatabase(static function (Connection $db) use ($body): void {
|
||||
$schema = new Rsgrinko\Proton\Database\Schema\Builder($db);
|
||||
|
||||
$schema->create('test_pairs', static function (Rsgrinko\Proton\Database\Schema\Blueprint $table): void {
|
||||
$table->string('pair_key', 64)->primary();
|
||||
$table->string('value', 64);
|
||||
$table->integer('hits')->default(0);
|
||||
});
|
||||
|
||||
$schema->create('test_events', static function (Rsgrinko\Proton\Database\Schema\Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->dateTime('happened_at');
|
||||
$table->date('happened_on');
|
||||
$table->index('idx_test_events_happened_at', 'happened_at');
|
||||
});
|
||||
|
||||
$body($db);
|
||||
});
|
||||
}
|
||||
|
||||
test('построитель: upsert вставляет новую строку и перезаписывает существующую', function (): void {
|
||||
withScratchTables(static function (Connection $db): void {
|
||||
$db->table('test_pairs')->upsert(['pair_key' => 'a', 'value' => 'раз', 'hits' => 1], ['pair_key']);
|
||||
$db->table('test_pairs')->upsert(['pair_key' => 'a', 'value' => 'два', 'hits' => 5], ['pair_key']);
|
||||
|
||||
$rows = $db->select('SELECT * FROM test_pairs');
|
||||
|
||||
assertCount(1, $rows, 'строка с тем же ключом не задвоилась');
|
||||
assertSame('два', (string) $rows[0]['value']);
|
||||
assertSame(5, (int) $rows[0]['hits']);
|
||||
});
|
||||
});
|
||||
|
||||
test('построитель: upsert обновляет только перечисленные колонки', function (): void {
|
||||
withScratchTables(static function (Connection $db): void {
|
||||
$db->table('test_pairs')->upsert(['pair_key' => 'a', 'value' => 'раз', 'hits' => 1], ['pair_key']);
|
||||
$db->table('test_pairs')->upsert(['pair_key' => 'a', 'value' => 'два', 'hits' => 9], ['pair_key'], ['hits']);
|
||||
|
||||
$row = assertNotNull($db->selectOne('SELECT * FROM test_pairs WHERE pair_key = :k', ['k' => 'a']));
|
||||
|
||||
assertSame('раз', (string) $row['value'], 'value не в списке — не тронуто');
|
||||
assertSame(9, (int) $row['hits']);
|
||||
|
||||
// Пустой список — «есть, так не трогать», и это не ошибка
|
||||
$db->table('test_pairs')->upsert(['pair_key' => 'a', 'value' => 'три', 'hits' => 0], ['pair_key'], []);
|
||||
|
||||
assertSame('раз', (string) $db->value('SELECT value FROM test_pairs WHERE pair_key = :k', ['k' => 'a']));
|
||||
});
|
||||
});
|
||||
|
||||
test('построитель: upsert пачкой и мимо накопленных условий', function (): void {
|
||||
withScratchTables(static function (Connection $db): void {
|
||||
$db->table('test_pairs')->upsert(['pair_key' => 'a', 'value' => 'старое', 'hits' => 0], ['pair_key']);
|
||||
|
||||
// where() к вставке отношения не имеет и не должен ломать параметры
|
||||
$db->table('test_pairs')->where('hits', '>', 100)->upsert([
|
||||
['pair_key' => 'a', 'value' => 'новое', 'hits' => 1],
|
||||
['pair_key' => 'b', 'value' => 'второе', 'hits' => 2],
|
||||
], ['pair_key']);
|
||||
|
||||
assertSame(
|
||||
['a' => 'новое', 'b' => 'второе'],
|
||||
array_column($db->select('SELECT pair_key, value FROM test_pairs ORDER BY pair_key'), 'value', 'pair_key')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('построитель: upsert отвергает ключ не из вставляемых колонок', function (): void {
|
||||
$error = assertThrows(static fn () => Connection::instance()->table('test_pairs')->upsert(['value' => 'x'], ['pair_key']));
|
||||
|
||||
assertContains('ключа', $error->getMessage());
|
||||
|
||||
assertThrows(static fn () => Connection::instance()->table('test_pairs')->upsert([
|
||||
['pair_key' => 'a', 'value' => 'x'],
|
||||
['value' => 'y', 'pair_key' => 'b'],
|
||||
], ['pair_key']), 'разный порядок колонок в пачке');
|
||||
});
|
||||
|
||||
test('построитель: whereDate сравнивает по дню и для dateTime, и для date', function (): void {
|
||||
withScratchTables(static function (Connection $db): void {
|
||||
foreach (['2026-10-28 23:59:59', '2026-10-29 00:00:00', '2026-10-29 12:30:00', '2026-10-29 23:59:59', '2026-10-30 00:00:00'] as $moment) {
|
||||
$db->insert('test_events', ['happened_at' => $moment, 'happened_on' => substr($moment, 0, 10)]);
|
||||
}
|
||||
|
||||
$count = static fn (string $column, string $operator, string|DateTimeInterface $date): int
|
||||
=> $db->table('test_events')->whereDate($column, $operator, $date)->count();
|
||||
|
||||
foreach (['happened_at', 'happened_on'] as $column) {
|
||||
assertSame(3, $count($column, '=', '2026-10-29'), $column . ' =');
|
||||
assertSame(2, $count($column, '<>', '2026-10-29'), $column . ' <>');
|
||||
assertSame(1, $count($column, '<', '2026-10-29'), $column . ' <');
|
||||
assertSame(4, $count($column, '<=', '2026-10-29'), $column . ' <=');
|
||||
assertSame(1, $count($column, '>', '2026-10-29'), $column . ' >');
|
||||
assertSame(4, $count($column, '>=', '2026-10-29'), $column . ' >=');
|
||||
}
|
||||
|
||||
// Объект даты: время отбрасывается, считается только день
|
||||
assertSame(3, $count('happened_at', '=', new DateTimeImmutable('2026-10-29 17:45:00')));
|
||||
});
|
||||
});
|
||||
|
||||
test('построитель: whereDate не принимает кривую дату и чужой оператор', function (): void {
|
||||
$query = static fn () => Connection::instance()->table('settings');
|
||||
|
||||
assertThrows(static fn () => $query()->whereDate('updated_at', '=', '29.10.2026'));
|
||||
assertThrows(static fn () => $query()->whereDate('updated_at', '=', '2026-02-30'), 'несуществующий день');
|
||||
assertThrows(static fn () => $query()->whereDate('updated_at', 'LIKE', '2026-10-29'));
|
||||
});
|
||||
@@ -69,3 +69,155 @@ test('HttpClient: ходит только по http и https', function (): void
|
||||
HttpClient::reset();
|
||||
}
|
||||
});
|
||||
|
||||
test('HttpClient: список заготовок выдаётся по очереди, последний повторяется', function (): void {
|
||||
HttpClient::fake(['https://api.example.com/*' => [['status' => 500], ['status' => 502], ['status' => 200, 'body' => 'ок']]]);
|
||||
|
||||
try {
|
||||
$client = new HttpClient();
|
||||
$statuses = [];
|
||||
|
||||
for ($i = 0; $i < 4; $i++) {
|
||||
$statuses[] = $client->get('https://api.example.com/orders/1')['status'];
|
||||
}
|
||||
|
||||
assertSame([500, 502, 200, 200], $statuses);
|
||||
assertSame('ок', $client->get('https://api.example.com/orders/1')['body']);
|
||||
} finally {
|
||||
HttpClient::reset();
|
||||
}
|
||||
});
|
||||
|
||||
test('HttpClient: заготовка-функция собирает ответ по запросу', function (): void {
|
||||
HttpClient::fake([
|
||||
'https://api.example.com/echo' => static fn (string $method, string $url, string $body): array => [
|
||||
'status' => 201,
|
||||
'body' => $method . ' ' . $body,
|
||||
],
|
||||
]);
|
||||
|
||||
try {
|
||||
$response = (new HttpClient())->post('https://api.example.com/echo', 'привет');
|
||||
|
||||
assertSame(201, $response['status']);
|
||||
assertSame('POST привет', $response['body']);
|
||||
} finally {
|
||||
HttpClient::reset();
|
||||
}
|
||||
});
|
||||
|
||||
test('HttpClient: reset() начинает список заготовок сначала', function (): void {
|
||||
$responses = ['*' => [['status' => 500], ['status' => 200]]];
|
||||
|
||||
HttpClient::fake($responses);
|
||||
(new HttpClient())->get('https://example.com');
|
||||
HttpClient::fake($responses);
|
||||
|
||||
try {
|
||||
assertSame(500, (new HttpClient())->get('https://example.com')['status']);
|
||||
} finally {
|
||||
HttpClient::reset();
|
||||
}
|
||||
});
|
||||
|
||||
test('HttpClient: прокси разбирается сразу, кривой адрес не принимается', function (): void {
|
||||
$parts = HttpClient::parseProxy('socks5://bot%40home:p%3Ass@10.0.0.5:1080');
|
||||
|
||||
assertSame(['type' => 'socks5', 'host' => '10.0.0.5', 'port' => 1080, 'user' => 'bot@home', 'pass' => 'p:ss'], $parts);
|
||||
assertSame('http://proxy.local:3128', (new HttpClient(5, ' http://proxy.local:3128 '))->proxy());
|
||||
assertSame('', (new HttpClient())->proxy(), 'без прокси — напрямую');
|
||||
|
||||
foreach (['ftp://proxy:21', 'socks4://proxy:1080', 'http://proxy', 'proxy.local:3128'] as $proxy) {
|
||||
assertThrows(static fn () => new HttpClient(5, $proxy), 'не должен пройти: ' . $proxy);
|
||||
}
|
||||
|
||||
assertSame('socks5://bot:***@10.0.0.5:1080', HttpClient::maskProxy('socks5://bot:secret@10.0.0.5:1080'));
|
||||
});
|
||||
|
||||
test('HttpClient: прокси попадает в записанный запрос', function (): void {
|
||||
HttpClient::fake();
|
||||
|
||||
try {
|
||||
(new HttpClient(5, 'socks5://10.0.0.5:1080'))->get('https://api.example.com/');
|
||||
(new HttpClient())->get('https://api.example.com/');
|
||||
|
||||
assertSame('socks5://10.0.0.5:1080', HttpClient::recorded()[0]['proxy']);
|
||||
assertSame('', HttpClient::recorded()[1]['proxy']);
|
||||
} finally {
|
||||
HttpClient::reset();
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Запрос через игрушечный прокси (tests/support/fake_proxy_server.php) и что
|
||||
* этот прокси увидел.
|
||||
*
|
||||
* @return array{response: array{status: int, body: string, duration: int}, report: array<string, mixed>}
|
||||
*/
|
||||
function requestThroughFakeProxy(string $mode, string $credentials, string $url): array
|
||||
{
|
||||
$token = bin2hex(random_bytes(4));
|
||||
$portFile = APP_ROOT . '/var/tmp/proxy-test-port-' . $token . '.txt';
|
||||
$logFile = APP_ROOT . '/var/tmp/proxy-test-log-' . $token . '.json';
|
||||
|
||||
$process = proc_open(
|
||||
['php', APP_ROOT . '/tests/support/fake_proxy_server.php', $portFile, $logFile, $mode],
|
||||
[1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
|
||||
$pipes
|
||||
);
|
||||
|
||||
try {
|
||||
$deadline = microtime(true) + 10;
|
||||
|
||||
while (!is_file($portFile) && microtime(true) < $deadline) {
|
||||
usleep(10000);
|
||||
}
|
||||
|
||||
$port = (int) trim((string) @file_get_contents($portFile));
|
||||
$proxy = ($mode === 'socks5' ? 'socks5' : 'http') . '://' . $credentials . '127.0.0.1:' . $port;
|
||||
$response = (new HttpClient(10, $proxy))->get($url);
|
||||
$report = json_decode((string) @file_get_contents($logFile), true);
|
||||
|
||||
return ['response' => $response, 'report' => is_array($report) ? $report : []];
|
||||
} finally {
|
||||
foreach ($pipes as $pipe) {
|
||||
@fclose($pipe);
|
||||
}
|
||||
|
||||
@proc_terminate($process);
|
||||
@proc_close($process);
|
||||
@unlink($portFile);
|
||||
@unlink($logFile);
|
||||
}
|
||||
}
|
||||
|
||||
test('HttpClient: запрос уходит через http-прокси с логином', function (): void {
|
||||
if (!function_exists('curl_init')) {
|
||||
skipTest('нет curl');
|
||||
}
|
||||
|
||||
// Хост выдуманный: дойти запрос может только через прокси
|
||||
$result = requestThroughFakeProxy('http', 'bot:secret@', 'http://service.invalid/ping?x=1');
|
||||
|
||||
assertSame(200, $result['response']['status']);
|
||||
assertSame('через прокси', $result['response']['body']);
|
||||
assertSame('GET http://service.invalid/ping?x=1 HTTP/1.1', $result['report']['request_line'] ?? '');
|
||||
assertSame('Basic ' . base64_encode('bot:secret'), $result['report']['proxy_authorization'] ?? '');
|
||||
});
|
||||
|
||||
test('HttpClient: запрос уходит через socks5, имя хоста резолвит прокси', function (): void {
|
||||
if (!function_exists('curl_init')) {
|
||||
skipTest('нет curl');
|
||||
}
|
||||
|
||||
$result = requestThroughFakeProxy('socks5', 'bot%40home:p%3Ass@', 'http://service.invalid:8080/ping');
|
||||
|
||||
assertSame(200, $result['response']['status']);
|
||||
assertSame('через прокси', $result['response']['body']);
|
||||
assertSame('bot@home', $result['report']['user'] ?? '');
|
||||
assertSame('p:ss', $result['report']['pass'] ?? '');
|
||||
assertSame(3, $result['report']['address_type'] ?? 0, 'адрес именем, а не IP: DNS на стороне прокси');
|
||||
assertSame('service.invalid', $result['report']['target_host'] ?? '');
|
||||
assertSame(8080, $result['report']['target_port'] ?? 0);
|
||||
assertSame('GET /ping HTTP/1.1', $result['report']['request_line'] ?? '');
|
||||
});
|
||||
@@ -125,3 +125,124 @@ test('настройки: база недоступна — работаем н
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Задача, которая запоминает, какое значение настройки увидела.
|
||||
*/
|
||||
final class SettingsRefreshTestJob extends Rsgrinko\Proton\Queue\Job
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function handle(array $payload): void
|
||||
{
|
||||
Setting::set('test:refresh:seen', (string) Config::get('ui.per_page'));
|
||||
}
|
||||
}
|
||||
|
||||
test('настройки: refresh() подхватывает правку из другого процесса', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
withConfig(['ui.per_page' => 25], static function (): void {
|
||||
Settings::apply();
|
||||
|
||||
assertSame(25, Config::get('ui.per_page'));
|
||||
|
||||
// Панель записала значение в базу — этот процесс о нём не знает
|
||||
Setting::set(Settings::PREFIX . 'ui.per_page', '11');
|
||||
|
||||
assertSame(25, Config::get('ui.per_page'), 'без refresh() держится прежнее');
|
||||
|
||||
Settings::refresh();
|
||||
|
||||
assertSame(11, Config::get('ui.per_page'));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('настройки: refresh() возвращает сброшенную настройку к .env', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
withConfig(['ui.per_page' => 25], static function (): void {
|
||||
Setting::set(Settings::PREFIX . 'ui.per_page', '11');
|
||||
|
||||
Settings::refresh();
|
||||
|
||||
assertSame(11, Config::get('ui.per_page'));
|
||||
|
||||
// Панель сбросила значение: строки в базе больше нет
|
||||
Setting::forget(Settings::PREFIX . 'ui.per_page');
|
||||
|
||||
Settings::refresh();
|
||||
|
||||
$fromEnv = ((array) require APP_ROOT . '/config/config.php')['ui']['per_page'] ?? null;
|
||||
|
||||
assertSame($fromEnv, Config::get('ui.per_page'), 'значение снова из .env');
|
||||
assertFalse(Settings::overridden('ui.per_page'));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('настройки: refresh() не трогает то, что база не перекрывала', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
withConfig(['ui.per_page' => 25, 'app.name' => 'Тестовое имя'], static function (): void {
|
||||
Setting::set(Settings::PREFIX . 'ui.per_page', '11');
|
||||
|
||||
Settings::refresh();
|
||||
Settings::refresh();
|
||||
|
||||
assertSame('Тестовое имя', Config::get('app.name'), 'значение не из базы остаётся как было');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('настройки: воркер видит правку из панели без перезапуска', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
withConfig(['ui.per_page' => 25], static function (): void {
|
||||
Settings::apply();
|
||||
|
||||
Setting::set(Settings::PREFIX . 'ui.per_page', '13');
|
||||
Rsgrinko\Proton\Queue\Queue::push(SettingsRefreshTestJob::class);
|
||||
|
||||
(new Rsgrinko\Proton\Queue\Worker())->run(true);
|
||||
|
||||
assertSame('13', Setting::get('test:refresh:seen'));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('настройки: дробное число принимает точку и запятую, хранится с точкой', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
Settings::register('test.ratio', 'Доля', Settings::FLOAT, 'Тест');
|
||||
|
||||
assertSame('', Settings::problem('test.ratio', '0.7'));
|
||||
assertSame('', Settings::problem('test.ratio', '0,7'));
|
||||
assertSame('', Settings::problem('test.ratio', '-2'));
|
||||
assertTrue(Settings::problem('test.ratio', 'семь') !== '');
|
||||
assertTrue(Settings::problem('test.ratio', '1.2.3') !== '');
|
||||
|
||||
Settings::put('test.ratio', '0,7');
|
||||
|
||||
assertSame('0.7', Setting::get(Settings::PREFIX . 'test.ratio'));
|
||||
assertSame(0.7, Config::get('test.ratio'));
|
||||
|
||||
Settings::refresh();
|
||||
|
||||
assertSame(0.7, Settings::value('test.ratio'), 'из базы читается числом');
|
||||
});
|
||||
});
|
||||
|
||||
test('настройки: Env::float() читает и точку, и запятую', function (): void {
|
||||
putenv('PROTON_TEST_RATIO_DOT=0.25');
|
||||
putenv('PROTON_TEST_RATIO_COMMA=0,7');
|
||||
putenv('PROTON_TEST_RATIO_EMPTY=');
|
||||
|
||||
try {
|
||||
assertSame(0.25, Rsgrinko\Proton\Support\Env::float('PROTON_TEST_RATIO_DOT'));
|
||||
assertSame(0.7, Rsgrinko\Proton\Support\Env::float('PROTON_TEST_RATIO_COMMA'));
|
||||
assertSame(1.5, Rsgrinko\Proton\Support\Env::float('PROTON_TEST_RATIO_EMPTY', 1.5), 'пусто — значение по умолчанию');
|
||||
assertSame(2.5, Rsgrinko\Proton\Support\Env::float('PROTON_TEST_RATIO_NONE', 2.5));
|
||||
} finally {
|
||||
putenv('PROTON_TEST_RATIO_DOT');
|
||||
putenv('PROTON_TEST_RATIO_COMMA');
|
||||
putenv('PROTON_TEST_RATIO_EMPTY');
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Демон в отдельном процессе — только для tests/DaemonTest.php: остановка
|
||||
* по флагу и по SIGTERM проверяется на настоящем процессе, а не на объекте
|
||||
* внутри раннера.
|
||||
*
|
||||
* Аргументы: <имя> <каталог флагов> <файл отчёта>
|
||||
* Отчёт — JSON {ticks, exit}: сколько кругов сделал и с каким кодом вышел.
|
||||
* Каждый круг дописывает отметку, по ней тест понимает, что демон работает.
|
||||
*/
|
||||
|
||||
require dirname(__DIR__, 2) . '/bootstrap.php';
|
||||
|
||||
use Rsgrinko\Proton\Console\DaemonCommand;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
|
||||
[$name, $flagsDir, $reportFile] = array_slice($argv, 1, 3) + ['', '', ''];
|
||||
|
||||
// База своя и пустая: настройки из боевой базы демону-подделке ни к чему,
|
||||
// а блокировка в SQLite — файловая
|
||||
Config::set('db', ['driver' => 'sqlite', 'sqlite' => ['path' => ':memory:']]);
|
||||
Config::set('paths.log', APP_ROOT . '/var/log/tests');
|
||||
Config::set('paths.daemon', $flagsDir);
|
||||
|
||||
$daemon = new class ($name, $reportFile) extends DaemonCommand {
|
||||
public int $ticks = 0;
|
||||
|
||||
public function __construct(private readonly string $daemonName, private readonly string $reportFile)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return $this->daemonName;
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'демон для теста';
|
||||
}
|
||||
|
||||
protected function interval(): int
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected function tick(): void
|
||||
{
|
||||
$this->ticks++;
|
||||
|
||||
file_put_contents($this->reportFile, json_encode(['ticks' => $this->ticks, 'exit' => null]));
|
||||
|
||||
usleep(50000);
|
||||
}
|
||||
};
|
||||
|
||||
$code = $daemon->withInput([], [])->run();
|
||||
|
||||
file_put_contents($reportFile, json_encode(['ticks' => $daemon->ticks, 'exit' => $code]));
|
||||
|
||||
exit($code);
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Игрушечный прокси на одно соединение — только для tests/HttpClientTest.php.
|
||||
* Настоящего прокси в окружении тестов нет, а проверить нужно настоящую ветку
|
||||
* curl: что запрос ушёл через прокси, с логином и с именем хоста, которое
|
||||
* резолвит прокси, а не мы.
|
||||
*
|
||||
* Аргументы: <файл для порта> <файл отчёта> <режим: http|socks5>
|
||||
* Отчёт — JSON: что прокси увидел (строка запроса, логин, хост назначения).
|
||||
* Ответ на любой запрос — 200 с телом «через прокси».
|
||||
*/
|
||||
|
||||
$portFile = (string) ($argv[1] ?? '');
|
||||
$logFile = (string) ($argv[2] ?? '');
|
||||
$mode = (string) ($argv[3] ?? 'http');
|
||||
|
||||
$server = stream_socket_server('tcp://127.0.0.1:0', $errno, $errstr);
|
||||
|
||||
if ($server === false) {
|
||||
fwrite(STDERR, $errstr);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$name = (string) stream_socket_get_name($server, false);
|
||||
|
||||
file_put_contents($portFile, substr($name, (int) strrpos($name, ':') + 1));
|
||||
|
||||
$client = @stream_socket_accept($server, 20);
|
||||
|
||||
if ($client === false) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
stream_set_timeout($client, 10);
|
||||
|
||||
/**
|
||||
* Ровно $length байт: fread на сокете отдаёт сколько пришло.
|
||||
*/
|
||||
function readExactly($socket, int $length): string
|
||||
{
|
||||
$data = '';
|
||||
|
||||
while (strlen($data) < $length && !feof($socket)) {
|
||||
$chunk = fread($socket, $length - strlen($data));
|
||||
|
||||
if ($chunk === false || $chunk === '') {
|
||||
break;
|
||||
}
|
||||
|
||||
$data .= $chunk;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
$report = ['mode' => $mode];
|
||||
|
||||
if ($mode === 'socks5') {
|
||||
// Приветствие: версия, число способов входа, сами способы
|
||||
[, $count] = array_values(unpack('C2', readExactly($client, 2)));
|
||||
$methods = array_values(unpack('C*', readExactly($client, $count)));
|
||||
|
||||
if (in_array(2, $methods, true)) {
|
||||
fwrite($client, "\x05\x02");
|
||||
|
||||
// Логин и пароль по RFC 1929
|
||||
readExactly($client, 1);
|
||||
$user = readExactly($client, ord(readExactly($client, 1)));
|
||||
$pass = readExactly($client, ord(readExactly($client, 1)));
|
||||
|
||||
$report['user'] = $user;
|
||||
$report['pass'] = $pass;
|
||||
|
||||
fwrite($client, "\x01\x00");
|
||||
} else {
|
||||
fwrite($client, "\x05\x00");
|
||||
}
|
||||
|
||||
// Запрос на соединение: версия, команда, резерв, тип адреса
|
||||
$head = array_values(unpack('C4', readExactly($client, 4)));
|
||||
|
||||
$report['address_type'] = $head[3];
|
||||
$report['target_host'] = match ($head[3]) {
|
||||
3 => readExactly($client, ord(readExactly($client, 1))),
|
||||
1 => inet_ntop(readExactly($client, 4)),
|
||||
default => '',
|
||||
};
|
||||
$report['target_port'] = unpack('n', readExactly($client, 2))[1];
|
||||
|
||||
fwrite($client, "\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00");
|
||||
}
|
||||
|
||||
// Дальше — обычный HTTP: прокси или туннель, нам всё равно
|
||||
$request = '';
|
||||
|
||||
while (!feof($client) && !str_contains($request, "\r\n\r\n")) {
|
||||
$line = fgets($client, 4096);
|
||||
|
||||
if ($line === false) {
|
||||
break;
|
||||
}
|
||||
|
||||
$request .= $line;
|
||||
}
|
||||
|
||||
$lines = explode("\r\n", trim($request));
|
||||
|
||||
$report['request_line'] = $lines[0] ?? '';
|
||||
|
||||
foreach ($lines as $line) {
|
||||
if (stripos($line, 'Proxy-Authorization:') === 0) {
|
||||
$report['proxy_authorization'] = trim(substr($line, strlen('Proxy-Authorization:')));
|
||||
}
|
||||
}
|
||||
|
||||
// Отчёт пишем до ответа: тест читает его сразу, как только получил ответ
|
||||
file_put_contents($logFile, json_encode($report, JSON_UNESCAPED_UNICODE));
|
||||
|
||||
$body = 'через прокси';
|
||||
|
||||
fwrite($client, "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: " . strlen($body) . "\r\nConnection: close\r\n\r\n" . $body);
|
||||
fclose($client);
|
||||
Reference in new issue
Block a user