Skip to content

Commit

Permalink
Increase UT coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
kitloong committed Nov 10, 2022
1 parent b092331 commit eb3151a
Show file tree
Hide file tree
Showing 19 changed files with 198 additions and 45 deletions.
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
/tests export-ignore
/.editorconfig export-ignore
/.php_cs.dist export-ignore
/_ide_helper.php export-ignore
/psalm.xml export-ignore
/psalm.xml.dist export-ignore
/testbench.yaml export-ignore
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ vendor
node_modules
.php-cs-fixer.cache
.DS_Store
_ide_helper.php
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@
"php": "^7.4|^8.0",
"illuminate/contracts": "^8.37|^9.0",
"kitloong/laravel-app-logger": "^1.0",
"spatie/laravel-package-tools": "^1.4.3"
"spatie/laravel-package-tools": "^1.4.3",
"ext-json": "*"
},
"require-dev": {
"barryvdh/laravel-ide-helper": "^2.12",
"brianium/paratest": "^6.2",
"friendsofphp/php-cs-fixer": "^3.5",
"nunomaduro/collision": "^5.3|^6.0",
Expand All @@ -43,6 +45,7 @@
},
"scripts": {
"psalm": "vendor/bin/psalm",
"phpcs": "vendor/bin/phpcs",
"test": "./vendor/bin/testbench package:test --parallel --no-coverage",
"test-coverage": "vendor/bin/phpunit --coverage-html coverage"
},
Expand Down
3 changes: 3 additions & 0 deletions phpcs.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<?xml version="1.0"?>
<ruleset name="PSR2">
<description>Standard Based on PSR2</description>
<file>src</file>
<file>tests</file>

<exclude-pattern type="relative-root">tests/*</exclude-pattern>
<rule ref="PSR2"/>
<rule ref="Generic.Files.LineLength">
Expand Down
21 changes: 7 additions & 14 deletions src/LaravelRequestDocs.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

class LaravelRequestDocs
{
public function getDocs()
public function getDocs(): array
{
$docs = [];
$excludePatterns = config('request-docs.hide_matching') ?? [];
Expand Down Expand Up @@ -68,20 +68,22 @@ public function getControllersInfo(): array
$routes = collect(Route::getRoutes());
$onlyRouteStartWith = config('request-docs.only_route_uri_start_with') ?? '';

/** @var \Illuminate\Routing\Route $route */
foreach ($routes as $route) {
if ($onlyRouteStartWith && !Str::startsWith($route->uri, $onlyRouteStartWith)) {
continue;
}

try {
$actionControllerName = $route->action['controller'] ?? $route->action["0"];
/// Show Pnly Controller Name
/// Show Only Controller Name
$controllerFullPath = explode('@', $actionControllerName)[0];
$getStartWord = strrpos(explode('@', $actionControllerName)[0], '\\') + 1;
$controllerName = substr($controllerFullPath, $getStartWord);

$method = explode('@', $actionControllerName)[1] ?? '__invoke';
$httpMethod = $route->methods[0];

foreach ($controllersInfo as $controllerInfo) {
if ($controllerInfo['uri'] == $route->uri && $controllerInfo['httpMethod'] == $httpMethod) {
// is duplicate
Expand Down Expand Up @@ -113,16 +115,17 @@ public function getControllersInfo(): array
return $controllersInfo;
}

public function appendRequestRules(array $controllersInfo)
public function appendRequestRules(array $controllersInfo): array
{
foreach ($controllersInfo as $index => $controllerInfo) {
$controller = $controllerInfo['controller_full_path'];
$method = $controllerInfo['method'];
try {
$reflectionMethod = new ReflectionMethod($controller, $method);
} catch (Throwable $e) {
// Skip to next if controller is not exists.
if (config('request-docs.debug')) {
throw $e;
throw $e; // @codeCoverageIgnore
}
continue;
}
Expand Down Expand Up @@ -187,16 +190,6 @@ public function lrdDocComment($docComment): string
return $lrdComment;
}

// get text between first and last tag
private function getTextBetweenTags($docComment, $tag1, $tag2)
{
$docComment = trim($docComment);
$start = strpos($docComment, $tag1);
$end = strpos($docComment, $tag2);
$text = substr($docComment, $start + strlen($tag1), $end - $start - strlen($tag1));
return $text;
}

public function flattenRules($mixedRules)
{
$rules = [];
Expand Down
1 change: 1 addition & 0 deletions src/LaravelRequestDocsFacade.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Support\Facades\Facade;

/**
* @codeCoverageIgnore
* @see \Rakutentech\LaravelRequestDocs\LaravelRequestDocs
*/
class LaravelRequestDocsFacade extends Facade
Expand Down
5 changes: 5 additions & 0 deletions src/LaravelRequestDocsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ public function configurePackage(Package $package): void
->hasViews()
->hasAssets()
->hasCommand(LaravelRequestDocsCommand::class);
}

public function packageBooted()
{
parent::packageBooted();

Route::get(config('request-docs.url'), [\Rakutentech\LaravelRequestDocs\Controllers\LaravelRequestDocsController::class, 'index'])
->name('request-docs.index')
Expand Down
12 changes: 0 additions & 12 deletions tests/ExampleTest.php

This file was deleted.

42 changes: 42 additions & 0 deletions tests/Feature/Commands/LaravelRequestDocsCommandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace Rakutentech\LaravelRequestDocs\Tests\Feature\Commands;

use Illuminate\Support\Facades\File;
use Rakutentech\LaravelRequestDocs\Tests\TestCase;

class LaravelRequestDocsCommandTest extends TestCase
{
protected function tearDown(): void
{
File::deleteDirectory(config('request-docs.docs_path'));
File::deleteDirectory(base_path('docs/request-docs/'));

parent::tearDown();
}

public function testHandle()
{
$this->assertFalse(File::exists(config('request-docs.docs_path') . '/index.html'));
$this->assertFalse(File::exists(config('request-docs.docs_path') . '/lrd-openapi.json'));

$this->artisan('lrd:generate')
->assertExitCode(0);

$this->assertTrue(File::exists(config('request-docs.docs_path') . '/index.html'));
$this->assertTrue(File::exists(config('request-docs.docs_path') . '/lrd-openapi.json'));

config('request-docs.docs_path');
}

public function testWillCreateDirectory()
{
File::deleteDirectory(config('request-docs.docs_path'));
$this->assertFalse(File::exists(config('request-docs.docs_path')));

$this->artisan('lrd:generate')
->assertExitCode(0);

$this->assertTrue(File::exists(config('request-docs.docs_path')));
}
}
29 changes: 29 additions & 0 deletions tests/Feature/Controllers/LaravelRequestDocsControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Rakutentech\LaravelRequestDocs\Tests\Feature\Controllers;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Config;
use Rakutentech\LaravelRequestDocs\Tests\TestCase;

class LaravelRequestDocsControllerTest extends TestCase
{
public function testIndex()
{
$this->get(config('request-docs.url'))
->assertStatus(Response::HTTP_OK);
}

public function testSortDocsByDefault()
{
Config::set('request-docs.sort_by', 'default');
$this->get(config('request-docs.url'))
->assertStatus(Response::HTTP_OK);
}

public function testOpenAPI()
{
$this->get(config('request-docs.url') . '?openapi=true')
->assertStatus(Response::HTTP_OK);
}
}
6 changes: 2 additions & 4 deletions tests/LRDOpenApiTest.php
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
<?php

namespace Rakutentech\LaravelRequestDocs\Tests;
use Route;

class LRDOpenApiTest extends TestCase
{
public function testDocsCount()
{
$docs = $this->lrd->getDocs();
$openApi = $this->lrdToOpenApi->openApi($docs)->toArray();
$routes = collect(Route::getRoutes());

$this->assertSame($routes->count(), count($docs));
$this->assertSame($this->countRoutesWithLRDDoc(), count($docs));

$countRoutes = 0;
foreach ($openApi["paths"] as $path) {
$countRoutes += count(array_keys($path));
}

$this->assertSame($routes->count(), $countRoutes);
$this->assertSame($this->countRoutesWithLRDDoc(), $countRoutes);
}
}
33 changes: 20 additions & 13 deletions tests/LRDTest.php
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
<?php

namespace Rakutentech\LaravelRequestDocs\Tests;
use Route;

use Illuminate\Support\Facades\Config;

class LRDTest extends TestCase
{
public function testDocsCount()
public function testGetDocs()
{
$docs = $this->lrd->getDocs();
$routes = collect(Route::getRoutes());

$this->assertSame($routes->count(), count($docs));
$this->assertSame($this->countRoutesWithLRDDoc(), count($docs));

$docSize = 9;
$firstDoc = $docs[0];
$this->assertCount($docSize, $firstDoc);
$this->assertArrayHasKey('uri', $firstDoc);
$this->assertArrayHasKey('methods', $firstDoc);
$this->assertArrayHasKey('middlewares', $firstDoc);
$this->assertArrayHasKey('controller', $firstDoc);
$this->assertArrayHasKey('controller_full_path', $firstDoc);
$this->assertArrayHasKey('method', $firstDoc);
$this->assertArrayHasKey('httpMethod', $firstDoc);
$this->assertArrayHasKey('rules', $firstDoc);
$this->assertArrayHasKey('docBlock', $firstDoc);
}

public function testDocsCanFetchAllMethods()
Expand All @@ -25,18 +38,12 @@ public function testDocsCanFetchAllMethods()
$this->assertSame(['DELETE', 'GET', 'HEAD', 'POST', 'PUT'], $methods);
}

public function testDocsCanFetchInfo()
public function testOnlyRouteURIStartWith()
{
Config::set('request-docs.only_route_uri_start_with', 'welcome');
$docs = $this->lrd->getDocs();
foreach ($docs as $doc) {
$this->assertNotEmpty($doc['rules']);
$this->assertNotEmpty($doc['methods']);
// $this->assertNotEmpty($doc['middlewares']); //todo: add middlewares to test
$this->assertNotEmpty($doc['controller']);
$this->assertNotEmpty($doc['controller_full_path']);
$this->assertNotEmpty($doc['method']);
$this->assertNotEmpty($doc['httpMethod']);
$this->assertNotEmpty($doc['rules']);
$this->assertStringStartsWith('welcome', $doc['uri']);
}
}
}
11 changes: 10 additions & 1 deletion tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,17 @@ public function getEnvironmentSetUp($app)
public function registerRoutes() {
Route::get('/', [TestControllers\WelcomeController::class, 'index']);
Route::get('welcome', [TestControllers\WelcomeController::class, 'index']);
Route::post('welcome', [TestControllers\WelcomeController::class, 'store']);
Route::post('welcome', [TestControllers\WelcomeController::class, 'store'])->middleware('auth:api');
Route::put('welcome', [TestControllers\WelcomeController::class, 'edit']);
Route::delete('welcome', [TestControllers\WelcomeController::class, 'destroy']);
Route::get('single', TestControllers\SingleActionController::class);

// Expected to be skipped
Route::get('telescope', [TestControllers\TelescopeController::class, 'index']);
}

protected function countRoutesWithLRDDoc(): int
{
return count(Route::getRoutes()) - 2; // Exclude `telescope`, `request-docs`
}
}
16 changes: 16 additions & 0 deletions tests/TestControllers/SingleActionController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Rakutentech\LaravelRequestDocs\Tests\TestControllers;

/**
* Single action controller with a single `__invoke` method
*
* @see https://laravel.com/docs/controllers#single-action-controllers
*/
class SingleActionController
{
public function __invoke()
{
return 1;
}
}
16 changes: 16 additions & 0 deletions tests/TestControllers/TelescopeController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Rakutentech\LaravelRequestDocs\Tests\TestControllers;

class TelescopeController
{
/**
* For `config('request-docs.hide_matching')` test.
*
* @return int
*/
public function index()
{
return 1;
}
}
12 changes: 12 additions & 0 deletions tests/TestControllers/WelcomeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,23 @@

class WelcomeController
{
/**
* @lrd:start
* #Hello markdown
* ## Documentation for /my route
* @lrd:end
*/
public function index(WelcomeIndexRequest $request)
{
return 1;
}

/**
* @QAparam search_string string
* @QAparam search_array array
* @QAparam search_integer integer
* @QAparam search_boolean boolean
*/
public function edit(WelcomeEditRequest $request)
{
return 1;
Expand Down
5 changes: 5 additions & 0 deletions tests/TestRequests/WelcomeIndexRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Rakutentech\LaravelRequestDocs\Tests\TestRequests;

use Illuminate\Foundation\Http\FormRequest;
use Rakutentech\LaravelRequestDocs\Tests\TestRules\Uppercase;

class WelcomeIndexRequest extends FormRequest
{
Expand All @@ -28,6 +29,10 @@ protected function prepareForValidation()
public function rules()
{
return [
'name' => ['nullable', 'string', 'min:5', 'max:255'],
'title' => new Uppercase(),
'file' => 'file',
'image' => 'image',
'page' => 'nullable|integer|min:1',
'per_page' => 'nullable|integer|min:1|max:100',
];
Expand Down
Loading

0 comments on commit eb3151a

Please sign in to comment.