ldc-crm/tests/Feature/ApiV2/ApiBase.php
2021-08-02 11:46:08 +02:00

90 lines
2.6 KiB
PHP

<?php
namespace Tests\Feature\ApiV2;
use App\Enums\ApiStatus;
use App\Models\Customer;
use App\Models\Service;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Testing\AssertableJsonString;
use Illuminate\Testing\TestResponse;
use Tests\CreatesApplication;
class ApiBase extends BaseTestCase
{
use CreatesApplication;
use DatabaseTransactions;
protected function assertApiResponseStatusIs(AssertableJsonString $json, ApiStatus $status)
{
$json->assertFragment(['status' => $status->value]);
}
/**
* Raw Function to call api
*
* @param string $method
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Testing\TestResponse
*/
protected function callApi(string $method, string $uri, array $data = [], array $headers = []): TestResponse
{
$time = \time();
$headers['X-API-TIMESTAMP'] = $time;
$data['timestamp'] = $time;
return $this->json($method, $uri, $data, $headers);
}
/**
* Raw Function to call api with Token
*
* @param Customer $customer
* @param Service $service
* @param string $method
* @param string $uri
* @param array $data
* @param array $headers
* @return \Illuminate\Testing\TestResponse
*/
protected function callApiWithToken(
Service $service,
string $method,
string $uri,
array $data = [],
array $headers = []
): TestResponse {
$apiToken = $service->api_token;
if (!$apiToken) {
$apiToken = $service->generateApiToken();
$service->saveOrFail();
}
$data['api_token'] = $apiToken;
return $this->callApi($method, $uri, $data, $headers);
}
/**
* @return array
*/
protected function getCustomer()
{
/** @var \App\Models\Costumer $customer */
$customer = Customer::whereHas('logins', function ($q) {
$q->where('status', true);
})->inRandomOrder()->firstOrFail();
/** @var \App\Models\Brand $brand */
$brand = $customer->logins()->where('status', true)->firstOrFail()->brand;
/** @var \App\Models\Service $service */
$service = $brand->services()->firstOrFail();
// regen bearer token to get the pwd in clear
$service->generateBearerToken();
$bearer_pwd = $service->bearer_pwd;
$service->saveOrFail();
$service->bearer_pwd = $bearer_pwd;
return compact('customer', 'service', 'brand');
}
}