core icon indicating copy to clipboard operation
core copied to clipboard

ApiTestCase can lead to several kernels (and therefore several entity managers and so on)

Open Niolak opened this issue 1 year ago • 1 comments

API Platform version(s) affected: 3.2.14

Description
ApiTestCase::createClient always creates a new kernel. If you need services in your test to create the context with static::getContainer()->get(MyService::class);, two kernels will be created, which leads to several entity managers.

How to reproduce

class TransmissionActionTest extends ApiTestCase
{
    public function testSomething(): void
    {
      $myService = static::getContainer()->get(MyService::class); // Here, the kernel is booted via getContainer
      $myService->createAContextForTheTest();
      
      $response = static::createClient()->request('POST', '/my-action'); // Here, a 2nd kernel is created
      
      // example of what could go wrong next
      $myRepo = static::getContainer()->get(MyResourceRepository::class);
      $resourceCreatedByTheAction = $myRepo->findOneBy(['created-by-my-action' => true]); // not the same entitymanager as the one used by the request
      $this->assertNotNull($resourceCreatedByTheAction); // failure
    }
}

(I've simplified the example for readability: I'm not sure that findOneBy would return null on such a simple example. The fact remains that the wrong entitymanager is used, which can be a problem in some cases.)

Possible Solution
In ApiTestCase::createClient(), create the kernel only if not booted. Replace

$kernel = static::bootKernel($kernelOptions);

by

$kernel = static::$booted ? static::$kernel : static::bootKernel($kernelOptions);

I even think that createClient should not create the kernel (dependency injection principle) but then the change would be a breaking change.

Niolak avatar Aug 14 '24 07:08 Niolak

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Oct 17 '24 00:10 stale[bot]