Skip to content

Commit

Permalink
introduce a ControllerTestCase with getEm(), assertFormError() and us…
Browse files Browse the repository at this point in the history
…e this in all controllers (#1441)
  • Loading branch information
pscheit authored Mar 20, 2024
1 parent 033b430 commit 1444a68
Show file tree
Hide file tree
Showing 10 changed files with 93 additions and 220 deletions.
12 changes: 3 additions & 9 deletions tests/Controller/AboutControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,18 @@

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class AboutControllerTest extends WebTestCase
class AboutControllerTest extends ControllerTestCase
{
public function testPackagist(): void
{
$client = self::createClient();

$crawler = $client->request('GET', '/about');
$crawler = $this->client->request('GET', '/about');
static::assertResponseIsSuccessful();
static::assertEquals('What is Packagist?', $crawler->filter('h2.title')->first()->text());
}

public function testComposerRedirect(): void
{
$client = self::createClient();

$client->request('GET', '/about-composer');
$this->client->request('GET', '/about-composer');
static::assertResponseRedirects('https://getcomposer.org/', 301);
}
}
32 changes: 5 additions & 27 deletions tests/Controller/ApiControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,17 @@

namespace App\Tests\Controller;

use App\Entity\Package;
use App\Entity\SecurityAdvisory;
use App\Entity\User;
use App\SecurityAdvisory\GitHubSecurityAdvisoriesSource;
use App\SecurityAdvisory\RemoteSecurityAdvisory;
use App\SecurityAdvisory\Severity;
use Doctrine\DBAL\Connection;
use Doctrine\Persistence\ManagerRegistry;
use Exception;
use App\Entity\Package;
use App\Entity\User;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Depends;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ApiControllerTest extends WebTestCase
class ApiControllerTest extends ControllerTestCase
{
private KernelBrowser $client;

public function setUp(): void
{
$this->client = self::createClient();
static::getContainer()->get(Connection::class)->beginTransaction();

parent::setUp();
}

public function tearDown(): void
{
static::getContainer()->get(Connection::class)->rollBack();

parent::tearDown();
}

public function testGithubFailsOnGet(): void
{
$this->client->request('GET', '/api/github');
Expand Down Expand Up @@ -73,7 +51,7 @@ public function testGithubApi($url): void
$user->setPassword('testtest');
$user->setApiToken('token');

$em = static::getContainer()->get(ManagerRegistry::class)->getManager();
$em = self::getEM();
$em->persist($package);
$em->persist($user);
$em->flush();
Expand Down Expand Up @@ -180,7 +158,7 @@ public function testSecurityAdvisories(): void
GitHubSecurityAdvisoriesSource::SOURCE_NAME,
Severity::MEDIUM,
), GitHubSecurityAdvisoriesSource::SOURCE_NAME);
$em = static::getContainer()->get(ManagerRegistry::class)->getManager();
$em = self::getEM();
$em->persist($advisory);
$em->flush();

Expand Down
39 changes: 3 additions & 36 deletions tests/Controller/ChangePasswordControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,34 +14,11 @@

use App\Entity\User;
use App\Validator\NotProhibitedPassword;
use Doctrine\DBAL\Connection;
use Doctrine\Persistence\ManagerRegistry;
use PHPUnit\Framework\Attributes\TestWith;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class ChangePasswordControllerTest extends WebTestCase
class ChangePasswordControllerTest extends ControllerTestCase
{
private KernelBrowser $client;

public function setUp(): void
{
$this->client = self::createClient();
$this->client->disableReboot(); // Prevent reboot between requests
static::getContainer()->get(Connection::class)->beginTransaction();

parent::setUp();
}

public function tearDown(): void
{
static::getContainer()->get(Connection::class)->rollBack();

parent::tearDown();
}

#[TestWith(['SuperSecret123', 'ok'])]
#[TestWith(['[email protected]', 'prohibited-password-error'])]
public function testChangePassword(string $newPassword, string $expectedResult): void
Expand All @@ -58,7 +35,7 @@ public function testChangePassword(string $newPassword, string $expectedResult):
$currentPasswordHash = self::getContainer()->get(UserPasswordHasherInterface::class)->hashPassword($user, $currentPassword);
$user->setPassword($currentPasswordHash);

$em = static::getContainer()->get(ManagerRegistry::class)->getManager();
$em = self::getEM();
$em->persist($user);
$em->flush();

Expand All @@ -83,17 +60,7 @@ public function testChangePassword(string $newPassword, string $expectedResult):

if ($expectedResult === 'prohibited-password-error') {
$this->assertResponseStatusCodeSame(422);
$this->assertFormError((new NotProhibitedPassword)->message, $crawler);
$this->assertFormError((new NotProhibitedPassword)->message, 'change_password_form', $crawler);
}
}

private function assertFormError(string $message, Crawler $crawler): void
{
$formCrawler = $crawler->filter('[name="change_password_form"]');
$this->assertCount(
1,
$formCrawler->filter('.alert-danger:contains("' . $message . '")'),
$formCrawler->html()."\nShould find an .alert-danger within the form with the message: '$message'",
);
}
}
57 changes: 57 additions & 0 deletions tests/Controller/ControllerTestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php declare(strict_types=1);

/*
* This file is part of Packagist.
*
* (c) Jordi Boggiano <[email protected]>
* Nils Adermann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace App\Tests\Controller;

use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DomCrawler\Crawler;

class ControllerTestCase extends WebTestCase
{
protected KernelBrowser $client;

public function setUp(): void
{
$this->client = self::createClient();
$this->client->disableReboot(); // prevent reboot to keep the transaction

static::getContainer()->get(Connection::class)->beginTransaction();

parent::setUp();
}

public function tearDown(): void
{
static::getContainer()->get(Connection::class)->rollBack();

parent::tearDown();
}

public function getEM(): EntityManagerInterface
{
return static::getContainer()->get(ManagerRegistry::class)->getManager();
}

protected function assertFormError(string $message, string $formName, Crawler $crawler): void
{
$formCrawler = $crawler->filter(sprintf('[name="%s"]', $formName));
$this->assertCount(
1,
$formCrawler->filter('.alert-danger:contains("' . $message . '")'),
$formCrawler->html()."\nShould find an .alert-danger within the form with the message: '$message'",
);
}
}
14 changes: 6 additions & 8 deletions tests/Controller/FeedControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,23 @@
namespace App\Tests\Controller;

use PHPUnit\Framework\Attributes\DataProvider;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class FeedControllerTest extends WebTestCase
class FeedControllerTest extends ControllerTestCase
{
#[DataProvider('provideForFeed')]
public function testFeedAction(string $feed, string $format, ?string $vendor = null): void
{
$client = static::createClient();

$url = static::getContainer()->get(UrlGeneratorInterface::class)->generate($feed, ['_format' => $format, 'vendor' => $vendor]);

$crawler = $client->request('GET', $url);
$this->client->request('GET', $url);

$this->assertEquals(200, $client->getResponse()->getStatusCode(), $client->getResponse()->getContent());
$this->assertStringContainsString($format, $client->getResponse()->getContent());
$response = $this->client->getResponse();
$this->assertEquals(200, $response->getStatusCode(), $response->getContent());
$this->assertStringContainsString($format, $response->getContent());

if ($vendor !== null) {
$this->assertStringContainsString($vendor, $client->getResponse()->getContent());
$this->assertStringContainsString($vendor, $response->getContent());
}
}

Expand Down
26 changes: 2 additions & 24 deletions tests/Controller/ProfileControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,9 @@
namespace App\Tests\Controller;

use App\Entity\User;
use Doctrine\DBAL\Connection;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ProfileControllerTest extends WebTestCase
class ProfileControllerTest extends ControllerTestCase
{
private KernelBrowser $client;

public function setUp(): void
{
$this->client = self::createClient();
$this->client->disableReboot(); // Prevent reboot between requests
static::getContainer()->get(Connection::class)->beginTransaction();

parent::setUp();
}

public function tearDown(): void
{
static::getContainer()->get(Connection::class)->rollBack();

parent::tearDown();
}

public function testEditProfile(): void
{
$user = new User;
Expand All @@ -51,7 +29,7 @@ public function testEditProfile(): void
$user->initializeConfirmationToken();
$user->setPasswordRequestedAt(new \DateTime());

$em = static::getContainer()->get(ManagerRegistry::class)->getManager();
$em = self::getEM();
$em->persist($user);
$em->flush();

Expand Down
39 changes: 3 additions & 36 deletions tests/Controller/RegistrationControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,10 @@

use App\Entity\User;
use App\Validator\NotProhibitedPassword;
use Doctrine\DBAL\Connection;
use Doctrine\Persistence\ManagerRegistry;
use PHPUnit\Framework\Attributes\TestWith;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DomCrawler\Crawler;

class RegistrationControllerTest extends WebTestCase
class RegistrationControllerTest extends ControllerTestCase
{
private KernelBrowser $client;

public function setUp(): void
{
$this->client = self::createClient();
$this->client->disableReboot(); // Prevent reboot between requests
static::getContainer()->get(Connection::class)->beginTransaction();

parent::setUp();
}

public function tearDown(): void
{
static::getContainer()->get(Connection::class)->rollBack();

parent::tearDown();
}

public function testRegisterWithoutOAuth(): void
{
$crawler = $this->client->request('GET', '/register/');
Expand All @@ -56,7 +33,7 @@ public function testRegisterWithoutOAuth(): void
$this->client->submit($form);
$this->assertResponseStatusCodeSame(302);

$em = static::getContainer()->get(ManagerRegistry::class)->getManager();
$em = self::getEM();
$user = $em->getRepository(User::class)->findOneBy(['username' => 'max.example']);
$this->assertInstanceOf(User::class, $user);
$this->assertSame('[email protected]', $user->getEmailCanonical(), "user email should have been canonicalized");
Expand All @@ -80,16 +57,6 @@ public function testRegisterWithTooSimplePasswords(string $password): void
$crawler = $this->client->submit($form);
$this->assertResponseStatusCodeSame(422, 'Should be invalid because password is the same as email or username');

$this->assertFormError((new NotProhibitedPassword)->message, $crawler);
}

private function assertFormError(string $message, Crawler $crawler): void
{
$formCrawler = $crawler->filter('[name="registration_form"]');
$this->assertCount(
1,
$formCrawler->filter('.alert-danger:contains("' . $message . '")'),
$formCrawler->html()."\nShould find an .alert-danger within the form with the message: '$message'",
);
$this->assertFormError((new NotProhibitedPassword)->message, 'registration_form', $crawler);
}
}
Loading

0 comments on commit 1444a68

Please sign in to comment.