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,26 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model;
use Esun\MultiLocaleTranslation\Model\BlogPostFields;
use PHPUnit\Framework\TestCase;
class BlogPostFieldsTest extends TestCase
{
public function testUrlKeyIsNotTranslatable(): void
{
self::assertNotContains('url_key', BlogPostFields::codes());
}
public function testReadsDefaultMetaValueFromMageplazaStoreJson(): void
{
self::assertSame(
'English meta title',
BlogPostFields::baseValue('meta_title', '{"0":"English meta title","2":"French title"}')
);
self::assertSame('Plain value', BlogPostFields::baseValue('meta_title', 'Plain value'));
self::assertSame('<p>Content</p>', BlogPostFields::baseValue('post_content', '<p>Content</p>'));
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model;
use Esun\MultiLocaleTranslation\Model\BlogPostTranslationApplier;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Framework\App\State;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Model\StoreManagerInterface;
use Mageplaza\Blog\Model\Post;
use PHPUnit\Framework\TestCase;
class BlogPostTranslationApplierTest extends TestCase
{
public function testAppliesCurrentStoreTranslationToPost(): void
{
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('getTranslations')->with(
1101,
3,
CmsTranslationRepository::ENTITY_BLOG_POST,
self::isType('array')
)->willReturn(['name' => 'Deutscher Titel']);
$post = $this->createMock(Post::class);
$post->method('getId')->willReturn(1101);
$post->expects(self::once())->method('setData')->with('name', 'Deutscher Titel')->willReturnSelf();
$this->createApplier($repository)->apply($post);
}
public function testAppliesCollectionTranslationsWithOneRepositoryQuery(): void
{
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('getTranslationsForEntities')->with(
[1101, 1102],
3,
CmsTranslationRepository::ENTITY_BLOG_POST,
self::isType('array')
)->willReturn([
1101 => ['name' => 'Erster Titel'],
1102 => ['name' => 'Zweiter Titel'],
]);
$first = $this->createMock(Post::class);
$first->method('getId')->willReturn(1101);
$first->expects(self::once())->method('setData')->with('name', 'Erster Titel')->willReturnSelf();
$second = $this->createMock(Post::class);
$second->method('getId')->willReturn(1102);
$second->expects(self::once())->method('setData')->with('name', 'Zweiter Titel')->willReturnSelf();
$this->createApplier($repository)->applyMany([$first, $second]);
}
private function createApplier(CmsTranslationRepository $repository): BlogPostTranslationApplier
{
$store = $this->createMock(StoreInterface::class);
$store->method('getId')->willReturn(3);
$storeManager = $this->createMock(StoreManagerInterface::class);
$storeManager->method('getStore')->willReturn($store);
$state = $this->createMock(State::class);
$state->method('getAreaCode')->willReturn('frontend');
return new BlogPostTranslationApplier($repository, $storeManager, $state);
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Config;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Magento\Framework\App\Config\ScopeConfigInterface;
use PHPUnit\Framework\TestCase;
class SkippedFieldsTest extends TestCase
{
public function testRecognizesConfiguredFields(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->willReturn(
'product.meta_keyword, cms_page.meta_keywords'
);
$config = new SkippedFields($scopeConfig);
self::assertTrue($config->isSkipped('product', 'meta_keyword'));
self::assertTrue($config->isSkipped('cms_page', 'meta_keywords'));
self::assertFalse($config->isSkipped('product', 'name'));
}
public function testEmptyConfigurationSkipsNothing(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->willReturn(null);
self::assertFalse((new SkippedFields($scopeConfig))->isSkipped('category', 'name'));
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\Entity\BlogPostEntity;
use Mageplaza\Blog\Model\Post;
use Mageplaza\Blog\Model\PostFactory;
use PHPUnit\Framework\TestCase;
class BlogPostEntityTest extends TestCase
{
public function testLoadsSourceTranslationAndTargetFallbackFromSamePost(): void
{
$post = $this->createMock(Post::class);
$post->method('load')->with(1101)->willReturnSelf();
$post->method('getId')->willReturn(1101);
$post->method('getData')->willReturnMap([
['name', null, 'English title'],
['short_description', null, 'English summary'],
['post_content', null, '<p>English content</p>'],
['meta_title', null, 'English meta title'],
['meta_keywords', null, 'English keywords'],
['meta_description', null, 'English meta description'],
]);
$postFactory = $this->createMock(PostFactory::class);
$postFactory->method('create')->willReturn($post);
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::exactly(2))->method('getTranslations')->willReturnOnConsecutiveCalls(
['name' => 'Titre français'],
[]
);
$skippedFields = $this->createMock(SkippedFields::class);
$fields = (new BlogPostEntity($postFactory, $repository, $skippedFields))->getFields(1101, 2, 3);
self::assertSame('Titre français', $fields[0]['source_value']);
self::assertSame('English title', $fields[0]['target_value']);
self::assertTrue($fields[0]['use_default']);
self::assertSame('post_content', $fields[2]['code']);
self::assertTrue($fields[2]['is_html']);
}
public function testSavesTranslationAndDeletesUseDefaultFields(): void
{
$post = $this->createMock(Post::class);
$post->method('load')->with(1101)->willReturnSelf();
$post->method('getId')->willReturn(1101);
$postFactory = $this->createMock(PostFactory::class);
$postFactory->method('create')->willReturn($post);
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('deleteTranslations')->with(
1101,
3,
CmsTranslationRepository::ENTITY_BLOG_POST,
['meta_keywords']
);
$repository->expects(self::once())->method('saveTranslations')->with(
1101,
3,
CmsTranslationRepository::ENTITY_BLOG_POST,
['name' => 'Deutscher Titel']
);
$entity = new BlogPostEntity(
$postFactory,
$repository,
$this->createMock(SkippedFields::class)
);
$entity->apply(
1101,
3,
['name' => 'Deutscher Titel', 'url_key' => 'must-not-be-saved'],
['meta_keywords' => true]
);
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Entity;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\Entity\CategoryEntity;
use Magento\Catalog\Model\Attribute\ScopeOverriddenValue;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Catalog\Model\ResourceModel\Category as CategoryResource;
use PHPUnit\Framework\TestCase;
class CategoryEntityTest extends TestCase
{
public function testSavesTranslationUsingTargetStoreScope(): void
{
$category = $this->createMock(Category::class);
$category->expects(self::once())->method('setStoreId')->with(24)->willReturnSelf();
$category->expects(self::once())->method('load')->with(21)->willReturnSelf();
$category->method('getId')->willReturn(21);
$category->expects(self::once())->method('setData')->with('name', 'Résine très vendue')->willReturnSelf();
$categoryFactory = $this->createMock(CategoryFactory::class);
$categoryFactory->method('create')->willReturn($category);
$categoryResource = $this->createMock(CategoryResource::class);
$categoryResource->expects(self::once())->method('save')->with($category);
$entity = new CategoryEntity(
$categoryFactory,
$categoryResource,
$this->createMock(ScopeOverriddenValue::class),
$this->createMock(SkippedFields::class)
);
$entity->apply(21, 24, ['name' => 'Résine très vendue']);
}
public function testDoesNotSaveAConfiguredSkippedField(): void
{
$category = $this->createMock(Category::class);
$category->method('setStoreId')->willReturnSelf();
$category->method('load')->willReturnSelf();
$category->method('getId')->willReturn(21);
$category->expects(self::never())->method('setData');
$categoryFactory = $this->createMock(CategoryFactory::class);
$categoryFactory->method('create')->willReturn($category);
$categoryResource = $this->createMock(CategoryResource::class);
$categoryResource->expects(self::once())->method('save')->with($category);
$skippedFields = $this->createMock(SkippedFields::class);
$skippedFields->method('isSkipped')->willReturnCallback(
static fn(string $entityType, string $field): bool => $entityType === 'category' && $field === 'name'
);
$entity = new CategoryEntity(
$categoryFactory,
$categoryResource,
$this->createMock(ScopeOverriddenValue::class),
$skippedFields
);
$entity->apply(21, 24, ['name' => 'Should not be saved']);
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\Entity\WikiCategoryEntity;
use Esun\Wiki\Model\Category;
use Esun\Wiki\Model\CategoryFactory;
use PHPUnit\Framework\TestCase;
class WikiCategoryEntityTest extends TestCase
{
public function testLoadsOnlyWikiContentFieldsAndNeverUrlFields(): void
{
$category = $this->createMock(Category::class);
$category->method('load')->with(12)->willReturnSelf();
$category->method('getId')->willReturn(12);
$category->method('getData')->willReturnMap([
['title', null, 'English title'],
['summary', null, 'English summary'],
['content', null, '<p>English content</p>'],
['meta_title', null, 'English meta'],
['meta_description', null, 'English description'],
['meta_keywords', null, 'English keywords'],
]);
$factory = $this->createMock(CategoryFactory::class);
$factory->method('create')->willReturn($category);
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::exactly(2))->method('getTranslations')->willReturnOnConsecutiveCalls(
['title' => 'Deutscher Titel'],
[]
);
$fields = (new WikiCategoryEntity(
$factory,
$repository,
$this->createMock(SkippedFields::class)
))->getFields(12, 16, 17);
self::assertSame('Deutscher Titel', $fields[0]['source_value']);
self::assertSame('English title', $fields[0]['target_value']);
self::assertSame('content', $fields[2]['code']);
self::assertTrue($fields[2]['is_html']);
self::assertNotContains('slug', array_column($fields, 'code'));
self::assertNotContains('custom_url_path', array_column($fields, 'code'));
}
public function testApplyFiltersUnknownAndUrlFields(): void
{
$category = $this->createMock(Category::class);
$category->method('load')->with(12)->willReturnSelf();
$category->method('getId')->willReturn(12);
$factory = $this->createMock(CategoryFactory::class);
$factory->method('create')->willReturn($category);
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('saveTranslations')->with(
12,
17,
CmsTranslationRepository::ENTITY_WIKI_CATEGORY,
['title' => 'Translated title']
);
(new WikiCategoryEntity(
$factory,
$repository,
$this->createMock(SkippedFields::class)
))->apply(12, 17, [
'title' => 'Translated title',
'slug' => 'must-not-save',
'custom_url_path' => 'must-not-save',
]);
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\Entity\WikiHomepageEntity;
use Esun\Wiki\Model\Homepage;
use Esun\Wiki\Model\ResourceModel\Homepage\Collection;
use Esun\Wiki\Model\ResourceModel\Homepage\CollectionFactory;
use PHPUnit\Framework\TestCase;
class WikiHomepageEntityTest extends TestCase
{
public function testLoadsHomepageTranslationFields(): void
{
$homepage = $this->createMock(Homepage::class);
$homepage->method('getId')->willReturn(1);
$homepage->method('getData')->willReturnMap([
['title', null, 'Wiki'],
['content', null, '<p>Wiki content</p>'],
['meta_title', null, 'Wiki meta'],
['meta_description', null, 'Wiki description'],
['meta_keywords', null, 'Wiki keywords'],
]);
$collection = $this->createMock(Collection::class);
$collection->method('addFieldToFilter')->willReturnSelf();
$collection->method('setPageSize')->willReturnSelf();
$collection->method('getFirstItem')->willReturn($homepage);
$factory = $this->createMock(CollectionFactory::class);
$factory->method('create')->willReturn($collection);
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->method('getTranslations')->willReturn([]);
$fields = (new WikiHomepageEntity(
$factory,
$repository,
$this->createMock(SkippedFields::class)
))->getFields(1, 0, 16);
self::assertSame(['title', 'content', 'meta_title', 'meta_description', 'meta_keywords'],
array_column($fields, 'code'));
self::assertTrue($fields[1]['is_html']);
}
}
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Html;
use Esun\MultiLocaleTranslation\Model\Html\TranslatableTextExtractor;
use PHPUnit\Framework\TestCase;
class TranslatableTextExtractorTest extends TestCase
{
private TranslatableTextExtractor $extractor;
protected function setUp(): void
{
$this->extractor = new TranslatableTextExtractor();
}
public function testExtractsVisibleTextWithoutChangingMarkupOffsets(): void
{
$html = '<div data-title="Keep"> Hello <strong>world</strong>! </div>';
$fragments = $this->extractor->extract($html, 30000);
self::assertSame(['Hello', 'world', '!'], array_column($fragments, 'text'));
foreach ($fragments as $fragment) {
self::assertSame(
$fragment['text'],
substr($html, $fragment['offset'], $fragment['length'])
);
}
}
public function testIgnoresCodeAndEncodedMarkup(): void
{
$html = '<style>.hero { display:block }</style>'
. '<p>Translate me</p>'
. '<div>&lt;style&gt;.box { margin: 0 }&lt;/style&gt;</div>'
. '<script>console.log("Do not translate")</script>';
$fragments = $this->extractor->extract($html, 30000);
self::assertSame(['Translate me'], array_column($fragments, 'text'));
}
public function testExtractsVisibleTextFromPageBuilderEncodedHtml(): void
{
$html = '<div data-content-type="html" data-element="main">'
. '&lt;div class="payment-label"&gt;Payment Methods&lt;/div&gt;'
. '&lt;style&gt;.hidden { display:none }&lt;/style&gt;'
. '&lt;p&gt;Secure Checkout &amp; Payment&lt;/p&gt;'
. '&lt;img src="{{media url=payment.png}}" alt="" /&gt;'
. '</div>';
$fragments = $this->extractor->extract($html, 30000);
self::assertSame(
['Payment Methods', 'Secure Checkout &amp; Payment'],
array_column($fragments, 'text')
);
foreach ($fragments as $fragment) {
self::assertSame(
$fragment['text'],
substr($html, $fragment['offset'], $fragment['length'])
);
}
}
public function testEncodedHtmlTextCanBeReplacedWithoutChangingPageBuilderMarkup(): void
{
$html = '<div data-content-type="html">&lt;p class="message"&gt;Original Text&lt;/p&gt;</div>';
$fragments = $this->extractor->extract($html, 30000);
$fragment = $fragments[0];
$translated = substr($html, 0, $fragment['offset'])
. 'Translated Text'
. substr($html, $fragment['offset'] + $fragment['length']);
self::assertSame(
'<div data-content-type="html">&lt;p class="message"&gt;Translated Text&lt;/p&gt;</div>',
$translated
);
}
public function testSplitsLargeTextAtUtf8SafeBoundaries(): void
{
$html = '<p>' . str_repeat('多语言内容 ', 20) . '</p>';
$fragments = $this->extractor->extract($html, 40);
self::assertGreaterThan(1, count($fragments));
self::assertSame(trim(str_repeat('多语言内容 ', 20)), implode('', array_column($fragments, 'text')));
foreach ($fragments as $fragment) {
self::assertLessThanOrEqual(40, strlen($fragment['text']));
self::assertSame(1, preg_match('//u', $fragment['text']));
}
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model;
use Esun\MultiLocaleTranslation\Model\LogCleaner;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use PHPUnit\Framework\TestCase;
class LogCleanerTest extends TestCase
{
public function testClearsEveryTranslationLogRecord(): void
{
$connection = $this->createMock(AdapterInterface::class);
$connection->expects(self::once())
->method('delete')
->with('esun_localetranslation_log')
->willReturn(504);
$resourceConnection = $this->createMock(ResourceConnection::class);
$resourceConnection->method('getConnection')->willReturn($connection);
$resourceConnection->method('getTableName')->willReturn('esun_localetranslation_log');
self::assertSame(504, (new LogCleaner($resourceConnection))->clearAll());
}
}
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Provider;
use Esun\MultiLocaleTranslation\Model\Google\AccessToken;
use Esun\MultiLocaleTranslation\Model\Google\Credentials;
use Esun\MultiLocaleTranslation\Model\Html\TranslatableTextExtractor;
use Esun\MultiLocaleTranslation\Model\Provider\Google;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\HTTP\Client\CurlFactory;
use PHPUnit\Framework\TestCase;
class GoogleTest extends TestCase
{
public function testTranslatesOnlyVisibleHtmlTextAndRestoresMarkup(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('isSetFlag')->willReturn(true);
$scopeConfig->method('getValue')->willReturnCallback(
static function (string $path): string {
return match (true) {
str_ends_with($path, '/location') => 'global',
str_ends_with($path, '/timeout') => '30',
default => '',
};
}
);
$credentials = $this->createMock(Credentials::class);
$credentials->method('get')->willReturn(['project_id' => 'test-project']);
$accessToken = $this->createMock(AccessToken::class);
$accessToken->method('get')->willReturn('test-token');
$curl = $this->createMock(Curl::class);
$curl->expects(self::once())->method('post')->with(
self::stringContains('test-project/locations/global:translateText'),
self::callback(static function (string $payload): bool {
$request = json_decode($payload, true);
return $request['contents'] === ['Hello', 'world']
&& $request['mimeType'] === 'text/html'
&& !str_contains($payload, '<style>')
&& !str_contains($payload, '<strong>');
})
);
$curl->method('getStatus')->willReturn(200);
$curl->method('getBody')->willReturn(json_encode([
'translations' => [
['translatedText' => 'Bonjour'],
['translatedText' => 'monde'],
],
], JSON_THROW_ON_ERROR));
$curlFactory = $this->createMock(CurlFactory::class);
$curlFactory->method('create')->willReturn($curl);
$provider = new Google(
$scopeConfig,
$credentials,
$accessToken,
$curlFactory,
new TranslatableTextExtractor()
);
$source = '<style>.hidden{display:none}</style><p>Hello <strong>world</strong></p>';
$result = $provider->translate([
'content' => ['value' => $source, 'is_html' => true],
], 'en', 'fr');
self::assertSame(
'<style>.hidden{display:none}</style><p>Bonjour <strong>monde</strong></p>',
$result['content']
);
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Queue;
use Esun\MultiLocaleTranslation\Model\Queue\CronConsumer;
use Esun\MultiLocaleTranslation\Model\Queue\QueueProcessor;
use Magento\Framework\App\Config\ScopeConfigInterface;
use PHPUnit\Framework\TestCase;
class CronConsumerTest extends TestCase
{
public function testUsesConfiguredQueueLimits(): void
{
$processor = $this->createMock(QueueProcessor::class);
$processor->expects(self::once())->method('process')->with(10, 50);
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->willReturnCallback(
static fn(string $path): string => str_ends_with($path, 'tasks_per_run') ? '10' : '50'
);
(new CronConsumer($processor, $scopeConfig))->execute();
}
public function testClampsQueueLimitsToAllowedRange(): void
{
$processor = $this->createMock(QueueProcessor::class);
$processor->expects(self::once())->method('process')->with(50, 10);
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->willReturnCallback(
static fn(string $path): string => str_ends_with($path, 'tasks_per_run') ? '999' : '1'
);
(new CronConsumer($processor, $scopeConfig))->execute();
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Queue;
use Esun\MultiLocaleTranslation\Model\EntityPool;
use Esun\MultiLocaleTranslation\Model\ProviderConfig;
use Esun\MultiLocaleTranslation\Model\Queue\QueueManager;
use Esun\MultiLocaleTranslation\Model\StoreViewProvider;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\DB\Select;
use PHPUnit\Framework\TestCase;
class QueueManagerTest extends TestCase
{
public function testClearsEveryQueueRecord(): void
{
$select = $this->createMock(Select::class);
$select->method('from')->willReturnSelf();
$select->method('where')->willReturnSelf();
$connection = $this->createMock(AdapterInterface::class);
$connection->method('select')->willReturn($select);
$connection->method('fetchOne')->willReturn('2');
$connection->expects(self::once())
->method('delete')
->with('esun_localetranslation_queue')
->willReturn(18);
$resourceConnection = $this->createMock(ResourceConnection::class);
$resourceConnection->method('getConnection')->willReturn($connection);
$resourceConnection->method('getTableName')->willReturn('esun_localetranslation_queue');
$manager = new QueueManager(
$resourceConnection,
$this->createMock(EntityPool::class),
$this->createMock(ProviderConfig::class),
$this->createMock(StoreViewProvider::class)
);
self::assertSame(['deleted' => 18, 'processing' => 2], $manager->clearAll());
}
}
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Queue;
use Esun\MultiLocaleTranslation\Api\TranslationProviderInterface;
use Esun\MultiLocaleTranslation\Model\EntityPool;
use Esun\MultiLocaleTranslation\Model\LocaleResolver;
use Esun\MultiLocaleTranslation\Model\ProviderPool;
use Esun\MultiLocaleTranslation\Model\Queue\QueueProcessor;
use Esun\MultiLocaleTranslation\Model\TranslatableEntityInterface;
use Esun\MultiLocaleTranslation\Model\TranslationLogger;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\DB\Select;
use PHPUnit\Framework\TestCase;
class QueueProcessorTest extends TestCase
{
public function testProcessesAndSavesOnePendingTask(): void
{
$select = $this->createMock(Select::class);
$select->method('from')->willReturnSelf();
$select->method('where')->willReturnSelf();
$select->method('order')->willReturnSelf();
$select->method('limit')->willReturnSelf();
$connection = $this->createMock(AdapterInterface::class);
$connection->method('select')->willReturn($select);
$connection->method('fetchOne')->willReturn(10);
$connection->method('fetchRow')->willReturn([
'queue_id' => 10,
'provider' => 'deepl',
'entity_type' => 'cms_page',
'entity_id' => 5,
'source_store_id' => 0,
'target_store_id' => 2,
]);
$connection->expects(self::exactly(2))->method('update')->willReturn(1);
$resourceConnection = $this->createMock(ResourceConnection::class);
$resourceConnection->method('getConnection')->willReturn($connection);
$resourceConnection->method('getTableName')->willReturn('esun_localetranslation_queue');
$entity = $this->createMock(TranslatableEntityInterface::class);
$entity->method('getFields')->with(5, 0, 2)->willReturn([
[
'code' => 'title',
'source_value' => 'About us',
'target_value' => '',
'is_html' => false,
'use_default' => true,
],
]);
$entity->expects(self::once())->method('apply')->with(5, 2, ['title' => 'À propos']);
$entityPool = new EntityPool(['cms_page' => $entity]);
$provider = $this->createMock(TranslationProviderInterface::class);
$provider->expects(self::once())->method('translate')
->with(['title' => ['value' => 'About us', 'is_html' => false]], 'EN', 'FR')
->willReturn(['title' => 'À propos']);
$providerPool = new ProviderPool(['deepl' => $provider]);
$localeResolver = $this->createMock(LocaleResolver::class);
$localeResolver->method('getLanguageCode')->willReturnMap([
[0, 'deepl', false, 'EN'],
[2, 'deepl', true, 'FR'],
]);
$logger = $this->createMock(TranslationLogger::class);
$logger->expects(self::once())->method('logSuccess');
$processor = new QueueProcessor(
$resourceConnection,
$entityPool,
$providerPool,
$localeResolver,
$logger
);
self::assertSame(1, $processor->process(1));
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model;
use Esun\MultiLocaleTranslation\Model\Html\TranslatableTextExtractor;
use Esun\MultiLocaleTranslation\Model\TranslationLogger;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use PHPUnit\Framework\TestCase;
class TranslationLoggerTest extends TestCase
{
public function testHtmlLogContainsOnlyVisibleText(): void
{
$connection = $this->createMock(AdapterInterface::class);
$connection->expects(self::once())
->method('insertMultiple')
->with(
'esun_localetranslation_log',
self::callback(static function (array $rows): bool {
return $rows[0]['source_text'] === "Hello\nworld"
&& $rows[0]['translated_text'] === "Bonjour\nmonde"
&& $rows[0]['character_count'] === 11
&& !str_contains($rows[0]['source_text'], 'display:none');
})
);
$resourceConnection = $this->createMock(ResourceConnection::class);
$resourceConnection->method('getConnection')->willReturn($connection);
$resourceConnection->method('getTableName')->willReturn('esun_localetranslation_log');
$logger = new TranslationLogger($resourceConnection, new TranslatableTextExtractor());
$logger->logSuccess(
'deepl',
'cms_page',
5,
0,
2,
'EN',
'FR',
[
'content' => [
'value' => '<style>.hidden{display:none}</style><p>Hello <strong>world</strong></p>',
'is_html' => true,
],
],
[
'content' => '<style>.hidden{display:none}</style><p>Bonjour <strong>monde</strong></p>',
]
);
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\WikiTranslationApplier;
use Esun\Wiki\Model\Category;
use Magento\Framework\App\State;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Model\StoreManagerInterface;
use PHPUnit\Framework\TestCase;
class WikiTranslationApplierTest extends TestCase
{
public function testAppliesCategoryCollectionTranslationsInOneQuery(): void
{
$first = $this->createMock(Category::class);
$first->method('getId')->willReturn(12);
$first->expects(self::once())->method('setData')->with('title', 'Titel 12');
$second = $this->createMock(Category::class);
$second->method('getId')->willReturn(13);
$second->expects(self::once())->method('setData')->with('summary', 'Zusammenfassung 13');
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('getTranslationsForEntities')->with(
[12, 13],
16,
CmsTranslationRepository::ENTITY_WIKI_CATEGORY,
self::isType('array')
)->willReturn([
12 => ['title' => 'Titel 12'],
13 => ['summary' => 'Zusammenfassung 13'],
]);
$store = $this->createMock(StoreInterface::class);
$store->method('getId')->willReturn(16);
$storeManager = $this->createMock(StoreManagerInterface::class);
$storeManager->method('getStore')->willReturn($store);
$state = $this->createMock(State::class);
$state->method('getAreaCode')->willReturn('frontend');
(new WikiTranslationApplier($repository, $storeManager, $state))->applyMany([$first, $second]);
}
}
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Plugin\Adminhtml;
use Esun\MultiLocaleTranslation\Plugin\Adminhtml\BlogPostEditButton;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\AuthorizationInterface;
use Magento\Framework\Registry;
use Mageplaza\Blog\Block\Adminhtml\Post\Edit;
use Mageplaza\Blog\Model\Post;
use PHPUnit\Framework\TestCase;
class BlogPostEditButtonTest extends TestCase
{
public function testAddsTranslateButtonThroughContainerApi(): void
{
$post = $this->createMock(Post::class);
$post->method('getId')->willReturn(1);
$registry = $this->createMock(Registry::class);
$registry->method('registry')->with('mageplaza_blog_post')->willReturn($post);
$authorization = $this->createMock(AuthorizationInterface::class);
$authorization->method('isAllowed')->with(
'Esun_MultiLocaleTranslation::translate_blog'
)->willReturn(true);
$request = $this->createMock(RequestInterface::class);
$request->method('getParam')->with('store')->willReturn(16);
$subject = $this->createMock(Edit::class);
$subject->method('getRequest')->willReturn($request);
$subject->method('getUrl')->willReturnCallback(
static fn (string $route): string => '/' . $route
);
$subject->expects(self::once())->method('addButton')->with(
'localetranslate_translate',
self::callback(
static fn (array $data): bool => (string)$data['label'] === 'Translate'
&& str_contains($data['onclick'], '"entityType":"blog_post"')
&& str_contains($data['onclick'], '"sourceStoreId":16')
),
0,
30
);
$plugin = new BlogPostEditButton($registry, $authorization);
self::assertSame([], $plugin->beforeToHtml($subject));
}
}
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Plugin\Adminhtml;
use Esun\MultiLocaleTranslation\Model\Entity\BlogPostEntity;
use Esun\MultiLocaleTranslation\Plugin\Adminhtml\BlogPostSave;
use Magento\Framework\App\Cache\Manager as CacheManager;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\AuthorizationInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
use Mageplaza\Blog\Controller\Adminhtml\Post\Save;
use PHPUnit\Framework\TestCase;
class BlogPostSaveTest extends TestCase
{
public function testDefaultScopeUsesMageplazaSaveController(): void
{
$request = $this->createMock(RequestInterface::class);
$request->method('getParam')->with('post', [])->willReturn([]);
$plugin = $this->createPlugin($request);
$expected = new \stdClass();
self::assertSame(
$expected,
$plugin->aroundExecute($this->createMock(Save::class), static fn () => $expected)
);
}
public function testStoreScopeSavesOnlyTranslatedFieldWhitelist(): void
{
$request = $this->createMock(RequestInterface::class);
$request->method('getParam')->willReturnCallback(
static fn (string $name, mixed $default = null): mixed => match ($name) {
'post' => [
'translation_store_id' => 16,
'name' => 'Translated post',
'url_key' => 'must-not-be-saved',
'image' => 'must-not-be-saved.jpg',
'use_default' => ['meta_keywords' => '1'],
],
'id' => 1,
default => $default,
}
);
$entity = $this->createMock(BlogPostEntity::class);
$entity->expects(self::once())->method('apply')->with(
1,
16,
['name' => 'Translated post'],
['meta_keywords' => '1']
);
$redirect = $this->createMock(Redirect::class);
$redirect->expects(self::once())->method('setPath')->with(
'mageplaza_blog/post/edit',
['id' => 1, 'store' => 16]
)->willReturnSelf();
$redirectFactory = $this->createMock(RedirectFactory::class);
$redirectFactory->method('create')->willReturn($redirect);
$cacheManager = $this->createMock(CacheManager::class);
$cacheManager->expects(self::once())->method('clean')->with(['full_page', 'block_html']);
$authorization = $this->createMock(AuthorizationInterface::class);
$authorization->method('isAllowed')->willReturn(true);
$plugin = new BlogPostSave(
$request,
$entity,
$redirectFactory,
$this->createMock(ManagerInterface::class),
$cacheManager,
$authorization
);
self::assertSame(
$redirect,
$plugin->aroundExecute(
$this->createMock(Save::class),
static fn () => self::fail('The Mageplaza save controller must not run for a translated scope.')
)
);
}
private function createPlugin(RequestInterface $request): BlogPostSave
{
return new BlogPostSave(
$request,
$this->createMock(BlogPostEntity::class),
$this->createMock(RedirectFactory::class),
$this->createMock(ManagerInterface::class),
$this->createMock(CacheManager::class),
$this->createMock(AuthorizationInterface::class)
);
}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Plugin\Blog;
use Esun\MultiLocaleTranslation\Model\BlogPostTranslationApplier;
use Esun\MultiLocaleTranslation\Plugin\Blog\ApplyStoreTranslationToPostCollection;
use Mageplaza\Blog\Model\ResourceModel\Post\Collection;
use PHPUnit\Framework\TestCase;
class ApplyStoreTranslationToPostCollectionTest extends TestCase
{
public function testNestedLoadDoesNotApplyCollectionTwice(): void
{
$collection = $this->createMock(Collection::class);
$applier = $this->createMock(BlogPostTranslationApplier::class);
$plugin = new ApplyStoreTranslationToPostCollection($applier);
$collection->expects(self::once())->method('getItems')->willReturnCallback(
function () use ($plugin, $collection): array {
$plugin->afterLoad($collection, $collection);
return [];
}
);
$applier->expects(self::once())->method('applyMany')->with([]);
self::assertSame($collection, $plugin->afterLoad($collection, $collection));
}
}
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Ui\Component\Listing\Column;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\StoreViewProvider;
use Esun\MultiLocaleTranslation\Ui\Component\Listing\Column\TranslatedLanguages;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use PHPUnit\Framework\TestCase;
class TranslatedLanguagesTest extends TestCase
{
public function testShowsSavedLanguagesAndCombinesDuplicateLocales(): void
{
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('getTranslatedStoreIdsForEntities')
->with([5], CmsTranslationRepository::ENTITY_PAGE)
->willReturn([5 => [22, 24, 33]]);
$stores = $this->createMock(StoreViewProvider::class);
$stores->method('getStoreViewOptions')->willReturn([
['store_id' => 22, 'code' => 'de_EU', 'label' => 'German', 'website' => 'EU Website', 'locale' => 'de_DE'],
['store_id' => 24, 'code' => 'fr_US', 'label' => 'French', 'website' => 'US Website', 'locale' => 'fr_FR'],
['store_id' => 33, 'code' => 'fr_EU', 'label' => 'French', 'website' => 'EU Website', 'locale' => 'fr_FR'],
]);
$column = new TranslatedLanguages(
$this->createMock(ContextInterface::class),
$this->createMock(UiComponentFactory::class),
$repository,
$stores,
[],
['name' => 'esun_translations', 'config' => ['entityType' => 'page', 'indexField' => 'page_id']]
);
$result = $column->prepareDataSource(['data' => ['items' => [['page_id' => 5]]]]);
$html = (string)$result['data']['items'][0]['esun_translations'];
self::assertStringContainsString('>DE</span>', $html);
self::assertStringContainsString('>FR</span>', $html);
self::assertSame(1, substr_count($html, '>FR</span>'));
self::assertStringContainsString('French / US Website (fr_US)', $html);
self::assertStringContainsString('French / EU Website (fr_EU)', $html);
}
public function testShowsNotTranslatedWhenNoSavedTranslationExists(): void
{
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->method('getTranslatedStoreIdsForEntities')->willReturn([]);
$stores = $this->createMock(StoreViewProvider::class);
$stores->method('getStoreViewOptions')->willReturn([]);
$column = new TranslatedLanguages(
$this->createMock(ContextInterface::class),
$this->createMock(UiComponentFactory::class),
$repository,
$stores,
[],
['name' => 'esun_translations']
);
$result = $column->prepareDataSource(['data' => ['items' => [['page_id' => 8]]]]);
self::assertStringContainsString(
'Not Translated',
(string)$result['data']['items'][0]['esun_translations']
);
}
public function testUsesConfiguredEntityTypeAndIndexField(): void
{
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('getTranslatedStoreIdsForEntities')
->with([12], CmsTranslationRepository::ENTITY_BLOCK)
->willReturn([]);
$stores = $this->createMock(StoreViewProvider::class);
$stores->method('getStoreViewOptions')->willReturn([]);
$column = new TranslatedLanguages(
$this->createMock(ContextInterface::class),
$this->createMock(UiComponentFactory::class),
$repository,
$stores,
[],
[
'name' => 'esun_translations',
'config' => ['entityType' => CmsTranslationRepository::ENTITY_BLOCK, 'indexField' => 'block_id'],
]
);
$column->prepareDataSource(['data' => ['items' => [['block_id' => 12]]]]);
}
}