Skip to content

Commit

Permalink
test: Add tests for custom HTTP clients
Browse files Browse the repository at this point in the history
  • Loading branch information
JanEbbing committed Jun 3, 2023
1 parent 46cae1c commit f7c61d9
Show file tree
Hide file tree
Showing 10 changed files with 413 additions and 101 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
* Allow users to supply their own custom HTTP client to the `Translator` object, in order to configure timeouts, security features etc more granularly.
* Thanks to [VincentLanglet](https://github.com/VincentLanglet) for the good input and work in [#22](https://github.com/DeepLcom/deepl-php/pull/22)
* Thanks to [VincentLanglet](https://github.com/VincentLanglet) for the good input and work in [#22](https://github.com/DeepLcom/deepl-php/pull/22)


## [1.4.0] - 2023-05-24
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"ramsey/uuid": "^4.2",
"squizlabs/php_codesniffer": "^3.3",
"friendsofphp/php-cs-fixer": "^3",
"php-mock/php-mock-phpunit": "^2.6"
"php-mock/php-mock-phpunit": "^2.6",
"guzzlehttp/guzzle": "^7.7.0"
},
"license": "MIT",
"autoload": {
Expand Down
9 changes: 6 additions & 3 deletions src/TranslatorOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public static function isValid(array $options): bool
$maybe_logger = $options[TranslatorOptions::LOGGER] ?? null;
if (isset($options[TranslatorOptions::HTTP_CLIENT])) {
foreach (TranslatorOptions::IGNORED_OPTIONS_WITH_CUSTOM_HTTP_CLIENT as $ignored_option) {
$is_valid &= !TranslatorOptions::isIgnoredOptionSet($ignored_option, $options, $maybe_logger);
$is_valid &= !TranslatorOptions::isIgnoredHttpOptionSet($ignored_option, $options, $maybe_logger);
}
}
foreach ($options as $option_key => $option_value) {
Expand All @@ -127,8 +127,11 @@ public static function isValid(array $options): bool
return $is_valid;
}

private static function isIgnoredOptionSet(string $keyToCheck, array $options, ?LoggerInterface $maybe_logger): bool
{
private static function isIgnoredHttpOptionSet(
string $keyToCheck,
array $options,
?LoggerInterface $maybe_logger
): bool {
if (array_key_exists($keyToCheck, $options)) {
if ($maybe_logger !== null) {
$maybe_logger->warning("Option $keyToCheck is ignored as a custom HTTP client is used.");
Expand Down
17 changes: 11 additions & 6 deletions tests/DeepLTestBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
namespace DeepL;

use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Ramsey\Uuid\Uuid;

class DeepLTestBase extends TestCase
Expand Down Expand Up @@ -173,13 +174,12 @@ public function makeTranslator(array $options = []): Translator
return new Translator($this->authKey, $mergedOptions);
}

public function makeTranslatorWithRandomAuthKey(): Translator
public function makeTranslatorWithRandomAuthKey(array $options = []): Translator
{
$mergedOptions = array_replace(
[TranslatorOptions::SERVER_URL => $this->serverUrl,
TranslatorOptions::HEADERS => $this->sessionHeaders()],
$options ?? []
);
$mergedOptions = array_replace([
TranslatorOptions::SERVER_URL => $this->serverUrl,
TranslatorOptions::HEADERS => $this->sessionHeaders(),
], $options ?? []);
$authKey = Uuid::uuid4();

return new Translator($authKey, $mergedOptions);
Expand Down Expand Up @@ -256,4 +256,9 @@ public static function setUpBeforeClass(): void
self::defineFunctionMock(__NAMESPACE__, 'curl_getinfo');
self::defineFunctionMock(__NAMESPACE__, 'curl_setopt_array');
}

public function provideHttpClient()
{
return [[null], [new \GuzzleHttp\Client()]];
}
}
111 changes: 88 additions & 23 deletions tests/GeneralTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,49 +6,84 @@

namespace DeepL;

use Psr\Http\Client\ClientInterface;

class GeneralTest extends DeepLTestBase
{
public function testEmptyAuthKey()
/**
* @dataProvider provideHttpClient
*/
public function testEmptyAuthKey(?ClientInterface $httpClient)
{
$this->expectException(DeepLException::class);
new Translator('', [TranslatorOptions::SERVER_URL => $this->serverUrl]);
new Translator('', [
TranslatorOptions::SERVER_URL => $this->serverUrl,
TranslatorOptions::HTTP_CLIENT => $httpClient
]);
}

public function testInvalidAuthKey()
/**
* @dataProvider provideHttpClient
*/
public function testInvalidAuthKey(?ClientInterface $httpClient)
{
$translator = new Translator('invalid', [TranslatorOptions::SERVER_URL => $this->serverUrl]);
$translator = new Translator('invalid', [
TranslatorOptions::SERVER_URL => $this->serverUrl,
TranslatorOptions::HTTP_CLIENT => $httpClient
]);

$this->expectException(AuthorizationException::class);
$translator->getUsage();
}

public function testInvalidServerUrl()
/**
* @dataProvider provideHttpClient
*/
public function testInvalidServerUrl(?ClientInterface $httpClient)
{
new Translator($this->authKey, [TranslatorOptions::SERVER_URL => null]);
new Translator($this->authKey, [
TranslatorOptions::SERVER_URL => null,
TranslatorOptions::HTTP_CLIENT => $httpClient
]);

$this->expectException(DeepLException::class);
new Translator($this->authKey, [TranslatorOptions::SERVER_URL => false]);
new Translator($this->authKey, [
TranslatorOptions::SERVER_URL => false,
TranslatorOptions::HTTP_CLIENT => $httpClient
]);
}

public function testUsage()
/**
* @dataProvider provideHttpClient
*/
public function testUsage(?ClientInterface $httpClient)
{
$translator = $this->makeTranslator();
$translator = $this->makeTranslator([TranslatorOptions::HTTP_CLIENT => $httpClient]);
$usage = $translator->getUsage();
$this->assertStringContainsString('Usage this billing period', strval($usage));
}

public function testLogger()
/**
* @dataProvider provideHttpClient
*/
public function testLogger(?ClientInterface $httpClient)
{
$logger = new TestLogger();
$translator = $this->makeTranslator([TranslatorOptions::LOGGER => $logger]);
$translator = $this->makeTranslator([
TranslatorOptions::LOGGER => $logger,
TranslatorOptions::HTTP_CLIENT => $httpClient
]);
$translator->getUsage();
$this->assertStringContainsString("Request to DeepL API", $logger->content);
$this->assertStringContainsString("DeepL API response", $logger->content);
}

public function testLanguage()
/**
* @dataProvider provideHttpClient
*/
public function testLanguage(?ClientInterface $httpClient)
{
$translator = $this->makeTranslator();
$translator = $this->makeTranslator([TranslatorOptions::HTTP_CLIENT => $httpClient]);
$sourceLanguages = $translator->getSourceLanguages();
foreach ($sourceLanguages as $sourceLanguage) {
if ($sourceLanguage->code === 'en') {
Expand All @@ -67,11 +102,12 @@ public function testLanguage()
}

/**
* @dataProvider provideHttpClient
* @throws DeepLException
*/
public function testGlossaryLanguage()
public function testGlossaryLanguage(?ClientInterface $httpClient)
{
$translator = $this->makeTranslator();
$translator = $this->makeTranslator([TranslatorOptions::HTTP_CLIENT => $httpClient]);
$glossaryLanguagePairs = $translator->getGlossaryLanguages();
$this->assertGreaterThan(0, count($glossaryLanguagePairs));
foreach ($glossaryLanguagePairs as $glossaryLanguagePair) {
Expand All @@ -81,9 +117,10 @@ public function testGlossaryLanguage()
}

/**
* @dataProvider provideHttpClient
* @throws DeepLException
*/
public function testProxyUsage()
public function testProxyUsage(?ClientInterface $httpClient)
{
$this->needsMockProxyServer();
$this->sessionExpectProxy = true;
Expand All @@ -100,31 +137,56 @@ public function testUsageNoResponse()
{
$this->needsMockServer();
$this->sessionNoResponse = 2;
$translator = $this->makeTranslator([TranslatorOptions::MAX_RETRIES => 0, TranslatorOptions::TIMEOUT => 1.0]);
$translator = $this->makeTranslator(
[TranslatorOptions::MAX_RETRIES => 0, TranslatorOptions::TIMEOUT => 1.0],
);

$this->expectException(ConnectionException::class);
$translator->getUsage();
}

public function testTranslateTooManyRequests()
public function testUsageNoResponseCustomClient()
{
$this->needsMockServer();
$this->sessionNoResponse = 2;
$translator = $this->makeTranslator([
TranslatorOptions::MAX_RETRIES => 0,
TranslatorOptions::HTTP_CLIENT => new \GuzzleHttp\Client(['timeout' => 1.0])
]);

$this->expectException(ConnectionException::class);
$translator->getUsage();
}

/**
* @dataProvider provideHttpClient
*/
public function testTranslateTooManyRequests(?ClientInterface $httpClient)
{
$this->needsMockServer();
$this->session429Count = 2;
$translator = $this->makeTranslator([TranslatorOptions::MAX_RETRIES => 1, TranslatorOptions::TIMEOUT => 1.0]);
$translator = $this->makeTranslator([
TranslatorOptions::MAX_RETRIES => 1,
TranslatorOptions::TIMEOUT => 1.0,
TranslatorOptions::HTTP_CLIENT => $httpClient,
]);

$this->expectException(TooManyRequestsException::class);
$translator->translateText(DeepLTestBase::EXAMPLE_TEXT['en'], null, 'de');
}

public function testUsageOverrun()
/**
* @dataProvider provideHttpClient
*/
public function testUsageOverrun(?ClientInterface $httpClient)
{
$this->needsMockServer();
$characterLimit = 20;
$documentLimit = 1;
$this->sessionInitCharacterLimit = $characterLimit;
$this->sessionInitDocumentLimit = $documentLimit;

$translator = $this->makeTranslatorWithRandomAuthKey();
$translator = $this->makeTranslatorWithRandomAuthKey([TranslatorOptions::HTTP_CLIENT => $httpClient]);
$usage = $translator->getUsage();
$this->assertFalse($usage->anyLimitReached());
$this->assertEquals($characterLimit, $usage->character->limit);
Expand All @@ -149,15 +211,18 @@ public function testUsageOverrun()
$translator->translateDocument($exampleDocument, $outputDocumentPath, null, "de");
}

public function testUsageTeamDocumentLimit()
/**
* @dataProvider provideHttpClient
*/
public function testUsageTeamDocumentLimit(?ClientInterface $httpClient)
{
$this->needsMockServer();
$teamDocumentLimit = 1;
$this->sessionInitCharacterLimit = 0;
$this->sessionInitDocumentLimit = 0;
$this->sessionInitTeamDocumentLimit = $teamDocumentLimit;

$translator = $this->makeTranslatorWithRandomAuthKey();
$translator = $this->makeTranslatorWithRandomAuthKey([TranslatorOptions::HTTP_CLIENT => $httpClient]);
$usage = $translator->getUsage();
$this->assertFalse($usage->anyLimitReached());
$this->assertNull($usage->character);
Expand Down
Loading

0 comments on commit f7c61d9

Please sign in to comment.