trypost/tests/Unit/Automation/AutomationConfigValidatorTest.php
Paulo Castellano 2bd2e72656 Validate webhook payload template is JSON before it can run
A webhook node parses its payload template as JSON before resolving
placeholders, so a template with unquoted {{ }} placeholders or any malformed
JSON could be saved, tested, and activated — only to fail midway through a run.

Reject it up front instead: AutomationConfigValidator is the single source of
truth for per-node config issues (keyed to the field the editor surfaces them
under), enforced on save (field errors), on activate, and before a test run.
The editor mirrors the check to disable Test/Activate with a clear reason, and
the test panel now surfaces the server's message instead of a generic toast.
2026-06-13 16:03:19 -03:00

56 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
use App\Services\Automation\AutomationConfigValidator;
use App\Services\Automation\WebhookNodeValidator;
it('treats empty and literal-null webhook payloads as valid', function (string $template) {
$issue = app(WebhookNodeValidator::class)->issueFor(['payload_template' => $template]);
expect($issue)->toBeNull();
})->with(['', ' ', 'null']);
it('accepts a webhook payload whose placeholders are quoted valid JSON', function () {
$issue = app(WebhookNodeValidator::class)->issueFor([
'payload_template' => '{"title": "{{fetched.title}}"}',
]);
expect($issue)->toBeNull();
});
it('rejects a webhook payload that is not valid JSON', function () {
$issue = app(WebhookNodeValidator::class)->issueFor([
'payload_template' => '{"title": {{fetched.title}}}',
]);
expect($issue)->toBe(__('automations.errors.webhook_invalid_payload_json'));
});
it('reports an issue per invalid node, keyed to its field and index', function () {
$nodes = [
['type' => 'trigger', 'data' => ['trigger_type' => 'schedule']],
['type' => 'webhook', 'data' => ['payload_template' => 'not json']],
['type' => 'webhook', 'data' => ['payload_template' => '{"ok": "{{x}}"}']],
['type' => 'webhook', 'data' => ['payload_template' => '{bad']],
];
$issues = app(AutomationConfigValidator::class)->issues($nodes);
expect($issues)->toHaveCount(2)
->and($issues[0])->toMatchArray(['node_index' => 1, 'field' => 'payload_template'])
->and($issues[1]['node_index'])->toBe(3);
});
it('returns the first issue message and null when every node is valid', function () {
$validator = app(AutomationConfigValidator::class);
$invalid = [
['type' => 'webhook', 'data' => ['payload_template' => 'nope']],
['type' => 'webhook', 'data' => ['payload_template' => 'also nope']],
];
$valid = [['type' => 'webhook', 'data' => ['payload_template' => '{}']]];
expect($validator->firstMessage($invalid))->toBe(__('automations.errors.webhook_invalid_payload_json'))
->and($validator->firstMessage($valid))->toBeNull();
});