Symfony and PhpUnit memory leak

We have memory leak problems loading Doctrine in our phpunit tests

Running Symfony documentation: http://symfony.com/doc/2.7/cookbook/testing/doctrine.html we wrote this test:

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; class memoryleakTest extends KernelTestCase { private $em; protected function setUp() { self::bootKernel(); $this->em = static::$kernel->getContainer() ->get('doctrine') ->getManager(); } protected function tearDown() { parent::tearDown(); $this->em->close(); } function testEEE1() { } function testEEE2() { } function testEEE3() { } function testEEE4() { } function testEEE5() { } function testEEE6() { } function testEEE7() { } function testEEE8() { } function testEEE9() { } function testEEE10() { } function testEEE11() { } function testEEE12() { } function testEEE13() { } function testEEE14() { } function testEEE15() { } function testEEE16() { } } 

we got this result (php_memory_usage between brackets):

 testEEE1: . (42M) testEEE2: . (42.7M) testEEE3: . (43.3M) testEEE4: . (44M) testEEE5: . (44.8M) testEEE6: . (45.5M) testEEE7: . (46.1M) testEEE8: . (46.8M) testEEE9: . (47.4M) testEEE10: . (48.1M) testEEE11: . (48.7M) testEEE12: . (49.4M) testEEE13: . (50.1M) testEEE14: . (50.7M) testEEE15: . (51.4M) testEEE16: . (52M) 

If we remove the doctrine manager download in the setup, we got (32.7 M) for each test

Is this the right way to offload the doctrine after each test in the gap function?

+7
symfony phpunit doctrine
source share
3 answers

The complete solution, as found here: https://github.com/symfony/symfony/issues/18236

For each service used in the phpunit test, you must free it by setting null to a variable if you want the garbage collector to free memory.

 protected function tearDown() { parent::tearDown(); $this->em->close(); $this->em=null; gc_collect_cycles(); } 
+5
source share

To make this even easier for you, you can have BaseTestCase.php with a break function and put it inside:

 // Remove properties defined during the test $refl = new \ReflectionObject($this); foreach ($refl->getProperties() as $prop) { if (!$prop->isStatic() && 0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) { $prop->setAccessible(true); $prop->setValue($this, null); } } 

This piece of code will save you some headaches :)

+1
source share

This is not a memory leak, just a normal thread, because you load the kernel 16 times.

Just try adding gc_collect_cycles(); into your tearDown() method, and you will see that memory usage has decreased. Alternatively, you can set memory_limit to 50M and you will see that gc works automatically

0
source share

All Articles