Skip to content

Commit

Permalink
Fix for issue #6519 (Pretty URLs in tests)
Browse files Browse the repository at this point in the history
When using pretty URLs in tests, the AdminUrlGenerator fails to provide the pretty URLs because it checks the use of pretty URLs through the context, which is null when doing requests from tests. This fixes this behaviour by checking the use of pretty URLs directly from the UrlGenerator (Router), which is what is done by the context anyway.

Tests have been adapted to use pretty URLs.
  • Loading branch information
Matthieu Renard committed Dec 20, 2024
1 parent 81e468d commit 7c28881
Show file tree
Hide file tree
Showing 16 changed files with 39 additions and 28 deletions.
3 changes: 1 addition & 2 deletions .ddev/example/Controller/Admin/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@
use EasyCorp\Bundle\EasyAdminBundle\Config\Dashboard;
use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Attribute\Route;

class DashboardController extends AbstractDashboardController
{
Expand Down
16 changes: 11 additions & 5 deletions src/Router/AdminUrlGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,8 @@ public function generateUrl(): string
$this->initialize();
}

$usePrettyUrls = $this->adminRouteGenerator->usesPrettyUrls();

if (true === $this->includeReferrer) {
$this->setRouteParameter(EA::REFERRER, $this->customPageReferrer ?? $this->currentPageReferrer);
}
Expand All @@ -239,7 +241,9 @@ public function generateUrl(): string
}

$this->dashboardRoute = $dashboardRoute;
$this->unset(EA::DASHBOARD_CONTROLLER_FQCN);
if (!$usePrettyUrls) {
$this->unset(EA::DASHBOARD_CONTROLLER_FQCN);
}
}

// if the current action is 'index' and an entity ID is defined, remove the entity ID to prevent exceptions automatically
Expand Down Expand Up @@ -276,20 +280,22 @@ public function generateUrl(): string
}

$context = $this->adminContextProvider->getContext();
$usePrettyUrls = null !== $context && $context->usePrettyUrls();
$urlType = null !== $context && false === $context->getAbsoluteUrls() ? UrlGeneratorInterface::ABSOLUTE_PATH : UrlGeneratorInterface::ABSOLUTE_URL;

if (null !== $this->get(EA::ROUTE_NAME)) {
return $this->urlGenerator->generate($this->dashboardRoute, $routeParameters, $urlType);
}

if ($usePrettyUrls) {
$dashboardControllerFqcn = $this->get(EA::DASHBOARD_CONTROLLER_FQCN) ?? $context->getRequest()->attributes->get(EA::DASHBOARD_CONTROLLER_FQCN) ?? $this->dashboardControllerRegistry->getFirstDashboardFqcn();
$crudControllerFqcn = $this->get(EA::CRUD_CONTROLLER_FQCN) ?? $context->getRequest()->attributes->get(EA::CRUD_CONTROLLER_FQCN);
$actionName = $this->get(EA::CRUD_ACTION) ?? $context->getRequest()->attributes->get(EA::CRUD_ACTION);
$dashboardControllerFqcn = $this->get(EA::DASHBOARD_CONTROLLER_FQCN) ?? $context?->getRequest()->attributes->get(EA::DASHBOARD_CONTROLLER_FQCN) ?? $this->dashboardControllerRegistry->getFirstDashboardFqcn();
$crudControllerFqcn = $this->get(EA::CRUD_CONTROLLER_FQCN) ?? $context?->getRequest()->attributes->get(EA::CRUD_CONTROLLER_FQCN);
$actionName = $this->get(EA::CRUD_ACTION) ?? $context?->getRequest()->attributes->get(EA::CRUD_ACTION);

if (null === $crudControllerFqcn || null === $routeName = $this->adminRouteGenerator->findRouteName($dashboardControllerFqcn, $crudControllerFqcn, $actionName)) {
$routeName = $this->dashboardRoute;
if (null === $crudControllerFqcn) {
unset($routeParameters[EA::DASHBOARD_CONTROLLER_FQCN]);
}
} else {
// remove these parameters so they don't appear in the query string when using pretty URLs
unset($routeParameters[EA::DASHBOARD_CONTROLLER_FQCN]);
Expand Down
6 changes: 3 additions & 3 deletions tests/Controller/CategoryCrudControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,8 @@ public function testToggle(string $method, ?string $invalidCsrfToken, ?string $f
$firstFoundToggleUrl = $crawler->filter('td.field-boolean .form-switch input[type="checkbox"]')->first()->attr('data-toggle-url');

// Get the category's active state from the DB
parse_str(parse_url($firstFoundToggleUrl, \PHP_URL_QUERY), $parameters);
$categoryId = $parameters['entityId'];
preg_match('#category/(\d+)/#', parse_url($firstFoundToggleUrl, \PHP_URL_PATH), $parameters);
$categoryId = $parameters[1] ?? null;
$active = $this->categories->find($categoryId)->isActive();
static::assertIsBool($active);

Expand Down Expand Up @@ -282,7 +282,7 @@ public function testPagination()

// test pagination maintains all query parameters, including custom ones
$queryParameters = http_build_query(['sort[name]' => 'DESC', 'CUSTOM_param' => 'foobar1234']);
$crawler = $this->client->request('GET', $this->generateIndexUrl().'&'.$queryParameters);
$crawler = $this->client->request('GET', $this->generateIndexUrl().'?'.$queryParameters);

$firstPageUrl = $crawler->filter('.list-pagination-paginator .page-item:nth-child(2) .page-link')->attr('href');
static::assertSame(['name' => 'DESC'], $this->getParameterFromUrlQueryString($firstPageUrl, 'sort'));
Expand Down
11 changes: 2 additions & 9 deletions tests/Controller/Search/DefaultCrudSearchControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ public function testDefaultEmptySearchForm()
$this->assertSelectorNotExists('form.form-action-search .content-search-reset', 'The empty search form should not display the button to reset contents');

$form = $crawler->filter('form.form-action-search');
$this->assertSame('index', $form->filter('input[type="hidden"][name="crudAction"]')->attr('value'));
$this->assertSame(DefaultCrudSearchController::class, $form->filter('input[type="hidden"][name="crudControllerFqcn"]')->attr('value'));
$this->assertSame('1', $form->filter('input[type="hidden"][name="page"]')->attr('value'));

$formSearchInput = $form->filter('input[name="query"]');
$this->assertSame('', $formSearchInput->attr('value'));
Expand All @@ -49,9 +46,6 @@ public function testSearchFormAfterMakingAQuery()
$crawler = $this->client->request('GET', $this->generateIndexUrl('blog post'));

$form = $crawler->filter('form.form-action-search');
$this->assertSame('index', $form->filter('input[type="hidden"][name="crudAction"]')->attr('value'));
$this->assertSame(DefaultCrudSearchController::class, $form->filter('input[type="hidden"][name="crudControllerFqcn"]')->attr('value'));
$this->assertSame('1', $form->filter('input[type="hidden"][name="page"]')->attr('value'));

$formSearchInput = $form->filter('input[name="query"]');
$this->assertSame('blog post', $formSearchInput->attr('value'));
Expand All @@ -60,7 +54,8 @@ public function testSearchFormAfterMakingAQuery()
$this->assertSame('off', $formSearchInput->attr('autocorrect'));

$this->assertSelectorExists('form.form-action-search .content-search-reset', 'After making a query, the search form should display the button to reset contents');
$this->assertSame($this->generateIndexUrl(), $crawler->filter('form.form-action-search .content-search-reset')->attr('href'));
// With prettyUrls, the generated URL contains the page parameter set to 1
$this->assertSame($this->generateIndexUrl() . '?page=1', $crawler->filter('form.form-action-search .content-search-reset')->attr('href'));
}

public function testPaginationNotDisplayedWhenNotNeeded()
Expand All @@ -72,7 +67,6 @@ public function testPaginationNotDisplayedWhenNotNeeded()

// assert that the pagination is not displayed because there are not enough results
$form = $crawler->filter('form.form-action-search');
$this->assertSame('1', $form->filter('input[type="hidden"][name="page"]')->attr('value'));
$this->assertSame('1', $crawler->filter('.list-pagination .list-pagination-counter strong')->text());
$this->assertSelectorNotExists('.list-pagination nav.pager');
}
Expand All @@ -90,7 +84,6 @@ public function testPaginationAndSortingIsResetAfterAQuery()

// assert that the pagination and sorting is reset
$form = $crawler->filter('form.form-action-search');
$this->assertSame('1', $form->filter('input[type="hidden"][name="page"]')->attr('value'));
$this->assertSame('1', $crawler->filter('.page-item.active .page-link')->text());

$this->assertCount(0, $crawler->filter('th[data-column="title"] a.sorted'));
Expand Down
2 changes: 1 addition & 1 deletion tests/Orm/BillSortTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function testSorting(array $query, ?\Closure $sortFunction, string $expec
}

// Act
$crawler = $this->client->request('GET', $this->generateIndexUrl().'&'.http_build_query($query));
$crawler = $this->client->request('GET', $this->generateIndexUrl().'?'.http_build_query($query));

// Assert
$this->assertResponseIsSuccessful();
Expand Down
2 changes: 1 addition & 1 deletion tests/Orm/CustomerSortTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function testSorting(array $query, ?\Closure $sortFunction, string $expec
}

// Act
$crawler = $this->client->request('GET', $this->generateIndexUrl().'&'.http_build_query($query));
$crawler = $this->client->request('GET', $this->generateIndexUrl().'?'.http_build_query($query));

// Assert
$this->assertResponseIsSuccessful();
Expand Down
2 changes: 1 addition & 1 deletion tests/Orm/PageSortTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function testSorting(array $query, ?string $sortFunction, string $expecte
}

// Act
$crawler = $this->client->request('GET', $this->generateIndexUrl().'&'.http_build_query($query));
$crawler = $this->client->request('GET', $this->generateIndexUrl().'?'.http_build_query($query));

// Assert
$this->assertResponseIsSuccessful();
Expand Down
2 changes: 1 addition & 1 deletion tests/Orm/WebsiteSortTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function testSorting(array $query, ?\Closure $sortFunction, string $expec
}

// Act
$crawler = $this->client->request('GET', $this->generateIndexUrl().'&'.http_build_query($query));
$crawler = $this->client->request('GET', $this->generateIndexUrl().'?'.http_build_query($query));

// Assert
$this->assertResponseIsSuccessful();
Expand Down
4 changes: 3 additions & 1 deletion tests/Router/AdminUrlGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminRouteGenerator;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGeneratorInterface;
use EasyCorp\Bundle\EasyAdminBundle\Tests\TestApplication\Controller\DashboardController;
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
Expand Down Expand Up @@ -303,11 +304,12 @@ private function getAdminUrlGenerator(bool $signedUrls = false, bool $absoluteUr
]);
$dashboardControllerRegistry->method('getNumberOfDashboards')->willReturn(2);
$dashboardControllerRegistry->method('getFirstDashboardRoute')->willReturn('admin');
$dashboardControllerRegistry->method('getFirstDashboardFqcn')->willReturn(DashboardController::class);

$container = Kernel::MAJOR_VERSION >= 6 ? static::getContainer() : self::$container;
$router = $container->get('router');

$adminRouteGenerator = $this->getMockBuilder(AdminRouteGenerator::class)->disableOriginalConstructor()->getMock();
$adminRouteGenerator = $container->get(AdminRouteGenerator::class);

return new AdminUrlGenerator($adminContextProvider, $router, $dashboardControllerRegistry, $adminRouteGenerator);
}
Expand Down
1 change: 1 addition & 0 deletions tests/TestApplication/config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@

return function (RoutingConfigurator $routes) {
$routes->import('../src/Controller/', Kernel::MAJOR_VERSION >= 7 ? 'attribute' : 'annotation');
$routes->import('.', 'easyadmin.routes');
};
8 changes: 8 additions & 0 deletions tests/TestApplication/config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use EasyCorp\Bundle\EasyAdminBundle\Router\AdminRouteGenerator;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminRouteLoader;
use EasyCorp\Bundle\EasyAdminBundle\Tests\TestApplication\DataFixtures\AppFixtures;

return static function (ContainerConfigurator $container) {
Expand All @@ -20,4 +22,10 @@
->tag('controller.service_arguments');

$services->set(AppFixtures::class)->tag('doctrine.fixture.orm');

$services
->set(AdminRouteLoader::class)
->arg(0, service(AdminRouteGenerator::class))
->tag('routing.loader', ['type' => AdminRouteLoader::ROUTE_LOADER_TYPE])
;
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace EasyCorp\Bundle\EasyAdminBundle\Tests\TestApplication\Controller;

use EasyCorp\Bundle\EasyAdminBundle\Attribute\AdminAction;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Assets;
Expand Down Expand Up @@ -62,6 +63,7 @@ public function configureFilters(Filters $filters): Filters
->add('active');
}

#[AdminAction(routePath: '/customAction', routeName: 'custom_action')]
public function customAction(AdminContext $context): Response
{
if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => AppAction::CUSTOM_ACTION, 'entity' => $context->getEntity()])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use EasyCorp\Bundle\EasyAdminBundle\Tests\TestApplication\Entity\BlogPost;
use EasyCorp\Bundle\EasyAdminBundle\Tests\TestApplication\Entity\Category;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Attribute\Route;

class CustomHtmlAttributeDashboardController extends AbstractDashboardController
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use EasyCorp\Bundle\EasyAdminBundle\Tests\TestApplication\Entity\BlogPost;
use EasyCorp\Bundle\EasyAdminBundle\Tests\TestApplication\Entity\Category;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Attribute\Route;

class DashboardController extends AbstractDashboardController
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Attribute\Route;

class ErrorDashboardController extends AbstractDashboardController
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use EasyCorp\Bundle\EasyAdminBundle\Tests\TestApplication\Entity\BlogPost;
use EasyCorp\Bundle\EasyAdminBundle\Tests\TestApplication\Entity\Category;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Attribute\Route;

class SecureDashboardController extends AbstractDashboardController
{
Expand Down

0 comments on commit 7c28881

Please sign in to comment.