This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
namespace Esun\Translation\Test\Unit\Model\Ai;
use Esun\Translation\Model\Ai\OpenAiCompatibleTranslator;
use Esun\Translation\Model\Config;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\Serialize\Serializer\Json;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use ReflectionMethod;
class OpenAiCompatibleTranslatorTest extends TestCase
{
public function testItAcceptsSchemaCompliantTranslations(): void
{
$translator = $this->createTranslator();
self::assertSame(
['name' => 'PLA-Matte DE'],
$this->normalize($translator, ['name' => 'PLA-Matte'], ['translations' => ['name' => 'PLA-Matte DE']])
);
}
public function testItRejectsMissingTranslationKeys(): void
{
$translator = $this->createTranslator();
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('AI response is missing translation key "name".');
$this->normalize($translator, ['name' => 'PLA-Matte'], ['translations' => []]);
}
public function testItRejectsUnexpectedTranslationKeys(): void
{
$translator = $this->createTranslator();
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('AI response contains unexpected translation key "description".');
$this->normalize(
$translator,
['name' => 'PLA-Matte'],
['translations' => ['name' => 'PLA-Matte DE', 'description' => 'Beschreibung']]
);
}
public function testItRejectsResponsesWithoutTranslationsObject(): void
{
$translator = $this->createTranslator();
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('AI response must be a JSON object with a "translations" object.');
$this->normalize($translator, ['name' => 'PLA-Matte'], ['name' => 'PLA-Matte DE']);
}
public function testItUsesExplicitTranslationsPromptWhenJsonSchemaIsUnsupported(): void
{
$config = $this->createMock(Config::class);
$config->method('getApiKey')->willReturn('test-key');
$config->method('getApiBaseUrl')->willReturn('https://example.test');
$config->method('getModel')->willReturn('test-model');
$config->method('getTemperature')->willReturn(0.2);
$config->method('getTimeout')->willReturn(10);
$json = new Json();
$payloads = [];
$curl = $this->createMock(Curl::class);
$curl->method('setTimeout');
$curl->method('addHeader');
$curl->expects(self::exactly(2))
->method('post')
->willReturnCallback(function (string $url, string $payload) use (&$payloads): void {
$payloads[] = json_decode($payload, true, 512, JSON_THROW_ON_ERROR);
});
$curl->expects(self::exactly(2))
->method('getStatus')
->willReturnOnConsecutiveCalls(400, 200);
$curl->expects(self::exactly(2))
->method('getBody')
->willReturnOnConsecutiveCalls(
'{"error":{"message":"This response_format type is unavailable now"}}',
'{"choices":[{"message":{"content":"{\"translations\":{\"name\":\"PLA-Matte\"}}"}}]}'
);
$translator = new OpenAiCompatibleTranslator(
$config,
$curl,
$json,
$this->createMock(LoggerInterface::class)
);
self::assertSame(['name' => 'PLA-Matte'], $translator->translate(['name' => 'PLA-Matte'], 'en', 'de'));
self::assertSame('json_schema', $payloads[0]['response_format']['type']);
self::assertSame('json_object', $payloads[1]['response_format']['type']);
self::assertStringContainsString('{"translations":{"field_key":"translated text"}}', $payloads[1]['messages'][0]['content']);
self::assertStringContainsString('__ESUN_TRANSLATION_PRESERVE_0__', $payloads[1]['messages'][0]['content']);
}
/**
* @param array<string, string> $sourceTexts
* @param array<mixed> $translated
* @return array<string, string>
*/
private function normalize(OpenAiCompatibleTranslator $translator, array $sourceTexts, array $translated): array
{
$method = new ReflectionMethod(OpenAiCompatibleTranslator::class, 'normalizeTranslations');
$method->setAccessible(true);
return $method->invoke($translator, $sourceTexts, $translated);
}
private function createTranslator(?LoggerInterface $logger = null): OpenAiCompatibleTranslator
{
return new OpenAiCompatibleTranslator(
$this->createMock(Config::class),
$this->createMock(Curl::class),
new Json(),
$logger ?: $this->createMock(LoggerInterface::class)
);
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Esun\Translation\Test\Unit\Model\Ai;
use Esun\Translation\Model\Ai\ProtectedTextProcessor;
use PHPUnit\Framework\TestCase;
class ProtectedTextProcessorTest extends TestCase
{
public function testItRestoresProtectedTokens(): void
{
$processor = new ProtectedTextProcessor();
[$protected, $map] = $processor->protect('Use {{media url="a.jpg"}} and https://example.com/%1.');
self::assertStringContainsString('__ESUN_TRANSLATION_PRESERVE_0__', $protected);
self::assertSame(
'Use {{media url="a.jpg"}} and https://example.com/%1.',
$processor->restore($protected, $map)
);
}
public function testItRejectsMissingProtectedTokens(): void
{
$processor = new ProtectedTextProcessor();
[, $map] = $processor->protect('Use {{media url="a.jpg"}}.');
$this->expectException(\RuntimeException::class);
$processor->restore('translated without token', $map);
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Esun\Translation\Test\Unit\Model\Entity;
use Esun\Translation\Api\TranslatableEntityInterface;
use Esun\Translation\Model\Entity\EntityPool;
use PHPUnit\Framework\TestCase;
class EntityPoolTest extends TestCase
{
public function testItReturnsConfiguredEntity(): void
{
$entity = $this->createMock(TranslatableEntityInterface::class);
$pool = new EntityPool(['cms_page' => $entity]);
self::assertSame($entity, $pool->get('cms_page'));
self::assertSame(['cms_page'], $pool->getTypes());
}
public function testItRejectsUnsupportedEntityType(): void
{
$pool = new EntityPool();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Unsupported translation entity type "unknown".');
$pool->get('unknown');
}
}
@@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace Esun\Translation\Test\Unit\Model\Html;
use Esun\Translation\Model\Html\HtmlTextExtractor;
use Esun\Translation\Model\Html\HtmlTranslationValidator;
use PHPUnit\Framework\TestCase;
class HtmlTextExtractorTest extends TestCase
{
public function testItTranslatesTextNodesWithoutChangingTags(): void
{
$extractor = new HtmlTextExtractor();
$fragment = $extractor->extract(
'<p class="intro">Fast <strong>printing</strong> {{media url="a.jpg"}}</p><img src="a.jpg">'
);
self::assertSame(
['html_0' => 'Fast ', 'html_1' => 'printing', 'html_2' => ' {{media url="a.jpg"}}'],
$fragment->getTexts()
);
$html = $fragment->applyTranslations([
'html_0' => 'Schneller ',
'html_1' => 'Druck',
'html_2' => ' {{media url="a.jpg"}}',
]);
self::assertStringContainsString('<p class="intro">Schneller <strong>Druck</strong>', $html);
self::assertStringContainsString('<img src="a.jpg">', $html);
}
public function testItPreservesMagentoDirectivesInsideHtmlAttributes(): void
{
$extractor = new HtmlTextExtractor();
$fragment = $extractor->extract(
'<figure class="pagebuilder-image">'
. '<img src="{{media url=wysiwyg/precision.png}}" alt="Precision image">'
. '<figcaption>High precision sample image</figcaption>'
. '</figure>'
);
$html = $fragment->applyTranslations([
'html_0' => 'Hochpraezises Beispielbild',
]);
self::assertStringContainsString('src="{{media url=wysiwyg/precision.png}}"', $html);
self::assertStringNotContainsString('%7B%7Bmedia%20url=wysiwyg/precision.png%7D%7D', $html);
self::assertStringContainsString('<figcaption>Hochpraezises Beispielbild</figcaption>', $html);
}
public function testItPreservesQuotedMagentoDirectivesInsideHtmlAttributes(): void
{
$extractor = new HtmlTextExtractor();
$fragment = $extractor->extract(
'<figure class="pagebuilder-image">'
. '<img src="{{media url=".renditions/wysiwyg/product_details/petg_luminous_filament.png"}}"'
. ' alt="" width="1000" height="444">'
. '<figcaption>PETG luminous filament</figcaption>'
. '</figure>'
);
$html = $fragment->applyTranslations([
'html_0' => 'PETG-Leuchtfilament',
]);
self::assertStringContainsString(
'src="{{media url=".renditions/wysiwyg/product_details/petg_luminous_filament.png"}}"',
$html
);
self::assertStringNotContainsString('&quot;.renditions/wysiwyg/product_details/petg_luminous_filament.png&quot;', $html);
self::assertStringContainsString('<figcaption>PETG-Leuchtfilament</figcaption>', $html);
}
public function testItNormalizesEncodedDirectiveQuotesInsideHtmlAttributes(): void
{
$extractor = new HtmlTextExtractor();
$fragment = $extractor->extract(
'<figure class="pagebuilder-image">'
. '<img src="{{media url=&quot;.renditions/wysiwyg/product_details/petg_luminous_filament.png&quot;}}"'
. ' alt="" width="1000" height="444">'
. '<figcaption>PETG luminous filament</figcaption>'
. '</figure>'
);
$html = $fragment->applyTranslations([
'html_0' => 'PETG-Leuchtfilament',
]);
self::assertStringContainsString(
'src="{{media url=".renditions/wysiwyg/product_details/petg_luminous_filament.png"}}"',
$html
);
self::assertStringNotContainsString('&quot;.renditions/wysiwyg/product_details/petg_luminous_filament.png&quot;', $html);
self::assertStringContainsString('<figcaption>PETG-Leuchtfilament</figcaption>', $html);
}
public function testValidatorRejectsDangerousHtml(): void
{
$validator = new HtmlTranslationValidator();
self::assertSame([], $validator->validate('<p>Safe content</p>'));
self::assertNotSame([], $validator->validate('<p onclick="alert(1)">Unsafe</p>'));
self::assertNotSame([], $validator->validate('<script>alert(1)</script>'));
}
public function testValidatorAllowsPageBuilderFigureHtml(): void
{
$validator = new HtmlTranslationValidator();
self::assertSame(
[],
$validator->validate(
'<figure class="pagebuilder-image" data-content-type="image">'
. '<img src="{{media url=.renditions/wysiwyg/product_details/demo.png}}" alt="">'
. '<figcaption>Product image</figcaption>'
. '</figure>'
)
);
}
}