Version 5.1 - All the GraphQL #32

Closed
timw4mail wants to merge 1160 commits from develop into master
87 changed files with 981 additions and 744 deletions
Showing only changes of commit e4a793306d - Show all commits

View File

@ -103,10 +103,8 @@ function _iterateToml(TomlBuilder $builder, iterable $data, mixed $parentKey = N
? "{$parentKey}.{$key}" ? "{$parentKey}.{$key}"
: $key; : $key;
if ( ! isSequentialArray($value))
{
$builder->addTable($newKey); $builder->addTable($newKey);
}
_iterateToml($builder, $value, $newKey); _iterateToml($builder, $value, $newKey);
} }
@ -154,12 +152,7 @@ if ( ! function_exists('array_is_list'))
*/ */
function isSequentialArray(mixed $array): bool function isSequentialArray(mixed $array): bool
{ {
if ( ! is_array($array)) return is_array($array) && array_is_list($array);
{
return FALSE;
}
return array_is_list($array);
} }
/** /**

View File

@ -44,13 +44,13 @@ class Json
* @param int $fileOptions - Options to pass to file_get_contents * @param int $fileOptions - Options to pass to file_get_contents
* @throws JsonException * @throws JsonException
*/ */
public static function encodeFile(string $filename, mixed $data, int $jsonOptions = 0, int $fileOptions = 0): bool public static function encodeFile(string $filename, mixed $data, int $jsonOptions = 0, int $fileOptions = 0): int
{ {
$json = self::encode($data, $jsonOptions); $json = self::encode($data, $jsonOptions);
$res = file_put_contents($filename, $json, $fileOptions); $res = file_put_contents($filename, $json, $fileOptions);
return $res !== FALSE; return ($res !== FALSE) ? $res : 0;
} }
/** /**

View File

@ -16,26 +16,30 @@
namespace Aviat\AnimeClient\Tests\API; namespace Aviat\AnimeClient\Tests\API;
use Aviat\AnimeClient\API\APIRequestBuilder;
use Aviat\Ion\Json;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use function Amp\Promise\wait; use function Amp\Promise\wait;
use function Aviat\AnimeClient\getResponse; use function Aviat\AnimeClient\getResponse;
use Aviat\AnimeClient\API\APIRequestBuilder; /**
use Aviat\Ion\Json; * @internal
use PHPUnit\Framework\TestCase; */
use Psr\Log\NullLogger; final class APIRequestBuilderTest extends TestCase
{
class APIRequestBuilderTest extends TestCase {
protected $builder; protected $builder;
public function setUp(): void { protected function setUp(): void
$this->builder = new class extends APIRequestBuilder { {
$this->builder = new class () extends APIRequestBuilder {
protected string $baseUrl = 'https://httpbin.org/'; protected string $baseUrl = 'https://httpbin.org/';
protected array $defaultHeaders = ['User-Agent' => "Tim's Anime Client Testsuite / 4.0"]; protected array $defaultHeaders = ['User-Agent' => "Tim's Anime Client Testsuite / 4.0"];
}; };
$this->builder->setLogger(new NullLogger); $this->builder->setLogger(new NullLogger());
} }
public function testGzipRequest(): void public function testGzipRequest(): void
@ -44,12 +48,12 @@ class APIRequestBuilderTest extends TestCase {
->getFullRequest(); ->getFullRequest();
$response = getResponse($request); $response = getResponse($request);
$body = Json::decode(wait($response->getBody()->buffer())); $body = Json::decode(wait($response->getBody()->buffer()));
$this->assertEquals(1, $body['gzipped']); $this->assertTrue($body['gzipped']);
} }
public function testInvalidRequestMethod(): void public function testInvalidRequestMethod(): void
{ {
$this->expectException(\InvalidArgumentException::class); $this->expectException(InvalidArgumentException::class);
$this->builder->newRequest('FOO', 'gzip') $this->builder->newRequest('FOO', 'gzip')
->getFullRequest(); ->getFullRequest();
} }
@ -63,7 +67,7 @@ class APIRequestBuilderTest extends TestCase {
$response = getResponse($request); $response = getResponse($request);
$body = Json::decode(wait($response->getBody()->buffer())); $body = Json::decode(wait($response->getBody()->buffer()));
$this->assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', $body['headers']['Authorization']); $this->assertSame('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', $body['headers']['Authorization']);
} }
public function testRequestWithQueryString(): void public function testRequestWithQueryString(): void
@ -71,17 +75,17 @@ class APIRequestBuilderTest extends TestCase {
$query = [ $query = [
'foo' => 'bar', 'foo' => 'bar',
'bar' => [ 'bar' => [
'foo' => 'bar' 'foo' => 'bar',
], ],
'baz' => [ 'baz' => [
'bar' => 'foo' 'bar' => 'foo',
] ],
]; ];
$expected = [ $expected = [
'foo' => 'bar',
'bar[foo]' => 'bar', 'bar[foo]' => 'bar',
'baz[bar]' => 'foo' 'baz[bar]' => 'foo',
'foo' => 'bar',
]; ];
$request = $this->builder->newRequest('GET', 'get') $request = $this->builder->newRequest('GET', 'get')
@ -91,14 +95,14 @@ class APIRequestBuilderTest extends TestCase {
$response = getResponse($request); $response = getResponse($request);
$body = Json::decode(wait($response->getBody()->buffer())); $body = Json::decode(wait($response->getBody()->buffer()));
$this->assertEquals($expected, $body['args']); $this->assertSame($expected, $body['args']);
} }
public function testFormValueRequest(): void public function testFormValueRequest(): void
{ {
$formValues = [ $formValues = [
'bar' => 'foo',
'foo' => 'bar', 'foo' => 'bar',
'bar' => 'foo'
]; ];
$request = $this->builder->newRequest('POST', 'post') $request = $this->builder->newRequest('POST', 'post')
@ -108,7 +112,7 @@ class APIRequestBuilderTest extends TestCase {
$response = getResponse($request); $response = getResponse($request);
$body = Json::decode(wait($response->getBody()->buffer())); $body = Json::decode(wait($response->getBody()->buffer()));
$this->assertEquals($formValues, $body['form']); $this->assertSame($formValues, $body['form']);
} }
public function testFullUrlRequest(): void public function testFullUrlRequest(): void
@ -119,9 +123,9 @@ class APIRequestBuilderTest extends TestCase {
'baz' => [2, 3, 4], 'baz' => [2, 3, 4],
'bazbar' => [ 'bazbar' => [
'a' => 1, 'a' => 1,
'b' => 2 'b' => 2,
] ],
] ],
]; ];
$request = $this->builder->newRequest('PUT', 'https://httpbin.org/put') $request = $this->builder->newRequest('PUT', 'https://httpbin.org/put')
@ -132,6 +136,6 @@ class APIRequestBuilderTest extends TestCase {
$response = getResponse($request); $response = getResponse($request);
$body = Json::decode(wait($response->getBody()->buffer())); $body = Json::decode(wait($response->getBody()->buffer()));
$this->assertEquals($data, $body['json']); $this->assertSame($data, $body['json']);
} }
} }

View File

@ -19,13 +19,17 @@ namespace Aviat\AnimeClient\Tests\API;
use Aviat\AnimeClient\API\CacheTrait; use Aviat\AnimeClient\API\CacheTrait;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
class CacheTraitTest extends AnimeClientTestCase { /**
* @internal
*/
final class CacheTraitTest extends AnimeClientTestCase
{
protected $testClass; protected $testClass;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->testClass = new class { $this->testClass = new class () {
use CacheTrait; use CacheTrait;
}; };
} }
@ -34,6 +38,6 @@ class CacheTraitTest extends AnimeClientTestCase {
{ {
$cachePool = $this->container->get('cache'); $cachePool = $this->container->get('cache');
$this->testClass->setCache($cachePool); $this->testClass->setCache($cachePool);
$this->assertEquals($cachePool, $this->testClass->getCache()); $this->assertSame($cachePool, $this->testClass->getCache());
} }
} }

View File

@ -18,11 +18,14 @@ namespace Aviat\AnimeClient\Tests\API\Kitsu;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
class ModelTest extends AnimeClientTestCase { /**
* @internal
*/
final class ModelTest extends AnimeClientTestCase
{
protected $model; protected $model;
public function setUp(): void protected function setUp(): void
{ {
parent::setup(); parent::setup();
$this->model = $this->container->get('kitsu-model'); $this->model = $this->container->get('kitsu-model');
@ -30,13 +33,13 @@ class ModelTest extends AnimeClientTestCase {
public function testGetAnimeKitsuIdFromMALId(): void public function testGetAnimeKitsuIdFromMALId(): void
{ {
$kitsuId = $this->model->getKitsuIdFromMALId("1", 'anime'); $kitsuId = $this->model->getKitsuIdFromMALId('1', 'anime');
self::assertEquals("1", $kitsuId); $this->assertSame('1', $kitsuId);
} }
public function testGetNullFromMALAnimeId(): void public function testGetNullFromMALAnimeId(): void
{ {
$kitsuId = $this->model->getKitsuIdFromMALId("0", 'anime'); $kitsuId = $this->model->getKitsuIdFromMALId('0', 'anime');
self::assertNull($kitsuId); $this->assertNull($kitsuId);
} }
} }

View File

@ -20,12 +20,17 @@ use Aviat\AnimeClient\API\Kitsu\Transformer\AnimeListTransformer;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
use Aviat\Ion\Json; use Aviat\Ion\Json;
class AnimeListTransformerTest extends AnimeClientTestCase { /**
* @internal
*/
final class AnimeListTransformerTest extends AnimeClientTestCase
{
protected string $dir; protected string $dir;
protected array $beforeTransform; protected array $beforeTransform;
protected AnimeListTransformer $transformer; protected AnimeListTransformer $transformer;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu'; $this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu';
@ -37,7 +42,7 @@ class AnimeListTransformerTest extends AnimeClientTestCase {
public function testTransform(): void public function testTransform(): void
{ {
$this->markTestSkipped("Old test data"); $this->markTestSkipped('Old test data');
$actual = $this->transformer->transform($this->beforeTransform); $actual = $this->transformer->transform($this->beforeTransform);
$this->assertMatchesSnapshot($actual); $this->assertMatchesSnapshot($actual);
@ -53,8 +58,8 @@ class AnimeListTransformerTest extends AnimeClientTestCase {
'episodes_watched' => 38, 'episodes_watched' => 38,
'rewatched' => 0, 'rewatched' => 0,
'notes' => 'Very formulaic.', 'notes' => 'Very formulaic.',
'edit' => true 'edit' => TRUE,
] ],
], [ ], [
'input' => [ 'input' => [
'id' => 14047981, 'id' => 14047981,
@ -66,8 +71,8 @@ class AnimeListTransformerTest extends AnimeClientTestCase {
'notes' => 'Very formulaic.', 'notes' => 'Very formulaic.',
'edit' => 'true', 'edit' => 'true',
'private' => 'On', 'private' => 'On',
'rewatching' => 'On' 'rewatching' => 'On',
] ],
], [ ], [
'input' => [ 'input' => [
'id' => 14047983, 'id' => 14047983,
@ -79,14 +84,13 @@ class AnimeListTransformerTest extends AnimeClientTestCase {
'notes' => '', 'notes' => '',
'edit' => 'true', 'edit' => 'true',
'private' => 'On', 'private' => 'On',
'rewatching' => 'On' 'rewatching' => 'On',
] ],
]]; ]];
} }
/** /**
* @dataProvider dataUntransform * @dataProvider dataUntransform
* @param array $input
*/ */
public function testUntransform(array $input): void public function testUntransform(array $input): void
{ {

View File

@ -20,13 +20,17 @@ use Aviat\AnimeClient\API\Kitsu\Transformer\AnimeTransformer;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
use Aviat\Ion\Json; use Aviat\Ion\Json;
class AnimeTransformerTest extends AnimeClientTestCase { /**
* @internal
*/
final class AnimeTransformerTest extends AnimeClientTestCase
{
protected $dir; protected $dir;
protected $beforeTransform; protected $beforeTransform;
protected $transformer; protected $transformer;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu'; $this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu';

View File

@ -20,11 +20,16 @@ use Aviat\AnimeClient\API\Kitsu\Transformer\CharacterTransformer;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
use Aviat\Ion\Json; use Aviat\Ion\Json;
class CharacterTransformerTest extends AnimeClientTestCase { /**
* @internal
*/
final class CharacterTransformerTest extends AnimeClientTestCase
{
protected array $beforeTransform; protected array $beforeTransform;
protected string $dir; protected string $dir;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu'; $this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu';

View File

@ -16,16 +16,20 @@
namespace Aviat\AnimeClient\Tests\API\Kitsu\Transformer; namespace Aviat\AnimeClient\Tests\API\Kitsu\Transformer;
use Aviat\AnimeClient\API\Kitsu\Transformer\AnimeHistoryTransformer; use Aviat\AnimeClient\API\Kitsu\Transformer\{AnimeHistoryTransformer, MangaHistoryTransformer};
use Aviat\AnimeClient\API\Kitsu\Transformer\MangaHistoryTransformer;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
use Aviat\Ion\Json; use Aviat\Ion\Json;
class HistoryTransformerTest extends AnimeClientTestCase { /**
* @internal
*/
final class HistoryTransformerTest extends AnimeClientTestCase
{
protected array $beforeTransform; protected array $beforeTransform;
protected string $dir; protected string $dir;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu'; $this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu';
@ -35,7 +39,7 @@ class HistoryTransformerTest extends AnimeClientTestCase {
public function testAnimeTransform(): void public function testAnimeTransform(): void
{ {
$this->markTestSkipped("Old test data"); $this->markTestSkipped('Old test data');
$actual = (new AnimeHistoryTransformer())->transform($this->beforeTransform); $actual = (new AnimeHistoryTransformer())->transform($this->beforeTransform);
$this->assertMatchesSnapshot($actual); $this->assertMatchesSnapshot($actual);

View File

@ -24,14 +24,18 @@ use Aviat\AnimeClient\Types\{
}; };
use Aviat\Ion\Json; use Aviat\Ion\Json;
class MangaListTransformerTest extends AnimeClientTestCase { /**
* @internal
*/
final class MangaListTransformerTest extends AnimeClientTestCase
{
protected $dir; protected $dir;
protected $rawBefore; protected $rawBefore;
protected $beforeTransform; protected $beforeTransform;
protected $transformer; protected $transformer;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu'; $this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu';
@ -56,17 +60,17 @@ class MangaListTransformerTest extends AnimeClientTestCase {
'chapters_read' => 67, 'chapters_read' => 67,
'manga' => [ 'manga' => [
'id' => '12345', 'id' => '12345',
'titles' => ["Bokura wa Minna Kawaisou"], 'titles' => ['Bokura wa Minna Kawaisou'],
'alternate_title' => NULL, 'alternate_title' => NULL,
'slug' => "bokura-wa-minna-kawaisou", 'slug' => 'bokura-wa-minna-kawaisou',
'url' => "https://kitsu.io/manga/bokura-wa-minna-kawaisou", 'url' => 'https://kitsu.io/manga/bokura-wa-minna-kawaisou',
'type' => 'manga', 'type' => 'manga',
'image' => 'https://media.kitsu.io/manga/poster_images/20286/small.jpg?1434293999', 'image' => 'https://media.kitsu.io/manga/poster_images/20286/small.jpg?1434293999',
'genres' => [], 'genres' => [],
], ],
'status' => 'current', 'status' => 'current',
'notes' => '', 'notes' => '',
'rereading' => false, 'rereading' => FALSE,
'reread_count' => 0, 'reread_count' => 0,
'new_rating' => 9, 'new_rating' => 9,
]; ];
@ -78,14 +82,13 @@ class MangaListTransformerTest extends AnimeClientTestCase {
'data' => FormItemData::from([ 'data' => FormItemData::from([
'status' => 'current', 'status' => 'current',
'progress' => 67, 'progress' => 67,
'reconsuming' => false, 'reconsuming' => FALSE,
'reconsumeCount' => 0, 'reconsumeCount' => 0,
'notes' => '', 'notes' => '',
'ratingTwenty' => 18, 'ratingTwenty' => 18,
]) ]),
]); ]);
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
} }

View File

@ -20,13 +20,17 @@ use Aviat\AnimeClient\API\Kitsu\Transformer\MangaTransformer;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
use Aviat\Ion\Json; use Aviat\Ion\Json;
class MangaTransformerTest extends AnimeClientTestCase { /**
* @internal
*/
final class MangaTransformerTest extends AnimeClientTestCase
{
protected $dir; protected $dir;
protected $beforeTransform; protected $beforeTransform;
protected $transformer; protected $transformer;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu'; $this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu';

View File

@ -20,11 +20,16 @@ use Aviat\AnimeClient\API\Kitsu\Transformer\PersonTransformer;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
use Aviat\Ion\Json; use Aviat\Ion\Json;
class PersonTransformerTest extends AnimeClientTestCase { /**
* @internal
*/
final class PersonTransformerTest extends AnimeClientTestCase
{
protected array $beforeTransform; protected array $beforeTransform;
protected string $dir; protected string $dir;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu'; $this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu';

View File

@ -20,11 +20,16 @@ use Aviat\AnimeClient\API\Kitsu\Transformer\UserTransformer;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
use Aviat\Ion\Json; use Aviat\Ion\Json;
class UserTransformerTest extends AnimeClientTestCase { /**
* @internal
*/
final class UserTransformerTest extends AnimeClientTestCase
{
protected array $beforeTransform; protected array $beforeTransform;
protected string $dir; protected string $dir;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu'; $this->dir = AnimeClientTestCase::TEST_DATA_DIR . '/Kitsu';

View File

@ -20,8 +20,11 @@ use Aviat\AnimeClient\API\ParallelAPIRequest;
use Aviat\Ion\Friend; use Aviat\Ion\Friend;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class ParallelAPIRequestTest extends TestCase { /**
* @internal
*/
final class ParallelAPIRequestTest extends TestCase
{
public function testAddStringUrlRequest() public function testAddStringUrlRequest()
{ {
$requester = new ParallelAPIRequest(); $requester = new ParallelAPIRequest();
@ -29,14 +32,14 @@ class ParallelAPIRequestTest extends TestCase {
$friend = new Friend($requester); $friend = new Friend($requester);
$this->assertEquals($friend->requests, ['https://httpbin.org']); $this->assertSame($friend->requests, ['https://httpbin.org']);
} }
public function testAddStringUrlRequests() public function testAddStringUrlRequests()
{ {
$requests = [ $requests = [
'foo' => 'http://example.com', 'foo' => 'http://example.com',
'bar' => 'https://example.com' 'bar' => 'https://example.com',
]; ];
$requester = new ParallelAPIRequest(); $requester = new ParallelAPIRequest();
@ -44,6 +47,6 @@ class ParallelAPIRequestTest extends TestCase {
$friend = new Friend($requester); $friend = new Friend($requester);
$this->assertEquals($friend->requests, $requests); $this->assertSame($friend->requests, $requests);
} }
} }

View File

@ -16,23 +16,20 @@
namespace Aviat\AnimeClient\Tests; namespace Aviat\AnimeClient\Tests;
use function Aviat\AnimeClient\arrayToToml; use DateTime;
use function Aviat\AnimeClient\checkFolderPermissions; use function Aviat\AnimeClient\{arrayToToml, checkFolderPermissions, clearCache, colNotEmpty, getLocalImg, getResponse, isSequentialArray, tomlToArray};
use function Aviat\AnimeClient\clearCache;
use function Aviat\AnimeClient\colNotEmpty;
use function Aviat\AnimeClient\getLocalImg;
use function Aviat\AnimeClient\getResponse;
use function Aviat\AnimeClient\isSequentialArray;
use function Aviat\AnimeClient\tomlToArray;
class AnimeClientTest extends AnimeClientTestCase /**
* @internal
*/
final class AnimeClientTest extends AnimeClientTestCase
{ {
public function testArrayToToml(): void public function testArrayToToml(): void
{ {
$arr = [ $arr = [
'cat' => false, 'cat' => FALSE,
'foo' => 'bar', 'foo' => 'bar',
'dateTime' => (array) new \DateTime(), 'dateTime' => (array) new DateTime(),
'bar' => [ 'bar' => [
'a' => 1, 'a' => 1,
'b' => 2, 'b' => 2,
@ -65,16 +62,16 @@ class AnimeClientTest extends AnimeClientTestCase
public function testArrayToTomlNullValue(): void public function testArrayToTomlNullValue(): void
{ {
$arr = [ $arr = [
'cat' => false, 'cat' => FALSE,
'bat' => null, 'bat' => NULL,
'foo' => 'bar', 'foo' => 'bar',
]; ];
$toml = arrayToToml($arr); $toml = arrayToToml($arr);
$parsedArray = tomlToArray($toml); $parsedArray = tomlToArray($toml);
$this->assertEquals([ $this->assertSame([
'cat' => false, 'cat' => FALSE,
'foo' => 'bar', 'foo' => 'bar',
], $parsedArray); ], $parsedArray);
} }
@ -96,19 +93,19 @@ class AnimeClientTest extends AnimeClientTestCase
{ {
$config = $this->container->get('config'); $config = $this->container->get('config');
$actual = checkFolderPermissions($config); $actual = checkFolderPermissions($config);
$this->assertTrue(is_array($actual)); $this->assertIsArray($actual);
} }
public function testGetLocalImageEmptyUrl(): void public function testGetLocalImageEmptyUrl(): void
{ {
$actual = getLocalImg(''); $actual = getLocalImg('');
$this->assertEquals('images/placeholder.webp', $actual); $this->assertSame('images/placeholder.webp', $actual);
} }
public function testGetLocalImageBadUrl(): void public function testGetLocalImageBadUrl(): void
{ {
$actual = getLocalImg('//foo.bar'); $actual = getLocalImg('//foo.bar');
$this->assertEquals('images/placeholder.webp', $actual); $this->assertSame('images/placeholder.webp', $actual);
} }
public function testColNotEmpty(): void public function testColNotEmpty(): void
@ -125,8 +122,8 @@ class AnimeClientTest extends AnimeClientTestCase
'foo' => 'baz', 'foo' => 'baz',
]]; ]];
$this->assertEquals(false, colNotEmpty($hasEmptyCols, 'foo')); $this->assertFalse(colNotEmpty($hasEmptyCols, 'foo'));
$this->assertEquals(true, colNotEmpty($hasNonEmptyCols, 'foo')); $this->assertTrue(colNotEmpty($hasNonEmptyCols, 'foo'));
} }
public function testClearCache(): void public function testClearCache(): void

View File

@ -16,27 +16,28 @@
namespace Aviat\AnimeClient\Tests; namespace Aviat\AnimeClient\Tests;
use Aviat\Ion\Di\ContainerAware; use Aviat\Ion\Di\{ContainerAware, ContainerInterface};
use Aviat\Ion\Di\ContainerInterface;
use function Aviat\Ion\_dir;
use Aviat\Ion\Json; use Aviat\Ion\Json;
use PHPUnit\Framework\TestCase;
use Spatie\Snapshots\MatchesSnapshots;
use Laminas\Diactoros\{ use Laminas\Diactoros\{
Response as HttpResponse, Response as HttpResponse,
ServerRequestFactory ServerRequestFactory
}; };
use PHPUnit\Framework\TestCase;
use Spatie\Snapshots\MatchesSnapshots;
use function Aviat\Ion\_dir;
use function call_user_func_array;
use const Aviat\AnimeClient\{ use const Aviat\AnimeClient\{
SLUG_PATTERN,
DEFAULT_CONTROLLER, DEFAULT_CONTROLLER,
SLUG_PATTERN,
}; };
/** /**
* Base class for TestCases * Base class for TestCases
*/ */
class AnimeClientTestCase extends TestCase { class AnimeClientTestCase extends TestCase
{
use ContainerAware; use ContainerAware;
use MatchesSnapshots; use MatchesSnapshots;
@ -55,7 +56,7 @@ class AnimeClientTestCase extends TestCase {
array_map('unlink', $files); array_map('unlink', $files);
} }
public function setUp(): void protected function setUp(): void
{ {
parent::setUp(); parent::setUp();
@ -66,7 +67,7 @@ class AnimeClientTestCase extends TestCase {
'data_cache_path' => _dir(self::TEST_DATA_DIR, 'cache'), 'data_cache_path' => _dir(self::TEST_DATA_DIR, 'cache'),
'cache' => [ 'cache' => [
'driver' => 'null', 'driver' => 'null',
'connection' => [] 'connection' => [],
], ],
'database' => [ 'database' => [
'collection' => [ 'collection' => [
@ -88,7 +89,7 @@ class AnimeClientTestCase extends TestCase {
'name' => 'default', 'name' => 'default',
'database' => '', 'database' => '',
'file' => ':memory:', 'file' => ':memory:',
] ],
], ],
'routes' => [], 'routes' => [],
]; ];
@ -101,6 +102,7 @@ class AnimeClientTestCase extends TestCase {
$container->set('session-handler', static function () { $container->set('session-handler', static function () {
$session_handler = new TestSessionHandler(); $session_handler = new TestSessionHandler();
session_set_save_handler($session_handler, TRUE); session_set_save_handler($session_handler, TRUE);
return $session_handler; return $session_handler;
}); });
@ -111,7 +113,6 @@ class AnimeClientTestCase extends TestCase {
* Set arbitrary superglobal values for testing purposes * Set arbitrary superglobal values for testing purposes
* *
* @param array $supers * @param array $supers
* @return void
*/ */
public function setSuperGlobals($supers = []): void public function setSuperGlobals($supers = []): void
{ {
@ -120,17 +121,15 @@ class AnimeClientTestCase extends TestCase {
'_GET' => $_GET, '_GET' => $_GET,
'_POST' => $_POST, '_POST' => $_POST,
'_COOKIE' => $_COOKIE, '_COOKIE' => $_COOKIE,
'_FILES' => $_FILES '_FILES' => $_FILES,
]; ];
$request = \call_user_func_array( $request = call_user_func_array(
[ServerRequestFactory::class, 'fromGlobals'], [ServerRequestFactory::class, 'fromGlobals'],
array_values(array_merge($default, $supers)), array_values(array_merge($default, $supers)),
); );
$this->container->setInstance('request', $request); $this->container->setInstance('request', $request);
$this->container->set('response', static function() { $this->container->set('response', static fn () => new HttpResponse());
return new HttpResponse();
});
} }
/** /**

View File

@ -18,19 +18,24 @@ namespace Aviat\AnimeClient\Tests\Command;
use Aviat\AnimeClient\Command\BaseCommand; use Aviat\AnimeClient\Command\BaseCommand;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
use Aviat\Ion\Di\Container;
use Aviat\Ion\Friend; use Aviat\Ion\Friend;
use ConsoleKit\Console; use ConsoleKit\Console;
use Aviat\Ion\Di\Container;
class Command extends BaseCommand {
class Command extends BaseCommand
{
} }
class BaseCommandTest extends AnimeClientTestCase { /**
* @internal
*/
final class BaseCommandTest extends AnimeClientTestCase
{
protected Command $base; protected Command $base;
protected Friend $friend; protected Friend $friend;
public function setUp(): void { protected function setUp(): void
{
$this->base = new Command(new Console()); $this->base = new Command(new Console());
$this->friend = new Friend($this->base); $this->friend = new Friend($this->base);
} }

View File

@ -16,22 +16,23 @@
namespace Aviat\AnimeClient\Tests; namespace Aviat\AnimeClient\Tests;
use Aura\Router\RouterFactory;
use Aura\Web\WebFactory;
use Aviat\AnimeClient\Controller; use Aviat\AnimeClient\Controller;
use Aviat\AnimeClient\Controller\{ use Aviat\AnimeClient\Controller\{
Anime as AnimeController, Anime as AnimeController,
Character as CharacterController,
AnimeCollection as AnimeCollectionController, AnimeCollection as AnimeCollectionController,
// MangaCollection as MangaCollectionController, Character as CharacterController,
Manga as MangaController Manga as MangaController // MangaCollection as MangaCollectionController,
}; };
class ControllerTest extends AnimeClientTestCase { /**
* @internal
*/
final class ControllerTest extends AnimeClientTestCase
{
protected $BaseController; protected $BaseController;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
// Create Request/Response Objects // Create Request/Response Objects
@ -41,7 +42,7 @@ class ControllerTest extends AnimeClientTestCase {
'_POST' => [], '_POST' => [],
'_COOKIE' => [], '_COOKIE' => [],
'_SERVER' => $GLOBALS['_SERVER'], '_SERVER' => $GLOBALS['_SERVER'],
'_FILES' => [] '_FILES' => [],
]); ]);
$this->BaseController = new Controller($this->container); $this->BaseController = new Controller($this->container);
@ -53,7 +54,7 @@ class ControllerTest extends AnimeClientTestCase {
$config->set('database', [ $config->set('database', [
'type' => 'sqlite', 'type' => 'sqlite',
'database' => '', 'database' => '',
'file' => ":memory:" 'file' => ':memory:',
]); ]);
$this->container->setInstance('config', $config); $this->container->setInstance('config', $config);
@ -81,15 +82,14 @@ class ControllerTest extends AnimeClientTestCase {
public function testBaseControllerSanity() public function testBaseControllerSanity()
{ {
$this->assertTrue(\is_object($this->BaseController)); $this->assertIsObject($this->BaseController);
} }
public function testFormatTitle() public function testFormatTitle()
{ {
$this->assertEquals( $this->assertSame(
$this->BaseController->formatTitle('foo', 'bar', 'baz'), $this->BaseController->formatTitle('foo', 'bar', 'baz'),
'foo · bar · baz' 'foo · bar · baz'
); );
} }
} }

View File

@ -17,17 +17,19 @@
namespace Aviat\AnimeClient\Tests; namespace Aviat\AnimeClient\Tests;
use Aura\Router\Route; use Aura\Router\Route;
use Aviat\AnimeClient\Controller; use Aviat\AnimeClient\{Controller, Dispatcher, UrlGenerator};
use Aviat\AnimeClient\Dispatcher;
use Aviat\AnimeClient\UrlGenerator;
use Aviat\Ion\Config; use Aviat\Ion\Config;
use Aviat\Ion\Di\ContainerInterface; use Aviat\Ion\Di\ContainerInterface;
use InvalidArgumentException;
use JetBrains\PhpStorm\ArrayShape;
use Monolog\Handler\TestHandler; use Monolog\Handler\TestHandler;
use Monolog\Logger; use Monolog\Logger;
/**
class DispatcherTest extends AnimeClientTestCase { * @internal
*/
final class DispatcherTest extends AnimeClientTestCase
{
protected ContainerInterface $container; protected ContainerInterface $container;
protected $router; protected $router;
protected $config; protected $config;
@ -41,11 +43,11 @@ class DispatcherTest extends AnimeClientTestCase {
'REQUEST_URI' => $uri, 'REQUEST_URI' => $uri,
'PATH_INFO' => $uri, 'PATH_INFO' => $uri,
'HTTP_HOST' => $host, 'HTTP_HOST' => $host,
'SERVER_NAME' => $host 'SERVER_NAME' => $host,
]); ]);
$this->setSuperGlobals([ $this->setSuperGlobals([
'_SERVER' => $GLOBALS['_SERVER'] '_SERVER' => $GLOBALS['_SERVER'],
]); ]);
$logger = new Logger('test_logger'); $logger = new Logger('test_logger');
@ -78,7 +80,7 @@ class DispatcherTest extends AnimeClientTestCase {
'login_form' => [ 'login_form' => [
'path' => '/login', 'path' => '/login',
'action' => 'login', 'action' => 'login',
'verb' => 'get' 'verb' => 'get',
], ],
'watching' => [ 'watching' => [
'path' => '/anime/watching{/view}', 'path' => '/anime/watching{/view}',
@ -87,8 +89,8 @@ class DispatcherTest extends AnimeClientTestCase {
'type' => 'currently-watching', 'type' => 'currently-watching',
], ],
'tokens' => [ 'tokens' => [
'view' => '[a-z_]+' 'view' => '[a-z_]+',
] ],
], ],
'plan_to_read' => [ 'plan_to_read' => [
'path' => '/manga/plan_to_read{/view}', 'path' => '/manga/plan_to_read{/view}',
@ -97,15 +99,15 @@ class DispatcherTest extends AnimeClientTestCase {
'type' => 'Plan to Read', 'type' => 'Plan to Read',
], ],
'tokens' => [ 'tokens' => [
'view' => '[a-z_]+' 'view' => '[a-z_]+',
] ],
], ],
], ],
'config' => [ 'config' => [
'anime_path' => 'anime', 'anime_path' => 'anime',
'manga_path' => 'manga', 'manga_path' => 'manga',
'default_list' => 'anime' 'default_list' => 'anime',
] ],
]; ];
$data = [ $data = [
@ -131,8 +133,8 @@ class DispatcherTest extends AnimeClientTestCase {
'config' => $defaultConfig, 'config' => $defaultConfig,
'controller' => 'manga', 'controller' => 'manga',
'host' => 'localhost', 'host' => 'localhost',
'uri' => '/manga/plan_to_read' 'uri' => '/manga/plan_to_read',
] ],
]; ];
$data['manga_default_routing_anime']['config']['default_list'] = 'manga'; $data['manga_default_routing_anime']['config']['default_list'] = 'manga';
@ -143,6 +145,10 @@ class DispatcherTest extends AnimeClientTestCase {
/** /**
* @dataProvider dataRoute * @dataProvider dataRoute
* @param mixed $config
* @param mixed $controller
* @param mixed $host
* @param mixed $uri
*/ */
public function testRoute($config, $controller, $host, $uri): void public function testRoute($config, $controller, $host, $uri): void
{ {
@ -151,16 +157,16 @@ class DispatcherTest extends AnimeClientTestCase {
$request = $this->container->get('request'); $request = $this->container->get('request');
// Check route setup // Check route setup
$this->assertEquals($config['routes'], $this->config->get('routes'), 'Incorrect route path'); $this->assertSame($config['routes'], $this->config->get('routes'), 'Incorrect route path');
$this->assertIsArray($this->router->getOutputRoutes()); $this->assertIsArray($this->router->getOutputRoutes());
// Check environment variables // Check environment variables
$this->assertEquals($uri, $request->getServerParams()['REQUEST_URI']); $this->assertSame($uri, $request->getServerParams()['REQUEST_URI']);
$this->assertEquals($host, $request->getServerParams()['HTTP_HOST']); $this->assertSame($host, $request->getServerParams()['HTTP_HOST']);
// Make sure the route is an anime type // Make sure the route is an anime type
//$this->assertTrue($matcher->count() > 0, '0 routes'); //$this->assertTrue($matcher->count() > 0, '0 routes');
$this->assertEquals($controller, $this->router->getController(), 'Incorrect Route type'); $this->assertSame($controller, $this->router->getController(), 'Incorrect Route type');
// Make sure the route matches, by checking that it is actually an object // Make sure the route matches, by checking that it is actually an object
$route = $this->router->getRoute(); $route = $this->router->getRoute();
@ -175,13 +181,13 @@ class DispatcherTest extends AnimeClientTestCase {
'manga_path' => 'manga', 'manga_path' => 'manga',
'default_anime_list_path' => 'watching', 'default_anime_list_path' => 'watching',
'default_manga_list_path' => 'all', 'default_manga_list_path' => 'all',
'default_list' => 'manga' 'default_list' => 'manga',
], ],
'routes' => [ 'routes' => [
'login_form' => [ 'login_form' => [
'path' => '/login', 'path' => '/login',
'action' => ['login'], 'action' => ['login'],
'verb' => 'get' 'verb' => 'get',
], ],
'index' => [ 'index' => [
'path' => '/', 'path' => '/',
@ -189,21 +195,22 @@ class DispatcherTest extends AnimeClientTestCase {
'params' => [ 'params' => [
'url' => '', // Determined by config 'url' => '', // Determined by config
'code' => '301', 'code' => '301',
'type' => 'manga' 'type' => 'manga',
] ],
] ],
] ],
]; ];
$this->expectException(\InvalidArgumentException::class); $this->expectException(InvalidArgumentException::class);
$this->doSetUp($config, '/', 'localhost'); $this->doSetUp($config, '/', 'localhost');
$this->assertEquals('//localhost/manga/all', $this->urlGenerator->defaultUrl('manga'), 'Incorrect default url'); $this->assertSame('//localhost/manga/all', $this->urlGenerator->defaultUrl('manga'), 'Incorrect default url');
$this->assertEquals('//localhost/anime/watching', $this->urlGenerator->defaultUrl('anime'), 'Incorrect default url'); $this->assertSame('//localhost/anime/watching', $this->urlGenerator->defaultUrl('anime'), 'Incorrect default url');
$this->urlGenerator->defaultUrl('foo'); $this->urlGenerator->defaultUrl('foo');
} }
#[ArrayShape(['controller_list_sanity_check' => "array", 'empty_controller_list' => "array"])]
public function dataGetControllerList(): array public function dataGetControllerList(): array
{ {
$expectedList = [ $expectedList = [
@ -240,15 +247,15 @@ class DispatcherTest extends AnimeClientTestCase {
'default_list' => 'manga', 'default_list' => 'manga',
'routes' => [], 'routes' => [],
], ],
'expected' => $expectedList 'expected' => $expectedList,
] ],
]; ];
} }
/** /**
* @dataProvider dataGetControllerList * @dataProvider dataGetControllerList
*/ */
public function testGetControllerList($config, $expected): void public function testGetControllerList(array $config, array $expected): void
{ {
$this->doSetUp($config, '/', 'localhost'); $this->doSetUp($config, '/', 'localhost');
$this->assertEquals($expected, $this->router->getControllerList()); $this->assertEquals($expected, $this->router->getControllerList());

View File

@ -74,7 +74,7 @@ const SETTINGS_MAP = [
'display' => FALSE, 'display' => FALSE,
'description' => '', 'description' => '',
'value' => 'foo_bar', 'value' => 'foo_bar',
] ],
], ],
'cache' => [ 'cache' => [
@ -86,7 +86,7 @@ const SETTINGS_MAP = [
'APCu' => 'apcu', 'APCu' => 'apcu',
'Memcached' => 'memcached', 'Memcached' => 'memcached',
'Redis' => 'redis', 'Redis' => 'redis',
'No Cache' => 'null' 'No Cache' => 'null',
], ],
], ],
'connection' => [ 'connection' => [
@ -147,7 +147,7 @@ const SETTINGS_MAP = [
'Automatically match OS theme' => 'auto', 'Automatically match OS theme' => 'auto',
'Original Light Theme' => 'light', 'Original Light Theme' => 'light',
'Dark Theme' => 'dark', 'Dark Theme' => 'dark',
] ],
], ],
'show_anime_collection' => [ 'show_anime_collection' => [
'type' => 'boolean', 'type' => 'boolean',
@ -181,7 +181,7 @@ const SETTINGS_MAP = [
'Dropped' => 'dropped', 'Dropped' => 'dropped',
'Completed' => 'completed', 'Completed' => 'completed',
'All' => 'all', 'All' => 'all',
] ],
], ],
'default_manga_list_path' => [ //reading|plan_to_read|on_hold|dropped|completed|all 'default_manga_list_path' => [ //reading|plan_to_read|on_hold|dropped|completed|all
'type' => 'select', 'type' => 'select',
@ -194,8 +194,8 @@ const SETTINGS_MAP = [
'Dropped' => 'dropped', 'Dropped' => 'dropped',
'Completed' => 'completed', 'Completed' => 'completed',
'All' => 'all', 'All' => 'all',
] ],
] ],
], ],
'database' => [ 'database' => [
'type' => [ 'type' => [
@ -222,7 +222,7 @@ const SETTINGS_MAP = [
'pass' => [ 'pass' => [
'type' => 'string', 'type' => 'string',
'title' => 'Password', 'title' => 'Password',
'description' => 'Database connection password' 'description' => 'Database connection password',
], ],
'port' => [ 'port' => [
'type' => 'string', 'type' => 'string',
@ -244,11 +244,15 @@ const SETTINGS_MAP = [
], ],
]; ];
/**
class FormGeneratorTest extends AnimeClientTestCase { * @internal
*/
final class FormGeneratorTest extends AnimeClientTestCase
{
public function testGeneration(): void public function testGeneration(): void
{ {
$generator = FormGenerator::new($this->container); $generator = FormGenerator::new($this->container);
foreach (SETTINGS_MAP as $section => $fields) foreach (SETTINGS_MAP as $section => $fields)
{ {
foreach ($fields as $name => $config) foreach ($fields as $name => $config)

View File

@ -19,7 +19,11 @@ namespace Aviat\AnimeClient\Tests\Helper;
use Aviat\AnimeClient\Helper\Form as FormHelper; use Aviat\AnimeClient\Helper\Form as FormHelper;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
class FormHelperTest extends AnimeClientTestCase { /**
* @internal
*/
final class FormHelperTest extends AnimeClientTestCase
{
public function testFormHelper(): void public function testFormHelper(): void
{ {
$helper = new FormHelper(); $helper = new FormHelper();
@ -29,7 +33,7 @@ class FormHelperTest extends AnimeClientTestCase {
'type' => 'text', 'type' => 'text',
'value' => 'foo', 'value' => 'foo',
'placeholder' => 'field', 'placeholder' => 'field',
'name' => 'test' 'name' => 'test',
]); ]);
$this->assertMatchesSnapshot($actual); $this->assertMatchesSnapshot($actual);

View File

@ -19,12 +19,16 @@ namespace Aviat\AnimeClient\Tests\Helper;
use Aviat\AnimeClient\Helper\Menu as MenuHelper; use Aviat\AnimeClient\Helper\Menu as MenuHelper;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
class MenuHelperTest extends AnimeClientTestCase { /**
* @internal
*/
final class MenuHelperTest extends AnimeClientTestCase
{
protected $helper; protected $helper;
protected $urlGenerator; protected $urlGenerator;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->helper = $this->container->get('html-helper'); $this->helper = $this->container->get('html-helper');
$this->urlGenerator = $this->container->get('url-generator'); $this->urlGenerator = $this->container->get('url-generator');
@ -36,15 +40,15 @@ class MenuHelperTest extends AnimeClientTestCase {
'no selection' => [ 'no selection' => [
'route_prefix' => '/foo', 'route_prefix' => '/foo',
'items' => [ 'items' => [
'bar' => '/bar' 'bar' => '/bar',
] ],
], ],
'selected' => [ 'selected' => [
'route_prefix' => '', 'route_prefix' => '',
'items' => [ 'items' => [
'index' => '/foobar' 'index' => '/foobar',
] ],
] ],
]; ];
$expected = []; $expected = [];
@ -71,8 +75,8 @@ class MenuHelperTest extends AnimeClientTestCase {
$this->setSuperGlobals([ $this->setSuperGlobals([
'_SERVER' => [ '_SERVER' => [
'HTTP_HOST' => 'localhost', 'HTTP_HOST' => 'localhost',
'REQUEST_URI' => '/foobar' 'REQUEST_URI' => '/foobar',
] ],
]); ]);
} }
else else
@ -80,14 +84,14 @@ class MenuHelperTest extends AnimeClientTestCase {
$this->setSuperGlobals([ $this->setSuperGlobals([
'_SERVER' => [ '_SERVER' => [
'HTTP_HOST' => 'localhost', 'HTTP_HOST' => 'localhost',
'REQUEST_URI' => '/applesauceisgreat' 'REQUEST_URI' => '/applesauceisgreat',
] ],
]); ]);
} }
$helper = new MenuHelper(); $helper = new MenuHelper();
$helper->setContainer($this->container); $helper->setContainer($this->container);
$this->assertEquals($expected[$case], (string)$helper($case)); $this->assertSame($expected[$case], (string) $helper($case));
} }
} }
} }

View File

@ -19,10 +19,13 @@ namespace Aviat\AnimeClient\Tests\Helper;
use Aviat\AnimeClient\Helper\Picture as PictureHelper; use Aviat\AnimeClient\Helper\Picture as PictureHelper;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
class PictureHelperTest extends AnimeClientTestCase { /**
* @internal
*/
final class PictureHelperTest extends AnimeClientTestCase
{
/** /**
* @dataProvider dataPictureCase * @dataProvider dataPictureCase
* @param array $params
*/ */
public function testPictureHelper(array $params): void public function testPictureHelper(array $params): void
{ {
@ -36,9 +39,6 @@ class PictureHelperTest extends AnimeClientTestCase {
/** /**
* @dataProvider dataSimpleImageCase * @dataProvider dataSimpleImageCase
* @param string $ext
* @param bool $isSimple
* @param string $fallbackExt
*/ */
public function testSimpleImage(string $ext, bool $isSimple, string $fallbackExt = 'jpg'): void public function testSimpleImage(string $ext, bool $isSimple, string $fallbackExt = 'jpg'): void
{ {
@ -50,7 +50,7 @@ class PictureHelperTest extends AnimeClientTestCase {
$actuallySimple = ! str_contains($actual, '<picture'); $actuallySimple = ! str_contains($actual, '<picture');
$this->assertEquals($isSimple, $actuallySimple); $this->assertSame($isSimple, $actuallySimple);
} }
public function testSimpleImageByFallback(): void public function testSimpleImageByFallback(): void
@ -58,7 +58,7 @@ class PictureHelperTest extends AnimeClientTestCase {
$helper = new PictureHelper(); $helper = new PictureHelper();
$helper->setContainer($this->container); $helper->setContainer($this->container);
$actual = $helper("foo.svg", 'svg'); $actual = $helper('foo.svg', 'svg');
$this->assertTrue( ! str_contains($actual, '<picture')); $this->assertTrue( ! str_contains($actual, '<picture'));
} }
@ -78,7 +78,7 @@ class PictureHelperTest extends AnimeClientTestCase {
], ],
'Partial webp URL' => [ 'Partial webp URL' => [
'params' => [ 'params' => [
'images/anime/15424.webp' 'images/anime/15424.webp',
], ],
], ],
'bmp with gif fallback' => [ 'bmp with gif fallback' => [
@ -90,25 +90,25 @@ class PictureHelperTest extends AnimeClientTestCase {
'webp placeholder image' => [ 'webp placeholder image' => [
'params' => [ 'params' => [
'images/placeholder.webp', 'images/placeholder.webp',
] ],
], ],
'png placeholder image' => [ 'png placeholder image' => [
'params' => [ 'params' => [
'images/placeholder.png', 'images/placeholder.png',
] ],
], ],
'jpeg2000' => [ 'jpeg2000' => [
'params' => [ 'params' => [
'images/foo.jpf', 'images/foo.jpf',
] ],
], ],
'svg with png fallback and lots of attributes' => [ 'svg with png fallback and lots of attributes' => [
'params' => [ 'params' => [
'images/example.svg', 'images/example.svg',
'png', 'png',
['width' => 200, 'height' => 300], ['width' => 200, 'height' => 300],
[ 'alt' => 'Example text' ] ['alt' => 'Example text'],
] ],
], ],
'simple image with attributes' => [ 'simple image with attributes' => [
'params' => [ 'params' => [
@ -116,8 +116,8 @@ class PictureHelperTest extends AnimeClientTestCase {
'jpg', 'jpg',
[], [],
['width' => 200, 'height' => 200, 'alt' => 'should exist'], ['width' => 200, 'height' => 200, 'alt' => 'should exist'],
] ],
] ],
]; ];
} }
@ -127,7 +127,7 @@ class PictureHelperTest extends AnimeClientTestCase {
'avif' => [ 'avif' => [
'ext' => 'avif', 'ext' => 'avif',
'isSimple' => FALSE, 'isSimple' => FALSE,
'fallback' => 'jpf' 'fallback' => 'jpf',
], ],
'apng' => [ 'apng' => [
'ext' => 'apng', 'ext' => 'apng',

View File

@ -1 +1,3 @@
<?php return '<picture loading="lazy"><source srcset="https://www.example.com/image.webp" type="image/webp" /><source srcset="https://www.example.com/image.jpg" type="image/jpeg" /><img src="https://www.example.com/image.jpg" alt="" loading="lazy" /></picture>'; <?php declare(strict_types=1);
return '<picture loading="lazy"><source srcset="https://www.example.com/image.webp" type="image/webp" /><source srcset="https://www.example.com/image.jpg" type="image/jpeg" /><img src="https://www.example.com/image.jpg" alt="" loading="lazy" /></picture>';

View File

@ -1 +1,3 @@
<?php return '<picture loading="lazy"><source srcset="https://localhost/assets/images/anime/15424.webp" type="image/webp" /><source srcset="https://localhost/assets/images/anime/15424.jpg" type="image/jpeg" /><img src="https://localhost/assets/images/anime/15424.jpg" alt="" loading="lazy" /></picture>'; <?php declare(strict_types=1);
return '<picture loading="lazy"><source srcset="https://localhost/assets/images/anime/15424.webp" type="image/webp" /><source srcset="https://localhost/assets/images/anime/15424.jpg" type="image/jpeg" /><img src="https://localhost/assets/images/anime/15424.jpg" alt="" loading="lazy" /></picture>';

View File

@ -1 +1,3 @@
<?php return '<picture loading="lazy"><source srcset="https://localhost/assets/images/avatar/25.bmp" type="image/bmp" /><source srcset="https://localhost/assets/images/avatar/25.gif" type="image/gif" /><img src="https://localhost/assets/images/avatar/25.gif" alt="" loading="lazy" /></picture>'; <?php declare(strict_types=1);
return '<picture loading="lazy"><source srcset="https://localhost/assets/images/avatar/25.bmp" type="image/bmp" /><source srcset="https://localhost/assets/images/avatar/25.gif" type="image/gif" /><img src="https://localhost/assets/images/avatar/25.gif" alt="" loading="lazy" /></picture>';

View File

@ -1 +1,3 @@
<?php return '<picture loading="lazy"><source srcset="https://localhost/assets/images/foo.jpf" type="image/jpx" /><source srcset="https://localhost/assets/images/foo.jpg" type="image/jpeg" /><img src="https://localhost/assets/images/foo.jpg" alt="" loading="lazy" /></picture>'; <?php declare(strict_types=1);
return '<picture loading="lazy"><source srcset="https://localhost/assets/images/foo.jpf" type="image/jpx" /><source srcset="https://localhost/assets/images/foo.jpg" type="image/jpeg" /><img src="https://localhost/assets/images/foo.jpg" alt="" loading="lazy" /></picture>';

View File

@ -1 +1,3 @@
<?php return '<img src="https://localhost/assets/images/placeholder.png" alt="placeholder.png" loading="lazy" />'; <?php declare(strict_types=1);
return '<img src="https://localhost/assets/images/placeholder.png" alt="placeholder.png" loading="lazy" />';

View File

@ -1 +1,3 @@
<?php return '<img src="https://localhost/assets/images/foo.jpg" alt="should exist" width="200" height="200" loading="lazy" />'; <?php declare(strict_types=1);
return '<img src="https://localhost/assets/images/foo.jpg" alt="should exist" width="200" height="200" loading="lazy" />';

View File

@ -1 +1,3 @@
<?php return '<picture width="200" height="300" loading="lazy"><source srcset="https://localhost/assets/images/example.svg" type="image/svg+xml" /><source srcset="https://localhost/assets/images/example.png" type="image/png" /><img src="https://localhost/assets/images/example.png" alt="Example text" loading="lazy" /></picture>'; <?php declare(strict_types=1);
return '<picture width="200" height="300" loading="lazy"><source srcset="https://localhost/assets/images/example.svg" type="image/svg+xml" /><source srcset="https://localhost/assets/images/example.png" type="image/png" /><img src="https://localhost/assets/images/example.png" alt="Example text" loading="lazy" /></picture>';

View File

@ -1 +1,3 @@
<?php return '<picture loading="lazy"><source srcset="https://localhost/assets/images/placeholder.webp" type="image/webp" /><source srcset="https://localhost/assets/images/placeholder.png" type="image/png" /><img src="https://localhost/assets/images/placeholder.png" alt="" loading="lazy" /></picture>'; <?php declare(strict_types=1);
return '<picture loading="lazy"><source srcset="https://localhost/assets/images/placeholder.webp" type="image/webp" /><source srcset="https://localhost/assets/images/placeholder.png" type="image/png" /><img src="https://localhost/assets/images/placeholder.png" alt="" loading="lazy" /></picture>';

View File

@ -16,21 +16,24 @@
namespace Aviat\AnimeClient\Tests\API; namespace Aviat\AnimeClient\Tests\API;
use Aviat\AnimeClient\API\Kitsu\Enum\MangaPublishingStatus; use Aviat\AnimeClient\API\Kitsu\Enum\{AnimeAiringStatus, MangaPublishingStatus};
use Aviat\AnimeClient\Kitsu; use Aviat\AnimeClient\Kitsu;
use Aviat\AnimeClient\API\Kitsu\Enum\AnimeAiringStatus;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class KitsuTest extends TestCase { /**
* @internal
*/
final class KitsuTest extends TestCase
{
public function testGetAiringStatus(): void public function testGetAiringStatus(): void
{ {
$actual = Kitsu::getAiringStatus('next week', 'next year'); $actual = Kitsu::getAiringStatus('next week', 'next year');
$this->assertEquals(AnimeAiringStatus::NOT_YET_AIRED, $actual); $this->assertSame(AnimeAiringStatus::NOT_YET_AIRED, $actual);
} }
public function testParseStreamingLinksEmpty(): void public function testParseStreamingLinksEmpty(): void
{ {
$this->assertEquals([], Kitsu::parseStreamingLinks([])); $this->assertSame([], Kitsu::parseStreamingLinks([]));
} }
public function testParseStreamingLinks(): void public function testParseStreamingLinks(): void
@ -38,7 +41,7 @@ class KitsuTest extends TestCase {
$nodes = [[ $nodes = [[
'url' => 'www.hulu.com/chobits', 'url' => 'www.hulu.com/chobits',
'dubs' => ['ja'], 'dubs' => ['ja'],
'subs' => ['en'] 'subs' => ['en'],
]]; ]];
$expected = [[ $expected = [[
@ -63,17 +66,17 @@ class KitsuTest extends TestCase {
'subs' => [], 'subs' => [],
]]; ]];
$this->assertEquals([], Kitsu::parseStreamingLinks($nodes)); $this->assertSame([], Kitsu::parseStreamingLinks($nodes));
} }
public function testGetAiringStatusEmptyArguments(): void public function testGetAiringStatusEmptyArguments(): void
{ {
$this->assertEquals(AnimeAiringStatus::NOT_YET_AIRED, Kitsu::getAiringStatus()); $this->assertSame(AnimeAiringStatus::NOT_YET_AIRED, Kitsu::getAiringStatus());
} }
public function testGetAiringStatusIsAiring(): void public function testGetAiringStatusIsAiring(): void
{ {
$this->assertEquals(AnimeAiringStatus::AIRING, Kitsu::getAiringStatus('yesterday')); $this->assertSame(AnimeAiringStatus::AIRING, Kitsu::getAiringStatus('yesterday'));
} }
public function getPublishingStatus(): array public function getPublishingStatus(): array
@ -86,19 +89,17 @@ class KitsuTest extends TestCase {
'future' => [ 'future' => [
'kitsuStatus' => 'foo', 'kitsuStatus' => 'foo',
'expected' => MangaPublishingStatus::NOT_YET_PUBLISHED, 'expected' => MangaPublishingStatus::NOT_YET_PUBLISHED,
] ],
]; ];
} }
/** /**
* @param string $kitsuStatus
* @param string $expected
* @dataProvider getPublishingStatus * @dataProvider getPublishingStatus
*/ */
public function testGetPublishingStatus(string $kitsuStatus, string $expected): void public function testGetPublishingStatus(string $kitsuStatus, string $expected): void
{ {
$actual = Kitsu::getPublishingStatus($kitsuStatus); $actual = Kitsu::getPublishingStatus($kitsuStatus);
$this->assertEquals($expected, $actual); $this->assertSame($expected, $actual);
} }
public function getFriendlyTime(): array public function getFriendlyTime(): array
@ -115,23 +116,21 @@ class KitsuTest extends TestCase {
'expected' => '1 hour', 'expected' => '1 hour',
], [ ], [
'seconds' => (2 * $SECONDS_IN_YEAR) + 30, 'seconds' => (2 * $SECONDS_IN_YEAR) + 30,
'expected' => '2 years, 30 seconds' 'expected' => '2 years, 30 seconds',
], [ ], [
'seconds' => (5 * $SECONDS_IN_YEAR) + (3 * $SECONDS_IN_DAY) + (17 * Kitsu::SECONDS_IN_MINUTE), 'seconds' => (5 * $SECONDS_IN_YEAR) + (3 * $SECONDS_IN_DAY) + (17 * Kitsu::SECONDS_IN_MINUTE),
'expected' => '5 years, 3 days, and 17 minutes' 'expected' => '5 years, 3 days, and 17 minutes',
]]; ]];
} }
/** /**
* @param int $seconds
* @param string $expected
* @dataProvider getFriendlyTime * @dataProvider getFriendlyTime
*/ */
public function testGetFriendlyTime(int $seconds, string $expected): void public function testGetFriendlyTime(int $seconds, string $expected): void
{ {
$actual = Kitsu::friendlyTime($seconds); $actual = Kitsu::friendlyTime($seconds);
$this->assertEquals($expected, $actual); $this->assertSame($expected, $actual);
} }
public function testFilterLocalizedTitles(): void public function testFilterLocalizedTitles(): void
@ -148,7 +147,7 @@ class KitsuTest extends TestCase {
$actual = Kitsu::filterLocalizedTitles($input); $actual = Kitsu::filterLocalizedTitles($input);
$this->assertEquals(['Foo the Movie'], $actual); $this->assertSame(['Foo the Movie'], $actual);
} }
public function testGetFilteredTitles(): void public function testGetFilteredTitles(): void
@ -156,13 +155,13 @@ class KitsuTest extends TestCase {
$input = [ $input = [
'canonical' => 'foo', 'canonical' => 'foo',
'localized' => [ 'localized' => [
'en' => 'Foo the Movie' 'en' => 'Foo the Movie',
], ],
'alternatives' => [], 'alternatives' => [],
]; ];
$actual = Kitsu::getFilteredTitles($input); $actual = Kitsu::getFilteredTitles($input);
$this->assertEquals(['Foo the Movie'], $actual); $this->assertSame(['Foo the Movie'], $actual);
} }
} }

View File

@ -19,12 +19,16 @@ namespace Aviat\AnimeClient\Tests;
use Aviat\AnimeClient\MenuGenerator; use Aviat\AnimeClient\MenuGenerator;
use Aviat\Ion\Friend; use Aviat\Ion\Friend;
class MenuGeneratorTest extends AnimeClientTestCase { /**
* @internal
*/
final class MenuGeneratorTest extends AnimeClientTestCase
{
protected $generator; protected $generator;
protected $friend; protected $friend;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->generator = MenuGenerator::new($this->container); $this->generator = MenuGenerator::new($this->container);
} }
@ -47,8 +51,8 @@ class MenuGeneratorTest extends AnimeClientTestCase {
'on_hold' => '/on_hold', 'on_hold' => '/on_hold',
'dropped' => '/dropped', 'dropped' => '/dropped',
'completed' => '/completed', 'completed' => '/completed',
'all' => '/all' 'all' => '/all',
] ],
], ],
]; ];
$expected = [ $expected = [
@ -58,10 +62,10 @@ class MenuGeneratorTest extends AnimeClientTestCase {
'On Hold' => '/anime/on_hold', 'On Hold' => '/anime/on_hold',
'Dropped' => '/anime/dropped', 'Dropped' => '/anime/dropped',
'Completed' => '/anime/completed', 'Completed' => '/anime/completed',
'All' => '/anime/all' 'All' => '/anime/all',
] ],
]; ];
$this->assertEquals($expected, $friend->parseConfig($menus)); $this->assertSame($expected, $friend->parseConfig($menus));
} }
public function testBadConfig() public function testBadConfig()
@ -75,8 +79,8 @@ class MenuGeneratorTest extends AnimeClientTestCase {
'on_hold' => '/on_hold', 'on_hold' => '/on_hold',
'dropped' => '/dropped', 'dropped' => '/dropped',
'completed' => '/completed', 'completed' => '/completed',
'all' => '/all' 'all' => '/all',
] ],
], ],
]; ];
$config = $this->container->get('config'); $config = $this->container->get('config');
@ -84,6 +88,6 @@ class MenuGeneratorTest extends AnimeClientTestCase {
$this->container->setInstance('config', $config); $this->container->setInstance('config', $config);
$expected = ''; $expected = '';
$this->assertEquals($expected, $this->generator->generate('manga_list')); $this->assertSame($expected, $this->generator->generate('manga_list'));
} }
} }

View File

@ -18,11 +18,14 @@ namespace Aviat\AnimeClient\Tests;
use PDO; use PDO;
class RequirementsTest extends AnimeClientTestCase { /**
* @internal
*/
final class RequirementsTest extends AnimeClientTestCase
{
public function testPHPVersion(): void public function testPHPVersion(): void
{ {
$this->assertTrue(version_compare(PHP_VERSION, "8", "ge")); $this->assertTrue(version_compare(PHP_VERSION, '8', 'ge'));
} }
public function testHasPDO(): void public function testHasPDO(): void
@ -33,6 +36,6 @@ class RequirementsTest extends AnimeClientTestCase {
public function testHasPDOSqlite(): void public function testHasPDOSqlite(): void
{ {
$drivers = PDO::getAvailableDrivers(); $drivers = PDO::getAvailableDrivers();
$this->assertTrue(in_array('sqlite', $drivers)); $this->assertTrue(in_array('sqlite', $drivers, TRUE));
} }
} }

View File

@ -17,9 +17,14 @@
namespace Aviat\AnimeClient\Tests; namespace Aviat\AnimeClient\Tests;
use Aviat\AnimeClient\RoutingBase; use Aviat\AnimeClient\RoutingBase;
use JetBrains\PhpStorm\ArrayShape;
class RoutingBaseTest extends AnimeClientTestCase { /**
* @internal
*/
final class RoutingBaseTest extends AnimeClientTestCase
{
#[ArrayShape(['empty_segment' => "array", 'three_segments' => "array"])]
public function dataSegments() public function dataSegments()
{ {
return [ return [
@ -27,33 +32,33 @@ class RoutingBaseTest extends AnimeClientTestCase {
'requestUri' => ' // ', 'requestUri' => ' // ',
'path' => '/', 'path' => '/',
'segments' => ['', ''], 'segments' => ['', ''],
'lastSegment' => NULL 'lastSegment' => NULL,
], ],
'three_segments' => [ 'three_segments' => [
'requestUri' => '/anime/watching/list ', 'requestUri' => '/anime/watching/list ',
'path' => '/anime/watching/list', 'path' => '/anime/watching/list',
'segments' => ['', 'anime', 'watching', 'list'], 'segments' => ['', 'anime', 'watching', 'list'],
'lastSegment' => 'list' 'lastSegment' => 'list',
] ],
]; ];
} }
/** /**
* @dataProvider dataSegments * @dataProvider dataSegments
*/ */
public function testSegments(string $requestUri, string $path, array $segments, $lastSegment): void public function testSegments(string $requestUri, string $path, array $segments, ?string $lastSegment): void
{ {
$this->setSuperGlobals([ $this->setSuperGlobals([
'_SERVER' => [ '_SERVER' => [
'REQUEST_URI' => $requestUri 'REQUEST_URI' => $requestUri,
] ],
]); ]);
$routingBase = new RoutingBase($this->container); $routingBase = new RoutingBase($this->container);
$this->assertEquals($path, $routingBase->path(), "Path is invalid"); $this->assertSame($path, $routingBase->path(), 'Path is invalid');
$this->assertEquals($segments, $routingBase->segments(), "Segments array is invalid"); $this->assertSame($segments, $routingBase->segments(), 'Segments array is invalid');
$this->assertEquals($lastSegment, $routingBase->lastSegment(), "Last segment is invalid"); $this->assertEquals($lastSegment, $routingBase->lastSegment(), 'Last segment is invalid');
foreach ($segments as $i => $value) foreach ($segments as $i => $value)
{ {

View File

@ -16,8 +16,10 @@
namespace Aviat\AnimeClient\Tests; namespace Aviat\AnimeClient\Tests;
class TestSessionHandler implements \SessionHandlerInterface { use SessionHandlerInterface;
class TestSessionHandler implements SessionHandlerInterface
{
public $data = []; public $data = [];
public $savePath = './test_data/sessions'; public $savePath = './test_data/sessions';
@ -28,12 +30,13 @@ class TestSessionHandler implements \SessionHandlerInterface {
public function destroy($id) public function destroy($id)
{ {
$file = "$this->savePath/$id"; $file = "{$this->savePath}/{$id}";
if (file_exists($file)) if (file_exists($file))
{ {
@unlink($file); @unlink($file);
} }
$this->data[$id] = []; $this->data[$id] = [];
return TRUE; return TRUE;
} }
@ -54,16 +57,15 @@ class TestSessionHandler implements \SessionHandlerInterface {
public function read($id) public function read($id)
{ {
return json_decode(@file_get_contents("$this->savePath/$id"), TRUE); return json_decode(@file_get_contents("{$this->savePath}/{$id}"), TRUE);
} }
public function write($id, $data) public function write($id, $data)
{ {
$file = "$this->savePath/$id"; $file = "{$this->savePath}/{$id}";
file_put_contents($file, json_encode($data)); file_put_contents($file, json_encode($data));
return TRUE; return TRUE;
} }
} }
// End of TestSessionHandler.php // End of TestSessionHandler.php

View File

@ -18,8 +18,12 @@ namespace Aviat\AnimeClient\Tests\Types;
use Aviat\AnimeClient\Types\Config; use Aviat\AnimeClient\Types\Config;
class ConfigTest extends ConfigTestCase { /**
public function setUp(): void * @internal
*/
final class ConfigTest extends ConfigTestCase
{
protected function setUp(): void
{ {
parent::setUp(); parent::setUp();
@ -34,7 +38,7 @@ class ConfigTest extends ConfigTestCase {
'database' => [], 'database' => [],
]); ]);
$this->assertEquals(3, $type->count()); $this->assertSame(3, $type->count());
} }
public function testOffsetUnset(): void public function testOffsetUnset(): void

View File

@ -19,13 +19,14 @@ namespace Aviat\AnimeClient\Tests\Types;
use Aviat\AnimeClient\Tests\AnimeClientTestCase; use Aviat\AnimeClient\Tests\AnimeClientTestCase;
use Aviat\AnimeClient\Types\UndefinedPropertyException; use Aviat\AnimeClient\Types\UndefinedPropertyException;
abstract class ConfigTestCase extends AnimeClientTestCase { abstract class ConfigTestCase extends AnimeClientTestCase
{
public string $testClass; public string $testClass;
public function testCheck(): void public function testCheck(): void
{ {
$result = $this->testClass::check([]); $result = $this->testClass::check([]);
$this->assertEquals([], $result); $this->assertSame([], $result);
} }
public function testSetUndefinedProperty(): void public function testSetUndefinedProperty(): void
@ -67,6 +68,6 @@ abstract class ConfigTestCase extends AnimeClientTestCase {
public function testCount(): void public function testCount(): void
{ {
$type = $this->testClass::from([]); $type = $this->testClass::from([]);
$this->assertEquals(0, $type->count()); $this->assertSame(0, $type->count());
} }
} }

View File

@ -17,47 +17,50 @@
namespace Aviat\AnimeClient\Tests; namespace Aviat\AnimeClient\Tests;
use Aviat\AnimeClient\UrlGenerator; use Aviat\AnimeClient\UrlGenerator;
use Aviat\Ion\Config; use InvalidArgumentException;
use Aviat\Ion\Exception\DoubleRenderException;
class UrlGeneratorTest extends AnimeClientTestCase {
/**
* @internal
*/
final class UrlGeneratorTest extends AnimeClientTestCase
{
public function assetUrlProvider() public function assetUrlProvider()
{ {
return [ return [
'single argument' => [ 'single argument' => [
'args' => [ 'args' => [
'images' 'images',
], ],
'expected' => 'https://localhost/assets/images', 'expected' => 'https://localhost/assets/images',
], ],
'multiple arguments' => [ 'multiple arguments' => [
'args' => [ 'args' => [
'images', 'anime', 'foo.png' 'images', 'anime', 'foo.png',
],
'expected' => 'https://localhost/assets/images/anime/foo.png',
], ],
'expected' => 'https://localhost/assets/images/anime/foo.png'
]
]; ];
} }
/** /**
* @dataProvider assetUrlProvider * @dataProvider assetUrlProvider
* @param mixed $args
* @param mixed $expected
*/ */
public function testAssetUrl($args, $expected) public function testAssetUrl($args, $expected)
{ {
$urlGenerator = new UrlGenerator($this->container); $urlGenerator = new UrlGenerator($this->container);
$result = $urlGenerator->assetUrl(...$args); $result = $urlGenerator->assetUrl(...$args);
$this->assertEquals($expected, $result); $this->assertSame($expected, $result);
} }
public function testDefaultUrlInvalidType(): void public function testDefaultUrlInvalidType(): void
{ {
$this->expectException(\InvalidArgumentException::class); $this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("Invalid default type: 'foo'"); $this->expectExceptionMessage("Invalid default type: 'foo'");
$urlGenerator = new UrlGenerator($this->container); $urlGenerator = new UrlGenerator($this->container);
$url = $urlGenerator->defaultUrl('foo'); $url = $urlGenerator->defaultUrl('foo');
} }
} }

View File

@ -18,11 +18,15 @@ namespace Aviat\AnimeClient\Tests;
use Aviat\AnimeClient\Util; use Aviat\AnimeClient\Util;
class UtilTest extends AnimeClientTestCase { /**
* @internal
*/
final class UtilTest extends AnimeClientTestCase
{
protected $util; protected $util;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->util = new Util($this->container); $this->util = new Util($this->container);
} }
@ -30,19 +34,19 @@ class UtilTest extends AnimeClientTestCase {
public function testIsSelected() public function testIsSelected()
{ {
// Failure to match // Failure to match
$this->assertEquals('', Util::isSelected('foo', 'bar')); $this->assertSame('', Util::isSelected('foo', 'bar'));
// Matches // Matches
$this->assertEquals('selected', Util::isSelected('foo', 'foo')); $this->assertSame('selected', Util::isSelected('foo', 'foo'));
} }
public function testIsNotSelected() public function testIsNotSelected()
{ {
// Failure to match // Failure to match
$this->assertEquals('selected', Util::isNotSelected('foo', 'bar')); $this->assertSame('selected', Util::isNotSelected('foo', 'bar'));
// Matches // Matches
$this->assertEquals('', Util::isNotSelected('foo', 'foo')); $this->assertSame('', Util::isNotSelected('foo', 'foo'));
} }
public function dataIsViewPage() public function dataIsViewPage()
@ -50,52 +54,56 @@ class UtilTest extends AnimeClientTestCase {
return [ return [
[ [
'uri' => '/anime/update', 'uri' => '/anime/update',
'expected' => FALSE 'expected' => FALSE,
], ],
[ [
'uri' => '/anime/watching', 'uri' => '/anime/watching',
'expected' => TRUE 'expected' => TRUE,
], ],
[ [
'uri' => '/manga/reading', 'uri' => '/manga/reading',
'expected' => TRUE 'expected' => TRUE,
], ],
[ [
'uri' => '/manga/update', 'uri' => '/manga/update',
'expected' => FALSE 'expected' => FALSE,
] ],
]; ];
} }
/** /**
* @dataProvider dataIsViewPage * @dataProvider dataIsViewPage
* @param mixed $uri
* @param mixed $expected
*/ */
public function testIsViewPage($uri, $expected) public function testIsViewPage($uri, $expected)
{ {
$this->setSuperGlobals([ $this->setSuperGlobals([
'_SERVER' => [ '_SERVER' => [
'REQUEST_URI' => $uri 'REQUEST_URI' => $uri,
] ],
]); ]);
$this->assertEquals($expected, $this->util->isViewPage()); $this->assertSame($expected, $this->util->isViewPage());
} }
/** /**
* @dataProvider dataIsViewPage * @dataProvider dataIsViewPage
* @param mixed $uri
* @param mixed $expected
*/ */
public function testIsFormPage($uri, $expected) public function testIsFormPage($uri, $expected)
{ {
$this->setSuperGlobals([ $this->setSuperGlobals([
'_SERVER' => [ '_SERVER' => [
'REQUEST_URI' => $uri 'REQUEST_URI' => $uri,
] ],
]); ]);
$this->assertEquals(!$expected, $this->util->isFormPage()); $this->assertSame( ! $expected, $this->util->isFormPage());
} }
public function testAriaCurrent(): void public function testAriaCurrent(): void
{ {
$this->assertEquals('true', Util::ariaCurrent(true)); $this->assertSame('true', Util::ariaCurrent(TRUE));
$this->assertEquals('false', Util::ariaCurrent(false)); $this->assertSame('false', Util::ariaCurrent(FALSE));
} }
} }

View File

@ -1,3 +1,5 @@
<?php return '<label><input type="radio" name="enabled" value="1" /> Yes</label> <?php declare(strict_types=1);
return '<label><input type="radio" name="enabled" value="1" /> Yes</label>
<label><input type="radio" name="enabled" value="0" checked /> No</label> <label><input type="radio" name="enabled" value="0" checked /> No</label>
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="connection" type="text" name="connection" value="" /> <?php declare(strict_types=1);
return '<input id="connection" type="text" name="connection" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="kitsu_username" type="text" name="kitsu_username" value="" /> <?php declare(strict_types=1);
return '<input id="kitsu_username" type="text" name="kitsu_username" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="whose_list" type="text" name="whose_list" value="" /> <?php declare(strict_types=1);
return '<input id="whose_list" type="text" name="whose_list" value="" />
'; ';

View File

@ -1,4 +1,6 @@
<?php return '<select id="theme" name="theme"> <?php declare(strict_types=1);
return '<select id="theme" name="theme">
<option value="auto">Automatically match OS theme</option> <option value="auto">Automatically match OS theme</option>
<option value="light">Original Light Theme</option> <option value="light">Original Light Theme</option>
<option value="dark">Dark Theme</option> <option value="dark">Dark Theme</option>

View File

@ -1,3 +1,5 @@
<?php return '<label><input type="radio" name="show_anime_collection" value="1" /> Yes</label> <?php declare(strict_types=1);
return '<label><input type="radio" name="show_anime_collection" value="1" /> Yes</label>
<label><input type="radio" name="show_anime_collection" value="0" checked /> No</label> <label><input type="radio" name="show_anime_collection" value="0" checked /> No</label>
'; ';

View File

@ -1,3 +1,5 @@
<?php return '<label><input type="radio" name="show_manga_collection" value="1" /> Yes</label> <?php declare(strict_types=1);
return '<label><input type="radio" name="show_manga_collection" value="1" /> Yes</label>
<label><input type="radio" name="show_manga_collection" value="0" checked /> No</label> <label><input type="radio" name="show_manga_collection" value="0" checked /> No</label>
'; ';

View File

@ -1,4 +1,6 @@
<?php return '<select id="default_list" name="default_list"> <?php declare(strict_types=1);
return '<select id="default_list" name="default_list">
<option value="anime">Anime</option> <option value="anime">Anime</option>
<option value="manga">Manga</option> <option value="manga">Manga</option>
</select> </select>

View File

@ -1,4 +1,6 @@
<?php return '<select id="default_anime_list_path" name="default_anime_list_path"> <?php declare(strict_types=1);
return '<select id="default_anime_list_path" name="default_anime_list_path">
<option value="watching">Watching</option> <option value="watching">Watching</option>
<option value="plan_to_watch">Plan to Watch</option> <option value="plan_to_watch">Plan to Watch</option>
<option value="on_hold">On Hold</option> <option value="on_hold">On Hold</option>

View File

@ -1,4 +1,6 @@
<?php return '<select id="default_manga_list_path" name="default_manga_list_path"> <?php declare(strict_types=1);
return '<select id="default_manga_list_path" name="default_manga_list_path">
<option value="reading">Reading</option> <option value="reading">Reading</option>
<option value="plan_to_read">Plan to Read</option> <option value="plan_to_read">Plan to Read</option>
<option value="on_hold">On Hold</option> <option value="on_hold">On Hold</option>

View File

@ -1,4 +1,6 @@
<?php return '<select id="type" name="type"> <?php declare(strict_types=1);
return '<select id="type" name="type">
<option value="mysql">MySQL</option> <option value="mysql">MySQL</option>
<option value="pgsql">PostgreSQL</option> <option value="pgsql">PostgreSQL</option>
<option value="sqlite">SQLite</option> <option value="sqlite">SQLite</option>

View File

@ -1,2 +1,4 @@
<?php return '<input id="client_id" type="text" name="client_id" value="" /> <?php declare(strict_types=1);
return '<input id="client_id" type="text" name="client_id" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="host" type="text" name="host" value="" /> <?php declare(strict_types=1);
return '<input id="host" type="text" name="host" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="user" type="text" name="user" value="" /> <?php declare(strict_types=1);
return '<input id="user" type="text" name="user" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="pass" type="text" name="pass" value="" /> <?php declare(strict_types=1);
return '<input id="pass" type="text" name="pass" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="port" type="text" name="port" value="" /> <?php declare(strict_types=1);
return '<input id="port" type="text" name="port" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="database" type="text" name="database" value="" /> <?php declare(strict_types=1);
return '<input id="database" type="text" name="database" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="file" type="text" name="file" value="" /> <?php declare(strict_types=1);
return '<input id="file" type="text" name="file" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="client_secret" type="text" name="client_secret" value="" /> <?php declare(strict_types=1);
return '<input id="client_secret" type="text" name="client_secret" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="username" type="text" name="username" value="" /> <?php declare(strict_types=1);
return '<input id="username" type="text" name="username" value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="access_token" type="text" name="access_token" readonly value="" /> <?php declare(strict_types=1);
return '<input id="access_token" type="text" name="access_token" readonly value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="access_token_expires" type="text" name="access_token_expires" readonly value="" /> <?php declare(strict_types=1);
return '<input id="access_token_expires" type="text" name="access_token_expires" readonly value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input id="refresh_token" type="text" name="refresh_token" readonly value="" /> <?php declare(strict_types=1);
return '<input id="refresh_token" type="text" name="refresh_token" readonly value="" />
'; ';

View File

@ -1,2 +1,4 @@
<?php return '<input type="hidden" name="special_hidden_flag" value="foo_bar" /> <?php declare(strict_types=1);
return '<input type="hidden" name="special_hidden_flag" value="foo_bar" />
'; ';

View File

@ -1,4 +1,6 @@
<?php return '<select id="driver" name="driver"> <?php declare(strict_types=1);
return '<select id="driver" name="driver">
<option value="apcu">APCu</option> <option value="apcu">APCu</option>
<option value="memcached">Memcached</option> <option value="memcached">Memcached</option>
<option value="redis">Redis</option> <option value="redis">Redis</option>

View File

@ -1,45 +1,52 @@
<?php <?php declare(strict_types=1);
/** /**
* All the mock classes that extend the classes they are used to test * All the mock classes that extend the classes they are used to test
*/ */
use Aviat\AnimeClient\Model\{ use Aviat\AnimeClient\Model\{
Anime as AnimeModel,
API as BaseApiModel, API as BaseApiModel,
Anime as AnimeModel,
Manga as MangaModel Manga as MangaModel
}; };
use Aviat\Ion\{Enum, Friend, Json};
use Aviat\Ion\Transformer\AbstractTransformer; use Aviat\Ion\Transformer\AbstractTransformer;
use Aviat\Ion\View\{HtmlView, HttpView, JsonView}; use Aviat\Ion\View\{HtmlView, HttpView, JsonView};
use Aviat\Ion\{Enum, Friend, Json};
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Mock the default error handler // Mock the default error handler
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class MockErrorHandler { class MockErrorHandler
public function addDataTable(string $name, array $values=[]): void {} {
public function addDataTable(string $name, array $values=[]): void
{
}
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Ion Mocks // Ion Mocks
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class TestEnum extends Enum { class TestEnum extends Enum
const FOO = 'bar'; {
const BAR = 'foo'; public const FOO = 'bar';
const FOOBAR = 'baz'; public const BAR = 'foo';
public const FOOBAR = 'baz';
} }
class FriendGrandParentTestClass { class FriendGrandParentTestClass
{
protected int $grandParentProtected = 84; protected int $grandParentProtected = 84;
} }
class FriendParentTestClass extends FriendGrandParentTestClass { class FriendParentTestClass extends FriendGrandParentTestClass
{
protected int $parentProtected = 47; protected int $parentProtected = 47;
private int $parentPrivate = 654; private int $parentPrivate = 654;
} }
class FriendTestClass extends FriendParentTestClass { class FriendTestClass extends FriendParentTestClass
{
protected int $protected = 356; protected int $protected = 356;
private int $private = 486; private int $private = 486;
@ -54,8 +61,8 @@ class FriendTestClass extends FriendParentTestClass {
} }
} }
class TestTransformer extends AbstractTransformer { class TestTransformer extends AbstractTransformer
{
public function transform($item): array public function transform($item): array
{ {
$out = []; $out = [];
@ -70,8 +77,10 @@ class TestTransformer extends AbstractTransformer {
} }
} }
trait MockViewOutputTrait { trait MockViewOutputTrait
protected function output(): void { {
protected function output(): void
{
$reflect = new ReflectionClass($this); $reflect = new ReflectionClass($this);
$properties = $reflect->getProperties(); $properties = $reflect->getProperties();
$props = []; $props = [];
@ -84,6 +93,7 @@ trait MockViewOutputTrait {
$view = new TestView(); $view = new TestView();
$friend = new Friend($view); $friend = new Friend($view);
foreach ($props as $name => $val) foreach ($props as $name => $val)
{ {
$friend->__set($name, $val); $friend->__set($name, $val);
@ -93,15 +103,20 @@ trait MockViewOutputTrait {
} }
} }
class MockUtil { class MockUtil
public function get_cached_image($api_path, $series_slug, $type = "anime"): string {
public function get_cached_image($api_path, $series_slug, $type = 'anime'): string
{ {
return "/public/images/{$type}/{$series_slug}.jpg"; return "/public/images/{$type}/{$series_slug}.jpg";
} }
} }
class TestView extends HttpView { class TestView extends HttpView
public function send(): void {} {
public function send(): void
{
}
protected function output(): void protected function output(): void
{ {
/*$content =& $this->response->content; /*$content =& $this->response->content;
@ -111,38 +126,46 @@ class TestView extends HttpView {
} }
} }
class TestHtmlView extends HtmlView { class TestHtmlView extends HtmlView
{
use MockViewOutputTrait; use MockViewOutputTrait;
} }
class TestHttpView extends HttpView { class TestHttpView extends HttpView
{
use MockViewOutputTrait; use MockViewOutputTrait;
} }
class TestJsonView extends JsonView { class TestJsonView extends JsonView
public function __destruct() {} {
public function __destruct()
{
}
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// AnimeClient Mocks // AnimeClient Mocks
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
trait MockInjectionTrait { trait MockInjectionTrait
{
public function __get(string $key): mixed public function __get(string $key): mixed
{ {
return $this->$key; return $this->{$key};
} }
public function __set(string $key, mixed $value) public function __set(string $key, mixed $value)
{ {
$this->$key = $value; $this->{$key} = $value;
return $this; return $this;
} }
} }
class MockBaseApiModel extends BaseApiModel { class MockBaseApiModel extends BaseApiModel
{
use MockInjectionTrait; use MockInjectionTrait;
protected string $base_url = 'https://httpbin.org/'; protected string $base_url = 'https://httpbin.org/';
protected function _get_list_from_api(string $status): array protected function _get_list_from_api(string $status): array
@ -151,16 +174,19 @@ class MockBaseApiModel extends BaseApiModel {
} }
} }
class TestAnimeModel extends AnimeModel { class TestAnimeModel extends AnimeModel
{
use MockInjectionTrait; use MockInjectionTrait;
} }
class TestMangaModel extends MangaModel { class TestMangaModel extends MangaModel
{
use MockInjectionTrait; use MockInjectionTrait;
protected function _check_cache($response) protected function _check_cache($response)
{ {
$file = __DIR__ . '/test_data/manga_list/manga-transformed.json'; $file = __DIR__ . '/test_data/manga_list/manga-transformed.json';
return Json::decodeFile($file); return Json::decodeFile($file);
} }
} }

View File

@ -18,11 +18,14 @@ namespace Aviat\Ion\Tests;
use Aviat\Ion\Model as BaseModel; use Aviat\Ion\Model as BaseModel;
class BaseModelTest extends IonTestCase { /**
* @internal
*/
final class BaseModelTest extends IonTestCase
{
public function testBaseModelSanity() public function testBaseModelSanity()
{ {
$baseModel = new BaseModel(); $baseModel = new BaseModel();
$this->assertTrue(is_object($baseModel)); $this->assertIsObject($baseModel);
} }
} }

View File

@ -18,11 +18,14 @@ namespace Aviat\Ion\Tests;
use Aviat\Ion\Config; use Aviat\Ion\Config;
class ConfigTest extends IonTestCase { /**
* @internal
*/
final class ConfigTest extends IonTestCase
{
protected Config $config; protected Config $config;
public function setUp(): void protected function setUp(): void
{ {
$this->config = new Config([ $this->config = new Config([
'foo' => 'bar', 'foo' => 'bar',
@ -47,8 +50,8 @@ class ConfigTest extends IonTestCase {
public function testConfigGet(): void public function testConfigGet(): void
{ {
$this->assertEquals('bar', $this->config->get('foo')); $this->assertSame('bar', $this->config->get('foo'));
$this->assertEquals('baz', $this->config->get('bar')); $this->assertSame('baz', $this->config->get('bar'));
$this->assertNull($this->config->get('baz')); $this->assertNull($this->config->get('baz'));
$this->assertNull($this->config->get(['apple', 'sauce', 'is'])); $this->assertNull($this->config->get(['apple', 'sauce', 'is']));
} }
@ -57,13 +60,13 @@ class ConfigTest extends IonTestCase {
{ {
$ret = $this->config->set('foo', 'foobar'); $ret = $this->config->set('foo', 'foobar');
$this->assertInstanceOf(Config::class, $ret); $this->assertInstanceOf(Config::class, $ret);
$this->assertEquals('foobar', $this->config->get('foo')); $this->assertSame('foobar', $this->config->get('foo'));
$this->config->set(['apple', 'sauce', 'is'], 'great'); $this->config->set(['apple', 'sauce', 'is'], 'great');
$apple = $this->config->get('apple'); $apple = $this->config->get('apple');
$this->assertEquals('great', $apple['sauce']['is'], 'Config value not set correctly'); $this->assertSame('great', $apple['sauce']['is'], 'Config value not set correctly');
$this->assertEquals('great', $this->config->get(['apple', 'sauce', 'is']), "Array argument get for config failed."); $this->assertSame('great', $this->config->get(['apple', 'sauce', 'is']), 'Array argument get for config failed.');
} }
public function dataConfigDelete(): array public function dataConfigDelete(): array
@ -74,57 +77,58 @@ class ConfigTest extends IonTestCase {
'assertKeys' => [ 'assertKeys' => [
[ [
'path' => ['apple', 'sauce', 'is'], 'path' => ['apple', 'sauce', 'is'],
'expected' => NULL 'expected' => NULL,
], ],
[ [
'path' => ['apple', 'sauce'], 'path' => ['apple', 'sauce'],
'expected' => NULL 'expected' => NULL,
], ],
[ [
'path' => 'apple', 'path' => 'apple',
'expected' => NULL 'expected' => NULL,
] ],
] ],
], ],
'mid level delete' => [ 'mid level delete' => [
'key' => ['apple', 'sauce'], 'key' => ['apple', 'sauce'],
'assertKeys' => [ 'assertKeys' => [
[ [
'path' => ['apple', 'sauce', 'is'], 'path' => ['apple', 'sauce', 'is'],
'expected' => NULL 'expected' => NULL,
], ],
[ [
'path' => ['apple', 'sauce'], 'path' => ['apple', 'sauce'],
'expected' => NULL 'expected' => NULL,
], ],
[ [
'path' => 'apple', 'path' => 'apple',
'expected' => [ 'expected' => [
'sauce' => NULL 'sauce' => NULL,
] ],
] ],
] ],
], ],
'deep delete' => [ 'deep delete' => [
'key' => ['apple', 'sauce', 'is'], 'key' => ['apple', 'sauce', 'is'],
'assertKeys' => [ 'assertKeys' => [
[ [
'path' => ['apple', 'sauce', 'is'], 'path' => ['apple', 'sauce', 'is'],
'expected' => NULL 'expected' => NULL,
], ],
[ [
'path' => ['apple', 'sauce'], 'path' => ['apple', 'sauce'],
'expected' => [ 'expected' => [
'is' => NULL 'is' => NULL,
] ],
] ],
] ],
] ],
]; ];
} }
/** /**
* @dataProvider dataConfigDelete * @dataProvider dataConfigDelete
* @param mixed $key
*/ */
public function testConfigDelete($key, array $assertKeys): void public function testConfigDelete($key, array $assertKeys): void
{ {
@ -134,7 +138,7 @@ class ConfigTest extends IonTestCase {
foreach ($assertKeys as $pair) foreach ($assertKeys as $pair)
{ {
$this->assertEquals($pair['expected'], $config->get($pair['path'])); $this->assertSame($pair['expected'], $config->get($pair['path']));
} }
} }

View File

@ -19,7 +19,8 @@ namespace Aviat\Ion\Tests\Di;
use Aviat\Ion\Di\{Container, ContainerAware, ContainerInterface}; use Aviat\Ion\Di\{Container, ContainerAware, ContainerInterface};
use Aviat\Ion\Tests\IonTestCase; use Aviat\Ion\Tests\IonTestCase;
class Aware { class Aware
{
use ContainerAware; use ContainerAware;
public function __construct(ContainerInterface $container) public function __construct(ContainerInterface $container)
@ -28,12 +29,14 @@ class Aware {
} }
} }
/**
class ContainerAwareTest extends IonTestCase { * @internal
*/
final class ContainerAwareTest extends IonTestCase
{
protected Aware $aware; protected Aware $aware;
public function setUp(): void protected function setUp(): void
{ {
$this->container = new Container(); $this->container = new Container();
$this->aware = new Aware($this->container); $this->aware = new Aware($this->container);
@ -47,7 +50,7 @@ class ContainerAwareTest extends IonTestCase {
$container2 = new Container([ $container2 = new Container([
'foo' => 'bar', 'foo' => 'bar',
'baz' => 'foobar' 'baz' => 'foobar',
]); ]);
$this->aware->setContainer($container2); $this->aware->setContainer($container2);
$this->assertSame($container2, $this->aware->getContainer()); $this->assertSame($container2, $this->aware->getContainer());

View File

@ -16,32 +16,39 @@
namespace Aviat\Ion\Tests\Di; namespace Aviat\Ion\Tests\Di;
use Aviat\Ion\Di\{Container, ContainerAware};
use Aviat\Ion\Di\Exception\ContainerException;
use Aviat\Ion\Tests\IonTestCase;
use Monolog\Logger;
use Monolog\Handler\{TestHandler, NullHandler};
use Aviat\Ion\Di\ContainerInterface; use Aviat\Ion\Di\ContainerInterface;
use Aviat\Ion\Di\Exception\NotFoundException; use Aviat\Ion\Di\Exception\{ContainerException, NotFoundException};
use Aviat\Ion\Di\{Container, ContainerAware};
use Aviat\Ion\Tests\IonTestCase;
use Monolog\Handler\{NullHandler, TestHandler};
use Monolog\Logger;
use Throwable; use Throwable;
use TypeError; use TypeError;
class FooTest { /**
* @internal
*/
final class FooTest
{
public $item; public $item;
public function __construct($item) { public function __construct($item)
{
$this->item = $item; $this->item = $item;
} }
} }
class FooTest2 { class FooTest2
{
use ContainerAware; use ContainerAware;
} }
class ContainerTest extends IonTestCase { /**
* @internal
public function setUp(): void */
final class ContainerTest extends IonTestCase
{
protected function setUp(): void
{ {
$this->container = new Container(); $this->container = new Container();
} }
@ -60,13 +67,14 @@ class ContainerTest extends IonTestCase {
'Non-existent id' => [ 'Non-existent id' => [
'id' => 'foo', 'id' => 'foo',
'exception' => NotFoundException::class, 'exception' => NotFoundException::class,
'message' => "Item 'foo' does not exist in container." 'message' => "Item 'foo' does not exist in container.",
] ],
]; ];
} }
/** /**
* @dataProvider dataGetWithException * @dataProvider dataGetWithException
* @param mixed $exception
*/ */
public function testGetWithException(mixed $id, $exception, ?string $message = NULL): void public function testGetWithException(mixed $id, $exception, ?string $message = NULL): void
{ {
@ -77,7 +85,7 @@ class ContainerTest extends IonTestCase {
catch (ContainerException $e) catch (ContainerException $e)
{ {
$this->assertInstanceOf($exception, $e); $this->assertInstanceOf($exception, $e);
$this->assertEquals($message, $e->getMessage()); $this->assertSame($message, $e->getMessage());
} }
catch (Throwable $e) catch (Throwable $e)
{ {
@ -87,6 +95,7 @@ class ContainerTest extends IonTestCase {
/** /**
* @dataProvider dataGetWithException * @dataProvider dataGetWithException
* @param mixed $exception
*/ */
public function testGetNewWithException(mixed $id, $exception, ?string $message = NULL): void public function testGetNewWithException(mixed $id, $exception, ?string $message = NULL): void
{ {
@ -117,6 +126,9 @@ class ContainerTest extends IonTestCase {
/** /**
* @dataProvider dataSetInstanceWithException * @dataProvider dataSetInstanceWithException
* @param mixed $id
* @param mixed $exception
* @param mixed $message
*/ */
public function testSetInstanceWithException($id, $exception, $message): void public function testSetInstanceWithException($id, $exception, $message): void
{ {
@ -127,48 +139,40 @@ class ContainerTest extends IonTestCase {
catch (ContainerException $e) catch (ContainerException $e)
{ {
$this->assertInstanceOf($exception, $e); $this->assertInstanceOf($exception, $e);
$this->assertEquals($message, $e->getMessage()); $this->assertSame($message, $e->getMessage());
} }
} }
public function testGetNew(): void public function testGetNew(): void
{ {
$this->container->set('footest', static function($item) { $this->container->set('footest', static fn ($item) => new FooTest($item));
return new FooTest($item);
});
// Check that the item is the container, if called without arguments // Check that the item is the container, if called without arguments
$footest1 = $this->container->getNew('footest'); $footest1 = $this->container->getNew('footest');
$this->assertInstanceOf(ContainerInterface::class, $footest1->item); $this->assertInstanceOf(ContainerInterface::class, $footest1->item);
$footest2 = $this->container->getNew('footest', ['Test String']); $footest2 = $this->container->getNew('footest', ['Test String']);
$this->assertEquals('Test String', $footest2->item); $this->assertSame('Test String', $footest2->item);
} }
public function testSetContainerInInstance(): void public function testSetContainerInInstance(): void
{ {
$this->container->set('footest2', function() { $this->container->set('footest2', static fn () => new FooTest2());
return new FooTest2();
});
$footest2 = $this->container->get('footest2'); $footest2 = $this->container->get('footest2');
$this->assertEquals($this->container, $footest2->getContainer()); $this->assertSame($this->container, $footest2->getContainer());
} }
public function testGetNewReturnCallable(): void public function testGetNewReturnCallable(): void
{ {
$this->container->set('footest', static function($item) { $this->container->set('footest', static fn ($item) => static fn () => $item);
return static function() use ($item) {
return $item;
};
});
// Check that the item is the container, if called without arguments // Check that the item is the container, if called without arguments
$footest1 = $this->container->getNew('footest'); $footest1 = $this->container->getNew('footest');
$this->assertInstanceOf(ContainerInterface::class, $footest1()); $this->assertInstanceOf(ContainerInterface::class, $footest1());
$footest2 = $this->container->getNew('footest', ['Test String']); $footest2 = $this->container->getNew('footest', ['Test String']);
$this->assertEquals('Test String', $footest2()); $this->assertSame('Test String', $footest2());
} }
public function testGetSet(): void public function testGetSet(): void
@ -181,7 +185,7 @@ class ContainerTest extends IonTestCase {
$this->assertInstanceOf(ContainerInterface::class, $container); $this->assertInstanceOf(ContainerInterface::class, $container);
// The factory returns a callable // The factory returns a callable
$this->assertTrue(is_callable($container->get('foo'))); $this->assertIsCallable($container->get('foo'));
} }
public function testLoggerMethods(): void public function testLoggerMethods(): void
@ -202,8 +206,8 @@ class ContainerTest extends IonTestCase {
$this->assertInstanceOf(ContainerInterface::class, $container); $this->assertInstanceOf(ContainerInterface::class, $container);
$this->assertInstanceOf(Container::class, $container2); $this->assertInstanceOf(Container::class, $container2);
$this->assertEquals($logger1, $this->container->getLogger('default')); $this->assertSame($logger1, $this->container->getLogger('default'));
$this->assertEquals($logger2, $this->container->getLogger('test')); $this->assertSame($logger2, $this->container->getLogger('test'));
$this->assertNull($this->container->getLogger('foo')); $this->assertNull($this->container->getLogger('foo'));
$this->assertTrue($this->container->hasLogger()); $this->assertTrue($this->container->hasLogger());

View File

@ -16,17 +16,19 @@
namespace Aviat\Ion\Tests; namespace Aviat\Ion\Tests;
use Aviat\Ion\Enum; /**
* @internal
class EnumTest extends IonTestCase { */
final class EnumTest extends IonTestCase
{
protected $expectedConstList = [ protected $expectedConstList = [
'FOO' => 'bar', 'FOO' => 'bar',
'BAR' => 'foo', 'BAR' => 'foo',
'FOOBAR' => 'baz' 'FOOBAR' => 'baz',
]; ];
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->enum = new TestEnum(); $this->enum = new TestEnum();
} }
@ -34,13 +36,13 @@ class EnumTest extends IonTestCase {
public function testStaticGetConstList() public function testStaticGetConstList()
{ {
$actual = TestEnum::getConstList(); $actual = TestEnum::getConstList();
$this->assertEquals($this->expectedConstList, $actual); $this->assertSame($this->expectedConstList, $actual);
} }
public function testGetConstList() public function testGetConstList()
{ {
$actual = $this->enum->getConstList(); $actual = $this->enum->getConstList();
$this->assertEquals($this->expectedConstList, $actual); $this->assertSame($this->expectedConstList, $actual);
} }
public function dataIsValid() public function dataIsValid()
@ -49,28 +51,31 @@ class EnumTest extends IonTestCase {
'Valid' => [ 'Valid' => [
'value' => 'baz', 'value' => 'baz',
'expected' => TRUE, 'expected' => TRUE,
'static' => FALSE 'static' => FALSE,
], ],
'ValidStatic' => [ 'ValidStatic' => [
'value' => 'baz', 'value' => 'baz',
'expected' => TRUE, 'expected' => TRUE,
'static' => TRUE 'static' => TRUE,
], ],
'Invalid' => [ 'Invalid' => [
'value' => 'foobar', 'value' => 'foobar',
'expected' => FALSE, 'expected' => FALSE,
'static' => FALSE 'static' => FALSE,
], ],
'InvalidStatic' => [ 'InvalidStatic' => [
'value' => 'foobar', 'value' => 'foobar',
'expected' => FALSE, 'expected' => FALSE,
'static' => TRUE 'static' => TRUE,
] ],
]; ];
} }
/** /**
* @dataProvider dataIsValid * @dataProvider dataIsValid
* @param mixed $value
* @param mixed $expected
* @param mixed $static
*/ */
public function testIsValid($value, $expected, $static) public function testIsValid($value, $expected, $static)
{ {
@ -78,6 +83,6 @@ class EnumTest extends IonTestCase {
? TestEnum::isValid($value) ? TestEnum::isValid($value)
: $this->enum->isValid($value); : $this->enum->isValid($value);
$this->assertEquals($expected, $actual); $this->assertSame($expected, $actual);
} }
} }

View File

@ -19,11 +19,14 @@ namespace Aviat\Ion\Tests;
use Aviat\Ion\Event; use Aviat\Ion\Event;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class EventTest extends TestCase { /**
* @internal
*/
final class EventTest extends TestCase
{
public function testEmit(): void public function testEmit(): void
{ {
Event::on('test-event', fn ($fired) => $this->assertTrue($fired)); Event::on('test-event', fn ($fired) => $this->assertTrue($fired));
Event::emit('test-event', [true]); Event::emit('test-event', [TRUE]);
} }
} }

View File

@ -19,8 +19,11 @@ namespace Aviat\Ion\Tests\Exception;
use Aviat\Ion\Exception\DoubleRenderException; use Aviat\Ion\Exception\DoubleRenderException;
use Aviat\Ion\Tests\IonTestCase; use Aviat\Ion\Tests\IonTestCase;
class DoubleRenderExceptionTest extends IonTestCase { /**
* @internal
*/
final class DoubleRenderExceptionTest extends IonTestCase
{
public function testDefaultMessage() public function testDefaultMessage()
{ {
$this->expectException(DoubleRenderException::class); $this->expectException(DoubleRenderException::class);

View File

@ -17,13 +17,16 @@
namespace Aviat\Ion\Tests; namespace Aviat\Ion\Tests;
use Aviat\Ion\Friend; use Aviat\Ion\Friend;
use Aviat\Ion\Tests\FriendTestClass;
class FriendTest extends IonTestCase {
/**
* @internal
*/
final class FriendTest extends IonTestCase
{
protected $friend; protected $friend;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$obj = new FriendTestClass(); $obj = new FriendTestClass();
$this->friend = new Friend($obj); $this->friend = new Friend($obj);
@ -32,28 +35,28 @@ class FriendTest extends IonTestCase {
public function testPrivateMethod(): void public function testPrivateMethod(): void
{ {
$actual = $this->friend->getPrivate(); $actual = $this->friend->getPrivate();
$this->assertEquals(23, $actual); $this->assertSame(23, $actual);
} }
public function testProtectedMethod(): void public function testProtectedMethod(): void
{ {
$actual = $this->friend->getProtected(); $actual = $this->friend->getProtected();
$this->assertEquals(4, $actual); $this->assertSame(4, $actual);
} }
public function testGet(): void public function testGet(): void
{ {
$this->assertEquals(356, $this->friend->protected); $this->assertSame(356, $this->friend->protected);
$this->assertNull($this->friend->foo); // Return NULL for non-existent properties $this->assertNull($this->friend->foo); // Return NULL for non-existent properties
$this->assertEquals(47, $this->friend->parentProtected); $this->assertSame(47, $this->friend->parentProtected);
$this->assertEquals(84, $this->friend->grandParentProtected); $this->assertSame(84, $this->friend->grandParentProtected);
$this->assertNull($this->friend->parentPrivate); // Can't get a parent's privates $this->assertNull($this->friend->parentPrivate); // Can't get a parent's privates
} }
public function testSet(): void public function testSet(): void
{ {
$this->friend->private = 123; $this->friend->private = 123;
$this->assertEquals(123, $this->friend->private); $this->assertSame(123, $this->friend->private);
$this->friend->foo = 32; $this->friend->foo = 32;
$this->assertNull($this->friend->foo); $this->assertNull($this->friend->foo);

View File

@ -16,16 +16,17 @@
namespace Aviat\Ion\Tests; namespace Aviat\Ion\Tests;
use function Aviat\Ion\_dir;
use Aviat\Ion\Di\ContainerInterface; use Aviat\Ion\Di\ContainerInterface;
use PHPUnit\Framework\TestCase;
use Laminas\Diactoros\ServerRequestFactory; use Laminas\Diactoros\ServerRequestFactory;
use PHPUnit\Framework\TestCase;
use function Aviat\Ion\_dir;
/** /**
* Base class for TestCases * Base class for TestCases
*/ */
class IonTestCase extends TestCase { class IonTestCase extends TestCase
{
// Test directory constants // Test directory constants
public const ROOT_DIR = AC_TEST_ROOT_DIR; public const ROOT_DIR = AC_TEST_ROOT_DIR;
public const SRC_DIR = SRC_DIR; public const SRC_DIR = SRC_DIR;
@ -44,7 +45,7 @@ class IonTestCase extends TestCase {
self::$session_handler = $session_handler; self::$session_handler = $session_handler;
}*/ }*/
public function setUp(): void protected function setUp(): void
{ {
parent::setUp(); parent::setUp();
@ -74,29 +75,30 @@ class IonTestCase extends TestCase {
'name' => 'default', 'name' => 'default',
'database' => '', 'database' => '',
'file' => ':memory:', 'file' => ':memory:',
] ],
], ],
'routes' => [ 'routes' => [
'route_config' => [ 'route_config' => [
'asset_path' => '/assets' 'asset_path' => '/assets',
], ],
'routes' => [ 'routes' => [
] ],
], ],
'redis' => [ 'redis' => [
'host' => (array_key_exists('REDIS_HOST', $_ENV)) ? $_ENV['REDIS_HOST'] : 'localhost', 'host' => (array_key_exists('REDIS_HOST', $_ENV)) ? $_ENV['REDIS_HOST'] : 'localhost',
'database' => 13 'database' => 13,
] ],
]; ];
// Set up DI container // Set up DI container
$di = require('di.php'); $di = require 'di.php';
$container = $di($config_array); $container = $di($config_array);
$container->set('session-handler', static function () { $container->set('session-handler', static function () {
// Use mock session handler // Use mock session handler
$session_handler = new TestSessionHandler(); $session_handler = new TestSessionHandler();
session_set_save_handler($session_handler, TRUE); session_set_save_handler($session_handler, TRUE);
return $session_handler; return $session_handler;
}); });
@ -105,9 +107,6 @@ class IonTestCase extends TestCase {
/** /**
* Set arbitrary superglobal values for testing purposes * Set arbitrary superglobal values for testing purposes
*
* @param array $supers
* @return void
*/ */
public function setSuperGlobals(array $supers = []): void public function setSuperGlobals(array $supers = []): void
{ {
@ -116,7 +115,7 @@ class IonTestCase extends TestCase {
'_GET' => $_GET, '_GET' => $_GET,
'_POST' => $_POST, '_POST' => $_POST,
'_COOKIE' => $_COOKIE, '_COOKIE' => $_COOKIE,
'_FILES' => $_FILES '_FILES' => $_FILES,
]; ];
$request = call_user_func_array( $request = call_user_func_array(

View File

@ -16,40 +16,43 @@
namespace Aviat\Ion\Tests; namespace Aviat\Ion\Tests;
use function Aviat\Ion\_dir;
use Aviat\Ion\{Json, JsonException}; use Aviat\Ion\{Json, JsonException};
class JsonTest extends IonTestCase { use function Aviat\Ion\_dir;
/**
* @internal
*/
final class JsonTest extends IonTestCase
{
public function testEncode() public function testEncode()
{ {
$data = (object) [ $data = (object) [
'foo' => [1, 2, 3, 4] 'foo' => [1, 2, 3, 4],
]; ];
$expected = '{"foo":[1,2,3,4]}'; $expected = '{"foo":[1,2,3,4]}';
$this->assertEquals($expected, Json::encode($data)); $this->assertSame($expected, Json::encode($data));
} }
public function dataEncodeDecode() public function dataEncodeDecode(): array
{ {
return [ return [
'set1' => [ 'set1' => [
'data' => [ 'data' => [
'apple' => [ 'apple' => [
'sauce' => ['foo','bar','baz'] 'sauce' => ['foo', 'bar', 'baz'],
] ],
], ],
'expected_size' => 39, 'expected_size' => 39,
'expected_json' => '{"apple":{"sauce":["foo","bar","baz"]}}' 'expected_json' => '{"apple":{"sauce":["foo","bar","baz"]}}',
] ],
]; ];
} }
/** /**
* @dataProvider dataEncodeDecode * @dataProvider dataEncodeDecode
*/ */
public function testEncodeDecodeFile($data, $expected_size, $expected_json) public function testEncodeDecodeFile(array $data, int $expected_size, string $expected_json): void
{ {
$target_file = _dir(self::TEST_DATA_DIR, 'json_write.json'); $target_file = _dir(self::TEST_DATA_DIR, 'json_write.json');
@ -57,8 +60,8 @@ class JsonTest extends IonTestCase {
$actual_json = file_get_contents($target_file); $actual_json = file_get_contents($target_file);
$this->assertTrue(Json::isJson($actual_json)); $this->assertTrue(Json::isJson($actual_json));
$this->assertEquals($expected_size, $actual_size); $this->assertSame($expected_size, $actual_size);
$this->assertEquals($expected_json, $actual_json); $this->assertSame($expected_json, $actual_json);
$this->assertEquals($data, Json::decodeFile($target_file)); $this->assertEquals($data, Json::decodeFile($target_file));
@ -69,10 +72,10 @@ class JsonTest extends IonTestCase {
{ {
$json = '{"foo":[1,2,3,4]}'; $json = '{"foo":[1,2,3,4]}';
$expected = [ $expected = [
'foo' => [1, 2, 3, 4] 'foo' => [1, 2, 3, 4],
]; ];
$this->assertEquals($expected, Json::decode($json)); $this->assertSame($expected, Json::decode($json));
$this->assertEquals((object)$expected, Json::decode($json, false)); $this->assertEquals((object) $expected, Json::decode($json, FALSE));
$badJson = '{foo:{1|2}}'; $badJson = '{foo:{1|2}}';
$this->expectException('Aviat\Ion\JsonException'); $this->expectException('Aviat\Ion\JsonException');

View File

@ -18,8 +18,8 @@ namespace Aviat\Ion\Tests;
use SessionHandlerInterface; use SessionHandlerInterface;
class TestSessionHandler implements SessionHandlerInterface { class TestSessionHandler implements SessionHandlerInterface
{
public $data = []; public $data = [];
public $save_path = './test_data/sessions'; public $save_path = './test_data/sessions';
@ -30,12 +30,13 @@ class TestSessionHandler implements SessionHandlerInterface {
public function destroy($id) public function destroy($id)
{ {
$file = "$this->save_path/$id"; $file = "{$this->save_path}/{$id}";
if (file_exists($file)) if (file_exists($file))
{ {
@unlink($file); @unlink($file);
} }
$this->data[$id] = []; $this->data[$id] = [];
return TRUE; return TRUE;
} }
@ -56,16 +57,15 @@ class TestSessionHandler implements SessionHandlerInterface {
public function read($id) public function read($id)
{ {
return json_decode(@file_get_contents("$this->save_path/$id"), TRUE); return json_decode(@file_get_contents("{$this->save_path}/{$id}"), TRUE);
} }
public function write($id, $data) public function write($id, $data)
{ {
$file = "$this->save_path/$id"; $file = "{$this->save_path}/{$id}";
file_put_contents($file, json_encode($data)); file_put_contents($file, json_encode($data));
return TRUE; return TRUE;
} }
} }
// End of TestSessionHandler.php // End of TestSessionHandler.php

View File

@ -18,14 +18,18 @@ namespace Aviat\Ion\Tests\Transformer;
use Aviat\Ion\Tests\IonTestCase; use Aviat\Ion\Tests\IonTestCase;
use Aviat\Ion\Tests\{TestTransformer, TestTransformerUntransform}; use Aviat\Ion\Tests\{TestTransformer, TestTransformerUntransform};
use BadMethodCallException;
class AbstractTransformerTest extends IonTestCase { /**
* @internal
*/
final class AbstractTransformerTest extends IonTestCase
{
protected $transformer; protected $transformer;
protected $untransformer; protected $untransformer;
protected function setUp(): void
public function setUp(): void { {
$this->transformer = new TestTransformer(); $this->transformer = new TestTransformer();
$this->untransformer = new TestTransformerUntransform(); $this->untransformer = new TestTransformerUntransform();
} }
@ -39,25 +43,25 @@ class AbstractTransformerTest extends IonTestCase {
['name' => 'Comedy'], ['name' => 'Comedy'],
['name' => 'Romance'], ['name' => 'Romance'],
['name' => 'School'], ['name' => 'School'],
['name' => 'Harem'] ['name' => 'Harem'],
], ],
(object) [ (object) [
['name' => 'Action'], ['name' => 'Action'],
['name' => 'Comedy'], ['name' => 'Comedy'],
['name' => 'Magic'], ['name' => 'Magic'],
['name' => 'Fantasy'], ['name' => 'Fantasy'],
['name' => 'Mahou Shoujo'] ['name' => 'Mahou Shoujo'],
], ],
(object) [ (object) [
['name' => 'Comedy'], ['name' => 'Comedy'],
['name' => 'Sci-Fi'] ['name' => 'Sci-Fi'],
] ],
], ],
'expected' => [ 'expected' => [
['Comedy', 'Romance', 'School', 'Harem'], ['Comedy', 'Romance', 'School', 'Harem'],
['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'], ['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
['Comedy', 'Sci-Fi'] ['Comedy', 'Sci-Fi'],
] ],
], ],
'array' => [ 'array' => [
'original' => [ 'original' => [
@ -65,25 +69,25 @@ class AbstractTransformerTest extends IonTestCase {
['name' => 'Comedy'], ['name' => 'Comedy'],
['name' => 'Romance'], ['name' => 'Romance'],
['name' => 'School'], ['name' => 'School'],
['name' => 'Harem'] ['name' => 'Harem'],
], ],
[ [
['name' => 'Action'], ['name' => 'Action'],
['name' => 'Comedy'], ['name' => 'Comedy'],
['name' => 'Magic'], ['name' => 'Magic'],
['name' => 'Fantasy'], ['name' => 'Fantasy'],
['name' => 'Mahou Shoujo'] ['name' => 'Mahou Shoujo'],
], ],
[ [
['name' => 'Comedy'], ['name' => 'Comedy'],
['name' => 'Sci-Fi'] ['name' => 'Sci-Fi'],
] ],
], ],
'expected' => [ 'expected' => [
['Comedy', 'Romance', 'School', 'Harem'], ['Comedy', 'Romance', 'School', 'Harem'],
['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'], ['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
['Comedy', 'Sci-Fi'] ['Comedy', 'Sci-Fi'],
] ],
], ],
]; ];
} }
@ -95,26 +99,26 @@ class AbstractTransformerTest extends IonTestCase {
'original' => [ 'original' => [
(object) ['Comedy', 'Romance', 'School', 'Harem'], (object) ['Comedy', 'Romance', 'School', 'Harem'],
(object) ['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'], (object) ['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
(object)['Comedy', 'Sci-Fi'] (object) ['Comedy', 'Sci-Fi'],
], ],
'expected' => [ 'expected' => [
['Comedy', 'Romance', 'School', 'Harem'], ['Comedy', 'Romance', 'School', 'Harem'],
['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'], ['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
['Comedy', 'Sci-Fi'] ['Comedy', 'Sci-Fi'],
] ],
], ],
'array' => [ 'array' => [
'original' => [ 'original' => [
['Comedy', 'Romance', 'School', 'Harem'], ['Comedy', 'Romance', 'School', 'Harem'],
['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'], ['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
['Comedy', 'Sci-Fi'] ['Comedy', 'Sci-Fi'],
], ],
'expected' => [ 'expected' => [
['Comedy', 'Romance', 'School', 'Harem'], ['Comedy', 'Romance', 'School', 'Harem'],
['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'], ['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
['Comedy', 'Sci-Fi'] ['Comedy', 'Sci-Fi'],
] ],
] ],
]; ];
} }
@ -125,33 +129,39 @@ class AbstractTransformerTest extends IonTestCase {
$expected = $data['object']['expected'][0]; $expected = $data['object']['expected'][0];
$actual = $this->transformer->transform($original); $actual = $this->transformer->transform($original);
$this->assertEquals($expected, $actual); $this->assertSame($expected, $actual);
} }
/** /**
* @dataProvider dataTransformCollection * @dataProvider dataTransformCollection
* @param mixed $original
* @param mixed $expected
*/ */
public function testTransformCollection($original, $expected) public function testTransformCollection($original, $expected)
{ {
$actual = $this->transformer->transformCollection($original); $actual = $this->transformer->transformCollection($original);
$this->assertEquals($expected, $actual); $this->assertSame($expected, $actual);
} }
/** /**
* @dataProvider dataUnTransformCollection * @dataProvider dataUnTransformCollection
* @param mixed $original
* @param mixed $expected
*/ */
public function testUntransformCollection($original, $expected) public function testUntransformCollection($original, $expected)
{ {
$actual = $this->untransformer->untransformCollection($original); $actual = $this->untransformer->untransformCollection($original);
$this->assertEquals($expected, $actual); $this->assertSame($expected, $actual);
} }
/** /**
* @dataProvider dataUnTransformCollection * @dataProvider dataUnTransformCollection
* @param mixed $original
* @param mixed $expected
*/ */
public function testUntransformCollectionWithException($original, $expected) public function testUntransformCollectionWithException($original, $expected)
{ {
$this->expectException(\BadMethodCallException::class); $this->expectException(BadMethodCallException::class);
$this->transformer->untransformCollection($original); $this->transformer->untransformCollection($original);
} }
} }

View File

@ -16,10 +16,14 @@
namespace Aviat\Ion\Tests\Type; namespace Aviat\Ion\Tests\Type;
use Aviat\Ion\Type\ArrayType;
use Aviat\Ion\Tests\IonTestCase; use Aviat\Ion\Tests\IonTestCase;
use Aviat\Ion\Type\ArrayType;
class ArrayTypeTest extends IonTestCase { /**
* @internal
*/
final class ArrayTypeTest extends IonTestCase
{
public function dataCall() public function dataCall()
{ {
$method_map = [ $method_map = [
@ -43,38 +47,38 @@ class ArrayTypeTest extends IonTestCase {
'method' => 'merge', 'method' => 'merge',
'array' => [1, 3, 5, 7], 'array' => [1, 3, 5, 7],
'args' => [[2, 4, 6, 8]], 'args' => [[2, 4, 6, 8]],
'expected' => [1, 3, 5, 7, 2, 4, 6, 8] 'expected' => [1, 3, 5, 7, 2, 4, 6, 8],
], ],
'array_product' => [ 'array_product' => [
'method' => 'product', 'method' => 'product',
'array' => [1, 2, 3], 'array' => [1, 2, 3],
'args' => [], 'args' => [],
'expected' => 6 'expected' => 6,
], ],
'array_reverse' => [ 'array_reverse' => [
'method' => 'reverse', 'method' => 'reverse',
'array' => [1, 2, 3, 4, 5], 'array' => [1, 2, 3, 4, 5],
'args' => [], 'args' => [],
'expected' => [5, 4, 3, 2, 1] 'expected' => [5, 4, 3, 2, 1],
], ],
'array_sum' => [ 'array_sum' => [
'method' => 'sum', 'method' => 'sum',
'array' => [1, 2, 3, 4, 5, 6], 'array' => [1, 2, 3, 4, 5, 6],
'args' => [], 'args' => [],
'expected' => 21 'expected' => 21,
], ],
'array_unique' => [ 'array_unique' => [
'method' => 'unique', 'method' => 'unique',
'array' => [1, 1, 3, 2, 2, 2, 3, 3, 5], 'array' => [1, 1, 3, 2, 2, 2, 3, 3, 5],
'args' => [SORT_REGULAR], 'args' => [SORT_REGULAR],
'expected' => [0 => 1, 2 => 3, 3 => 2, 8 => 5] 'expected' => [0 => 1, 2 => 3, 3 => 2, 8 => 5],
], ],
'array_values' => [ 'array_values' => [
'method' => 'values', 'method' => 'values',
'array' => ['foo' => 'bar', 'baz' => 'foobar'], 'array' => ['foo' => 'bar', 'baz' => 'foobar'],
'args' => [], 'args' => [],
'expected' => ['bar', 'foobar'] 'expected' => ['bar', 'foobar'],
] ],
]; ];
} }
@ -82,16 +86,13 @@ class ArrayTypeTest extends IonTestCase {
* Test the array methods defined for the __Call method * Test the array methods defined for the __Call method
* *
* @dataProvider dataCall * @dataProvider dataCall
* @param string $method
* @param array $array
* @param array $args
* @param $expected * @param $expected
*/ */
public function testCall(string $method, array $array, array $args, $expected): void public function testCall(string $method, array $array, array $args, $expected): void
{ {
$obj = ArrayType::from($array); $obj = ArrayType::from($array);
$actual = $obj->__call($method, $args); $actual = $obj->__call($method, $args);
$this->assertEquals($expected, $actual); $this->assertSame($expected, $actual);
} }
public function testSet(): void public function testSet(): void
@ -100,16 +101,16 @@ class ArrayTypeTest extends IonTestCase {
$arraytype = $obj->set('foo', 'bar'); $arraytype = $obj->set('foo', 'bar');
$this->assertInstanceOf(ArrayType::class, $arraytype); $this->assertInstanceOf(ArrayType::class, $arraytype);
$this->assertEquals('bar', $obj->get('foo')); $this->assertSame('bar', $obj->get('foo'));
} }
public function testGet(): void public function testGet(): void
{ {
$array = [1, 2, 3, 4, 5]; $array = [1, 2, 3, 4, 5];
$obj = ArrayType::from($array); $obj = ArrayType::from($array);
$this->assertEquals($array, $obj->get()); $this->assertSame($array, $obj->get());
$this->assertEquals(1, $obj->get(0)); $this->assertSame(1, $obj->get(0));
$this->assertEquals(5, $obj->get(4)); $this->assertSame(5, $obj->get(4));
} }
public function testGetDeepKey(): void public function testGetDeepKey(): void
@ -117,22 +118,20 @@ class ArrayTypeTest extends IonTestCase {
$arr = [ $arr = [
'foo' => 'bar', 'foo' => 'bar',
'baz' => [ 'baz' => [
'bar' => 'foobar' 'bar' => 'foobar',
] ],
]; ];
$obj = ArrayType::from($arr); $obj = ArrayType::from($arr);
$this->assertEquals('foobar', $obj->getDeepKey(['baz', 'bar'])); $this->assertSame('foobar', $obj->getDeepKey(['baz', 'bar']));
$this->assertNull($obj->getDeepKey(['foo', 'bar', 'baz'])); $this->assertNull($obj->getDeepKey(['foo', 'bar', 'baz']));
} }
public function testMap(): void public function testMap(): void
{ {
$obj = ArrayType::from([1, 2, 3]); $obj = ArrayType::from([1, 2, 3]);
$actual = $obj->map(function($item) { $actual = $obj->map(static fn ($item) => $item * 2);
return $item * 2;
});
$this->assertEquals([2, 4, 6], $actual); $this->assertSame([2, 4, 6], $actual);
} }
public function testBadCall(): void public function testBadCall(): void
@ -153,14 +152,14 @@ class ArrayTypeTest extends IonTestCase {
$actual = $obj->shuffle(); $actual = $obj->shuffle();
//$this->assertNotEquals($actual, $original); //$this->assertNotEquals($actual, $original);
$this->assertTrue(is_array($actual)); $this->assertIsArray($actual);
} }
public function testHasKey(): void public function testHasKey(): void
{ {
$obj = ArrayType::from([ $obj = ArrayType::from([
'a' => 'b', 'a' => 'b',
'z' => 'y' 'z' => 'y',
]); ]);
$this->assertTrue($obj->hasKey('a')); $this->assertTrue($obj->hasKey('a'));
$this->assertFalse($obj->hasKey('b')); $this->assertFalse($obj->hasKey('b'));
@ -200,7 +199,7 @@ class ArrayTypeTest extends IonTestCase {
{ {
$obj = ArrayType::from([1, 2, 5, 7, 47]); $obj = ArrayType::from([1, 2, 5, 7, 47]);
$actual = $obj->search(47); $actual = $obj->search(47);
$this->assertEquals(4, $actual); $this->assertSame(4, $actual);
} }
public function testFill(): void public function testFill(): void
@ -208,6 +207,6 @@ class ArrayTypeTest extends IonTestCase {
$obj = ArrayType::from([]); $obj = ArrayType::from([]);
$expected = ['?', '?', '?']; $expected = ['?', '?', '?'];
$actual = $obj->fill(0, 3, '?'); $actual = $obj->fill(0, 3, '?');
$this->assertEquals($actual, $expected); $this->assertSame($actual, $expected);
} }
} }

View File

@ -16,52 +16,51 @@
namespace Aviat\Ion\Tests\Type; namespace Aviat\Ion\Tests\Type;
use Aviat\Ion\Type\StringType;
use Aviat\Ion\Tests\IonTestCase; use Aviat\Ion\Tests\IonTestCase;
use Aviat\Ion\Type\StringType;
class StringTypeTest extends IonTestCase { /**
* @internal
*/
final class StringTypeTest extends IonTestCase
{
public function dataFuzzyCaseMatch(): array public function dataFuzzyCaseMatch(): array
{ {
return [ return [
'space separated' => [ 'space separated' => [
'str1' => 'foo bar baz', 'str1' => 'foo bar baz',
'str2' => 'foo-bar-baz', 'str2' => 'foo-bar-baz',
'expected' => true 'expected' => TRUE,
], ],
'camelCase' => [ 'camelCase' => [
'str1' => 'fooBarBaz', 'str1' => 'fooBarBaz',
'str2' => 'foo-bar-baz', 'str2' => 'foo-bar-baz',
'expected' => true 'expected' => TRUE,
], ],
'PascalCase' => [ 'PascalCase' => [
'str1' => 'FooBarBaz', 'str1' => 'FooBarBaz',
'str2' => 'foo-bar-baz', 'str2' => 'foo-bar-baz',
'expected' => true 'expected' => TRUE,
], ],
'snake_case' => [ 'snake_case' => [
'str1' => 'foo_bar_baz', 'str1' => 'foo_bar_baz',
'str2' => 'foo-bar-baz', 'str2' => 'foo-bar-baz',
'expected' => true 'expected' => TRUE,
], ],
'mEsSYcAse' => [ 'mEsSYcAse' => [
'str1' => 'fOObArBAZ', 'str1' => 'fOObArBAZ',
'str2' => 'foo-bar-baz', 'str2' => 'foo-bar-baz',
'expected' => false 'expected' => FALSE,
], ],
]; ];
} }
/** /**
* @dataProvider dataFuzzyCaseMatch * @dataProvider dataFuzzyCaseMatch
* @param string $str1
* @param string $str2
* @param bool $expected
*/ */
public function testFuzzyCaseMatch(string $str1, string $str2, bool $expected): void public function testFuzzyCaseMatch(string $str1, string $str2, bool $expected): void
{ {
$actual = StringType::from($str1)->fuzzyCaseMatch($str2); $actual = StringType::from($str1)->fuzzyCaseMatch($str2);
$this->assertEquals($expected, $actual); $this->assertSame($expected, $actual);
} }
} }

View File

@ -16,15 +16,19 @@
namespace Aviat\Ion\Tests\View; namespace Aviat\Ion\Tests\View;
use function Aviat\Ion\_dir;
use Aviat\Ion\Tests\TestHtmlView; use Aviat\Ion\Tests\TestHtmlView;
class HtmlViewTest extends HttpViewTest { use function Aviat\Ion\_dir;
/**
* @internal
*/
final class HtmlViewTest extends HttpViewTest
{
protected $template_path; protected $template_path;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->view = new TestHtmlView($this->container); $this->view = new TestHtmlView($this->container);
} }
@ -34,9 +38,8 @@ class HtmlViewTest extends HttpViewTest {
$path = _dir(self::TEST_VIEW_DIR, 'test_view.php'); $path = _dir(self::TEST_VIEW_DIR, 'test_view.php');
$expected = '<tag>foo</tag>'; $expected = '<tag>foo</tag>';
$actual = $this->view->renderTemplate($path, [ $actual = $this->view->renderTemplate($path, [
'var' => 'foo' 'var' => 'foo',
]); ]);
$this->assertEquals($expected, $actual); $this->assertSame($expected, $actual);
} }
} }

View File

@ -16,17 +16,17 @@
namespace Aviat\Ion\Tests\View; namespace Aviat\Ion\Tests\View;
use Aviat\Ion\Friend;
use Aviat\Ion\Exception\DoubleRenderException; use Aviat\Ion\Exception\DoubleRenderException;
use Aviat\Ion\Tests\IonTestCase; use Aviat\Ion\Friend;
use Aviat\Ion\Tests\TestHttpView; use Aviat\Ion\Tests\{IonTestCase, TestHttpView};
class HttpViewTest extends IonTestCase {
class HttpViewTest extends IonTestCase
{
protected $view; protected $view;
protected $friend; protected $friend;
public function setUp(): void { protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->view = new TestHttpView(); $this->view = new TestHttpView();
$this->friend = new Friend($this->view); $this->friend = new Friend($this->view);
@ -35,38 +35,38 @@ class HttpViewTest extends IonTestCase {
public function testGetOutput(): void public function testGetOutput(): void
{ {
$this->friend->setOutput('foo'); $this->friend->setOutput('foo');
$this->assertEquals('foo', $this->friend->getOutput()); $this->assertSame('foo', $this->friend->getOutput());
$this->assertFalse($this->friend->hasRendered); $this->assertFalse($this->friend->hasRendered);
$this->assertEquals($this->friend->getOutput(), $this->friend->__toString()); $this->assertSame($this->friend->getOutput(), $this->friend->__toString());
$this->assertTrue($this->friend->hasRendered); $this->assertTrue($this->friend->hasRendered);
} }
public function testSetOutput(): void public function testSetOutput(): void
{ {
$same = $this->view->setOutput('<h1></h1>'); $same = $this->view->setOutput('<h1></h1>');
$this->assertEquals($same, $this->view); $this->assertSame($same, $this->view);
$this->assertEquals('<h1></h1>', $this->view->getOutput()); $this->assertSame('<h1></h1>', $this->view->getOutput());
} }
public function testAppendOutput(): void public function testAppendOutput(): void
{ {
$this->view->setOutput('<h1>'); $this->view->setOutput('<h1>');
$this->view->appendOutput('</h1>'); $this->view->appendOutput('</h1>');
$this->assertEquals('<h1></h1>', $this->view->getOutput()); $this->assertSame('<h1></h1>', $this->view->getOutput());
} }
public function testSetStatusCode(): void public function testSetStatusCode(): void
{ {
$view = $this->view->setStatusCode(404); $view = $this->view->setStatusCode(404);
$this->assertEquals(404, $view->response->getStatusCode()); $this->assertSame(404, $view->response->getStatusCode());
} }
public function testAddHeader(): void public function testAddHeader(): void
{ {
$view = $this->view->addHeader('foo', 'bar'); $view = $this->view->addHeader('foo', 'bar');
$this->assertTrue($view->response->hasHeader('foo')); $this->assertTrue($view->response->hasHeader('foo'));
$this->assertEquals(['bar'], $view->response->getHeader('foo')); $this->assertSame(['bar'], $view->response->getHeader('foo'));
} }
public function testSendDoubleRenderException(): void public function testSendDoubleRenderException(): void
@ -81,7 +81,7 @@ class HttpViewTest extends IonTestCase {
$this->view->send(); $this->view->send();
} }
public function test__toStringDoubleRenderException():void public function testToStringDoubleRenderException(): void
{ {
$this->expectException(DoubleRenderException::class); $this->expectException(DoubleRenderException::class);
$this->expectExceptionMessage('A view can only be rendered once, because headers can only be sent once.'); $this->expectExceptionMessage('A view can only be rendered once, because headers can only be sent once.');

View File

@ -19,9 +19,13 @@ namespace Aviat\Ion\Tests\View;
use Aviat\Ion\Friend; use Aviat\Ion\Friend;
use Aviat\Ion\Tests\TestJsonView; use Aviat\Ion\Tests\TestJsonView;
class JsonViewTest extends HttpViewTest { /**
* @internal
public function setUp(): void { */
final class JsonViewTest extends HttpViewTest
{
protected function setUp(): void
{
parent::setUp(); parent::setUp();
$this->view = new TestJsonView(); $this->view = new TestJsonView();
@ -37,7 +41,7 @@ class JsonViewTest extends HttpViewTest {
$content = ['foo' => 'bar']; $content = ['foo' => 'bar'];
$expected = json_encode($content); $expected = json_encode($content);
$view->setOutput($content); $view->setOutput($content);
$this->assertEquals($expected, $view->getOutput()); $this->assertSame($expected, $view->getOutput());
} }
public function testSetOutput(): void public function testSetOutput(): void
@ -47,11 +51,11 @@ class JsonViewTest extends HttpViewTest {
$content = '{}'; $content = '{}';
$expected = '{}'; $expected = '{}';
$view->setOutput($content); $view->setOutput($content);
$this->assertEquals($expected, $view->getOutput()); $this->assertSame($expected, $view->getOutput());
} }
public function testOutputType(): void public function testOutputType(): void
{ {
$this->assertEquals('application/json', $this->friend->contentType); $this->assertSame('application/json', $this->friend->contentType);
} }
} }

View File

@ -2,11 +2,9 @@
use Aura\Html\HelperLocatorFactory; use Aura\Html\HelperLocatorFactory;
use Aura\Session\SessionFactory; use Aura\Session\SessionFactory;
use Laminas\Diactoros\ServerRequestFactory;
use Laminas\Diactoros\Response;
use Aviat\Ion\Config; use Aviat\Ion\Config;
use Aviat\Ion\Di\Container; use Aviat\Ion\Di\Container;
use Laminas\Diactoros\{Response, ServerRequestFactory};
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Setup DI container // Setup DI container
@ -14,9 +12,7 @@ use Aviat\Ion\Di\Container;
return static function (array $config_array = []) { return static function (array $config_array = []) {
$container = new Container(); $container = new Container();
$container->set('config', static function() { $container->set('config', static fn () => new Config([]));
return new Config([]);
});
$container->setInstance('config', new Config($config_array)); $container->setInstance('config', new Config($config_array));
@ -30,18 +26,14 @@ return static function(array $config_array = []) {
); );
}); });
$container->set('response', static function() { $container->set('response', static fn () => new Response());
return new Response();
});
// Create session Object // Create session Object
$container->set('session', static function() { $container->set('session', static fn () => (new SessionFactory())->newInstance($_COOKIE));
return (new SessionFactory())->newInstance($_COOKIE);
});
// Create Html helper Object // Create Html helper Object
$container->set('html-helper', fn() => (new HelperLocatorFactory)->newInstance()); $container->set('html-helper', static fn () => (new HelperLocatorFactory())->newInstance());
$container->set('component-helper', fn() => (new HelperLocatorFactory)->newInstance()); $container->set('component-helper', static fn () => (new HelperLocatorFactory())->newInstance());
return $container; return $container;
}; };

View File

@ -16,18 +16,21 @@
namespace Aviat\Ion\Tests; namespace Aviat\Ion\Tests;
use function Aviat\Ion\_dir;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
class functionsTest extends TestCase { use function Aviat\Ion\_dir;
use const DIRECTORY_SEPARATOR;
/**
public function test_dir() * @internal
*/
final class functionsTest extends TestCase
{
public function testDir()
{ {
$args = ['foo', 'bar', 'baz']; $args = ['foo', 'bar', 'baz'];
$expected = implode(\DIRECTORY_SEPARATOR, $args); $expected = implode(DIRECTORY_SEPARATOR, $args);
$this->assertEquals(_dir(...$args), $expected); $this->assertSame(_dir(...$args), $expected);
} }
} }

View File

@ -16,40 +16,46 @@
namespace Aviat\Ion\Tests; namespace Aviat\Ion\Tests;
use Aviat\Ion\Enum;
use Aviat\Ion\Exception\DoubleRenderException; use Aviat\Ion\Exception\DoubleRenderException;
use Aviat\Ion\Friend;
use Aviat\Ion\Transformer\AbstractTransformer; use Aviat\Ion\Transformer\AbstractTransformer;
use Aviat\Ion\View\{HtmlView, HttpView, JsonView}; use Aviat\Ion\View\{HtmlView, HttpView, JsonView};
use Aviat\Ion\{Enum, Friend};
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Mock the default error handler // Mock the default error handler
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class MockErrorHandler { class MockErrorHandler
public function addDataTable($name, array $values=[]) {} {
public function addDataTable($name, array $values=[])
{
}
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// Ion Mocks // Ion Mocks
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class TestEnum extends Enum { class TestEnum extends Enum
const FOO = 'bar'; {
const BAR = 'foo'; public const FOO = 'bar';
const FOOBAR = 'baz'; public const BAR = 'foo';
public const FOOBAR = 'baz';
} }
class FriendGrandParentTestClass { class FriendGrandParentTestClass
{
protected $grandParentProtected = 84; protected $grandParentProtected = 84;
} }
class FriendParentTestClass extends FriendGrandParentTestClass { class FriendParentTestClass extends FriendGrandParentTestClass
{
protected $parentProtected = 47; protected $parentProtected = 47;
private $parentPrivate = 654; private $parentPrivate = 654;
} }
class FriendTestClass extends FriendParentTestClass { class FriendTestClass extends FriendParentTestClass
{
protected $protected = 356; protected $protected = 356;
private $private = 486; private $private = 486;
@ -64,8 +70,8 @@ class FriendTestClass extends FriendParentTestClass {
} }
} }
class TestTransformer extends AbstractTransformer { class TestTransformer extends AbstractTransformer
{
public function transform(array|object $item): array public function transform(array|object $item): array
{ {
$out = []; $out = [];
@ -80,14 +86,16 @@ class TestTransformer extends AbstractTransformer {
} }
} }
class TestTransformerUntransform extends TestTransformer { class TestTransformerUntransform extends TestTransformer
{
public function untransform($item) public function untransform($item)
{ {
return (array) $item; return (array) $item;
} }
} }
trait MockViewOutputTrait { trait MockViewOutputTrait
{
/*protected function output() { /*protected function output() {
$reflect = new ReflectionClass($this); $reflect = new ReflectionClass($this);
$properties = $reflect->getProperties(); $properties = $reflect->getProperties();
@ -120,7 +128,8 @@ trait MockViewOutputTrait {
} }
} }
class TestHtmlView extends HtmlView { class TestHtmlView extends HtmlView
{
protected function output(): void protected function output(): void
{ {
if ($this->hasRendered) if ($this->hasRendered)
@ -132,7 +141,8 @@ class TestHtmlView extends HtmlView {
} }
} }
class TestHttpView extends HttpView { class TestHttpView extends HttpView
{
protected function output(): void protected function output(): void
{ {
if ($this->hasRendered) if ($this->hasRendered)
@ -144,8 +154,11 @@ class TestHttpView extends HttpView {
} }
} }
class TestJsonView extends JsonView { class TestJsonView extends JsonView
public function __destruct() {} {
public function __destruct()
{
}
protected function output(): void protected function output(): void
{ {
@ -162,15 +175,17 @@ class TestJsonView extends JsonView {
// AnimeClient Mocks // AnimeClient Mocks
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
trait MockInjectionTrait { trait MockInjectionTrait
{
public function __get($key) public function __get($key)
{ {
return $this->$key; return $this->{$key};
} }
public function __set($key, $value) public function __set($key, $value)
{ {
$this->$key = $value; $this->{$key} = $value;
return $this; return $this;
} }
} }