cms/tests/Feature/TranslationProviderTest.php

121 lines
3.7 KiB
PHP
Raw Permalink Normal View History

<?php
namespace Tests\Feature;
use App\Models\Role;
use App\Models\Setting;
use App\Models\User;
use App\Services\TranslationProviderService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
class TranslationProviderTest extends TestCase
{
use RefreshDatabase;
protected User $admin;
protected TranslationProviderService $service;
protected function setUp(): void
{
parent::setUp();
$adminRole = Role::create(['name' => 'Admin', 'slug' => 'admin']);
$this->admin = User::factory()->create();
$this->admin->roles()->attach($adminRole);
Cache::flush();
$this->service = app(TranslationProviderService::class);
}
public function test_can_translate_with_mock_driver()
{
$this->service->setDriver('mock');
$result = $this->service->translate('Hello', 'en', 'es');
$this->assertEquals('[es] Hello', $result);
}
public function test_can_translate_with_google_driver()
{
Http::fake([
'https://translation.googleapis.com/*' => Http::response([
'data' => [
'translations' => [
['translatedText' => 'Hola']
]
]
], 200)
]);
Setting::set('translation_driver', 'google');
Setting::set('google_translate_key', 'test-key');
Cache::flush();
$this->service = app(TranslationProviderService::class);
$result = $this->service->translate('Hello', 'en', 'es');
$this->assertEquals('Hola', $result);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'translation.googleapis.com') &&
$request['q'] === 'Hello' &&
$request['key'] === 'test-key';
});
}
public function test_can_translate_with_deepl_driver()
{
Http::fake([
'https://api-free.deepl.com/*' => Http::response([
'translations' => [
['text' => 'Hola']
]
], 200)
]);
Setting::set('translation_driver', 'deepl');
Setting::set('deepl_api_key', 'test-deepl-key');
Cache::flush();
$this->service = app(TranslationProviderService::class);
$result = $this->service->translate('Hello', 'en', 'es');
$this->assertEquals('Hola', $result);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'api-free.deepl.com') &&
$request['text'] === ['Hello'] &&
$request->header('Authorization')[0] === 'DeepL-Auth-Key test-deepl-key';
});
}
public function test_can_translate_with_openai_driver()
{
Http::fake([
'https://api.openai.com/*' => Http::response([
'choices' => [
[
'message' => [
'content' => 'Hola'
]
]
]
], 200)
]);
Setting::set('translation_driver', 'openai');
Setting::set('openai_api_key', 'test-openai-key');
Cache::flush();
$this->service = app(TranslationProviderService::class);
$result = $this->service->translate('Hello', 'en', 'es');
$this->assertEquals('Hola', $result);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'api.openai.com') &&
$request['model'] === 'gpt-4o-mini' &&
$request->header('Authorization')[0] === 'Bearer test-openai-key';
});
}
}