Skip to content

Commit e8be281

Browse files
committed
[WIP][TASK] Refactor tests
The tests used a php mocking system, which did not respect the TYPO3 configurations for HTTP and used the functionality of cURL requests instead of the TYPO3 RequestFactory, which respects all settings. This has bad impacts on testing, in special for proxy and building correct requests against the DeepL API. Therefore, the AbstractDeepLTestCase is refactored using proper TYPO3 configuration.
1 parent 50f6b2a commit e8be281

File tree

9 files changed

+58
-138
lines changed

9 files changed

+58
-138
lines changed

Classes/AbstractClient.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,23 @@ abstract class AbstractClient implements ClientInterface
2222

2323
protected LoggerInterface $logger;
2424

25+
/**
26+
* Copied from TranslatorOptions
27+
* for iterating over Client Configuration
28+
* @see TranslatorOptions::OPTIONS_KEYS
29+
*/
30+
private const OPTIONS_KEYS = [
31+
TranslatorOptions::SERVER_URL,
32+
TranslatorOptions::HEADERS,
33+
TranslatorOptions::TIMEOUT,
34+
TranslatorOptions::MAX_RETRIES,
35+
TranslatorOptions::PROXY,
36+
TranslatorOptions::LOGGER,
37+
TranslatorOptions::HTTP_CLIENT,
38+
TranslatorOptions::SEND_PLATFORM_INFO,
39+
TranslatorOptions::APP_INFO,
40+
];
41+
2542
public function __construct(ConfigurationInterface $configuration)
2643
{
2744
$this->configuration = $configuration;
@@ -46,6 +63,11 @@ protected function getTranslator(): Translator
4663
throw new ApiKeyNotSetException('The api key ist not set', 1708081233823);
4764
}
4865
$options[TranslatorOptions::HTTP_CLIENT] = GeneralUtility::makeInstance(GuzzleClientFactory::class)->getClient();
66+
foreach (self::OPTIONS_KEYS as $option) {
67+
if ($options[TranslatorOptions::HTTP_CLIENT]->getConfig($option) !== null) {
68+
$options[$option] = $options[TranslatorOptions::HTTP_CLIENT]->getConfig($option);
69+
}
70+
}
4971
$this->translator = new Translator($this->configuration->getApiKey(), $options);
5072
return $this->translator;
5173
}

Classes/Client.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@
1212
use DeepL\TextResult;
1313
use DeepL\TranslateTextOptions;
1414
use DeepL\Usage;
15+
use Symfony\Component\DependencyInjection\Attribute\AsAlias;
1516
use WebVision\Deepltranslate\Core\Exception\ApiKeyNotSetException;
1617

1718
/**
1819
* @internal No public usage
1920
*/
21+
#[AsAlias(id: ClientInterface::class, public: true)]
2022
final class Client extends AbstractClient
2123
{
2224
/**

Tests/Functional/AbstractDeepLTestCase.php

Lines changed: 9 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,17 @@
44

55
namespace WebVision\Deepltranslate\Core\Tests\Functional;
66

7-
use Closure;
8-
use DeepL\Translator;
97
use DeepL\TranslatorOptions;
108
use Exception;
11-
use phpmock\phpunit\PHPMock;
12-
use Psr\Log\NullLogger;
139
use Ramsey\Uuid\Uuid;
1410
use RuntimeException;
1511
use SBUERK\TYPO3\Testing\TestCase\FunctionalTestCase;
16-
use Symfony\Component\DependencyInjection\Container;
1712
use TYPO3\CMS\Core\Information\Typo3Version;
13+
use TYPO3\CMS\Core\Utility\ArrayUtility;
1814
use TYPO3\CMS\Core\Utility\StringUtility;
19-
use WebVision\Deepltranslate\Core\Client;
20-
use WebVision\Deepltranslate\Core\ClientInterface;
21-
use WebVision\Deepltranslate\Core\ConfigurationInterface;
2215

2316
abstract class AbstractDeepLTestCase extends FunctionalTestCase
2417
{
25-
use PHPMock;
2618

2719
/**
2820
* @var string
@@ -113,7 +105,6 @@ abstract class AbstractDeepLTestCase extends FunctionalTestCase
113105
'web-vision/deepl-base',
114106
'web-vision/deeplcom-deepl-php',
115107
'web-vision/deepltranslate-core',
116-
__DIR__ . '/Fixtures/Extensions/test_services_override',
117108
];
118109

119110
protected const EXAMPLE_DOCUMENT_INPUT = AbstractDeepLTestCase::EXAMPLE_TEXT['en'];
@@ -153,13 +144,13 @@ protected function setUp(): void
153144
}
154145
$this->authKey = getenv('DEEPL_AUTH_KEY');
155146
}
156-
parent::setUp();
157147
$this->instantiateMockServerClient();
148+
parent::setUp();
158149
}
159150

160151
private function makeSessionName(): string
161152
{
162-
return sprintf('%s/%s', self::getInstanceIdentifier(), StringUtility::getUniqueId());
153+
return sprintf('%s/%s', self::getInstanceIdentifier(), StringUtility::getUniqueId('deepl-mock-'));
163154
}
164155

165156
/**
@@ -211,29 +202,12 @@ protected function instantiateMockServerClient(array $options = []): void
211202
if ($this->serverUrl !== false) {
212203
$mergedOptions[TranslatorOptions::SERVER_URL] = $this->serverUrl;
213204
}
214-
$mockConfiguration = $this
215-
->getMockBuilder(ConfigurationInterface::class)
216-
->getMock();
217-
$mockConfiguration
218-
->method('getApiKey')
219-
->willReturn(self::getInstanceIdentifier());
220-
221-
$client = new Client($mockConfiguration);
222-
$client->setLogger(new NullLogger());
223-
224-
// use closure to set private option for translation
225-
$translator = new Translator(self::getInstanceIdentifier(), $mergedOptions);
226-
Closure::bind(
227-
function (Translator $translator) {
228-
$this->translator = $translator;
229-
},
230-
$client,
231-
Client::class
232-
)->call($client, $translator);
233-
234-
/** @var Container $container */
235-
$container = $this->getContainer();
236-
$container->set(ClientInterface::class, $client);
205+
ArrayUtility::mergeRecursiveWithOverrule(
206+
$this->configurationToUseInTestInstance,
207+
[
208+
'HTTP' => $mergedOptions,
209+
],
210+
);
237211
}
238212

239213
public static function readFile(string $filepath): string
@@ -302,20 +276,4 @@ public function assertExceptionClass(string $class, callable $function): Excepti
302276
}
303277
static::fail("Expected exception of class '$class' but nothing was thrown");
304278
}
305-
306-
/**
307-
* This is necessary due to https://github.com/php-mock/php-mock-phpunit#restrictions
308-
* In short, as these methods can be called by other tests before UserAgentTest and other
309-
* tests that use their mocks are executed, we need to call `defineFunctionMock` before
310-
* calling the unmocked function, or the mock will not work.
311-
* Otherwise the tests will fail with:
312-
* Expectation failed for method name is "delegate" when invoked 1 time(s).
313-
* Method was expected to be called 1 times, actually called 0 times.
314-
*/
315-
public static function setUpBeforeClass(): void
316-
{
317-
self::defineFunctionMock(__NAMESPACE__, 'curl_exec');
318-
self::defineFunctionMock(__NAMESPACE__, 'curl_getinfo');
319-
self::defineFunctionMock(__NAMESPACE__, 'curl_setopt_array');
320-
}
321279
}

Tests/Functional/Container/ContentElementsInContainerTest.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ final class ContentElementsInContainerTest extends AbstractDeepLTestCase
2424
'web-vision/deepl-base',
2525
'web-vision/deeplcom-deepl-php',
2626
'web-vision/deepltranslate-core',
27-
__DIR__ . '/../Fixtures/Extensions/test_services_override',
2827
__DIR__ . '/Fixtures/Extensions/test_container',
2928
];
3029

Tests/Functional/Fixtures/Extensions/test_services_override/Configuration/Services.php

Lines changed: 0 additions & 21 deletions
This file was deleted.

Tests/Functional/Fixtures/Extensions/test_services_override/composer.json

Lines changed: 0 additions & 15 deletions
This file was deleted.

Tests/Functional/Fixtures/Extensions/test_services_override/ext_emconf.php

Lines changed: 0 additions & 30 deletions
This file was deleted.

Tests/Functional/Hooks/TranslationWithModifiedTcaConfigurationTest.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,6 @@ final class TranslationWithModifiedTcaConfigurationTest extends AbstractDeepLTes
6969
'web-vision/deepl-base',
7070
'web-vision/deeplcom-deepl-php',
7171
'web-vision/deepltranslate-core',
72-
__DIR__ . '/../Fixtures/Extensions/test_services_override',
7372
__DIR__ . '/Fixtures/Extensions/test_tca_override',
7473
];
7574

Tests/Functional/Services/UsageServiceTest.php

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66

77
use DeepL\Usage;
88
use DeepL\UsageDetail;
9+
use PHPUnit\Framework\Attributes\RunClassInSeparateProcess;
910
use PHPUnit\Framework\Attributes\Test;
11+
use WebVision\Deepltranslate\Core\Domain\Dto\TranslateContext;
1012
use WebVision\Deepltranslate\Core\Service\DeeplService;
1113
use WebVision\Deepltranslate\Core\Service\ProcessingInstruction;
1214
use WebVision\Deepltranslate\Core\Service\UsageService;
@@ -35,7 +37,7 @@ public function classLoadable(): void
3537
{
3638
$usageService = $this->get(UsageService::class);
3739

38-
static::assertInstanceOf(UsageService::class, $usageService);
40+
self::assertInstanceOf(UsageService::class, $usageService);
3941
}
4042

4143
#[Test]
@@ -46,7 +48,7 @@ public function usageReturnsValue(): void
4648

4749
$usage = $usageService->getCurrentUsage();
4850

49-
static::assertInstanceOf(Usage::class, $usage);
51+
self::assertInstanceOf(Usage::class, $usage);
5052
}
5153

5254
#[Test]
@@ -55,13 +57,13 @@ public function limitExceedReturnsFalse(): void
5557
/** @var UsageService $usageService */
5658
$usageService = $this->get(UsageService::class);
5759

58-
static::assertFalse($usageService->checkTranslateLimitWillBeExceeded(''));
60+
self::assertFalse($usageService->checkTranslateLimitWillBeExceeded(''));
5961
}
6062

6163
#[Test]
6264
public function limitExceedReturnsTrueIfLimitIsReached(): void
6365
{
64-
$translateContent = 'proton beam';
66+
$translateContent = self::EXAMPLE_TEXT['en'];
6567

6668
/** @var UsageService $usageService */
6769
$usageService = $this->get(UsageService::class);
@@ -70,38 +72,42 @@ public function limitExceedReturnsTrueIfLimitIsReached(): void
7072
$deeplService = $this->get(DeeplService::class);
7173

7274
// Execute translation to check translation limit
73-
$responseObject = $deeplService->translateRequest(
74-
$translateContent,
75-
'DE',
76-
'EN'
77-
);
75+
$translateContext = new TranslateContext($translateContent);
76+
$translateContext->setSourceLanguageCode('EN');
77+
$translateContext->setTargetLanguageCode('DE');
78+
$translatedContent = $deeplService->translateContent($translateContext);
7879

80+
self::assertEquals(self::EXAMPLE_TEXT['de'], $translatedContent);
7981
$isLimitExceeded = $usageService->checkTranslateLimitWillBeExceeded($translateContent);
80-
static::assertTrue($isLimitExceeded);
82+
self::assertTrue($isLimitExceeded);
8183
}
8284

8385
#[Test]
8486
public function checkHTMLMarkupsIsNotPartOfLimit(): void
8587
{
86-
$translateContent = 'proton beam';
88+
$translateContent = self::EXAMPLE_TEXT['en'];
8789

8890
/** @var UsageService $usageService */
8991
$usageService = $this->get(UsageService::class);
9092

9193
/** @var DeeplService $deeplService */
9294
$deeplService = $this->get(DeeplService::class);
9395

96+
$translateContext = new TranslateContext('<p>' . $translateContent . '</p>');
97+
$translateContext->setSourceLanguageCode('EN');
98+
$translateContext->setTargetLanguageCode('DE');
9499
// Execute translation to check translation limit
95-
$responseObject = $deeplService->translateRequest(
96-
'<p>' . $translateContent . '</p>',
97-
'DE',
98-
'EN'
99-
);
100+
// @todo at the moment the mock server returns an empty result, when the
101+
// translation string is given with HTML tags, but increases character
102+
// usage. I have no idea, why this is happening, but with this behaviour
103+
// there is no possibility checking the response onto valid value.
104+
$response = $deeplService->translateContent($translateContext);
105+
100106

101107
$usage = $usageService->getCurrentUsage();
102-
static::assertInstanceOf(Usage::class, $usage);
108+
self::assertInstanceOf(Usage::class, $usage);
103109
$character = $usage->character;
104-
static::assertInstanceOf(UsageDetail::class, $character);
105-
static::assertEquals(strlen($translateContent), $character->count);
110+
self::assertInstanceOf(UsageDetail::class, $character);
111+
self::assertEquals(strlen($translateContent), $character->count);
106112
}
107113
}

0 commit comments

Comments
 (0)