[WIP] Начало работы над тестом KktMonitorTest

pull/10/head
Anthony Axenov 2021-11-18 19:07:32 +08:00
parent 03591600dd
commit 949b31a85a
10 changed files with 270 additions and 88 deletions

View File

@ -58,7 +58,7 @@
}, },
"autoload-dev": { "autoload-dev": {
"psr-4": { "psr-4": {
"AtolOnline\\Tests\\": "tests/" "AtolOnlineTests\\": "tests/"
} }
}, },
"scripts": { "scripts": {

View File

@ -29,7 +29,7 @@ abstract class AtolClient
/** /**
* @var bool Флаг тестового режима * @var bool Флаг тестового режима
*/ */
protected bool $test_mode = true; protected bool $test_mode;
/** /**
* @var Client HTTP-клиент для работы с API * @var Client HTTP-клиент для работы с API
@ -59,6 +59,7 @@ abstract class AtolClient
/** /**
* Конструктор * Конструктор
* *
* @param bool $test_mode
* @param string|null $login * @param string|null $login
* @param string|null $password * @param string|null $password
* @param array $config * @param array $config
@ -69,6 +70,7 @@ abstract class AtolClient
* @see https://guzzle.readthedocs.io/en/latest/request-options.html Допустимые параметры для $config * @see https://guzzle.readthedocs.io/en/latest/request-options.html Допустимые параметры для $config
*/ */
public function __construct( public function __construct(
bool $test_mode = true,
?string $login = null, ?string $login = null,
?string $password = null, ?string $password = null,
array $config = [] array $config = []
@ -76,8 +78,9 @@ abstract class AtolClient
$this->http = new Client(array_merge($config, [ $this->http = new Client(array_merge($config, [
'http_errors' => $config['http_errors'] ?? false, 'http_errors' => $config['http_errors'] ?? false,
])); ]));
$login && $this->setLogin($login); $this->setTestMode($test_mode);
$password && $this->setPassword($password); !is_null($login) && $this->setLogin($login);
!is_null($password) && $this->setPassword($password);
} }
/** /**
@ -96,7 +99,7 @@ abstract class AtolClient
* @param bool $test_mode * @param bool $test_mode
* @return $this * @return $this
*/ */
public function setTestMode(bool $test_mode): self public function setTestMode(bool $test_mode = true): self
{ {
$this->test_mode = $test_mode; $this->test_mode = $test_mode;
return $this; return $this;
@ -139,7 +142,7 @@ abstract class AtolClient
* *
* @return string|null * @return string|null
*/ */
protected function getLogin(): ?string public function getLogin(): ?string
{ {
return $this->login; return $this->login;
} }
@ -169,7 +172,7 @@ abstract class AtolClient
* *
* @return string|null * @return string|null
*/ */
protected function getPassword(): ?string public function getPassword(): ?string
{ {
return $this->password; return $this->password;
} }

View File

@ -1,48 +0,0 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
* This code is licensed under MIT.
* Этот код распространяется по лицензии MIT.
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
namespace AtolOnline\Tests;
use PHPUnit\Framework\TestCase;
class AtolClientTest extends TestCase
{
public function testAuth()
{
}
public function testSetPassword()
{
}
public function testSetTestMode()
{
}
public function testGetToken()
{
}
public function testSetLogin()
{
}
public function testSetToken()
{
}
public function testGetResponse()
{
}
public function testIsTestMode()
{
}
}

View File

@ -9,9 +9,12 @@
declare(strict_types = 1); declare(strict_types = 1);
namespace AtolOnline\Tests; namespace AtolOnlineTests;
use AtolOnline\Entities\Entity; use AtolOnline\Entities\Entity;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Collection;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
/** /**
@ -20,15 +23,41 @@ use PHPUnit\Framework\TestCase;
class BasicTestCase extends TestCase class BasicTestCase extends TestCase
{ {
/** /**
* @todo требуется рефакторинг * Проверяет наличие подключения к ресурсу по URL
*
* @param string $url
* @param int $code
* @return bool
* @throws GuzzleException
*/ */
public function setUp(): void protected function ping(string $url, int $code): bool
{ {
//parent::setUp(); $result = (new Client(['http_errors' => false]))->request('GET', $url);
defined('ATOL_KKT_GROUP') ?: define('ATOL_KKT_GROUP', 'v4-online-atol-ru_4179'); //$this->assertEquals(200, $result->getStatusCode());
defined('ATOL_KKT_LOGIN') ?: define('ATOL_KKT_LOGIN', 'v4-online-atol-ru'); return $result->getStatusCode() === $code;
defined('ATOL_KKT_PASS') ?: define('ATOL_KKT_PASS', 'iGFFuihss'); }
defined('ATOL_CALLBACK_URL') ?: define('ATOL_CALLBACK_URL', 'http://example.com/callback');
/**
* Проверяет доступность API мониторинга
*
* @return bool
* @throws GuzzleException
*/
protected function isMonitoringOnline(): bool
{
return $this->ping('https://testonline.atol.ru/api/auth/v1/gettoken', 400);
}
/**
* Пропускает текущий тест если API мониторинга недоступно
*
* @throws GuzzleException
*/
protected function skipIfMonitoringIsOffline(): void
{
if (!$this->isMonitoringOnline()) {
$this->markTestSkipped($this->getName() . ': Monitoring API is inaccessible. Skipping test.');
}
} }
/** /**
@ -50,6 +79,79 @@ class BasicTestCase extends TestCase
} }
} }
/**
* Тестирует идентичность двух классов
*
* @param object|string $expected
* @param object|string $actual
*/
public function assertIsSameClass(object|string $expected, object|string $actual)
{
$this->assertEquals(
is_object($expected) ? $expected::class : $expected,
is_object($actual) ? $actual::class : $actual
);
}
/**
* Тестирует наследование класса (объекта) от указанных классов
*
* @param string[] $parents
* @param object|string $actual
*/
public function assertExtendsClasses(array $parents, object|string $actual)
{
$this->checkClassesIntersection($parents, $actual, 'class_parents');
}
/**
* Тестирует имплементацию классом (объектом) указанных интерфейсов
*
* @param string[] $parents
* @param object|string $actual
*/
public function assertImplementsInterfaces(array $parents, object|string $actual)
{
$this->checkClassesIntersection($parents, $actual, 'class_implements');
}
/**
* Тестирует использование классом (объектом) указанных трейтов
*
* @param string[] $parents
* @param object|string $actual
*/
public function assertUsesTraits(array $parents, object|string $actual)
{
$this->checkClassesIntersection($parents, $actual, 'class_uses');
}
/**
* Проверяет пересечение классов указанной функцией SPL
*
* @param object|string $class Класс для проверки на вхождение, или объект, класс коего нужно проверить
* @param array $classes Массив классов, вхождение в который нужно проверить
* @param string $function class_parents|class_implements|class_uses
*/
protected function checkClassesIntersection(array $classes, object|string $class, string $function): void
{
$actual_classes = is_object($class) ? $function($class) : [$class::class];
$this->assertIsArray($actual_classes);
$this->assertNotEmpty(array_intersect($classes, $actual_classes));
}
/**
* Тестирует, является ли объект коллекцией
*
* @param mixed $expected
*/
public function assertIsCollection(mixed $expected): void
{
$this->assertIsObject($expected);
$this->assertIsIterable($expected);
$this->assertIsSameClass($expected, Collection::class);
}
/** /**
* Провайдер валидных телефонов * Провайдер валидных телефонов
* *

View File

@ -7,7 +7,7 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE * https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/ */
namespace AtolOnline\Tests; namespace AtolOnlineTests;
use AtolOnline\{ use AtolOnline\{
Entities\Client, Entities\Client,
@ -16,7 +16,8 @@ use AtolOnline\{
Exceptions\TooLongEmailException, Exceptions\TooLongEmailException,
Exceptions\TooLongNameException, Exceptions\TooLongNameException,
Exceptions\TooLongPhoneException, Exceptions\TooLongPhoneException,
Helpers}; Helpers
};
/** /**
* Набор тестов для проверки работы класс покупателя * Набор тестов для проверки работы класс покупателя

View File

@ -7,7 +7,7 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE * https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/ */
namespace AtolOnline\Tests; namespace AtolOnlineTests;
use AtolOnline\{ use AtolOnline\{
Constants\SnoTypes, Constants\SnoTypes,

View File

@ -7,7 +7,7 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE * https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/ */
namespace AtolOnline\Tests; namespace AtolOnlineTests;
use AtolOnline\Helpers; use AtolOnline\Helpers;

View File

@ -7,7 +7,7 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE * https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/ */
namespace AtolOnline\Tests; namespace AtolOnlineTests;
use AtolOnline\{ use AtolOnline\{
Constants\PaymentMethods, Constants\PaymentMethods,

View File

@ -1,40 +1,163 @@
<?php <?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov) namespace AtolOnlineTests;
*
* This code is licensed under MIT. use AtolOnline\Api\AtolClient;
* Этот код распространяется по лицензии MIT. use AtolOnline\Api\KktMonitor;
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE use AtolOnline\Exceptions\EmptyLoginException;
use AtolOnline\Exceptions\EmptyPasswordException;
use AtolOnline\Exceptions\TooLongLoginException;
use AtolOnline\Exceptions\TooLongPasswordException;
use AtolOnline\Helpers;
/**
* Набор тестов для проверки работы API-клиента на примере монитора ККТ
*/ */
class KktMonitorTest extends BasicTestCase
namespace AtolOnline\Tests;
use PHPUnit\Framework\TestCase;
class KktMonitorTest extends TestCase
{ {
/**
* Тестирует успешное создание объекта монитора без аргументов конструктора
*
* @covers \AtolOnline\Api\KktMonitor::__construct
* @covers \AtolOnline\Api\KktMonitor::getLogin
* @covers \AtolOnline\Api\KktMonitor::getPassword
*/
public function testConstructorWithoutArgs()
{
$client = new KktMonitor();
$this->assertIsObject($client);
$this->assertIsSameClass(KktMonitor::class, $client);
$this->assertExtendsClasses([AtolClient::class], $client);
$this->assertNull($client->getLogin());
$this->assertNull($client->getPassword());
}
public function testSetToken() /**
* Тестирует успешное создание объекта монитора с аргументами конструктора
*
* @covers \AtolOnline\Api\KktMonitor::__construct
* @covers \AtolOnline\Api\KktMonitor::setLogin
* @covers \AtolOnline\Api\KktMonitor::setPassword
* @covers \AtolOnline\Api\KktMonitor::getLogin
* @covers \AtolOnline\Api\KktMonitor::getPassword
*/
public function testConstructorWithArgs()
{
$client = new KktMonitor(false, 'login', 'password', []);
$this->assertIsObject($client);
$this->assertIsSameClass(KktMonitor::class, $client);
$this->assertExtendsClasses([AtolClient::class], $client);
//$this->assertFalse($client->isTestMode());
//$this->assertEquals('login', $client->getLogin());
//$this->assertEquals('password', $client->getPassword());
}
/**
* Тестирует исключение при попытке передать пустой логин в конструктор
*
* @covers \AtolOnline\Api\KktMonitor::__construct
* @covers \AtolOnline\Api\KktMonitor::setLogin
*/
public function testConstructorWithShortLogin()
{
$this->expectException(EmptyLoginException::class);
new KktMonitor(login: '');
}
/**
* Тестирует исключение при попытке передать слишком длинный логин в конструктор
*
* @covers \AtolOnline\Api\KktMonitor::__construct
* @covers \AtolOnline\Api\KktMonitor::setLogin
*/
public function testConstructorWithLongLogin()
{
$this->expectException(TooLongLoginException::class);
new KktMonitor(login: Helpers::randomStr(101));
}
/**
* Тестирует исключение при попытке передать пустой пароль в конструктор
*
* @covers \AtolOnline\Api\KktMonitor::__construct
* @covers \AtolOnline\Api\KktMonitor::setPassword
*/
public function testConstructorWithShortPassword()
{
$this->expectException(EmptyPasswordException::class);
new KktMonitor(password: '');
}
/**
* Тестирует исключение при попытке передать слишком длинный пароль в конструктор
*
* @covers \AtolOnline\Api\KktMonitor::__construct
* @covers \AtolOnline\Api\KktMonitor::setPassword
*/
public function testConstructorWithLongPassword()
{
$this->expectException(TooLongPasswordException::class);
new KktMonitor(password: Helpers::randomStr(101));
}
/**
* Тестирует установку тестового режима
*
* @covers \AtolOnline\Api\KktMonitor::__construct
* @covers \AtolOnline\Api\KktMonitor::isTestMode
* @covers \AtolOnline\Api\KktMonitor::setTestMode
*/
public function testTestMode()
{
$client = new KktMonitor();
$this->assertTrue($client->isTestMode());
$client = new KktMonitor(true);
$this->assertTrue($client->isTestMode());
$client = new KktMonitor(false);
$this->assertFalse($client->isTestMode());
$client = (new KktMonitor())->setTestMode();
$this->assertTrue($client->isTestMode());
$client = (new KktMonitor())->setTestMode(true);
$this->assertTrue($client->isTestMode());
$client = (new KktMonitor())->setTestMode(false);
$this->assertFalse($client->isTestMode());
}
public function todo_testGetToken()
{ {
} }
public function testGetResponse() public function todo_testGetResponse()
{
//$this->skipIfMonitoringIsOffline();
}
public function todo_testSetPassword()
{ {
} }
public function testSetLogin() public function todo_testAuth()
{ {
} }
public function testAuth() public function todo_testGetAll()
{ {
} }
public function testGetToken() public function todo_testSetToken()
{ {
} }
public function testSetPassword() public function todo_testGetOne()
{
}
public function todo_testSetLogin()
{ {
} }
} }

View File

@ -7,11 +7,12 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE * https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/ */
namespace AtolOnline\Tests; namespace AtolOnlineTests;
use AtolOnline\{ use AtolOnline\{
Constants\VatTypes, Constants\VatTypes,
Entities\Vat}; Entities\Vat
};
/** /**
* Class VatTest * Class VatTest