ldc-crm/tests/Feature/ApiV2/ApiBase.php

101 lines
3.1 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;
$apiToken = $service->generateApiToken();
$service->saveOrFail();
$data['api_token'] = $apiToken;
return $this->callApi($method, $uri, $data, $headers);
}
/**
* Get Customer models with given status (active or not)
*
* @param boolean $status the customer status for a brand
* @return array
*/
protected function getCustomer(bool $status = true, bool $random = true): array
{
/** @var \App\Models\Costumer $customer */
$customer = Customer::whereHas('logins', function ($q) use ($status) {
$q->where('status', $status);
});
if ($random) {
$customer = $customer->inRandomOrder();
}
$customer = $customer->firstOrFail();
/** @var \App\Models\Login $login */
$login = $customer->logins()->where('status', $status)->firstOrFail();
/** @var \App\Models\Brand $brand */
$brand = $login->brand;
/** @var \App\Models\Service $service */
$service = $brand->services()->firstOrFail();
// regen bearer token to get the pwd in clear
$bearer_token = $service->generateBearerToken();
$bearer_pwd = $service->bearer_pwd;
$service->saveOrFail();
$service->bearer_token = $bearer_token;
$service->bearer_pwd = $bearer_pwd;
// get customer info
$info = $customer->info($brand, Customer::FIRST_OR_FAIL);
return compact('customer', 'service', 'login', 'brand', 'info');
}
}