Coder Social home page Coder Social logo

alicebundle's Introduction

AliceBundle

A Symfony bundle to manage fixtures with nelmio/alice and fzaninotto/Faker.

The database support is done in FidryAliceDataFixtures. Check this project to know which database/ORM is supported.

Warning: this is the documentation for HautelookAliceBundle 2.0. If you want to check the documentation for 1.x, head this way.

Package version Build Status SensioLabsInsight Dependency Status Scrutinizer Code Quality Code Coverage Slack

When to use this bundle?

HautelookAliceBundle changed a lot, it first was acting as a simple bundle for nelmio/alice, it then started to ship some additional features to enrich it.

HautelookAliceBundle 1.x was the first milestone reaching a certain level of maturity in its usage:

  • Easily load a set of fixtures from a command
  • Being able to define different sets of fixtures for multiple environments
  • Customize the data generation with custom Faker providers
  • Customize the loading behaviour with processors

HautelookAliceBundle 2.x changes a lot, although not so much. In 1.x, a lot of complexity was brought in the bundle due to nelmio/alice 2.x limitations and were at best workarounds (like the lack of handling of circular references). A lot of that complexity has been pushed back to nelmio/alice 3.x which has a much more flexible design. As a result:

  • nelmio/alice 3.x allows you to easily create PHP objects with random data in an elegant way
  • FidryAliceDataFixtures is a persistence layer for nelmio/alice 3.x. If you need to persist the loaded objects, it is the package you need. It provides you the flexibility to be able to purge the data between each loadings or wrap the loading in a transaction for your tests for example to simply rollback once the test is finished instead of calling an expansive purge.
  • hautelook/alice-bundle 2.x provides high-level features including fixtures discovery (find the appropriate files and load them), and helpers for database testing. If you just need to load specific sets of files for your tests, FidryAliceDataFixtures is enough.

Documentation

  1. Install
  2. Basic usage
  3. Database testing
  4. Advanced usage
    1. Enabling databases
    2. Environment specific fixtures
    3. Fixtures parameters
      1. Alice parameters
      2. Application parameters
    4. Use service factories
    5. Load fixtures in a specific order
      1. Load fixtures in a specific order
      2. Persisting the classes in a specific order
    6. Validation
  5. Custom Faker Providers
  6. Custom Alice Processors
  7. Resources

Installation

With Symfony Flex (recommended):

# If you do not have Doctrine installed yet:
composer require doctrine-orm

composer require --dev hautelook/alice-bundle

You're ready to use AliceBundle, and can jump to the next section!

Without Flex you will have to install doctrine/orm and register the bundles accordingly in app/AppKernel.php or wherever your Kernel class is located:

<?php
// app/AppKernel.php

public function registerBundles(): iterable
{
    $bundles = [
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        // ...
        new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
    ];

    if (in_array($this->getEnvironment(), ['dev', 'test'])) {
        //...
        $bundles[] = new Nelmio\Alice\Bridge\Symfony\NelmioAliceBundle();
        $bundles[] = new Fidry\AliceDataFixtures\Bridge\Symfony\FidryAliceDataFixturesBundle();
        $bundles[] = new Hautelook\AliceBundle\HautelookAliceBundle();
    }

    return $bundles;
}

Configure the bundle to your needs, for example:

# config/packages/dev/hautelook_alice.yaml

hautelook_alice:
    fixtures_path: 'fixtures' # Path to which to look for fixtures relative to the project directory or the bundle path. May be a string or an array of strings.
    root_dirs:
        - '%kernel.root_dir%'
        - '%kernel.project_dir%'

If you are using a non-flex architecture, you may want to use Resources/fixtures instead of fixtures.

Basic usage

Assuming you are using Doctrine, make sure you have the doctrine/doctrine-bundle and doctrine/data-fixtures packages installed.

Then create a fixture file in one of the following location:

  • fixtures if you are using flex
  • app/Resources/fixtures if you have a non-flex bundle-less Symfony application
  • src/AppBundle/Resources/fixtures or any bundle under which you want to place the fixtures
# fixtures/dummy.yaml

App\Entity\Dummy:
    dummy_{1..10}:
        name: <name()>
        related_dummy: '@related_dummy*'
# fixtures/related_dummy.yaml

App\Entity\RelatedDummy:
    related_dummy_{1..10}:
        name: <name()>

Then simply load your fixtures with the doctrine command php bin/console hautelook:fixtures:load.

If you want to load the fixtures of a bundle only, do php bin/console hautelook:fixtures:load -b MyFirstBundle -b MySecondBundle.

See more.
Next chapter: Advanced usage

Database testing

The bundle provides nice helpers, inspired by Laravel, dedicated for database testing: RefreshDatabaseTrait, ReloadDatabaseTrait and RecreateDatabaseTrait. These traits allow to easily reset the database in a known state before each PHPUnit test: it purges the database then loads the fixtures.

They are particularly helpful when writing functional tests and when using Panther.

To improve performance, RefreshDatabaseTrait populates the database only one time, then wraps every tests in a transaction that will be rolled back at the end after its execution (regardless of if it's a success or a failure):

<?php

namespace App\Tests;

use Hautelook\AliceBundle\PhpUnit\RefreshDatabaseTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class NewsTest extends WebTestCase
{
    use RefreshDatabaseTrait;

    public function postCommentTest()
    {
        $client = static::createClient(); // The transaction starts just after the boot of the Symfony kernel
        $crawler = $client->request('GET', '/my-news');
        $form = $crawler->filter('#post-comment')->form(['new-comment' => 'Symfony is so cool!']);
        $client->submit($form);
        // At the end of this test, the transaction will be rolled back (even if the test fails)
    }
}

Sometimes, wrapping tests in transactions is not possible. For instance, when using Panther, changes to the database are made by another PHP process, so it wont work. In such cases, use the ReloadDatabase trait. It will purge the DB and load fixtures before every tests:

<?php

namespace App\Tests;

use Hautelook\AliceBundle\PhpUnit\ReloadDatabaseTrait;
use Symfony\Component\Panther\PantherTestCase;

class NewsTest extends PantherTestCase // Be sure to extends KernelTestCase, WebTestCase or PantherTestCase
{
    use ReloadDatabaseTrait;

    public function postCommentTest()
    {
        $client = static::createPantherClient();// The database will be reset after every boot of the Symfony kernel

        $crawler = $client->request('GET', '/my-news');
        $form = $crawler->filter('#post-comment')->form(['new-comment' => 'Symfony is so cool!']);
        $client->submit($form);
    }
}

This strategy doesn't work when using Panther, because the changes to the database are done by another process, outside of the transaction.

Both traits provide several configuration options as protected static properties:

  • self::$manager: The name of the Doctrine manager to use
  • self::$bundles: The list of bundles where to look for fixtures
  • self::$append: Append fixtures instead of purging
  • self::$purgeWithTruncate: Use TRUNCATE to purge
  • self::$connection: The name of the Doctrine connection to use

Use them in the setUpBeforeClass method.

<?php

namespace App\Tests;

use Hautelook\AliceBundle\PhpUnit\RefreshDatabaseTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class NewsTest extends WebTestCase
{
    use RefreshDatabaseTrait;

    public static function setUpBeforeClass()
    {
        self::$append = true;
    }

    // ...
}

Finally, if you're using in memory SQLite for your tests, use RecreateDatabaseTrait to create the database schema "on the fly":

<?php

namespace App\Tests;

use Hautelook\AliceBundle\PhpUnit\RecreateDatabaseTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class NewsTest extends WebTestCase
{
    use RecreateDatabaseTrait;

    // ...
}

Resources

Credits

This bundle was originaly developped by Baldur RENSCH and HauteLook. It is now maintained by Théo FIDRY.

Other contributors.

License

license

alicebundle's People

Contributors

baldurrensch avatar bernardstanislas avatar cacahouwete avatar curry684 avatar dunglas avatar franmomu avatar garypegeot avatar gelolabs avatar greg0ire avatar hjr3 avatar intranettus avatar jjanvier avatar kingcrunch avatar metalrex100 avatar nek- avatar nowiko avatar olix21 avatar pwlb avatar robertfausk avatar rowanparker avatar snebes avatar soullivaneuh avatar soyuka avatar spolischook avatar stof avatar teohhanhui avatar theofidry avatar tifabien avatar vincentchalamon avatar weaverryan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

alicebundle's Issues

There are no commands defined in the "hautelook:fixtures" namespace

Hello,

I've just installed the bundle, and the command php bin/console hautelook:fixtures:load is throwing the error:
There are no commands defined in the "hautelook:fixtures" namespace

It seems that the issue is existing since three months at least:
https://stackoverflow.com/questions/76563869/error-in-loading-fixtures-on-symfony-with-hautelook-alicebundle

`
[WARNING] Some commands could not be registered:

In DoctrineOrmLoadDataFixturesCommand.php line 41:

[TypeError]
Argument 2 passed to Hautelook\AliceBundle\Console\Command\Doctrine\DoctrineOrmLoadDataFixturesCommand::__construct() must be an i
nstance of Doctrine\Common\Persistence\ManagerRegistry, instance of Doctrine\Bundle\DoctrineBundle\Registry given, called in /app/
var/cache/dev/ContainerX0vuky0/getHautelookAlice_Console_Command_Doctrine_DoctrineOrmLoadDataFixturesCommandService.php on line 23

Exception trace:
at /app/vendor/hautelook/alice-bundle/src/Console/Command/Doctrine/DoctrineOrmLoadDataFixturesCommand.php:41
Hautelook\AliceBundle\Console\Command\Doctrine\DoctrineOrmLoadDataFixturesCommand->__construct() at /app/var/cache/dev/ContainerX0vuky0/getHautelookAlice_Console_Command_Doctrine_DoctrineOrmLoadDataFixturesCommandService.php:23
ContainerX0vuky0\getHautelookAlice_Console_Command_Doctrine_DoctrineOrmLoadDataFixturesCommandService::do() at /app/var/cache/dev/ContainerX0vuky0/App_KernelDevDebugContainer.php:426
ContainerX0vuky0\App_KernelDevDebugContainer->load() at /app/vendor/symfony/dependency-injection/Container.php:238
Symfony\Component\DependencyInjection\Container->make() at /app/vendor/symfony/dependency-injection/Container.php:220
Symfony\Component\DependencyInjection\Container->get() at /app/vendor/symfony/framework-bundle/Console/Application.php:191
Symfony\Bundle\FrameworkBundle\Console\Application->registerCommands() at /app/vendor/symfony/framework-bundle/Console/Application.php:74
Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /app/vendor/symfony/console/Application.php:171
Symfony\Component\Console\Application->run() at /app/bin/console:43`

PHP 7.4
Symfony 5.4.27

Thanks!

bin/console hautelook:fixtures:load for only data base test

Hello,
First of all, thanks for the awsome bundle.
I actually use two database in dev mode: one for dev (same as database in production) and other is real data in test.
When I run bin/console hautelook:fixtures:load it purge my database dev.
What I want is it affect only my database test. If there's a way in a config file to do that ?
Thanks a lot

Non exiting service Doctrine\Common\Persistence\ManagerRegistry

After installing this bundle I keep gettings this error:

Argument 2 passed to Hautelook\AliceBundle\Console\Command\Doctrine\DoctrineOrmLoadDataFixturesCommand::__construct() must be an instance of Doctrine\Common\Persistence\ManagerRegistry, instance of Doctrine  
  \Bundle\DoctrineBundle\Registry given, called in /api/var/cache/dev/ContainerQDxT5xx/App_KernelDevDebugContainer.php on line 4774 

Using symfony 5.4 and doctrine library versions

doctrine/annotations                    1.13.3  Docblock Annotations Parser
doctrine/cache                          2.2.0   PHP Doctrine Cache library is a popular cache implementation that supports many different drivers such as redis, memcache, apc, mongodb and others.
doctrine/collections                    1.6.8   PHP Doctrine Collections library that adds additional functionality on top of PHP arrays.
doctrine/common                         3.3.0   PHP Doctrine Common project is a library that provides additional functionality that other Doctrine projects depend on such as better reflection support, pr...
doctrine/data-fixtures                  1.5.3   Data Fixtures for all Doctrine Object Managers
doctrine/dbal                           3.3.7   Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.
doctrine/deprecations                   v1.0.0  A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.
doctrine/doctrine-bundle                2.7.0   Symfony DoctrineBundle
doctrine/doctrine-fixtures-bundle       3.4.2   Symfony DoctrineFixturesBundle
doctrine/doctrine-migrations-bundle     3.2.2   Symfony DoctrineMigrationsBundle
doctrine/event-manager                  1.1.1   The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.
doctrine/inflector                      2.0.4   PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/lowercase and singular/plural forms of words.
doctrine/instantiator                   1.4.1   A small, lightweight utility to instantiate objects in PHP without invoking their constructors
doctrine/lexer                          1.2.3   PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.
doctrine/migrations                     3.5.1   PHP Doctrine Migrations project offer additional functionality on top of the database abstraction layer (DBAL) for versioning your database schema and easil...
doctrine/orm                            2.12.3  Object-Relational-Mapper for PHP
doctrine/persistence                    3.0.2   The Doctrine Persistence project is a set of shared interfaces and functionality that the different Doctrine object mappers share.
doctrine/sql-formatter                  1.1.3   a PHP SQL highlighting library
symfony/doctrine-bridge                 v5.4.10 Provides integration for Doctrine with various Symfony components

Problem was , that the project is using php 7.4 and the max library version i could install was 2.6.

Getting an entity inside a test when RefreshDatabaseTrait is used, strange behaviour?

Here is an example test case. When invoking POST /api/users a new user in inserted into the database. I'd like to check for the result but... $obj1 is always null while $obj2 it's the actual instance. Why so?

It's like getting a fresh instance of Doctrine and the repository will return the instance, while storing a reference of the entity manager or the repository prior to run the test will return slate data.

Am I wrong?

<?php

namespace App\Tests\Entity;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use App\Entity\User;
use Hautelook\AliceBundle\PhpUnit\RefreshDatabaseTrait;

class UserTest extends ApiTestCase
{
    use RefreshDatabaseTrait;

    /** @var \Doctrine\ORM\EntityManager */
    private $entityManager;

    /** @var \Doctrine\Persistence\ObjectRepository */
    private $repository;

    public function testSomething(): void
    {
        $response = static::createClient()->request('POST', '/api/users', [
            'headers' => [
                'accept' => 'application/json',
            ],
            'json' => [
                'username' => 'foo',
                'plainPassword' => 'bar'
            ],
        ]);

        $this->assertResponseIsSuccessful();

        $data = $response->toArray();
        $this->assertIsArray($data);
        $this->assertNotEmpty($data['id']);
        $this->assertEquals($data['username'], 'foo');

        $obj1 = $this->repository->findOneBy(['id' => $data['id']]);
        var_dump($obj1); // null

        $obj2 = static::getContainer()->get('doctrine')->getRepository(User::class)->findOneBy(['id' => $data['id']]);
        var_dump($obj2); // object
    }

    protected function setUp(): void
    {
        $this->entityManager = static::getContainer()->get('doctrine')->getManager();
        $this->repository = $this->entityManager->getRepository(User::class);
    }

    protected function tearDown(): void
    {
        $this->entityManager->clear();
        $this->entityManager = null;
        $this->repository = null;
    }
}

Complete reference to random data functions + related pre-existing entity in database

Hello, where can I find a complete reference to functions like <firstName()>, <lastName()>, <sentence()> etc.? I'm unable to find it in the docs.

And... Is there a function to reference a related pre-existing entity in database? This entity is not loaded in any fixture but already exists in database and has a relation to current entity in fixture.

Thank you.

`UnitOfWork` may not be empty at the start of test in case of database population

Currently, the database population using traits does not include a cleanup of the identity map within Doctrine's UnitOfWork.

It causes UnitOfWork to be in a "dirty" state by the time of running the test method and may cause unexpected side effects in the test.

In my application, I have a test that fails because of entity information that is left during the database population, so the case is practical.

The solution is simple: a call of EntityManager::clear() needs to be added after loading of the fixtures

static::$fixtures = $container->get('hautelook_alice.loader')->load(
new Application(static::$kernel), // OK this is ugly... But there is no other way without redesigning LoaderInterface from the ground.
$container->get('doctrine')->getManager(static::$manager),
static::$bundles,
static::$kernel->getEnvironment(),
static::$append,
static::$purgeWithTruncate,
static::$shard
);

I need help with this error

Im getting this error and I don't know why

Fidry\AliceDataFixtures\Bridge\Doctrine\Persister\ObjectManagerPersister::getMetadata(): Argument #2 ($object) must be of type object, array given, called in /srv/api/vendor/theofidry/alice-data-fixtures/src/Bridge/Doctrine/Persister/ObjectManagerPersister.php on line 164

Call to a member function getSQLLogger() on null

Hi,

I have recently updated symfony and some packages and when I try to launch fixtures with console h:f:l --env=test --no-interaction --purge-with-truncate the folowing error occurs :

app.INFO: fixtures found {"files":["...x.yaml"]} []
app.INFO: Purging database with purge mode "TRUNCATE_MODE". [] []
app.INFO: Loading fixtures. [] []
app.INFO: Pre-processing objects. [] []
app.INFO: Flushing objects. [] []
php.CRITICAL: Uncaught Error: Call to a member function getSQLLogger() on null {"exception":"[object] (Error(code: 0): Call to a member function getSQLLogger() on null at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:1513)"} []

I am using :

  • Symfony 5.4
  • Doctrine\ORM 2.10
  • hautelook\alice-bundle 2.9

fixtures.yaml :

hautelook_alice:
  fixtures_path: 'fixtures'
  root_dirs:
    - '%kernel.project_dir%'

If I remove the logger part in /vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php::executeStatement() which is causing the error everything works fine.

Let me know if you need further information.

Thanks you

Fixture directory structure

Hello,

I've struggled with this bundle because i've created a folder structure under the "fixtures" directory.

fixtures/user/user.yaml
fixtures/user/user_type.yaml
// etc

But after digging it seems that I can not do that because of :

$files = SymfonyFinder::create()->files()->in($fullPaths)->depth(0)->name('/.*\.(ya?ml|php)$/i');

In vendor/hautelook/alice-bundle/src/Locator/EnvDirectoryLocator.php:85

Is there a special reason to limit the depth ?

I will put my files at the root dir

Fetch() method does not exist anymore with DBAL3

Since upgrading my symfony 5.4 app to DBAL 3, I get this error when loading fixtures :
bin/console hautelook:fixtures:load -n --env test --purge-with-truncate

In ObjectToLegacyProperty.php line 40:
                                                                                           
  Attempted to call an undefined method named "fetch" of class "Doctrine\DBAL\Statement"

Indeed, method has been removed, see doc here.

I'm using those versions of doctrine related packages :

doctrine/data-fixtures                  1.5.3              Data Fixtures for all Doctrine Object Managers
doctrine/dbal                           3.3.6              Powerful PHP database abstraction layer (DBAL) with many features for d...
doctrine/doctrine-bundle                2.6.3              Symfony DoctrineBundle
doctrine/doctrine-migrations-bundle     3.2.2              Symfony DoctrineMigrationsBundle
doctrine/orm                            2.12.2             Object-Relational-Mapper for PHP
doctrine/persistence                    2.5.3              The Doctrine Persistence project is a set of shared interfaces and func...
gedmo/doctrine-extensions               v3.7.0             Doctrine2 behavioral extensions
symfony/doctrine-bridge                 v5.4.9   

Drop compatibility with unsupported versions of Symfony and PHP

Currently the bundle allows for very old and unsupported versions of Symfony. Is there any benefit to dropping that, especially since we'll be adding Symfony 6 support (#3)

    "symfony/finder": "^3.4 || ^4.0 || ^5.0",
    "symfony/framework-bundle": "^3.4.24 || ^4.0 || ^5.0",

Maybe there's no benefit to dropping support for before 4.4, but I'd hate to see improvements being held back because of support for unsupported versions.

Ditto on support for 7.3, so the bundle can use some features from 7.4.

Thoughts?

You have requested a non-existent service "hautelook_alice.loader".

Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "hautelook_alice.loader".

/prj/vendor/symfony/dependency-injection/Container.php:289
/prj/vendor/symfony/dependency-injection/Container.php:231
/prj/vendor/symfony/framework-bundle/Test/TestContainer.php:106
/prj/vendor/hautelook/alice-bundle/src/PhpUnit/BaseDatabaseTrait.php:67
/prj/vendor/hautelook/alice-bundle/src/PhpUnit/RefreshDatabaseTrait.php:34

RefreshDatabaseTrait is not executed in time

I was trying to use RefreshDatabaseTrait for API testing but for some reason the assert gave me 404.

<?php

namespace App\Tests\Functional;

use App\test\CustomApiTestCase;
use Hautelook\AliceBundle\PhpUnit\RefreshDatabaseTrait;


class UserResourceTest extends CustomApiTestCase
{
    use RefreshDatabaseTrait;

    public function testGetItemUser(): void
    {
        $client = static::createClient();
        
        $user = $this->createUser($client, '[email protected]', 'Test_password_1!', 'Test User 1');

        $client->request('GET', '/api/users/' . $user->getId());
        $this->assertResponseStatusCodeSame(401, 'GET item (no auth)');
    }
}

After a long time of testing, I found out that with this code only the first assert fails.

    public function testGetItemUser(): void
    {
        $client = static::createClient();

        $user = $this->createUser($client, '[email protected]', 'Test_password_1!', 'Test User 1');
        
        $client->request('GET', '/api/users/' . $user->getId());
        $this->assertResponseStatusCodeSame(401, 'GET item (no auth 1)');

        $client->request('GET', '/api/users/' . $user->getId());
        $this->assertResponseStatusCodeSame(401, 'GET item (no auth 2)');
    }

It feels like the database refresh is not finishing in time so that the first user is deleted

1. database refresh start
2. Create User
3. database refresh end

Allow Doctrine ORM v3

Currently this bundle prevents upgrading to ORM v3. Can you pease look into that?

Clear entity manager

We have an issue with fixtures being loaded before running a test (RefreshDatabaseTrait). Some entity does not update the inverse side at runtime ...

In prod env the collection on the inverse side is lazy loaded, so no issues ...

In test env the collection remains empty, causing the test to fail (but only if it runs first, eg. bin/phpunit SpecificTest.php).

Invoking $container->get('doctine')->getManager()->clear() after fixtures are loaded solves it. IMHO this makes the testsuite more deterministic (i only noticed when running some test isolated).

Would you consider a PR for that?

RefreshDatabaseTrait is deprecated

Hi,

I am having the following error when using RefreshDatabaseTrait in my tests suite:
Doctrine\ORM\Exception\NotSupported: Feature was deprecated in doctrine/dbal 2.x and is not supported by installed doctrine/dbal:3.x, please see the doctrine/deprecations logs for new alternative approaches.

Any idea what could be a good workaround?

Thanks!

Load only specific fixtures files in test

Hi,

First of all, thank you for the awesome bundle!

I know that fixtures files are loaded automatically based on the hautelook_alice.yaml config and you can load different fixture definitions per environment but when there is a lot of logic putting all fixture definitions into a single yaml file can be a bit hard to manage.

Is there a way to load only specific yaml/php fixtures files for in a test class?

I'm specifically looking for something like this:

/**
 * Class ProductControllerTest
 *
 * @package App\Tests\Controller
 */
class ProductControllerTest extends WebTestCase
{

    use ReloadDatabaseTrait;

    /**
     * {@inheritdoc}
     */
    protected function setUp(): void
    {
        // define fixtures files to load.
        self::$fixtures = ['auth.yaml', 'ordered_products.yaml'];

        parent::setUp(); // populates database with fixtures from self::$fixtures only.
    }

...
}

Thanks in advance!

Deprecation warning "Nesting transactions without enabling savepoints is deprecated."

With Doctrine/DBAL 3.4 they deprecated transaction nesting without enabling savepoints. Resulting in a deprecation warning when running tests using the RefreshDatabaseTrait.

Warning:

1x: Nesting transactions without enabling savepoints is deprecated.
Call Doctrine\DBAL\Connection::setNestTransactionsWithSavepoints(true) to enable savepoints. (Connection.php:1380 called by UnitOfWork.php:426, https://github.com/doctrine/dbal/pull/5383, package doctrine/dbal)
    1x in NewWholesaleGasMessageHandlerTest::testValidBALLNotificationForExistingMeasuringPoint from App\Tests\MessageHandler

It seems we need to explicitly enable this in the trait in order to workarround this warning. However i am not fully sure what kind of implications this might have.

I would suggest the following change in RefreshDatabaseTrait.php

Replace

$container->get('doctrine')->getConnection(static::$connection)->beginTransaction();

With

$conn = $container->get('doctrine')->getConnection(static::$connection);
$conn->setNestTransactionsWithSavepoints(true);
$conn->beginTransaction();

RefreshDatabaseTrait repopulates the database on every new TestCase

Our tests have been running slowly for a while now and I finally got around to looking into it, and I think its because the variable $dbPopulated in RefreshDatabaseTrait is always false. Or at least is false on each new class it's instantiated on to. This means it repopulates the database each time it moves to a new TestCase which uses RefreshDatabaseTrait.

If I replace RefreshDatabaseTrait with this:

trait TestTrait
{
    private static int $x = 0;

    protected static function bootKernel(array $options = [])
    {
        $kernel = parent::bootKernel($options);

        if (!static::$x) {
            echo "x = ".self::$x.PHP_EOL;
            static::$x++;
        }
        return $kernel;
    }
}

It just outputs :

x = 0
x = 0
x = 0
x = 0

I'm using PHP 8.1.3, and I think it's because calling a static element on a trait was deprecated in 8.1.0.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.