64 lines
2.1 KiB
PHP
64 lines
2.1 KiB
PHP
<?php
|
|||
|
|
|
||
|
|
use App\Models\AiProvider;
|
||
|
|
use App\Support\AiProviders\AiGenerationException;
|
||
|
|
use App\Support\AiProviders\StabilityAiDriver;
|
||
|
|
use Illuminate\Support\Facades\Http;
|
||
|
|
|
||
|
|
test('it generates an image successfully', function () {
|
||
|
|
$bytes = 'fake-png-bytes';
|
||
|
|
|
||
|
|
Http::fake([
|
||
|
|
'api.stability.ai/*' => Http::response([
|
||
|
|
'image' => base64_encode($bytes),
|
||
|
|
'seed' => 42,
|
||
|
|
'finish_reason' => 'SUCCESS',
|
||
|
|
], 200),
|
||
|
|
]);
|
||
|
|
|
||
|
|
$provider = AiProvider::factory()->create(['provider' => 'stability_ai', 'api_key' => 'sk-test']);
|
||
|
|
|
||
|
|
$result = (new StabilityAiDriver)->generate($provider, 'a red bicycle');
|
||
|
|
|
||
|
|
expect($result->content)->toBe($bytes);
|
||
|
|
expect($result->contentType)->toBe('image/png');
|
||
|
|
expect($result->raw['seed'])->toBe(42);
|
||
|
|
|
||
|
|
Http::assertSent(function ($request) {
|
||
|
|
return $request->url() === 'https://api.stability.ai/v2beta/stable-image/generate/core'
|
||
|
|
&& $request->hasHeader('Authorization', 'Bearer sk-test');
|
||
|
|
});
|
||
|
|
});
|
||
|
|
|
||
|
|
test('it respects an output_format override', function () {
|
||
|
|
Http::fake([
|
||
|
|
'api.stability.ai/*' => Http::response(['image' => base64_encode('bytes')]),
|
||
|
|
]);
|
||
|
|
|
||
|
|
$provider = AiProvider::factory()->create(['provider' => 'stability_ai']);
|
||
|
|
|
||
|
|
$result = (new StabilityAiDriver)->generate($provider, 'prompt', ['output_format' => 'webp']);
|
||
|
|
|
||
|
|
expect($result->contentType)->toBe('image/webp');
|
||
|
|
});
|
||
|
|
|
||
|
|
test('it throws when StabilityAI returns an error', function () {
|
||
|
|
Http::fake([
|
||
|
|
'api.stability.ai/*' => Http::response(['errors' => ['invalid prompt']], 400),
|
||
|
|
]);
|
||
|
|
|
||
|
|
$provider = AiProvider::factory()->create(['provider' => 'stability_ai']);
|
||
|
|
|
||
|
|
(new StabilityAiDriver)->generate($provider, 'prompt');
|
||
|
|
})->throws(AiGenerationException::class, 'invalid prompt');
|
||
|
|
|
||
|
|
test('it throws when the response has no image data', function () {
|
||
|
|
Http::fake([
|
||
|
|
'api.stability.ai/*' => Http::response(['finish_reason' => 'CONTENT_FILTERED']),
|
||
|
|
]);
|
||
|
|
|
||
|
|
$provider = AiProvider::factory()->create(['provider' => 'stability_ai']);
|
||
|
|
|
||
|
|
(new StabilityAiDriver)->generate($provider, 'prompt');
|
||
|
|
})->throws(AiGenerationException::class);
|