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

Add readme.md and make pipeline green #3

Merged
merged 22 commits into from
Jul 6, 2023
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
8 changes: 5 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ jobs:
- name: Install dependencies
run: composer update --prefer-dist --no-progress --no-suggest --prefer-stable ${{ matrix.composer-flags }}

- run: '[[ "${{ matrix.composer-flags }}" != "--prefer-lowest" ]] || cp phpunit9.xml.dist phpunit.xml.dist'

- name: Run test suite
run: composer test

Expand All @@ -50,10 +52,10 @@ jobs:
run: composer update --prefer-dist --no-progress --no-suggest --prefer-stable

- name: Run test suite
run: php -dpcov.enabled=1 -dpcov.exclude="~vendor~" vendor/bin/phpunit --testsuite unit --coverage-clover ./.coverage/coverage.xml
run: php -dpcov.enabled=1 -dpcov.exclude="~vendor~" vendor/bin/phpunit --coverage-clover ./.coverage/coverage.xml

- name: Check coverage
run: test ! -f ./.coverage/coverage.xml || php vendor/bin/phpfci inspect ./.coverage/coverage.xml ./.coverage/phpfci.xml --exit-code-on-failure
run: test ! -f ./.coverage/coverage.xml || php vendor/bin/phpfci inspect ./.coverage/coverage.xml --exit-code-on-failure --reportText

quality:
name: Quality checks
Expand All @@ -64,7 +66,7 @@ jobs:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.0
php-version: 8.1
coverage: none

- name: Install dependencies
Expand Down
55 changes: 54 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,57 @@
[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%208.0-8892BF)](https://php.net/)
[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%208.1-8892BF)](https://php.net/)

## PHPUnit extensions

Utility classes to make unit testing life easier.


## Features

### withConsecutive
In PHPUnit 10 withConsecutive method was removed. To still be able to migrate existing codebases a replacement method:

PHPUnit <= 9.5:
```php
$mock->method('myMethod')->withConsecutive([123, 'foobar'], [456]);
```
PHPUnit >= 9.6:
```php
$mock->method('myMethod')->with(...consecutive([123, 'foobar'], [456]));
```


### Symfony controller tests
Testing a Symfony controller internally invokes the dependency container. A utility class to mock these classes more easily.

```php
use DR\PHPUnitExtensions\Symfony\AbstractControllerTestCase;

class MyControllerTest extends AbstractControllerTestCase
{
public function myTest(): void
{
$this->expectDenyAccessUnlessGranted('attribute', null, true);
$this->expectGetUser(new User());
$this->expectCreateForm(TextType::class);

($this->controller)();
}

public function getController() {
return new MyController();
}
}
```

**Methods**
- `expectGetUser`
- `expectDenyAccessUnlessGranted`
- `expectCreateForm`
- `expectAddFlash`
- `expectGenerateUrl`
- `expectRedirectToRoute`
- `expectForward`
- `expectRender`

## About us

Expand Down
3 changes: 1 addition & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@
"fix": "@fix:phpcbf",
"fix:phpcbf": "phpcbf src tests",
"test": "phpunit",
"test:integration": "phpunit --testsuite integration",
"test:unit": "phpunit --testsuite unit"
"test:integration": "phpunit --testsuite integration"
},
"suggest": {
"symfony/form": "Symfony form component is required for testing the controller createForm methods",
Expand Down
17 changes: 5 additions & 12 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
bootstrap="vendor/autoload.php"
forceCoversAnnotation="true"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.2/phpunit.xsd"
failOnRisky="true"
failOnWarning="true"
beStrictAboutChangesToGlobalState="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutResourceUsageDuringSmallTests="true"
beStrictAboutTodoAnnotatedTests="true"
executionOrder="defects"
>
requireCoverageMetadata="true">
<testsuites>
<testsuite name="integration">
<directory>tests/Integration</directory>
</testsuite>
<testsuite name="unit">
<directory>tests/Unit</directory>
</testsuite>
</testsuites>
<coverage>
<source>
<include>
<directory suffix=".php">src</directory>
<directory>src</directory>
</include>
</coverage>
</source>
</phpunit>
23 changes: 23 additions & 0 deletions phpunit9.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
forceCoversAnnotation="true"
failOnRisky="true"
failOnWarning="true"
beStrictAboutChangesToGlobalState="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutResourceUsageDuringSmallTests="true"
beStrictAboutTodoAnnotatedTests="true"
executionOrder="defects"
>
<testsuites>
<testsuite name="integration">
<directory>tests/Integration</directory>
</testsuite>
</testsuites>
<coverage>
<include>
<directory suffix=".php">src</directory>
</include>
</coverage>
</phpunit>
78 changes: 41 additions & 37 deletions src/Mock/consecutive.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,47 +8,51 @@
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\Constraint\IsAnything;

/**
* @param array<mixed> $firstInvocationArguments A list of arguments for each invocation that will be asserted against.
* Will fail on: too many invocations or if the argument doesn't match for each invocation.
* @param array<mixed> $secondInvocationArguments
* @param array<mixed> ...$expectedArgumentList
*
* @note Full qualified name to appease to phpstorm inspection gods
* phpcs:ignore
* @return \PHPUnit\Framework\Constraint\Callback<mixed>[]
* @example <code>->with(...consecutive([5, 'foo'], [6, 'bar']))</code>
*/
function consecutive(array $firstInvocationArguments, array $secondInvocationArguments, array ...$expectedArgumentList): array
{
array_unshift($expectedArgumentList, $secondInvocationArguments);
array_unshift($expectedArgumentList, $firstInvocationArguments);

// count arguments
$maxArguments = (int)max(array_map(static fn($args) => count($args), $expectedArgumentList));
if ($maxArguments === 0) {
throw new InvalidArgumentException('consecutive() is expecting at least 1 or more arguments for invocation');
}
// @codeCoverageIgnoreStart
if (function_exists('\DR\PHPUnitExtensions\Mock\consecutive') === false) {
// @codeCoverageIgnoreEnd
/**
* @param array<mixed> $firstInvocationArguments A list of arguments for each invocation that will be asserted against.
* Will fail on: too many invocations or if the argument doesn't match for each invocation.
* @param array<mixed> $secondInvocationArguments
* @param array<mixed> ...$expectedArgumentList
*
* @note Full qualified name to appease to phpstorm inspection gods
* phpcs:ignore
* @return \PHPUnit\Framework\Constraint\Callback<mixed>[]
* @example <code>->with(...consecutive([5, 'foo'], [6, 'bar']))</code>
*/
function consecutive(array $firstInvocationArguments, array $secondInvocationArguments, array ...$expectedArgumentList): array
{
array_unshift($expectedArgumentList, $secondInvocationArguments);
array_unshift($expectedArgumentList, $firstInvocationArguments);

// count arguments
$maxArguments = (int)max(array_map(static fn($args) => count($args), $expectedArgumentList));
if ($maxArguments === 0) {
throw new InvalidArgumentException('consecutive() is expecting at least 1 or more arguments for invocation');
}

// reorganize arguments per argument index
$argumentsByIndex = [];
foreach ($expectedArgumentList as $invocation => $expectedArguments) {
foreach ($expectedArguments as $index => $argument) {
$argumentsByIndex[$index][$invocation] = $argument;
// reorganize arguments per argument index
$argumentsByIndex = [];
foreach ($expectedArgumentList as $invocation => $expectedArguments) {
foreach ($expectedArguments as $index => $argument) {
$argumentsByIndex[$index][$invocation] = $argument;
}
}
}

$callbacks = [];
/** @var array<int, mixed> $arguments */
foreach ($argumentsByIndex as $arguments) {
for ($i = 0; $i < $maxArguments; $i++) {
if (isset($arguments[$i]) === false) {
$arguments[$i] = new IsAnything();
$callbacks = [];
/** @var array<int, mixed> $arguments */
foreach ($argumentsByIndex as $arguments) {
for ($i = 0; $i < $maxArguments; $i++) {
if (isset($arguments[$i]) === false) {
$arguments[$i] = new IsAnything();
}
}
$constraint = new ConsecutiveParameters($arguments);
$callbacks[] = new Callback(static fn($actualArgument): bool => $constraint->evaluate($actualArgument));
}
$constraint = new ConsecutiveParameters($arguments);
$callbacks[] = new Callback(static fn($actualArgument): bool => $constraint->evaluate($actualArgument));
}

return $callbacks;
return $callbacks;
}
}
2 changes: 2 additions & 0 deletions src/Symfony/AbstractControllerTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ public function expectCreateForm(string $type, mixed $data = null, array $option
public function expectAddFlash(string $type, mixed $message): void
{
$flashBag = $this->createMock(FlashBagInterface::class);
$flashBag->method('getName')->willReturn('name');
$flashBag->method('getStorageKey')->willReturn('storageKey');
$request = new Request();
$request->setSession(new Session(new MockArraySessionStorage(), null, $flashBag));
$requestStack = new RequestStack();
Expand Down
11 changes: 5 additions & 6 deletions tests/Integration/Mock/ConsecutiveTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@

namespace DR\PHPUnitExtensions\Tests\Integration\Mock;

use DR\PHPUnitExtensions\Mock\ConsecutiveParameters;
use DR\PHPUnitExtensions\Tests\Resources\Mock\ConsecutiveMock;
use DR\PHPUnitExtensions\Tests\Resources\Mock\MockInterface;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\CoversFunction;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;

use function DR\PHPUnitExtensions\Mock\consecutive;

#[CoversClass(ConsecutiveParameters::class)]
#[CoversFunction('DR\PHPUnitExtensions\Mock\consecutive')]
/**
* @covers \DR\PHPUnitExtensions\Mock\ConsecutiveParameters
* @covers \DR\PHPUnitExtensions\Mock\consecutive
*/
class ConsecutiveTest extends TestCase
{
public function testConsecutiveSingle(): void
Expand Down Expand Up @@ -59,7 +58,7 @@ public function testConsecutiveMinimumOfOneArguments(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('consecutive() is expecting at least 1 or more arguments for invocation');
consecutive([123], []);
consecutive([], []);
}

public function testConsecutiveInvokeMoreThanExpected(): void
Expand Down
5 changes: 3 additions & 2 deletions tests/Integration/Symfony/Controller/FormControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,16 @@ public function testInvoke(): void

public function testInvokeInvalid(): void
{
$formView = new FormView();
$request = new Request();
$this->expectCreateForm(FormType::class)
->handleRequest($request)
->isSubmittedWillReturn(true)
->isValidWillReturn(false)
->createViewWillReturn(new FormView())
->createViewWillReturn($formView)
->getWillReturn(['name' => 'foobar']);

$this->expectRender('form.html.twig', ['form' => new FormView()], 'FormView');
$this->expectRender('form.html.twig', ['form' => $formView], 'FormView');

static::assertSame('FormView', ($this->controller)($request)->getContent());
}
Expand Down
2 changes: 1 addition & 1 deletion tests/Resources/Symfony/Controller/FormController.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ public function __invoke(Request $request): Response

$form->get('name');

return $this->render('form.html.twig', ['form' => $form]);
return $this->render('form.html.twig', ['form' => $form->createView()]);
}
}