|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Tests\Http; |
| 6 | + |
| 7 | +use GuzzleHttp\Psr7\Response; |
| 8 | +use Wati\Http\WatiResponse; |
| 9 | + |
| 10 | +it('can create from response', function (): void { |
| 11 | + $response = new Response(200, ['Content-Type' => 'application/json'], '{"key":"value"}'); |
| 12 | + $watiResponse = WatiResponse::fromResponse($response); |
| 13 | + |
| 14 | + expect($watiResponse->getStatusCode())->toBe(200) |
| 15 | + ->and($watiResponse->getHeaderLine('Content-Type'))->toBe('application/json') |
| 16 | + ->and($watiResponse->getBody()->getContents())->toBe('{"key":"value"}'); |
| 17 | +}); |
| 18 | + |
| 19 | +it('can parse json body', function (): void { |
| 20 | + $response = new Response(200, [], '{"name":"John","age":30}'); |
| 21 | + $watiResponse = WatiResponse::fromResponse($response); |
| 22 | + |
| 23 | + expect($watiResponse->json())->toBe(['name' => 'John', 'age' => 30]); |
| 24 | +}); |
| 25 | + |
| 26 | +it('returns null for invalid json', function (): void { |
| 27 | + $response = new Response(200, [], 'not valid json'); |
| 28 | + $watiResponse = WatiResponse::fromResponse($response); |
| 29 | + |
| 30 | + expect($watiResponse->json())->toBeNull(); |
| 31 | +}); |
| 32 | + |
| 33 | +it('returns true when result is success', function (): void { |
| 34 | + $response = new Response(200, [], '{"result":"success","data":[]}'); |
| 35 | + $watiResponse = WatiResponse::fromResponse($response); |
| 36 | + |
| 37 | + expect($watiResponse->isSuccessful())->toBeTrue(); |
| 38 | +}); |
| 39 | + |
| 40 | +it('returns false when result is not success', function (): void { |
| 41 | + $response = new Response(200, [], '{"result":"error","message":"Failed"}'); |
| 42 | + $watiResponse = WatiResponse::fromResponse($response); |
| 43 | + |
| 44 | + expect($watiResponse->isSuccessful())->toBeFalse(); |
| 45 | +}); |
| 46 | + |
| 47 | +it('returns false when result key is missing', function (): void { |
| 48 | + $response = new Response(200, [], '{"status":"ok","data":[]}'); |
| 49 | + $watiResponse = WatiResponse::fromResponse($response); |
| 50 | + |
| 51 | + expect($watiResponse->isSuccessful())->toBeFalse(); |
| 52 | +}); |
| 53 | + |
| 54 | +it('returns false for non array json', function (): void { |
| 55 | + $response = new Response(200, [], '"just a string"'); |
| 56 | + $watiResponse = WatiResponse::fromResponse($response); |
| 57 | + |
| 58 | + expect($watiResponse->isSuccessful())->toBeFalse(); |
| 59 | +}); |
| 60 | + |
| 61 | +it('preserves protocol version and reason phrase', function (): void { |
| 62 | + $response = new Response(404, [], 'Not Found', '1.1', 'Not Found'); |
| 63 | + $watiResponse = WatiResponse::fromResponse($response); |
| 64 | + |
| 65 | + expect($watiResponse->getProtocolVersion())->toBe('1.1') |
| 66 | + ->and($watiResponse->getReasonPhrase())->toBe('Not Found'); |
| 67 | +}); |
0 commit comments