SmokeTesting icon indicating copy to clipboard operation
SmokeTesting copied to clipboard

Use TestWith() attribute to test routes

Open tacman opened this issue 1 year ago • 2 comments

I've been playing around with the functional test generator and phpunit 10+ with php 8 (attributes), where we can use with TestWith attribute. The code is much smaller.

namespace App\Tests;

use PHPUnit\Framework\Attributes\TestWith;
use Pierstoval\SmokeTesting\FunctionalSmokeTester;
use Pierstoval\SmokeTesting\FunctionalTestData;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class FunctionalTest extends WebTestCase
{
    use FunctionalSmokeTester;

    #[TestWith(['/api','api_entrypoint'])]
    #[TestWith(['/','app_homepage'])]
    public function testRoute(string $url, string $route, string $method='GET'): void
    {
        $this->runFunctionalTest(
            FunctionalTestData::withUrl($url)
                ->withMethod($method)
                ->expectRouteName($route)
                ->appendCallableExpectation($this->assertStatusCodeLessThan500($method, $url))
        );

    }

    public function assertStatusCodeLessThan500(string $method, string $url): \Closure
    {
        return function (KernelBrowser $browser) use ($method, $url) {
            $statusCode = $browser->getResponse()->getStatusCode();
            $routeName = $browser->getRequest()->attributes->get('_route', 'unknown');

            static::assertLessThan(
                500,
                $statusCode,
                sprintf('Request "%s %s" for %s route returned an internal error.', $method, $url, $routeName),
            );
        };
    }
}

If you like the approach, I can make a PR. The main issue is that it only works with PHP8+ and phpunit 10+.

Would you be open to use nette/php-generator to create the test? It always generates valid PHP code, and will adjust to the version of PHP being used. It adds a dependency, but it gets rid of the php template that generates PHP.

tacman avatar Feb 09 '25 12:02 tacman

I'm almost finished a generator that doesn't use the Symfony maker bundle, so it can be run in the test environment, using the nette/php-generator.

How would you like me to add this -- a separate command in my branch, or just replace make:smoke-test with it?

tacman avatar Feb 10 '25 12:02 tacman

My fork now supports a Symfony command that generates the tests that doesn't require symfony/maker. One big advantage is that you can generate routes specific to the test environment, e.g.

bin/console generate:smoke --env=test --force StaticRoutesTest

I'm testing it in my projects and it's working well for me. I keep getting distracted by errors it's uncovering!

tacman avatar Feb 10 '25 14:02 tacman