Skip to content

Commit

Permalink
Merge pull request #6 from richcongress/v1.0.2
Browse files Browse the repository at this point in the history
V1.0.2
  • Loading branch information
NicolasGuilloux authored Feb 28, 2020
2 parents d7d2c3e + 4009530 commit c70ef65
Show file tree
Hide file tree
Showing 39 changed files with 1,097 additions and 385 deletions.
27 changes: 24 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,28 @@
## Version 1.0.2

#### Bug fix

- Fix bad annotation checking for the container.
- Fix some documentation issue again.
- Handles errors for the AbstractCommand.
- Fix CommandTestCase bugs related to the usage of Helpers withing the command.
- Fix not mocked services during the fixture loading.
- Fix Fixtures creation when the property is inherited.


#### New features

- Add handy functions for the fixture creation.
- Add the `DATE_FORMAT` function to the SQLite language that behave like MySQL function.
- Add better `ConnectionFactory`.
- Add the `buildObject` function for all tests.



## Version 1.0.1

#### Bug fix

- Fix composer annotation autoloading
- Fix inspector errors and code cleaning
- Fix some documentation issue
- Fix composer annotation autoloading.
- Fix inspector errors and code cleaning.
- Fix some documentation issue.
67 changes: 63 additions & 4 deletions DataFixture/AbstractFixture.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ abstract class AbstractFixture extends Fixture implements DataFixtureInterface
*/
protected $manager;

/**
* @var integer
*/
protected $count = 0;

/**
* Loads the fixtures. All persisted data will be flushed at the end of the function.
*
Expand All @@ -40,9 +45,7 @@ abstract protected function loadFixtures(): void;
public function load(ObjectManager $manager): void
{
$this->manager = $manager;

$this->loadFixtures();

$manager->flush();
}

Expand All @@ -56,15 +59,71 @@ public function load(ObjectManager $manager): void
protected function createObject($references, string $class, array $data)
{
$object = self::buildObject($class, $data);
$this->referenceAndPersist($references, $object);

return $object;
}

/**
* @param string|array $references
* @param array $data
*
* @return object|mixed
*/
protected function createFromDefault($references, array $data = [])
{
$object = $this->generateDefaultEntity();

self::setValue($object, 'id', null);
self::setValues($object, $data);
$this->referenceAndPersist($references, $object);

return $object;
}

/**
* @param string|object $base
* @param string|array $references
* @param array $data
*
* @return object|mixed
*/
protected function createFrom($base, $references, array $data = [])
{
$object = \is_string($base)
? clone $this->getReference($base)
: clone $base;

self::setValue($object, 'id', null);
self::setValues($object, $data);
$this->referenceAndPersist($references, $object);

return $object;
}

/**
* @return object|mixed
*/
protected function generateDefaultEntity()
{
throw new \LogicException('You must override "generateDefaultEntity" to generate the default entity.');
}

/**
* @param string|array $references
* @param object $object
*
* @return void
*/
private function referenceAndPersist($references, $object): void
{
foreach ((array) $references as $reference) {
$this->setReference($reference, $object);
}

if ($this->manager !== null) {
$this->manager->persist($object);
$this->count++;
}

return $object;
}
}
10 changes: 5 additions & 5 deletions DependencyInjection/RichCongressUnitExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
namespace RichCongress\Bundle\UnitBundle\DependencyInjection;

use Doctrine\Bundle\FixturesBundle\DependencyInjection\CompilerPass\FixturesCompilerPass;
use Liip\TestFixturesBundle\Factory\ConnectionFactory;
use RichCongress\Bundle\UnitBundle\DataFixture\DataFixtureInterface;
use RichCongress\Bundle\UnitBundle\DependencyInjection\Compiler\DataFixturesPass;
use RichCongress\Bundle\UnitBundle\DependencyInjection\Compiler\OverrideServicesPass;
use RichCongress\Bundle\UnitBundle\Doctrine\ConnectionFactory\TestConnectionFactory;
use RichCongress\Bundle\UnitBundle\Doctrine\Functions\Sqlite\DateFormatFunction;
use RichCongress\Bundle\UnitBundle\OverrideService\LoggerStub;
use RichCongress\Bundle\UnitBundle\OverrideService\OverrideServiceInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
Expand Down Expand Up @@ -61,7 +62,7 @@ public function prepend(ContainerBuilder $container): void

$container->setParameter(
'doctrine.dbal.connection_factory.class',
ConnectionFactory::class
TestConnectionFactory::class
);

$container->prependExtensionConfig(
Expand All @@ -70,11 +71,10 @@ public function prepend(ContainerBuilder $container): void
'dbal' => [
'driver' => 'pdo_sqlite',
'user' => 'test',
'dbname' => 'test',
'path' => '%kernel.cache_dir%/__DBNAME__.db',
'path' => '%kernel.cache_dir%/test.db',
'url' => null,
'memory' => false,
]
],
]
);
}
Expand Down
2 changes: 2 additions & 0 deletions Docs/Annotations.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ To use `@WithContainer`, add it to the class PHP Doc or the test PHP Doc. It wil

- `getManager()`: Returns the default EntityManager from the default container.

- `getService()`: Returns the desired service from the default container.

- `executeCommand()`: Execute a command using the default container and returns the display.

- `mockService()`: Replace the target service with the mentioned service for the specified container or the default container as a fallback. If the service is an object, it will just replace it. If the service is a string, it will create a `Mockery\Mock` of it. If no mock service is set, it will try to mock the overriden service.
Expand Down
18 changes: 17 additions & 1 deletion Docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,20 @@ This is a list of default stubs provided by the unit-bundle. Find out the availa

- `test_roles`

This is a list of available roles for the DataProvider. Check out the [documentation](RolesProvider.md) to learn more about this feature.
This is a list of available roles for the DataProvider. Check out the [documentation](RolesProvider.md) to learn more about this feature.



## Enable Doctrine functions

The Unit bundle provides SQLite functions that behave like the MySQL one. The following configuration can be add to your doctrine configuration to enable the functions:

```yaml
doctrine:
orm:
entity_managers:
app:
dql:
datetime_functions:
DATE_FORMAT: RichCongress\Bundle\UnitBundle\Doctrine\Functions\Sqlite\DateFormatFunction
```
2 changes: 1 addition & 1 deletion Docs/TestCases.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

In the following TestCase, it is recommanded to avoid overriding `setUp()` and `tearDown()` and to use respectively `beforeTest()` and `afterTest()` instead. This makes sure that no initialization nor finalization action is missing. Moreover, it can insert an action managed by the test case to respect the workflow. For instance, loading the container before the `beforeTest()`.

Moreover, each test case uses from the MockeryPHPUnitIntegration so no need to use the integration trait.
Moreover, each test case uses from the `MockeryPHPUnitIntegration` and the `FixturesCreationTrait` so no need to use the integration trait. It means you can either use Mocks in the test or the `buildObject` function to create an object.

To use a container or fixtures, please follow this [documentation](Annotations.md).

Expand Down
44 changes: 41 additions & 3 deletions Docs/TestFixtures.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ use RichCongress\Bundle\UnitBundle\Tests\Resources\Entity\User;

class LoadUserData extends AbstractFixture
{
public function loadFixtures() : void{
public function loadFixtures() : void
{
self::createObject('user-1', User::class, [
'username' => 'username_1',
'password' => 'unicorn_1',
Expand Down Expand Up @@ -44,7 +45,8 @@ use RichCongress\Bundle\UnitBundle\Tests\Resources\DataFixture\LoadUserData;

class LoadDummyEntityData extends AbstractFixture implements DependentFixtureInterface
{
public function loadFixtures() : void{
public function loadFixtures() : void
{
/** @var User $user */
$user = $this->getReference('user-1');
// ...
Expand All @@ -59,6 +61,36 @@ class LoadDummyEntityData extends AbstractFixture implements DependentFixtureInt
}
```

Moreover, you can copy or use a default entity to build a new entity.

```php
use RichCongress\Bundle\UnitBundle\DataFixture\AbstractFixture;
use RichCongress\Bundle\UnitBundle\Tests\Resources\DataFixture\LoadUserData;

class LoadDummyEntityData extends AbstractFixture
{
public function loadFixtures() : void
{
// Based on the entity returned by generateDefaultEntity
$this->createFromDefault('dummy-entity-1', [
'name' => 'Entity 1',
]);

// Based on the previously created fixture
$this->createFrom('dummy-entity-1', 'dummy-entity-2', [
'name' => 'Entity 2',
]);
}

protected function generateDefaultEntity()
{
return self::buildObject(DummyEntity::class, [
'name' => 'Default Name n°' . $this->count,
'keyname' => \random_int(0, 20),
]);
}
}
```

#### Useful functions

Expand All @@ -70,4 +102,10 @@ In this case, populating an object works also for private and protected properti

- `setValues()`: Populates the input object with the input data.

- `setValue()`: Set the input value of the input property for the input object.
- `setValue()`: Set the input value of the input property for the input object.

- `createFrom()`: Creates a copy of the object or the reference and overrides the properties with the input data, persists it and attaches the input reference on it.

- `createFromDefault()`: Generates an entity from the `generateDefaultEntity` method and overrides its properties with the input data, persists it and attaches the input reference on it.

- `generateDefaultEntity()`: When using `createFromDefault`, the entity returned by this function is used.
50 changes: 50 additions & 0 deletions Doctrine/ConnectionFactory/TestConnectionFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace RichCongress\Bundle\UnitBundle\Doctrine\ConnectionFactory;

use Doctrine\Bundle\DoctrineBundle\ConnectionFactory;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DBALException;

/**
* Class TestConnectionFactory
*
* @package RichCongress\Bundle\UnitBundle\Doctrine\ConnectionFactory
* @author Nicolas Guilloux <[email protected]>
* @copyright 2014 - 2020 RichCongress (https://www.richcongress.com)
*/
class TestConnectionFactory extends ConnectionFactory
{
/**
* Create a connection by name.
*
* @param array $params
* @param Configuration $config
* @param EventManager $eventManager
* @param array $mappingTypes
*
* @return Connection
* @throws DBALException
*/
public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = []): Connection
{
$parameters = self::processParameters($params);

return parent::createConnection($parameters, $config, $eventManager, $mappingTypes);
}

/**
* @param array $params
*
* @return array
*/
protected function processParameters(array $params): array
{
$params['dbName'] = $params['dbName'] ?? 'dbTest';
$params['dbName'] .= getenv('TEST_TOKEN');

return $params;
}
}
Loading

0 comments on commit c70ef65

Please sign in to comment.