ldc-arcadia-genesis-php-client/tests/Unit/Lib/Pagination/StreamOfTest.php

91 lines
2.7 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Unit\Lib\Pagination;
use PHPUnit\Framework\TestCase;
use Uwil\ArcadiaApiPhpClient\Error\NetworkError;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\PageOf;
use Uwil\ArcadiaApiPhpClient\Lib\ApiDto\Dto\PaginationDto;
use Uwil\ArcadiaApiPhpClient\Lib\Pagination\PageSize;
use Uwil\ArcadiaApiPhpClient\Lib\Pagination\Pagination;
use Uwil\ArcadiaApiPhpClient\Lib\Pagination\StreamOf;
covers(StreamOf::class);
uses(TestCase::class);
describe('StreamOf Unit Tests', function (): void {
it('iterates through multiple pages sequentially', function (): void {
// GIVEN
$data = range(1, 25); // 25 items across 3 pages of size 10
$fetcher = function (Pagination $pagination) use ($data): PageOf {
$offset = $pagination->from();
$limit = $pagination->pageSize();
$slice = array_slice($data, $offset, $limit);
$paginationDto = new PaginationDto(
page: $pagination->pageNumber(),
pageSize: $limit,
totalItems: count($data),
totalPages: (int) ceil(count($data) / $limit),
);
return new PageOf($paginationDto, $slice);
};
$stream = new StreamOf($fetcher, new PageSize(10));
// WHEN
$result = iterator_to_array($stream);
// THEN
expect($result)->toBe($data)
->and($stream->totalCount())->toBe(25)
->and($stream->totalPages())->toBe(3)
->and($stream->lastError())->toBeNull();
});
it('handles empty page result', function (): void {
// GIVEN
$fetcher = function (Pagination $_): PageOf {
$paginationDto = new PaginationDto(
page: 1,
pageSize: 10,
totalItems: 0,
totalPages: 0,
);
return new PageOf($paginationDto, []);
};
$stream = new StreamOf($fetcher, new PageSize(10));
// WHEN
$result = iterator_to_array($stream);
// THEN
expect($result)->toBeEmpty()
->and($stream->totalCount())->toBe(0)
->and($stream->totalPages())->toBe(0);
});
it('stops iteration on error and captures lastError', function (): void {
// GIVEN
$fetcher = function (Pagination $_): NetworkError {
return new NetworkError('Connection timed out');
};
$stream = new StreamOf($fetcher, new PageSize(10));
// WHEN
$result = iterator_to_array($stream);
// THEN
expect($result)->toBeEmpty()
->and($stream->lastError())->toBeInstanceOf(NetworkError::class)
->and($stream->lastError()?->message())->toBe('Connection timed out');
});
});