Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change: adding test for panel_prefix config #28

Merged
merged 2 commits into from
Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .phpunit.cache/test-results
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"version":"pest_2.34.1","defects":[],"times":{"P\\Tests\\ApiServiceTest::__pest_evaluable_it_throws_when_sorting_by_a_field_that_is_not_allowed":0.194,"P\\Tests\\ApiServiceTest::__pest_evaluable_it_can_return_a_list_of_products_with_allowed_attributes":0.101,"P\\Tests\\ApiServiceTest::__pest_evaluable_it_can_make_routes_for_a_product_resource":0.007,"P\\Tests\\ApiServiceTest::__pest_evaluable_it_throws_when_filtering_by_a_field_that_is_not_allowed":0.125,"P\\Tests\\ApiServiceTest::__pest_evaluable_it_can_return_a_list_of_products_with_selected_fields":0.086,"P\\Tests\\ApiServiceTest::__pest_evaluable_it_can_return_a_list_of_products_with_a_custom_transformer":0.083,"P\\Tests\\ApiServiceTest::__pest_evaluable_it_can_return_a_list_of_products_with_selected_sorts":0.084,"P\\Tests\\ApiServiceTest::__pest_evaluable_it_can_return_a_list_of_products_with_selected_filters":0.085,"P\\Tests\\ApiServiceTest::__pest_evaluable_it_throws_when_selecting_a_field_that_is_not_allowed":0.124,"P\\Tests\\WithoutPanelPrefix\\ApiServiceWithoutPanelPrefixTest::__pest_evaluable_it_can_make_routes_without_panel_prefix":0.007,"P\\Tests\\ArchTest::__pest_evaluable_it_will_not_use_debugging_functions":0.143,"P\\Tests\\WithPanelPrefix\\ApiServiceTest::__pest_evaluable_it_can_make_routes_for_a_product_resource":0.005,"P\\Tests\\WithPanelPrefix\\ApiServiceTest::__pest_evaluable_it_throws_when_selecting_a_field_that_is_not_allowed":0.124,"P\\Tests\\WithPanelPrefix\\ApiServiceTest::__pest_evaluable_it_throws_when_filtering_by_a_field_that_is_not_allowed":0.124,"P\\Tests\\WithPanelPrefix\\ApiServiceTest::__pest_evaluable_it_throws_when_sorting_by_a_field_that_is_not_allowed":0.125,"P\\Tests\\WithPanelPrefix\\ApiServiceTest::__pest_evaluable_it_can_return_a_list_of_products_with_allowed_attributes":0.084,"P\\Tests\\WithPanelPrefix\\ApiServiceTest::__pest_evaluable_it_can_return_a_list_of_products_with_a_custom_transformer":0.083,"P\\Tests\\WithPanelPrefix\\ApiServiceTest::__pest_evaluable_it_can_return_a_list_of_products_with_selected_filters":0.085,"P\\Tests\\WithPanelPrefix\\ApiServiceTest::__pest_evaluable_it_can_return_a_list_of_products_with_selected_fields":0.084,"P\\Tests\\WithPanelPrefix\\ApiServiceTest::__pest_evaluable_it_can_return_a_list_of_products_with_selected_sorts":0.083,"P\\Tests\\WithoutPanelPrefix\\ApiServiceWithoutPanelPrefixTest::__pest_evaluable_it_can_return_a_list_of_products_with_selected_fields":0.147,"P\\Tests\\WithoutPanelPrefix\\ApiServiceWithoutPanelPrefixTest::__pest_evaluable_it_can_return_a_list_of_products_with_a_custom_transformer":0.084,"P\\Tests\\WithoutPanelPrefix\\ApiServiceWithoutPanelPrefixTest::__pest_evaluable_it_can_return_a_list_of_products_with_selected_filters":0.082,"P\\Tests\\WithoutPanelPrefix\\ApiServiceWithoutPanelPrefixTest::__pest_evaluable_it_throws_when_selecting_a_field_that_is_not_allowed":0.138,"P\\Tests\\WithoutPanelPrefix\\ApiServiceWithoutPanelPrefixTest::__pest_evaluable_it_can_return_a_list_of_products_with_allowed_attributes":0.088,"P\\Tests\\WithoutPanelPrefix\\ApiServiceWithoutPanelPrefixTest::__pest_evaluable_it_can_make_routes_for_a_product_resource":0.006,"P\\Tests\\WithoutPanelPrefix\\ApiServiceWithoutPanelPrefixTest::__pest_evaluable_it_throws_when_sorting_by_a_field_that_is_not_allowed":0.125,"P\\Tests\\WithoutPanelPrefix\\ApiServiceWithoutPanelPrefixTest::__pest_evaluable_it_can_return_a_list_of_products_with_selected_sorts":0.084,"P\\Tests\\WithoutPanelPrefix\\ApiServiceWithoutPanelPrefixTest::__pest_evaluable_it_throws_when_filtering_by_a_field_that_is_not_allowed":0.126}}
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ return [
],
],
'route' => [
'wrap_with_panel_id' => true,
'panel_prefix' => true,
],
];
```
Expand All @@ -57,7 +57,7 @@ return [
php artisan make:filament-api-service BlogResource
```

From version 3.0, routes automatically registered. it will grouped as '/api/`admin`'. `admin` is panelId.
Since version 3.0, routes automatically registered. it will grouped as '/api/`admin`'. `admin` is panelId. to disable panelId prefix, please set `route.panel_prefix` to `false`

So, You don't need to register the routes manually.

Expand Down Expand Up @@ -193,7 +193,7 @@ You can edit prefix & group route name as you want, default this plugin use mode

## How to secure it?

From version 3.0, it will automatically detect routes and secure it using sanctum.
Since version 3.0, it will automatically detect routes and secure it using sanctum.

To Generate Token, you just need create it from admin panel. It will be Token Resource there.

Expand Down
2 changes: 1 addition & 1 deletion config/api-service.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@
],
],
'route' => [
'wrap_with_panel_id' => true,
'panel_prefix' => true,
],
];
19 changes: 8 additions & 11 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use Filament\Facades\Filament;
use Illuminate\Support\Facades\Route;
use Rupadana\ApiService\ApiService;

Route::prefix('api')
->name('api.')
Expand All @@ -10,17 +11,13 @@

foreach ($panels as $key => $panel) {
try {
if (config('api-service.route.wrap_with_panel_id', true)) {
Route::prefix($panel->getId())
->name($panel->getId() . '.')
->group(function () use ($panel) {
$panel->getPlugin('api-service')
->route($panel);
});
} else {
$panel->getPlugin('api-service')
->route($panel);
}
$panelPrefix = ApiService::isRoutePrefixedByPanel() ? $panel->getId() : '';
Route::name($panelPrefix)
->prefix($panelPrefix)
->group(function () use ($panel) {
$panel->getPlugin('api-service')
->route($panel);
});
} catch (Exception $e) {
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/ApiService.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,9 @@ public static function handlers(): array
{
return [];
}

public static function isRoutePrefixedByPanel(): bool
{
return config('api-service.route.panel_prefix', true);
}
}
6 changes: 4 additions & 2 deletions tests/Pest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use Rupadana\ApiService\Tests\TestCase;
use Rupadana\ApiService\Tests\WithoutPanelPrefix\TestCase as WithoutPanelPrefixTestCase;
use Rupadana\ApiService\Tests\WithPanelPrefix\TestCase as WithPanelPrefixTestCase;

uses(TestCase::class)->in(__DIR__);
uses(WithPanelPrefixTestCase::class)->in(__DIR__ . '/WithPanelPrefix');
uses(WithoutPanelPrefixTestCase::class)->in(__DIR__ . '/WithoutPanelPrefix');
File renamed without changes.
17 changes: 2 additions & 15 deletions tests/TestCase.php → tests/WithPanelPrefix/TestCase.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace Rupadana\ApiService\Tests;
namespace Rupadana\ApiService\Tests\WithPanelPrefix;

use BladeUI\Heroicons\BladeHeroiconsServiceProvider;
use BladeUI\Icons\BladeIconsServiceProvider;
Expand All @@ -18,7 +18,6 @@
use Livewire\LivewireServiceProvider;
use Orchestra\Testbench\TestCase as Orchestra;
use Rupadana\ApiService\ApiServiceServiceProvider;
use Rupadana\ApiService\Tests\Fixtures\ProductApiService\ProductApiService;
use Rupadana\ApiService\Tests\Fixtures\Providers\AdminPanelProvider;
use RyanChandler\BladeCaptureDirective\BladeCaptureDirectiveServiceProvider;
use Spatie\QueryBuilder\QueryBuilderServiceProvider;
Expand All @@ -27,11 +26,6 @@ class TestCase extends Orchestra
{
use RefreshDatabase;

protected function setUp(): void
{
parent::setUp();
}

protected function getPackageProviders($app)
{
return [
Expand Down Expand Up @@ -74,13 +68,6 @@ protected function defineDatabaseMigrations()
$this->loadLaravelMigrations();

// Migrations for test fixtures
$this->loadMigrationsFrom(realpath(__DIR__ . '/Fixtures/Database/Migrations'));
}

protected function defineRoutes($router)
{
// $router->group(['prefix' => 'api'], function () {
// ProductApiService::routes();
// });
$this->loadMigrationsFrom(realpath(__DIR__ . '/../Fixtures/Database/Migrations'));
}
}
181 changes: 181 additions & 0 deletions tests/WithoutPanelPrefix/ApiServiceWithoutPanelPrefixTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
<?php

use Illuminate\Routing\Route as RoutingRoute;
use Rupadana\ApiService\Tests\Fixtures\Database\Seeders\ProductsSeeder;
use Rupadana\ApiService\Tests\Fixtures\Database\Seeders\UserSeeder;
use Rupadana\ApiService\Tests\Fixtures\Models\Product;
use Rupadana\ApiService\Tests\Fixtures\Models\User;

it('can make routes for a product resource', function () {
$routes = collect(app('router')->getRoutes())->map(function (RoutingRoute $route) {
return implode('|', $route->methods()) . ' ' . $route->uri();
});

// The route name is customized to `our-products` in the `ProductApiService` class
expect($routes)->toContain('POST api/our-products');
expect($routes)->toContain('PUT api/our-products/{id}');
expect($routes)->toContain('DELETE api/our-products/{id}');
expect($routes)->toContain('GET|HEAD api/our-products');
expect($routes)->toContain('GET|HEAD api/our-products/{id}');
});

it('can return a list of products with allowed attributes', function () {
$this->seed(ProductsSeeder::class);
$this->seed(UserSeeder::class);

$user = User::find(1);
$token = $user->createToken('testing')->plainTextToken;

$response = $this->get('/api/our-products', [
'Authorization' => 'Bearer ' . $token,
])
->assertStatus(200);

$products = Product::all()->map(function ($product) {
return [
'name' => $product['name'],
'description' => $product['description'],
'price' => $product['price'],
];
})->toArray();

foreach ($products as $product) {
$response->assertJsonFragment($product);
}

// Check that the slug (hidden) is not returned
$response->assertJsonMissing([
'slug' => 't-shirt',
]);
});

it('can return a list of products with selected fields', function () {
$this->seed(ProductsSeeder::class);
$this->seed(UserSeeder::class);

$user = User::find(1);
$token = $user->createToken('testing')->plainTextToken;

$response = $this->get('/api/our-products?fields[products]=name,price', [
'Authorization' => 'Bearer ' . $token,
])
->assertStatus(200);

$response->assertJsonFragment([
'name' => 'T-Shirt',
'price' => 500,
]);
});

it('throws when selecting a field that is not allowed', function () {
$this->seed(ProductsSeeder::class);
$this->seed(UserSeeder::class);

$user = User::find(1);
$token = $user->createToken('testing')->plainTextToken;

$this->get('/api/our-products?fields[products]=name,slug,price', [
'Authorization' => 'Bearer ' . $token,
])
->assertStatus(400)
->assertJsonFragment([
'message' => 'Requested field(s) `products.slug` are not allowed.',
]);
})->throws(\Spatie\QueryBuilder\Exceptions\InvalidFieldQuery::class);

it('can return a list of products with selected sorts', function () {
$this->seed(ProductsSeeder::class);
$this->seed(UserSeeder::class);

$user = User::find(1);
$token = $user->createToken('testing')->plainTextToken;

$response = $this->get('/api/our-products?sort=-price', [
'Authorization' => 'Bearer ' . $token,
])
->assertStatus(200);

$data = Product::all()
->sortByDesc('price')
->values()
->map(function ($product) {
return [
'name' => $product['name'],
'price' => $product['price'],
];
})
->toArray();

foreach ($data as $product) {
$response->assertJsonFragment($product);
}
});

it('throws when sorting by a field that is not allowed', function () {
$this->seed(ProductsSeeder::class);
$this->seed(UserSeeder::class);

$user = User::find(1);
$token = $user->createToken('testing')->plainTextToken;

$this->get('/api/our-products?sort=-slug', [
'Authorization' => 'Bearer ' . $token,
])
->assertStatus(400)
->assertJsonFragment([
'message' => 'Requested sort(s) `products.slug` are not allowed.',
]);
})->throws(\Spatie\QueryBuilder\Exceptions\InvalidSortQuery::class);

it('can return a list of products with selected filters', function () {
$this->seed(ProductsSeeder::class);
$this->seed(UserSeeder::class);

$user = User::find(1);
$token = $user->createToken('testing')->plainTextToken;

$response = $this->get('/api/our-products?filter[name]=T-Shirt&filter[price]=500', [
'Authorization' => 'Bearer ' . $token,
])
->assertStatus(200);

$response->assertJsonFragment([
'name' => 'T-Shirt',
'price' => 500,
]);
});

it('throws when filtering by a field that is not allowed', function () {
$this->seed(ProductsSeeder::class);
$this->seed(UserSeeder::class);

$user = User::find(1);
$token = $user->createToken('testing')->plainTextToken;

$this->get('/api/our-products?filter[name]=T-Shirt&filter[slug]=t-shirt', [
'Authorization' => 'Bearer ' . $token,
])
->assertStatus(400)
->assertJsonFragment([
'message' => 'Requested filter(s) `products.slug` are not allowed.',
]);
})->throws(\Spatie\QueryBuilder\Exceptions\InvalidFilterQuery::class);

it('can return a list of products with a custom transformer', function () {
$this->seed(ProductsSeeder::class);
$this->seed(UserSeeder::class);

$user = User::find(1);
$token = $user->createToken('testing')->plainTextToken;

$response = $this->get('/api/our-products', [
'Authorization' => 'Bearer ' . $token,
])
->assertStatus(200);

$product = Product::first();

$response->assertJsonFragment([
'hash' => md5($product['name']),
]);
});
74 changes: 74 additions & 0 deletions tests/WithoutPanelPrefix/TestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace Rupadana\ApiService\Tests\WithoutPanelPrefix;

use BladeUI\Heroicons\BladeHeroiconsServiceProvider;
use BladeUI\Icons\BladeIconsServiceProvider;
use Filament\Actions\ActionsServiceProvider;
use Filament\FilamentServiceProvider;
use Filament\Forms\FormsServiceProvider;
use Filament\Infolists\InfolistsServiceProvider;
use Filament\Notifications\NotificationsServiceProvider;
use Filament\Support\SupportServiceProvider;
use Filament\Tables\TablesServiceProvider;
use Filament\Widgets\WidgetsServiceProvider;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\SanctumServiceProvider;
use Livewire\LivewireServiceProvider;
use Orchestra\Testbench\TestCase as Orchestra;
use Rupadana\ApiService\ApiServiceServiceProvider;
use Rupadana\ApiService\Tests\Fixtures\Providers\AdminPanelProvider;
use RyanChandler\BladeCaptureDirective\BladeCaptureDirectiveServiceProvider;
use Spatie\QueryBuilder\QueryBuilderServiceProvider;

class TestCase extends Orchestra
{
use RefreshDatabase;

protected function getPackageProviders($app)
{
return [
ActionsServiceProvider::class,
BladeCaptureDirectiveServiceProvider::class,
BladeHeroiconsServiceProvider::class,
BladeIconsServiceProvider::class,
FilamentServiceProvider::class,
FormsServiceProvider::class,
InfolistsServiceProvider::class,
LivewireServiceProvider::class,
NotificationsServiceProvider::class,
SupportServiceProvider::class,
TablesServiceProvider::class,
WidgetsServiceProvider::class,
QueryBuilderServiceProvider::class,
AdminPanelProvider::class,
SanctumServiceProvider::class,
ApiServiceServiceProvider::class,
];
}

public function getEnvironmentSetUp($app)
{
tap($app['config'], function (Repository $config) {
$config->set('database.default', 'testing');
$config->set('database.connections.testing', [
'driver' => 'sqlite',
'database' => ':memory:',
]);

$config->set('app.env', env('APP_ENV', 'testing'));
$config->set('app.debug', env('APP_DEBUG', true));
$config->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8=');
$config->set('api-service.route.panel_prefix', false);
});
}

protected function defineDatabaseMigrations()
{
$this->loadLaravelMigrations();

// Migrations for test fixtures
$this->loadMigrationsFrom(realpath(__DIR__ . '/../Fixtures/Database/Migrations'));
}
}
Loading