Skip to content

Commit

Permalink
Update/add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Seldaek committed Nov 7, 2024
1 parent eb5c190 commit 43f6fa1
Show file tree
Hide file tree
Showing 10 changed files with 143 additions and 108 deletions.
1 change: 1 addition & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd"
colors="true"
bootstrap="tests/bootstrap.php"
displayDetailsOnTestsThatTriggerWarnings="true"
>
<php>
<ini name="display_errors" value="1"/>
Expand Down
63 changes: 14 additions & 49 deletions tests/Controller/ApiControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,33 +39,21 @@ public function testGitHubFailsWithInvalidCredentials(): void
#[DataProvider('githubApiProvider')]
public function testGithubApi($url): void
{
$package = $this->createPackage('test/'.bin2hex(random_bytes(10)), $url);

$user = new User;
$user->addPackage($package);
$package->addMaintainer($user);
$user->setEnabled(true);
$user->setUsername('test');
$user->setEmail('[email protected]');
$user->setPassword('testtest');
$user->setApiToken('token');

$em = self::getEM();
$em->persist($package);
$em->persist($user);
$em->flush();
$user = self::createUser();
$package = self::createPackage('test/'.bin2hex(random_bytes(10)), $url, maintainers: [$user]);
$this->store($user, $package);

$scheduler = $this->createMock('App\Service\Scheduler');

$scheduler->expects($this->once())
->method('scheduleUpdate')
->with($package);

static::$kernel->getContainer()->set('doctrine.orm.entity_manager', $em);
static::$kernel->getContainer()->set('doctrine.orm.entity_manager', self::getEM());
static::$kernel->getContainer()->set('App\Service\Scheduler', $scheduler);

$payload = json_encode(['repository' => ['url' => 'git://github.com/composer/composer']]);
$this->client->request('POST', '/api/github?username=test&apiToken=token', ['payload' => $payload]);
$this->client->request('POST', '/api/github?username=test&apiToken=api-token', ['payload' => $payload]);
$this->assertEquals(202, $this->client->getResponse()->getStatusCode(), $this->client->getResponse()->getContent());
}

Expand All @@ -81,49 +69,28 @@ public static function githubApiProvider(): array

public function testUnsafeApiRejectsSafeApiToken(): void
{
$user = new User;
$user->setEnabled(true);
$user->setUsername('test');
$user->setEmail('[email protected]');
$user->setPassword('testtest');
$user->setApiToken('token');
$user->setSafeApiToken('safetoken');

$em = self::getEM();
$em->persist($user);
$em->flush();
$user = self::createUser();
$this->store($user);

$payload = json_encode(['repository' => 'https://github.com/composer/composer']);
$this->client->request('POST', '/api/create-package?username=test&apiToken=safetoken', ['payload' => $payload]);
$this->client->request('POST', '/api/create-package?username=test&apiToken=safe-api-token', ['payload' => $payload]);
$this->assertEquals(406, $this->client->getResponse()->getStatusCode(), $this->client->getResponse()->getContent());
$this->assertEquals(json_encode(['status' => 'error', 'message' => 'Missing or invalid username/apiToken in request']), $this->client->getResponse()->getContent());
}

public function testSafeApiAcceptsBothApiTokens(): void
{
$url = 'https://github.com/composer/composer';
$package = $this->createPackage('test/'.bin2hex(random_bytes(10)), $url);
$user = new User;
$user->addPackage($package);
$package->addMaintainer($user);
$user->setEnabled(true);
$user->setUsername('test');
$user->setEmail('[email protected]');
$user->setPassword('testtest');
$user->setApiToken('token');
$user->setSafeApiToken('safetoken');

$em = self::getEM();
$em->persist($package);
$em->persist($user);
$em->flush();
$user = self::createUser();
$package = self::createPackage('test/'.bin2hex(random_bytes(10)), $url, maintainers: [$user]);
$this->store($user, $package);

$payload = json_encode(['repository' => $url]);
$this->client->request('POST', '/api/update-package?username=test&apiToken=safetoken', ['payload' => $payload]);
$this->client->request('POST', '/api/update-package?username=test&apiToken=safe-api-token', ['payload' => $payload]);
$this->assertEquals(202, $this->client->getResponse()->getStatusCode(), $this->client->getResponse()->getContent());

$payload = json_encode(['repository' => 'https://packagist.org/packages/'.$package->getName()]);
$this->client->request('POST', '/api/update-package?username=test&apiToken=token', ['payload' => $payload]);
$this->client->request('POST', '/api/update-package?username=test&apiToken=api-token', ['payload' => $payload]);
$this->assertEquals(202, $this->client->getResponse()->getStatusCode(), $this->client->getResponse()->getContent());
}

Expand Down Expand Up @@ -205,9 +172,7 @@ public function testSecurityAdvisories(): void
GitHubSecurityAdvisoriesSource::SOURCE_NAME,
Severity::MEDIUM,
), GitHubSecurityAdvisoriesSource::SOURCE_NAME);
$em = self::getEM();
$em->persist($advisory);
$em->flush();
$this->store($advisory);

$this->client->request('GET', '/api/security-advisories/?packages[]=acme/package');
$this->assertEquals(200, $this->client->getResponse()->getStatusCode(), $this->client->getResponse()->getContent());
Expand Down
13 changes: 3 additions & 10 deletions tests/Controller/ChangePasswordControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,13 @@ class ChangePasswordControllerTest extends ControllerTestCase
#[TestWith(['[email protected]', 'prohibited-password-error'])]
public function testChangePassword(string $newPassword, string $expectedResult): void
{
$user = new User;
$user->setEnabled(true);
$user->setUsername('test');
$user->setEmail('[email protected]');
$user->setPassword('testtest');
$user->setApiToken('token');
$user->setGithubId('123456');
$user = self::createUser();

$currentPassword = 'current-one-123';
$currentPasswordHash = self::getContainer()->get(UserPasswordHasherInterface::class)->hashPassword($user, $currentPassword);
$user->setPassword($currentPasswordHash);

$em = self::getEM();
$em->persist($user);
$em->flush();
$this->store($user);

$this->client->loginUser($user);

Expand All @@ -52,6 +44,7 @@ public function testChangePassword(string $newPassword, string $expectedResult):
if ($expectedResult == 'ok') {
$this->assertResponseStatusCodeSame(302);

$em = self::getEM();
$em->clear();
$user = $em->getRepository(User::class)->find($user->getId());
$this->assertNotNull($user);
Expand Down
49 changes: 47 additions & 2 deletions tests/Controller/ControllerTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
namespace App\Tests\Controller;

use App\Entity\Package;
use App\Entity\User;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
Expand Down Expand Up @@ -42,7 +43,7 @@ public function tearDown(): void
parent::tearDown();
}

public function getEM(): EntityManagerInterface
public static function getEM(): EntityManagerInterface
{
return static::getContainer()->get(ManagerRegistry::class)->getManager();
}
Expand All @@ -57,17 +58,61 @@ protected function assertFormError(string $message, string $formName, Crawler $c
);
}

/**
* @param object|array<object> $objects
*/
protected function store(array|object ...$objects): void
{
$em = $this->getEM();
foreach ($objects as $obj) {
if (is_array($obj)) {
foreach ($obj as $obj2) {
$em->persist($obj2);
}
} else {
$em->persist($obj);
}
}

$em->flush();
}

/**
* Creates a Package entity without running the slow network-based repository initialization step
*
* @param array<User> $maintainers
*/
protected function createPackage(string $name, string $repository, ?string $remoteId = null)
protected static function createPackage(string $name, string $repository, ?string $remoteId = null, array $maintainers = []): Package
{
$package = new Package();

$package->setName($name);
$package->setRemoteId($remoteId);
(new ReflectionProperty($package, 'repository'))->setValue($package, $repository);
if (\count($maintainers) > 0) {
foreach ($maintainers as $user) {
$package->addMaintainer($user);
$user->addPackage($package);
}
}

return $package;
}

/**
* @param array<string> $roles
*/
protected static function createUser(string $username = 'test', string $email = '[email protected]', string $password = 'testtest', string $apiToken = 'api-token', string $safeApiToken = 'safe-api-token', string $githubId = '12345', bool $enabled = true, array $roles = []): User
{
$user = new User();
$user->setEnabled(true);
$user->setUsername($username);
$user->setEmail($email);
$user->setPassword($password);
$user->setApiToken($apiToken);
$user->setSafeApiToken($safeApiToken);
$user->setGithubId($githubId);

return $user;
}
}
57 changes: 57 additions & 0 deletions tests/Controller/PackageControllerTest.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 App\Entity\Package;
use App\Search\Query;
use App\Tests\Search\AlgoliaMock;

class PackageControllerTest extends ControllerTestCase
{
public function testView(): void
{
$package = self::createPackage('test/pkg', 'https://example.com/test/pkg');
$this->store($package);

$crawler = $this->client->request('GET', '/packages/test/pkg');
self::assertResponseIsSuccessful();
self::assertSame('composer require test/pkg', $crawler->filter('.requireme input')->attr('value'));
}

public function testEdit(): void
{
$user = self::createUser();
$package = self::createPackage('test/pkg', 'https://example.com/test/pkg', maintainers: [$user]);

$this->store($user, $package);

$this->client->loginUser($user);

$crawler = $this->client->request('GET', '/packages/test/pkg');
self::assertResponseIsSuccessful();
self::assertSame('example.com/test/pkg', $crawler->filter('.canonical')->text());

$form = $crawler->selectButton('Edit')->form();
$crawler = $this->client->submit($form);

self::assertResponseIsSuccessful();

$form = $crawler->selectButton('Update')->form(['form[repository]' => 'https://github.com/composer/composer']);
$this->client->submit($form);
self::assertResponseRedirects();
$crawler = $this->client->followRedirect();

self::assertResponseIsSuccessful();
self::assertSame('github.com/composer/composer', $crawler->filter('.canonical')->text());
}
}
30 changes: 7 additions & 23 deletions tests/Controller/ProfileControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,8 @@ class ProfileControllerTest extends ControllerTestCase
{
public function testEditProfile(): void
{
$user = new User;
$user->setEnabled(true);
$user->setUsername('test');
$user->setEmail('[email protected]');
$user->setPassword('testtest');
$user->setApiToken('token');
$user->setGithubId('123456');

$user->initializeConfirmationToken();
$user->setPasswordRequestedAt(new \DateTime());

$em = self::getEM();
$em->persist($user);
$em->flush();
$user = self::createUser();
$this->store($user);

$this->client->loginUser($user);

Expand All @@ -44,6 +32,7 @@ public function testEditProfile(): void

$this->assertResponseStatusCodeSame(302);

$em = self::getEM();
$em->clear();
$user = $em->getRepository(User::class)->find($user->getId());
$this->assertNotNull($user);
Expand All @@ -54,18 +43,12 @@ public function testEditProfile(): void

public function testTokenRotate(): void
{
$user = new User;
$user->setEnabled(true);
$user->setUsername('test');
$user->setEmail('[email protected]');
$user->setPassword('testtest');
$user = self::createUser();
$this->store($user);

$token = $user->getApiToken();
$safeToken = $user->getSafeApiToken();

$em = self::getEM();
$em->persist($user);
$em->flush();

$this->client->loginUser($user);

$crawler = $this->client->request('GET', '/profile/');
Expand All @@ -77,6 +60,7 @@ public function testTokenRotate(): void

$this->assertResponseStatusCodeSame(302);

$em = self::getEM();
$em->clear();
$user = $em->getRepository(User::class)->find($user->getId());
$this->assertNotNull($user);
Expand Down
11 changes: 2 additions & 9 deletions tests/Controller/ResetPasswordControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,22 +61,15 @@ public function testResetPasswordToProhibited(): void

private function setupUserWithPasswordResetRequest(bool $withTwoFactor): User
{
$user = new User;
$user->setEnabled(true);
$user->setUsername('test');
$user->setEmail('[email protected]');
$user->setPassword('testtest');
$user->setApiToken('token');
$user = self::createUser();
$user->initializeConfirmationToken();
$user->setPasswordRequestedAt(new \DateTime());

if ($withTwoFactor) {
$user->setTotpSecret('secret');
}

$em = self::getEM();
$em->persist($user);
$em->flush();
$this->store($user);

return $user;
}
Expand Down
13 changes: 3 additions & 10 deletions tests/Controller/UserControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,8 @@ class UserControllerTest extends ControllerTestCase
{
public function testEnableTwoFactoCode(): void
{
$user = new User;
$user->setEnabled(true);
$user->setUsername('test');
$user->setEmail('[email protected]');
$user->setPassword('testtest');
$user->setApiToken('token');

$em = self::getEM();
$em->persist($user);
$em->flush();
$user = self::createUser();
$this->store($user);

$this->client->loginUser($user);

Expand All @@ -49,6 +41,7 @@ public function testEnableTwoFactoCode(): void
$this->client->submit($form);
$this->assertResponseStatusCodeSame(302);

$em = self::getEM();
$em->clear();
$this->assertTrue($em->getRepository(User::class)->find($user->getId())->isTotpAuthenticationEnabled());
}
Expand Down
Loading

0 comments on commit 43f6fa1

Please sign in to comment.