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}"
: $key;
if ( ! isSequentialArray($value))
{
$builder->addTable($newKey);
}
$builder->addTable($newKey);
_iterateToml($builder, $value, $newKey);
}
@ -154,12 +152,7 @@ if ( ! function_exists('array_is_list'))
*/
function isSequentialArray(mixed $array): bool
{
if ( ! is_array($array))
{
return FALSE;
}
return array_is_list($array);
return is_array($array) && array_is_list($array);
}
/**

View File

@ -44,13 +44,13 @@ class Json
* @param int $fileOptions - Options to pass to file_get_contents
* @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);
$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;
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 Aviat\AnimeClient\getResponse;
use Aviat\AnimeClient\API\APIRequestBuilder;
use Aviat\Ion\Json;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
class APIRequestBuilderTest extends TestCase {
/**
* @internal
*/
final class APIRequestBuilderTest extends TestCase
{
protected $builder;
public function setUp(): void {
$this->builder = new class extends APIRequestBuilder {
protected function setUp(): void
{
$this->builder = new class () extends APIRequestBuilder {
protected string $baseUrl = 'https://httpbin.org/';
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
@ -44,12 +48,12 @@ class APIRequestBuilderTest extends TestCase {
->getFullRequest();
$response = getResponse($request);
$body = Json::decode(wait($response->getBody()->buffer()));
$this->assertEquals(1, $body['gzipped']);
$this->assertTrue($body['gzipped']);
}
public function testInvalidRequestMethod(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectException(InvalidArgumentException::class);
$this->builder->newRequest('FOO', 'gzip')
->getFullRequest();
}
@ -63,7 +67,7 @@ class APIRequestBuilderTest extends TestCase {
$response = getResponse($request);
$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
@ -71,17 +75,17 @@ class APIRequestBuilderTest extends TestCase {
$query = [
'foo' => 'bar',
'bar' => [
'foo' => 'bar'
'foo' => 'bar',
],
'baz' => [
'bar' => 'foo'
]
'bar' => 'foo',
],
];
$expected = [
'foo' => 'bar',
'bar[foo]' => 'bar',
'baz[bar]' => 'foo'
'baz[bar]' => 'foo',
'foo' => 'bar',
];
$request = $this->builder->newRequest('GET', 'get')
@ -91,14 +95,14 @@ class APIRequestBuilderTest extends TestCase {
$response = getResponse($request);
$body = Json::decode(wait($response->getBody()->buffer()));
$this->assertEquals($expected, $body['args']);
$this->assertSame($expected, $body['args']);
}
public function testFormValueRequest(): void
{
$formValues = [
'bar' => 'foo',
'foo' => 'bar',
'bar' => 'foo'
];
$request = $this->builder->newRequest('POST', 'post')
@ -108,7 +112,7 @@ class APIRequestBuilderTest extends TestCase {
$response = getResponse($request);
$body = Json::decode(wait($response->getBody()->buffer()));
$this->assertEquals($formValues, $body['form']);
$this->assertSame($formValues, $body['form']);
}
public function testFullUrlRequest(): void
@ -119,9 +123,9 @@ class APIRequestBuilderTest extends TestCase {
'baz' => [2, 3, 4],
'bazbar' => [
'a' => 1,
'b' => 2
]
]
'b' => 2,
],
],
];
$request = $this->builder->newRequest('PUT', 'https://httpbin.org/put')
@ -132,6 +136,6 @@ class APIRequestBuilderTest extends TestCase {
$response = getResponse($request);
$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\Tests\AnimeClientTestCase;
class CacheTraitTest extends AnimeClientTestCase {
/**
* @internal
*/
final class CacheTraitTest extends AnimeClientTestCase
{
protected $testClass;
public function setUp(): void {
protected function setUp(): void
{
parent::setUp();
$this->testClass = new class {
$this->testClass = new class () {
use CacheTrait;
};
}
@ -34,6 +38,6 @@ class CacheTraitTest extends AnimeClientTestCase {
{
$cachePool = $this->container->get('cache');
$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;
class ModelTest extends AnimeClientTestCase {
/**
* @internal
*/
final class ModelTest extends AnimeClientTestCase
{
protected $model;
public function setUp(): void
protected function setUp(): void
{
parent::setup();
$this->model = $this->container->get('kitsu-model');
@ -30,13 +33,13 @@ class ModelTest extends AnimeClientTestCase {
public function testGetAnimeKitsuIdFromMALId(): void
{
$kitsuId = $this->model->getKitsuIdFromMALId("1", 'anime');
self::assertEquals("1", $kitsuId);
$kitsuId = $this->model->getKitsuIdFromMALId('1', 'anime');
$this->assertSame('1', $kitsuId);
}
public function testGetNullFromMALAnimeId(): void
{
$kitsuId = $this->model->getKitsuIdFromMALId("0", 'anime');
self::assertNull($kitsuId);
$kitsuId = $this->model->getKitsuIdFromMALId('0', 'anime');
$this->assertNull($kitsuId);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,19 +18,24 @@ namespace Aviat\AnimeClient\Tests\Command;
use Aviat\AnimeClient\Command\BaseCommand;
use Aviat\AnimeClient\Tests\AnimeClientTestCase;
use Aviat\Ion\Di\Container;
use Aviat\Ion\Friend;
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 Friend $friend;
public function setUp(): void {
protected function setUp(): void
{
$this->base = new Command(new Console());
$this->friend = new Friend($this->base);
}

View File

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

View File

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

View File

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

View File

@ -19,12 +19,16 @@ namespace Aviat\AnimeClient\Tests\Helper;
use Aviat\AnimeClient\Helper\Menu as MenuHelper;
use Aviat\AnimeClient\Tests\AnimeClientTestCase;
class MenuHelperTest extends AnimeClientTestCase {
/**
* @internal
*/
final class MenuHelperTest extends AnimeClientTestCase
{
protected $helper;
protected $urlGenerator;
public function setUp(): void {
protected function setUp(): void
{
parent::setUp();
$this->helper = $this->container->get('html-helper');
$this->urlGenerator = $this->container->get('url-generator');
@ -36,15 +40,15 @@ class MenuHelperTest extends AnimeClientTestCase {
'no selection' => [
'route_prefix' => '/foo',
'items' => [
'bar' => '/bar'
]
'bar' => '/bar',
],
],
'selected' => [
'route_prefix' => '',
'items' => [
'index' => '/foobar'
]
]
'index' => '/foobar',
],
],
];
$expected = [];
@ -64,15 +68,15 @@ class MenuHelperTest extends AnimeClientTestCase {
$config->set('menus', $menus);
$this->container->setInstance('config', $config);
foreach($menus as $case => $config)
foreach ($menus as $case => $config)
{
if ($case === 'selected')
{
$this->setSuperGlobals([
'_SERVER' => [
'HTTP_HOST' => 'localhost',
'REQUEST_URI' => '/foobar'
]
'REQUEST_URI' => '/foobar',
],
]);
}
else
@ -80,14 +84,14 @@ class MenuHelperTest extends AnimeClientTestCase {
$this->setSuperGlobals([
'_SERVER' => [
'HTTP_HOST' => 'localhost',
'REQUEST_URI' => '/applesauceisgreat'
]
'REQUEST_URI' => '/applesauceisgreat',
],
]);
}
$helper = new MenuHelper();
$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\Tests\AnimeClientTestCase;
class PictureHelperTest extends AnimeClientTestCase {
/**
* @internal
*/
final class PictureHelperTest extends AnimeClientTestCase
{
/**
* @dataProvider dataPictureCase
* @param array $params
*/
public function testPictureHelper(array $params): void
{
@ -36,9 +39,6 @@ class PictureHelperTest extends AnimeClientTestCase {
/**
* @dataProvider dataSimpleImageCase
* @param string $ext
* @param bool $isSimple
* @param string $fallbackExt
*/
public function testSimpleImage(string $ext, bool $isSimple, string $fallbackExt = 'jpg'): void
{
@ -50,7 +50,7 @@ class PictureHelperTest extends AnimeClientTestCase {
$actuallySimple = ! str_contains($actual, '<picture');
$this->assertEquals($isSimple, $actuallySimple);
$this->assertSame($isSimple, $actuallySimple);
}
public function testSimpleImageByFallback(): void
@ -58,9 +58,9 @@ class PictureHelperTest extends AnimeClientTestCase {
$helper = new PictureHelper();
$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'));
}
public function dataPictureCase(): array
@ -78,7 +78,7 @@ class PictureHelperTest extends AnimeClientTestCase {
],
'Partial webp URL' => [
'params' => [
'images/anime/15424.webp'
'images/anime/15424.webp',
],
],
'bmp with gif fallback' => [
@ -90,25 +90,25 @@ class PictureHelperTest extends AnimeClientTestCase {
'webp placeholder image' => [
'params' => [
'images/placeholder.webp',
]
],
],
'png placeholder image' => [
'params' => [
'images/placeholder.png',
]
],
],
'jpeg2000' => [
'params' => [
'images/foo.jpf',
]
],
],
'svg with png fallback and lots of attributes' => [
'params' => [
'images/example.svg',
'png',
[ 'width' => 200, 'height' => 300 ],
[ 'alt' => 'Example text' ]
]
['width' => 200, 'height' => 300],
['alt' => 'Example text'],
],
],
'simple image with attributes' => [
'params' => [
@ -116,8 +116,8 @@ class PictureHelperTest extends AnimeClientTestCase {
'jpg',
[],
['width' => 200, 'height' => 200, 'alt' => 'should exist'],
]
]
],
],
];
}
@ -127,7 +127,7 @@ class PictureHelperTest extends AnimeClientTestCase {
'avif' => [
'ext' => 'avif',
'isSimple' => FALSE,
'fallback' => 'jpf'
'fallback' => 'jpf',
],
'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;
use Aviat\AnimeClient\API\Kitsu\Enum\MangaPublishingStatus;
use Aviat\AnimeClient\API\Kitsu\Enum\{AnimeAiringStatus, MangaPublishingStatus};
use Aviat\AnimeClient\Kitsu;
use Aviat\AnimeClient\API\Kitsu\Enum\AnimeAiringStatus;
use PHPUnit\Framework\TestCase;
class KitsuTest extends TestCase {
/**
* @internal
*/
final class KitsuTest extends TestCase
{
public function testGetAiringStatus(): void
{
$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
{
$this->assertEquals([], Kitsu::parseStreamingLinks([]));
$this->assertSame([], Kitsu::parseStreamingLinks([]));
}
public function testParseStreamingLinks(): void
@ -38,7 +41,7 @@ class KitsuTest extends TestCase {
$nodes = [[
'url' => 'www.hulu.com/chobits',
'dubs' => ['ja'],
'subs' => ['en']
'subs' => ['en'],
]];
$expected = [[
@ -63,17 +66,17 @@ class KitsuTest extends TestCase {
'subs' => [],
]];
$this->assertEquals([], Kitsu::parseStreamingLinks($nodes));
$this->assertSame([], Kitsu::parseStreamingLinks($nodes));
}
public function testGetAiringStatusEmptyArguments(): void
{
$this->assertEquals(AnimeAiringStatus::NOT_YET_AIRED, Kitsu::getAiringStatus());
$this->assertSame(AnimeAiringStatus::NOT_YET_AIRED, Kitsu::getAiringStatus());
}
public function testGetAiringStatusIsAiring(): void
{
$this->assertEquals(AnimeAiringStatus::AIRING, Kitsu::getAiringStatus('yesterday'));
$this->assertSame(AnimeAiringStatus::AIRING, Kitsu::getAiringStatus('yesterday'));
}
public function getPublishingStatus(): array
@ -86,19 +89,17 @@ class KitsuTest extends TestCase {
'future' => [
'kitsuStatus' => 'foo',
'expected' => MangaPublishingStatus::NOT_YET_PUBLISHED,
]
],
];
}
/**
* @param string $kitsuStatus
* @param string $expected
* @dataProvider getPublishingStatus
*/
public function testGetPublishingStatus(string $kitsuStatus, string $expected): void
{
$actual = Kitsu::getPublishingStatus($kitsuStatus);
$this->assertEquals($expected, $actual);
$this->assertSame($expected, $actual);
}
public function getFriendlyTime(): array
@ -115,23 +116,21 @@ class KitsuTest extends TestCase {
'expected' => '1 hour',
], [
'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),
'expected' => '5 years, 3 days, and 17 minutes'
'expected' => '5 years, 3 days, and 17 minutes',
]];
}
/**
* @param int $seconds
* @param string $expected
* @dataProvider getFriendlyTime
*/
public function testGetFriendlyTime(int $seconds, string $expected): void
{
$actual = Kitsu::friendlyTime($seconds);
$this->assertEquals($expected, $actual);
$this->assertSame($expected, $actual);
}
public function testFilterLocalizedTitles(): void
@ -148,7 +147,7 @@ class KitsuTest extends TestCase {
$actual = Kitsu::filterLocalizedTitles($input);
$this->assertEquals(['Foo the Movie'], $actual);
$this->assertSame(['Foo the Movie'], $actual);
}
public function testGetFilteredTitles(): void
@ -156,13 +155,13 @@ class KitsuTest extends TestCase {
$input = [
'canonical' => 'foo',
'localized' => [
'en' => 'Foo the Movie'
'en' => 'Foo the Movie',
],
'alternatives' => [],
];
$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\Ion\Friend;
class MenuGeneratorTest extends AnimeClientTestCase {
/**
* @internal
*/
final class MenuGeneratorTest extends AnimeClientTestCase
{
protected $generator;
protected $friend;
public function setUp(): void {
protected function setUp(): void
{
parent::setUp();
$this->generator = MenuGenerator::new($this->container);
}
@ -47,8 +51,8 @@ class MenuGeneratorTest extends AnimeClientTestCase {
'on_hold' => '/on_hold',
'dropped' => '/dropped',
'completed' => '/completed',
'all' => '/all'
]
'all' => '/all',
],
],
];
$expected = [
@ -58,10 +62,10 @@ class MenuGeneratorTest extends AnimeClientTestCase {
'On Hold' => '/anime/on_hold',
'Dropped' => '/anime/dropped',
'Completed' => '/anime/completed',
'All' => '/anime/all'
]
'All' => '/anime/all',
],
];
$this->assertEquals($expected, $friend->parseConfig($menus));
$this->assertSame($expected, $friend->parseConfig($menus));
}
public function testBadConfig()
@ -75,8 +79,8 @@ class MenuGeneratorTest extends AnimeClientTestCase {
'on_hold' => '/on_hold',
'dropped' => '/dropped',
'completed' => '/completed',
'all' => '/all'
]
'all' => '/all',
],
],
];
$config = $this->container->get('config');
@ -84,6 +88,6 @@ class MenuGeneratorTest extends AnimeClientTestCase {
$this->container->setInstance('config', $config);
$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;
class RequirementsTest extends AnimeClientTestCase {
/**
* @internal
*/
final class RequirementsTest extends AnimeClientTestCase
{
public function testPHPVersion(): void
{
$this->assertTrue(version_compare(PHP_VERSION, "8", "ge"));
$this->assertTrue(version_compare(PHP_VERSION, '8', 'ge'));
}
public function testHasPDO(): void
@ -33,6 +36,6 @@ class RequirementsTest extends AnimeClientTestCase {
public function testHasPDOSqlite(): void
{
$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;
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()
{
return [
@ -27,35 +32,35 @@ class RoutingBaseTest extends AnimeClientTestCase {
'requestUri' => ' // ',
'path' => '/',
'segments' => ['', ''],
'lastSegment' => NULL
'lastSegment' => NULL,
],
'three_segments' => [
'requestUri' => '/anime/watching/list ',
'path' => '/anime/watching/list',
'segments' => ['', 'anime', 'watching', 'list'],
'lastSegment' => 'list'
]
'lastSegment' => 'list',
],
];
}
/**
* @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([
'_SERVER' => [
'REQUEST_URI' => $requestUri
]
'REQUEST_URI' => $requestUri,
],
]);
$routingBase = new RoutingBase($this->container);
$this->assertEquals($path, $routingBase->path(), "Path is invalid");
$this->assertEquals($segments, $routingBase->segments(), "Segments array is invalid");
$this->assertEquals($lastSegment, $routingBase->lastSegment(), "Last segment is invalid");
$this->assertSame($path, $routingBase->path(), 'Path is invalid');
$this->assertSame($segments, $routingBase->segments(), 'Segments array is invalid');
$this->assertEquals($lastSegment, $routingBase->lastSegment(), 'Last segment is invalid');
foreach($segments as $i => $value)
foreach ($segments as $i => $value)
{
$this->assertEquals($value, $routingBase->getSegment($i), "Segment {$i} is invalid");
}

View File

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

View File

@ -18,8 +18,12 @@ namespace Aviat\AnimeClient\Tests\Types;
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();
@ -34,7 +38,7 @@ class ConfigTest extends ConfigTestCase {
'database' => [],
]);
$this->assertEquals(3, $type->count());
$this->assertSame(3, $type->count());
}
public function testOffsetUnset(): void

View File

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

View File

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

View File

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

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="light">Original Light 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>
';

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>
';

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="manga">Manga</option>
</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="plan_to_watch">Plan to Watch</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="plan_to_read">Plan to Read</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="pgsql">PostgreSQL</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="memcached">Memcached</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
*/
use Aviat\AnimeClient\Model\{
Anime as AnimeModel,
API as BaseApiModel,
Anime as AnimeModel,
Manga as MangaModel
};
use Aviat\Ion\{Enum, Friend, Json};
use Aviat\Ion\Transformer\AbstractTransformer;
use Aviat\Ion\View\{HtmlView, HttpView, JsonView};
use Aviat\Ion\{Enum, Friend, Json};
// -----------------------------------------------------------------------------
// Mock the default error handler
// -----------------------------------------------------------------------------
class MockErrorHandler {
public function addDataTable(string $name, array $values=[]): void {}
class MockErrorHandler
{
public function addDataTable(string $name, array $values=[]): void
{
}
}
// -----------------------------------------------------------------------------
// Ion Mocks
// -----------------------------------------------------------------------------
class TestEnum extends Enum {
const FOO = 'bar';
const BAR = 'foo';
const FOOBAR = 'baz';
class TestEnum extends Enum
{
public const FOO = 'bar';
public const BAR = 'foo';
public const FOOBAR = 'baz';
}
class FriendGrandParentTestClass {
class FriendGrandParentTestClass
{
protected int $grandParentProtected = 84;
}
class FriendParentTestClass extends FriendGrandParentTestClass {
class FriendParentTestClass extends FriendGrandParentTestClass
{
protected int $parentProtected = 47;
private int $parentPrivate = 654;
}
class FriendTestClass extends FriendParentTestClass {
class FriendTestClass extends FriendParentTestClass
{
protected int $protected = 356;
private int $private = 486;
@ -54,14 +61,14 @@ class FriendTestClass extends FriendParentTestClass {
}
}
class TestTransformer extends AbstractTransformer {
class TestTransformer extends AbstractTransformer
{
public function transform($item): array
{
$out = [];
$genre_list = (array) $item;
foreach($genre_list as $genre)
foreach ($genre_list as $genre)
{
$out[] = $genre['name'];
}
@ -70,13 +77,15 @@ class TestTransformer extends AbstractTransformer {
}
}
trait MockViewOutputTrait {
protected function output(): void {
trait MockViewOutputTrait
{
protected function output(): void
{
$reflect = new ReflectionClass($this);
$properties = $reflect->getProperties();
$props = [];
foreach($properties as $reflectProp)
foreach ($properties as $reflectProp)
{
$reflectProp->setAccessible(TRUE);
$props[$reflectProp->getName()] = $reflectProp->getValue($this);
@ -84,7 +93,8 @@ trait MockViewOutputTrait {
$view = new TestView();
$friend = new Friend($view);
foreach($props as $name => $val)
foreach ($props as $name => $val)
{
$friend->__set($name, $val);
}
@ -93,15 +103,20 @@ trait MockViewOutputTrait {
}
}
class MockUtil {
public function get_cached_image($api_path, $series_slug, $type = "anime"): string
class MockUtil
{
public function get_cached_image($api_path, $series_slug, $type = 'anime'): string
{
return "/public/images/{$type}/{$series_slug}.jpg";
}
}
class TestView extends HttpView {
public function send(): void {}
class TestView extends HttpView
{
public function send(): void
{
}
protected function output(): void
{
/*$content =& $this->response->content;
@ -111,38 +126,46 @@ class TestView extends HttpView {
}
}
class TestHtmlView extends HtmlView {
class TestHtmlView extends HtmlView
{
use MockViewOutputTrait;
}
class TestHttpView extends HttpView {
class TestHttpView extends HttpView
{
use MockViewOutputTrait;
}
class TestJsonView extends JsonView {
public function __destruct() {}
class TestJsonView extends JsonView
{
public function __destruct()
{
}
}
// -----------------------------------------------------------------------------
// AnimeClient Mocks
// -----------------------------------------------------------------------------
trait MockInjectionTrait {
trait MockInjectionTrait
{
public function __get(string $key): mixed
{
return $this->$key;
return $this->{$key};
}
public function __set(string $key, mixed $value)
{
$this->$key = $value;
$this->{$key} = $value;
return $this;
}
}
class MockBaseApiModel extends BaseApiModel {
class MockBaseApiModel extends BaseApiModel
{
use MockInjectionTrait;
protected string $base_url = 'https://httpbin.org/';
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;
}
class TestMangaModel extends MangaModel {
class TestMangaModel extends MangaModel
{
use MockInjectionTrait;
protected function _check_cache($response)
{
$file = __DIR__ . '/test_data/manga_list/manga-transformed.json';
return Json::decodeFile($file);
}
}

View File

@ -18,11 +18,14 @@ namespace Aviat\Ion\Tests;
use Aviat\Ion\Model as BaseModel;
class BaseModelTest extends IonTestCase {
/**
* @internal
*/
final class BaseModelTest extends IonTestCase
{
public function testBaseModelSanity()
{
$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;
class ConfigTest extends IonTestCase {
/**
* @internal
*/
final class ConfigTest extends IonTestCase
{
protected Config $config;
public function setUp(): void
protected function setUp(): void
{
$this->config = new Config([
'foo' => 'bar',
@ -47,8 +50,8 @@ class ConfigTest extends IonTestCase {
public function testConfigGet(): void
{
$this->assertEquals('bar', $this->config->get('foo'));
$this->assertEquals('baz', $this->config->get('bar'));
$this->assertSame('bar', $this->config->get('foo'));
$this->assertSame('baz', $this->config->get('bar'));
$this->assertNull($this->config->get('baz'));
$this->assertNull($this->config->get(['apple', 'sauce', 'is']));
}
@ -57,13 +60,13 @@ class ConfigTest extends IonTestCase {
{
$ret = $this->config->set('foo', 'foobar');
$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');
$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
@ -74,57 +77,58 @@ class ConfigTest extends IonTestCase {
'assertKeys' => [
[
'path' => ['apple', 'sauce', 'is'],
'expected' => NULL
'expected' => NULL,
],
[
'path' => ['apple', 'sauce'],
'expected' => NULL
'expected' => NULL,
],
[
'path' => 'apple',
'expected' => NULL
]
]
'expected' => NULL,
],
],
],
'mid level delete' => [
'key' => ['apple', 'sauce'],
'assertKeys' => [
[
'path' => ['apple', 'sauce', 'is'],
'expected' => NULL
'expected' => NULL,
],
[
'path' => ['apple', 'sauce'],
'expected' => NULL
'expected' => NULL,
],
[
'path' => 'apple',
'expected' => [
'sauce' => NULL
]
]
]
'sauce' => NULL,
],
],
],
],
'deep delete' => [
'key' => ['apple', 'sauce', 'is'],
'assertKeys' => [
[
'path' => ['apple', 'sauce', 'is'],
'expected' => NULL
'expected' => NULL,
],
[
'path' => ['apple', 'sauce'],
'expected' => [
'is' => NULL
]
]
]
]
'is' => NULL,
],
],
],
],
];
}
/**
* @dataProvider dataConfigDelete
* @param mixed $key
*/
public function testConfigDelete($key, array $assertKeys): void
{
@ -132,9 +136,9 @@ class ConfigTest extends IonTestCase {
$config->set(['apple', 'sauce', 'is'], 'great');
$config->delete($key);
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\Tests\IonTestCase;
class Aware {
class Aware
{
use ContainerAware;
public function __construct(ContainerInterface $container)
@ -28,12 +29,14 @@ class Aware {
}
}
class ContainerAwareTest extends IonTestCase {
/**
* @internal
*/
final class ContainerAwareTest extends IonTestCase
{
protected Aware $aware;
public function setUp(): void
protected function setUp(): void
{
$this->container = new Container();
$this->aware = new Aware($this->container);
@ -47,7 +50,7 @@ class ContainerAwareTest extends IonTestCase {
$container2 = new Container([
'foo' => 'bar',
'baz' => 'foobar'
'baz' => 'foobar',
]);
$this->aware->setContainer($container2);
$this->assertSame($container2, $this->aware->getContainer());

View File

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

View File

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

View File

@ -17,49 +17,52 @@
namespace Aviat\Ion\Tests;
use Aviat\Ion\Friend;
use Aviat\Ion\Tests\FriendTestClass;
class FriendTest extends IonTestCase {
/**
* @internal
*/
final class FriendTest extends IonTestCase
{
protected $friend;
public function setUp(): void {
protected function setUp(): void
{
parent::setUp();
$obj = new FriendTestClass();
$this->friend = new Friend($obj);
}
public function testPrivateMethod():void
public function testPrivateMethod(): void
{
$actual = $this->friend->getPrivate();
$this->assertEquals(23, $actual);
$this->assertSame(23, $actual);
}
public function testProtectedMethod():void
public function testProtectedMethod(): void
{
$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->assertEquals(47, $this->friend->parentProtected);
$this->assertEquals(84, $this->friend->grandParentProtected);
$this->assertSame(47, $this->friend->parentProtected);
$this->assertSame(84, $this->friend->grandParentProtected);
$this->assertNull($this->friend->parentPrivate); // Can't get a parent's privates
}
public function testSet(): void
{
$this->friend->private = 123;
$this->assertEquals(123, $this->friend->private);
$this->assertSame(123, $this->friend->private);
$this->friend->foo = 32;
$this->assertNull($this->friend->foo);
}
public function testBadInvokation():void
public function testBadInvokation(): void
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Friend must be an object');
@ -67,7 +70,7 @@ class FriendTest extends IonTestCase {
$friend = new Friend('foo');
}
public function testBadMethod():void
public function testBadMethod(): void
{
$this->expectException('BadMethodCallException');
$this->expectExceptionMessage("Method 'foo' does not exist");

View File

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

View File

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

View File

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

View File

@ -18,14 +18,18 @@ namespace Aviat\Ion\Tests\Transformer;
use Aviat\Ion\Tests\IonTestCase;
use Aviat\Ion\Tests\{TestTransformer, TestTransformerUntransform};
use BadMethodCallException;
class AbstractTransformerTest extends IonTestCase {
/**
* @internal
*/
final class AbstractTransformerTest extends IonTestCase
{
protected $transformer;
protected $untransformer;
public function setUp(): void {
protected function setUp(): void
{
$this->transformer = new TestTransformer();
$this->untransformer = new TestTransformerUntransform();
}
@ -35,29 +39,29 @@ class AbstractTransformerTest extends IonTestCase {
return [
'object' => [
'original' => [
(object)[
(object) [
['name' => 'Comedy'],
['name' => 'Romance'],
['name' => 'School'],
['name' => 'Harem']
['name' => 'Harem'],
],
(object)[
(object) [
['name' => 'Action'],
['name' => 'Comedy'],
['name' => 'Magic'],
['name' => 'Fantasy'],
['name' => 'Mahou Shoujo']
['name' => 'Mahou Shoujo'],
],
(object)[
(object) [
['name' => 'Comedy'],
['name' => 'Sci-Fi']
]
['name' => 'Sci-Fi'],
],
],
'expected' => [
['Comedy', 'Romance', 'School', 'Harem'],
['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
['Comedy', 'Sci-Fi']
]
['Comedy', 'Sci-Fi'],
],
],
'array' => [
'original' => [
@ -65,25 +69,25 @@ class AbstractTransformerTest extends IonTestCase {
['name' => 'Comedy'],
['name' => 'Romance'],
['name' => 'School'],
['name' => 'Harem']
['name' => 'Harem'],
],
[
['name' => 'Action'],
['name' => 'Comedy'],
['name' => 'Magic'],
['name' => 'Fantasy'],
['name' => 'Mahou Shoujo']
['name' => 'Mahou Shoujo'],
],
[
['name' => 'Comedy'],
['name' => 'Sci-Fi']
]
['name' => 'Sci-Fi'],
],
],
'expected' => [
['Comedy', 'Romance', 'School', 'Harem'],
['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
['Comedy', 'Sci-Fi']
]
['Comedy', 'Sci-Fi'],
],
],
];
}
@ -93,28 +97,28 @@ class AbstractTransformerTest extends IonTestCase {
return [
'object' => [
'original' => [
(object)['Comedy', 'Romance', 'School', 'Harem'],
(object)['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
(object)['Comedy', 'Sci-Fi']
(object) ['Comedy', 'Romance', 'School', 'Harem'],
(object) ['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
(object) ['Comedy', 'Sci-Fi'],
],
'expected' => [
['Comedy', 'Romance', 'School', 'Harem'],
['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
['Comedy', 'Sci-Fi']
]
['Comedy', 'Sci-Fi'],
],
],
'array' => [
'original' => [
['Comedy', 'Romance', 'School', 'Harem'],
['Action', 'Comedy', 'Magic', 'Fantasy', 'Mahou Shoujo'],
['Comedy', 'Sci-Fi']
['Comedy', 'Sci-Fi'],
],
'expected' => [
['Comedy', 'Romance', 'School', 'Harem'],
['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];
$actual = $this->transformer->transform($original);
$this->assertEquals($expected, $actual);
$this->assertSame($expected, $actual);
}
/**
* @dataProvider dataTransformCollection
* @param mixed $original
* @param mixed $expected
*/
public function testTransformCollection($original, $expected)
{
$actual = $this->transformer->transformCollection($original);
$this->assertEquals($expected, $actual);
$this->assertSame($expected, $actual);
}
/**
* @dataProvider dataUnTransformCollection
* @param mixed $original
* @param mixed $expected
*/
public function testUntransformCollection($original, $expected)
{
$actual = $this->untransformer->untransformCollection($original);
$this->assertEquals($expected, $actual);
$this->assertSame($expected, $actual);
}
/**
* @dataProvider dataUnTransformCollection
* @param mixed $original
* @param mixed $expected
*/
public function testUntransformCollectionWithException($original, $expected)
{
$this->expectException(\BadMethodCallException::class);
$this->expectException(BadMethodCallException::class);
$this->transformer->untransformCollection($original);
}
}

View File

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

View File

@ -16,52 +16,51 @@
namespace Aviat\Ion\Tests\Type;
use Aviat\Ion\Type\StringType;
use Aviat\Ion\Tests\IonTestCase;
use Aviat\Ion\Type\StringType;
class StringTypeTest extends IonTestCase {
/**
* @internal
*/
final class StringTypeTest extends IonTestCase
{
public function dataFuzzyCaseMatch(): array
{
return [
'space separated' => [
'str1' => 'foo bar baz',
'str2' => 'foo-bar-baz',
'expected' => true
'expected' => TRUE,
],
'camelCase' => [
'str1' => 'fooBarBaz',
'str2' => 'foo-bar-baz',
'expected' => true
'expected' => TRUE,
],
'PascalCase' => [
'str1' => 'FooBarBaz',
'str2' => 'foo-bar-baz',
'expected' => true
'expected' => TRUE,
],
'snake_case' => [
'str1' => 'foo_bar_baz',
'str2' => 'foo-bar-baz',
'expected' => true
'expected' => TRUE,
],
'mEsSYcAse' => [
'str1' => 'fOObArBAZ',
'str2' => 'foo-bar-baz',
'expected' => false
'expected' => FALSE,
],
];
}
/**
* @dataProvider dataFuzzyCaseMatch
* @param string $str1
* @param string $str2
* @param bool $expected
*/
public function testFuzzyCaseMatch(string $str1, string $str2, bool $expected): void
{
$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;
use function Aviat\Ion\_dir;
use Aviat\Ion\Tests\TestHtmlView;
class HtmlViewTest extends HttpViewTest {
use function Aviat\Ion\_dir;
/**
* @internal
*/
final class HtmlViewTest extends HttpViewTest
{
protected $template_path;
public function setUp(): void {
protected function setUp(): void
{
parent::setUp();
$this->view = new TestHtmlView($this->container);
}
@ -34,9 +38,8 @@ class HtmlViewTest extends HttpViewTest {
$path = _dir(self::TEST_VIEW_DIR, 'test_view.php');
$expected = '<tag>foo</tag>';
$actual = $this->view->renderTemplate($path, [
'var' => 'foo'
'var' => 'foo',
]);
$this->assertEquals($expected, $actual);
$this->assertSame($expected, $actual);
}
}

View File

@ -16,60 +16,60 @@
namespace Aviat\Ion\Tests\View;
use Aviat\Ion\Friend;
use Aviat\Ion\Exception\DoubleRenderException;
use Aviat\Ion\Tests\IonTestCase;
use Aviat\Ion\Tests\TestHttpView;
class HttpViewTest extends IonTestCase {
use Aviat\Ion\Friend;
use Aviat\Ion\Tests\{IonTestCase, TestHttpView};
class HttpViewTest extends IonTestCase
{
protected $view;
protected $friend;
public function setUp(): void {
protected function setUp(): void
{
parent::setUp();
$this->view = new TestHttpView();
$this->friend = new Friend($this->view);
}
public function testGetOutput():void
public function testGetOutput(): void
{
$this->friend->setOutput('foo');
$this->assertEquals('foo', $this->friend->getOutput());
$this->assertSame('foo', $this->friend->getOutput());
$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);
}
public function testSetOutput():void
public function testSetOutput(): void
{
$same = $this->view->setOutput('<h1></h1>');
$this->assertEquals($same, $this->view);
$this->assertEquals('<h1></h1>', $this->view->getOutput());
$this->assertSame($same, $this->view);
$this->assertSame('<h1></h1>', $this->view->getOutput());
}
public function testAppendOutput():void
public function testAppendOutput(): void
{
$this->view->setOutput('<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);
$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');
$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
{
$this->expectException(DoubleRenderException::class);
$this->expectExceptionMessage('A view can only be rendered once, because headers can only be sent once.');
@ -81,7 +81,7 @@ class HttpViewTest extends IonTestCase {
$this->view->send();
}
public function test__toStringDoubleRenderException():void
public function testToStringDoubleRenderException(): void
{
$this->expectException(DoubleRenderException::class);
$this->expectExceptionMessage('A view can only be rendered once, because headers can only be sent once.');

View File

@ -19,16 +19,20 @@ namespace Aviat\Ion\Tests\View;
use Aviat\Ion\Friend;
use Aviat\Ion\Tests\TestJsonView;
class JsonViewTest extends HttpViewTest {
public function setUp(): void {
/**
* @internal
*/
final class JsonViewTest extends HttpViewTest
{
protected function setUp(): void
{
parent::setUp();
$this->view = new TestJsonView();
$this->friend = new Friend($this->view);
}
public function testSetOutputJSON():void
public function testSetOutputJSON(): void
{
// Extend view class to remove destructor which does output
$view = new TestJsonView();
@ -37,21 +41,21 @@ class JsonViewTest extends HttpViewTest {
$content = ['foo' => 'bar'];
$expected = json_encode($content);
$view->setOutput($content);
$this->assertEquals($expected, $view->getOutput());
$this->assertSame($expected, $view->getOutput());
}
public function testSetOutput():void
public function testSetOutput(): void
{
// Directly set string
$view = new TestJsonView();
$content = '{}';
$expected = '{}';
$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,25 +2,21 @@
use Aura\Html\HelperLocatorFactory;
use Aura\Session\SessionFactory;
use Laminas\Diactoros\ServerRequestFactory;
use Laminas\Diactoros\Response;
use Aviat\Ion\Config;
use Aviat\Ion\Di\Container;
use Laminas\Diactoros\{Response, ServerRequestFactory};
// -----------------------------------------------------------------------------
// Setup DI container
// -----------------------------------------------------------------------------
return static function(array $config_array = []) {
return static function (array $config_array = []) {
$container = new Container();
$container->set('config', static function() {
return new Config([]);
});
$container->set('config', static fn () => new Config([]));
$container->setInstance('config', new Config($config_array));
$container->set('request', static function() {
$container->set('request', static function () {
return ServerRequestFactory::fromGlobals(
$GLOBALS['_SERVER'],
$_GET,
@ -30,18 +26,14 @@ return static function(array $config_array = []) {
);
});
$container->set('response', static function() {
return new Response();
});
$container->set('response', static fn () => new Response());
// Create session Object
$container->set('session', static function() {
return (new SessionFactory())->newInstance($_COOKIE);
});
$container->set('session', static fn () => (new SessionFactory())->newInstance($_COOKIE));
// Create Html helper Object
$container->set('html-helper', fn() => (new HelperLocatorFactory)->newInstance());
$container->set('component-helper', fn() => (new HelperLocatorFactory)->newInstance());
$container->set('html-helper', static fn () => (new HelperLocatorFactory())->newInstance());
$container->set('component-helper', static fn () => (new HelperLocatorFactory())->newInstance());
return $container;
};

View File

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