Skip to content

Commit

Permalink
#111. Add BaseControllerTest, Fix GeneratorTraitTest, Change Json for…
Browse files Browse the repository at this point in the history
… tests with exit, Add @dataProvider
  • Loading branch information
arthurkushman committed Jan 20, 2019
1 parent 3bb6354 commit 3974b37
Show file tree
Hide file tree
Showing 4 changed files with 221 additions and 3 deletions.
24 changes: 22 additions & 2 deletions src/helpers/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,21 @@ public static function outputSerializedRelations(Request $request, array $data)
$arr[JSONApiInterface::CONTENT_LINKS] = [
JSONApiInterface::CONTENT_SELF => $request->getUri(),
];

$arr[JSONApiInterface::CONTENT_DATA] = $data;
echo self::encode($arr);
exit(JSONApiInterface::EXIT_STATUS_SUCCESS);

self::successExit();
}

/**
* Exits with status code 0 on production servers
*/
private static function successExit() : void
{
if (env('APP_ENV') !== 'dev') {
exit(JSONApiInterface::EXIT_STATUS_SUCCESS);
}
}

/**
Expand All @@ -145,8 +157,10 @@ public static function getResource(BaseFormRequest $formRequest, $model, string

return $collection;
}

$item = new Item($model, $transformer, strtolower($entity));
$item->setMeta($meta);

return $item;
}

Expand All @@ -163,21 +177,25 @@ public static function outputSerializedData(ResourceInterface $resource, int $re
if ($responseCode === JSONApiInterface::HTTP_RESPONSE_CODE_NO_CONTENT) {
exit;
}

if (empty($resource->getData())) { // preventing 3d party libs (League etc) from crash on empty data
echo self::encode([
ModelsInterface::PARAM_DATA => []
]);
exit;
}

$host = $_SERVER['HTTP_HOST'];
$manager = new Manager();

if (isset($_GET['include'])) {
$manager->parseIncludes($_GET['include']);
}

$manager->setSerializer(new JsonApiSerializer($host));
echo self::getSelectedData($manager->createData($resource)->toJson(), $data);
exit(JSONApiInterface::EXIT_STATUS_SUCCESS);

self::successExit();
}

/**
Expand Down Expand Up @@ -209,8 +227,10 @@ private static function getSelectedData(string $json, array $data) : string
if (current($data) === PhpInterface::ASTERISK) {// do nothing - grab all fields
return $json;
}

$jsonArr = self::decode($json);
$current = current($jsonArr[ApiInterface::RAML_DATA]);

if (empty($current[JSONApiInterface::CONTENT_ATTRIBUTES]) === false) {// this is an array of values
self::unsetArray($jsonArr, $data);
} else {// this is just one element
Expand Down
40 changes: 40 additions & 0 deletions tests/unit/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace rjapitest\unit;

use Faker\Factory;
use Illuminate\Foundation\Testing\TestCase as TestCaseLaravel;
use rjapi\ApiGenerator;
use rjapi\types\ConfigInterface;
Expand Down Expand Up @@ -63,4 +64,43 @@ public function createConfig()
fwrite($fp, $str);
fclose($fp);
}

/**
* Fake generated provider for articles
*/
public function articleProvider()
{
$faker = Factory::create();

return [
[[
[
'id' => uniqid(),
'title' => $faker->title,
'fake_attr' => 'attr',
'description' => $faker->name,
'url' => $faker->url . uniqid('', true),
'topic_id' => $faker->randomNumber(),
'rate' => $faker->randomFloat(),
'status' => 'draft',
'show_in_top' => random_int(0, 1),
'date_posted' => $faker->date(),
'time_to_live' => $faker->time(),
],
[
'id' => uniqid(),
'title' => $faker->title,
'fake_attr' => 'attr',
'description' => $faker->name,
'url' => $faker->url . uniqid('', true),
'topic_id' => $faker->randomNumber(),
'rate' => $faker->randomFloat(),
'status' => 'draft',
'show_in_top' => random_int(0, 1),
'date_posted' => $faker->date(),
'time_to_live' => $faker->time(),
],
]],
];
}
}
8 changes: 7 additions & 1 deletion tests/unit/controllers/GeneratorTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use rjapi\controllers\GeneratorTrait;
use rjapi\types\ConsoleInterface;
use rjapi\types\DirsInterface;
use rjapi\types\PhpInterface;
use rjapitest\unit\TestCase;

class GeneratorTraitTest extends TestCase
Expand Down Expand Up @@ -36,6 +37,11 @@ public function setUp()
];
}

public function formatGenPathByDir(): string
{
return DirsInterface::GEN_DIR . PhpInterface::SLASH . $this->genDir . PhpInterface::SLASH;
}

/**
* @test
*/
Expand All @@ -50,7 +56,7 @@ public function it_sets_merge_types()
];
$this->setMergedTypes();
$this->assertNotEmpty($this->types);
$this->options = [ // merge last option
$this->options = [ // merge time option
ConsoleInterface::OPTION_MERGE => date('Y-m-d H:i:s', time() - 3600),
];
$this->setMergedTypes();
Expand Down
152 changes: 152 additions & 0 deletions tests/unit/extension/BaseControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<?php

namespace rjapitest\unit\extensions;


use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Modules\V2\Entities\Article;
use Modules\V2\Http\Controllers\ArticleController;
use ReflectionException;
use rjapi\exceptions\AttributesException;
use rjapi\extension\BaseController;
use rjapitest\_data\ArticleFixture;
use rjapitest\unit\TestCase;

/**
* This method is used not only here, but in constructor of BaseController
* to retrieve headers etc
*
* @param array $json
* @return Request
*/
function request(array $json = [])
{
$req = new Request();
$req->headers->set('Content-TYpe', 'application/json;ext=bulk');
$req->initialize([], [], [], [], [], [], json_encode($json));

return $req;
}

/**
* Class BaseControllerTest
* @package rjapitest\unit\extensions
*
* @property BaseController baseController
*/
class BaseControllerTest extends TestCase
{
private $baseController;

public function setUp()
{
parent::setUp(); // TODO: Change the autogenerated stub

$_SERVER['HTTP_HOST'] = 'localhost';

$router = new Route(['POST', 'GET'], '', function () {
});
$this->baseController = new ArticleController($router);
}

/**
* @test
* @dataProvider articleProvider
* @runInSeparateProcess
* @preserveGlobalState disabled
* @param $data
*/
public function it_creates_bulk($data)
{
try {
$this->baseController->createBulk(\rjapitest\unit\extensions\request($data));
} catch (AttributesException $e) {
echo $e->getTraceAsString();
}

$this->assertInstanceOf(BaseController::class, $this->baseController);
}

/**
* @test
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function it_updates_bulk()
{
/** @var Article $firstItem */
$firstItem = ArticleFixture::createAndGet();
$secondItem = ArticleFixture::createAndGet();

$data = [
'data' => [
[
'type' => 'article',
'id' => $firstItem->id,
'title' => $firstItem->title,
'description' => $firstItem->description,
'fake_attr' => 'attr',
'url' => $firstItem->url,
'show_in_top' => $firstItem->show_in_top,
'topic_id' => $firstItem->topic_id,
'rate' => $firstItem->rate,
'date_posted' => $firstItem->date_posted,
'time_to_live' => $firstItem->time_to_live,
],
[
'type' => 'article',
'id' => $secondItem->id,
'title' => $secondItem->title,
'description' => $secondItem->description,
'fake_attr' => 'attr',
'url' => $secondItem->url,
'show_in_top' => $secondItem->show_in_top,
'topic_id' => $secondItem->topic_id,
'rate' => $secondItem->rate,
'date_posted' => $secondItem->date_posted,
'time_to_live' => $secondItem->time_to_live,
],
],
];

try {
$this->baseController->updateBulk(\rjapitest\unit\extensions\request($data));
} catch (AttributesException $e) {
echo $e->getTraceAsString();
}

$this->assertInstanceOf(BaseController::class, $this->baseController);
}

/**
* @test
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function it_deletes_bulk()
{
$router = new Route(['DELETE'], '', function () {
});
$this->baseController = new ArticleController($router);

$firstItem = ArticleFixture::createAndGet();
$secondItem = ArticleFixture::createAndGet();

$data = [
'data' => [
[
'type' => 'article',
'id' => $firstItem->id,
],
[
'type' => 'article',
'id' => $secondItem->id,
],
],
];

$this->baseController->deleteBulk(\rjapitest\unit\extensions\request($data));
$this->assertInstanceOf(BaseController::class, $this->baseController);
}
}

0 comments on commit 3974b37

Please sign in to comment.