phpvms/tests/TestCase.php

322 lines
8.1 KiB
PHP
Raw Permalink Normal View History

2017-06-09 02:28:26 +08:00
<?php
use App\Repositories\SettingRepository;
use App\Services\DatabaseService;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Notification;
use Tests\CreatesApplication;
use Tests\TestData;
2017-06-20 00:30:39 +08:00
class TestCase extends Illuminate\Foundation\Testing\TestCase
2017-06-09 02:28:26 +08:00
{
use TestData;
use CreatesApplication;
2017-06-09 02:28:26 +08:00
/**
* The base URL to use while testing the application.
*
* @var string
*/
public static $prefix = '/api';
2017-06-10 03:47:02 +08:00
protected $app;
2017-06-09 02:28:26 +08:00
protected $baseUrl = 'http://localhost';
2019-05-12 23:50:38 +08:00
protected $connectionsToTransact = ['test'];
2017-06-09 02:28:26 +08:00
protected $user;
protected static $auth_headers = [
2018-08-27 00:40:04 +08:00
'x-api-key' => 'testadminapikey',
];
/**
* @throws Exception
*/
public function setUp(): void
{
parent::setUp();
// Don't throttle requests when running the tests
$this->withoutMiddleware(
ThrottleRequests::class
);
Notification::fake();
Artisan::call('database:create', ['--reset' => true]);
Artisan::call('migrate:refresh', ['--env' => 'testing']);
}
public function tearDown(): void
2019-05-12 23:50:38 +08:00
{
parent::tearDown();
}
/**
* @param $user
* @param array $headers
2018-08-27 00:40:04 +08:00
*
* @return array
*/
2018-08-27 00:40:04 +08:00
public function headers($user = null, array $headers = []): array
{
2018-08-27 00:40:04 +08:00
if ($user !== null) {
$headers['x-api-key'] = $user->api_key;
2018-08-27 02:50:08 +08:00
return $headers;
}
if ($this->user !== null) {
$headers['x-api-key'] = $this->user->api_key;
}
return $headers;
}
/**
* Import data from a YML file
2018-08-27 00:40:04 +08:00
*
* @param $file
2017-06-09 02:28:26 +08:00
*/
2017-06-20 00:30:39 +08:00
public function addData($file)
{
$svc = app(DatabaseService::class);
2018-08-27 00:40:04 +08:00
$file_path = base_path('tests/data/'.$file.'.yml');
2018-01-05 09:33:23 +08:00
try {
$svc->seed_from_yaml_file($file_path);
} catch (Exception $e) {
}
}
/**
* Make sure an object has the list of keys
2018-08-27 00:40:04 +08:00
*
2018-01-05 09:33:23 +08:00
* @param $obj
* @param array $keys
*/
2018-08-27 02:50:08 +08:00
public function assertHasKeys($obj, array $keys = []): void
2018-01-05 09:33:23 +08:00
{
2018-08-27 00:40:04 +08:00
foreach ($keys as $key) {
2018-01-05 09:33:23 +08:00
$this->assertArrayHasKey($key, $obj);
}
2017-06-20 00:30:39 +08:00
}
/**
* Read a file from the data directory
*
* @param $filename
*
* @return false|string
*/
public function readDataFile($filename)
{
$paths = [
'data/'.$filename,
'tests/data/'.$filename,
];
foreach ($paths as $p) {
if (file_exists($p)) {
return file_get_contents($p);
}
}
return false;
}
/**
* Return a mock Guzzle Client with a response loaded from $mockFile
*
* @param array|string $files
*/
public function mockGuzzleClient($files): void
{
if (!is_array($files)) {
$files = [$files];
}
$responses = [];
foreach ($files as $file) {
$responses[] = new Response(200, [
'Content-Type' => 'application/json; charset=utf-8',
], $this->readDataFile($file));
}
$mock = new MockHandler($responses);
$handler = HandlerStack::create($mock);
$guzzleClient = new Client(['handler' => $handler]);
app()->instance(Client::class, $guzzleClient);
}
/**
* @param array|string $files The filename or files to respond with
*/
public function mockXmlResponse($files)
{
if (!is_array($files)) {
$files = [$files];
}
$responses = [];
foreach ($files as $file) {
$responses[] = new Response(200, [
'Content-Type' => 'text/xml',
], $this->readDataFile($file));
}
$mock = new MockHandler($responses);
$handler = HandlerStack::create($mock);
$guzzleClient = new Client(['handler' => $handler]);
app()->instance(Client::class, $guzzleClient);
}
/**
* Update a setting
*
* @param $key
* @param $value
*/
public function updateSetting($key, $value)
{
$settingsRepo = app(SettingRepository::class);
$settingsRepo->store($key, $value);
}
/**
* So we can test private/protected methods
* http://bit.ly/1mr5hMq
2018-08-27 00:40:04 +08:00
*
* @param $object
* @param $methodName
* @param array $parameters
2018-08-27 00:40:04 +08:00
*
* @throws ReflectionException
2018-08-27 00:40:04 +08:00
*
* @return mixed
*/
public function invokeMethod(&$object, $methodName, array $parameters = [])
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
/**
* Transform any data that's passed in. E.g, make sure that any mutator
* classes (e.g, units) are not passed in as the mutator class
2018-08-27 00:40:04 +08:00
*
* @param array $data
2018-08-27 00:40:04 +08:00
*
* @return array
*/
2018-05-04 05:13:25 +08:00
protected function transformData(&$data)
{
2018-08-27 00:40:04 +08:00
foreach ($data as $key => &$value) {
if (is_array($value)) {
2018-05-04 05:13:25 +08:00
$this->transformData($value);
2018-05-04 04:36:26 +08:00
}
if (is_subclass_of($value, App\Contracts\Unit::class)) {
$data[$key] = $value->__toString();
}
2018-08-27 00:40:04 +08:00
if ($value instanceof DateTimeImmutable) {
$data[$key] = $value->format(DATE_ATOM);
} elseif ($value instanceof Carbon) {
$data[$key] = $value->toIso8601ZuluString();
}
}
return $data;
}
/**
* Override the GET call to inject the user API key
2018-08-27 00:40:04 +08:00
*
* @param string $uri
2018-08-27 00:40:04 +08:00
* @param array $headers
* @param null $user
*
* @return \Illuminate\Foundation\Testing\TestResponse
*/
2018-08-27 00:40:04 +08:00
public function get($uri, array $headers = [], $user = null): \Illuminate\Foundation\Testing\TestResponse
{
$req = parent::get($uri, $this->headers($user, $headers));
2018-08-27 00:40:04 +08:00
if ($req->isClientError() || $req->isServerError()) {
Log::error('GET Error: '.$uri, $req->json());
}
return $req;
}
/**
* Override the POST calls to inject the user API key
2018-08-27 00:40:04 +08:00
*
* @param string $uri
2018-08-27 00:40:04 +08:00
* @param array $data
* @param array $headers
* @param null $user
*
* @return \Illuminate\Foundation\Testing\TestResponse
*/
2018-08-27 00:40:04 +08:00
public function post($uri, array $data = [], array $headers = [], $user = null)
{
$data = $this->transformData($data);
$req = parent::post($uri, $data, $this->headers($user, $headers));
if ($req->isClientError() || $req->isServerError()) {
2018-08-27 00:40:04 +08:00
Log::error('POST Error: '.$uri, $req->json());
}
return $req;
}
/**
* Override the PUT calls to inject the user API key
2018-08-27 00:40:04 +08:00
*
* @param string $uri
2018-08-27 00:40:04 +08:00
* @param array $data
* @param array $headers
* @param null $user
*
* @return \Illuminate\Foundation\Testing\TestResponse
*/
public function put($uri, array $data = [], array $headers = [], $user = null)
{
$req = parent::put($uri, $this->transformData($data), $this->headers($user, $headers));
if ($req->isClientError() || $req->isServerError()) {
2018-08-27 00:40:04 +08:00
Log::error('PUT Error: '.$uri, $req->json());
}
return $req;
}
/**
* Override the DELETE calls to inject the user API key
2018-08-27 00:40:04 +08:00
*
* @param string $uri
2018-08-27 00:40:04 +08:00
* @param array $data
* @param array $headers
* @param null $user
*
* @return \Illuminate\Foundation\Testing\TestResponse
*/
2018-08-27 00:40:04 +08:00
public function delete($uri, array $data = [], array $headers = [], $user = null)
{
$req = parent::delete($uri, $this->transformData($data), $this->headers($user, $headers));
if ($req->isClientError() || $req->isServerError()) {
2018-08-27 00:40:04 +08:00
Log::error('DELETE Error: '.$uri, $req->json());
}
return $req;
}
2017-06-09 02:28:26 +08:00
}