Showing posts with label PHPUnit. Show all posts
Showing posts with label PHPUnit. Show all posts

Monday, April 30, 2018

PHPConsoleOutput

Simple PHP console output helper.

While using PHPUnit, you may want to output or debug your tests.
Normal echo/print_r/dump only outputs after PHPUnit's output, if at all.
Using ConsoleOutput will echo inline with PHPUnits output,
giving you a better context of your output/debugging.

Usage:
$this->consoleOutput = new ConsoleOutput();

$this->consoleOutput->showWarning('test showWarning');

test showWarning

View on GitHub

Monday, March 12, 2018

PHPUnit exceeds memory limit

If you happen to be stuck running PHPUnit 4.8 or such,
you many run into memory limits when you run a large number of tests.

With PHPUnit 4.8, you can add some extra code to clear out the variables you created during each test, thus saving some memory.

class YourTestCase extends WebTestCase
{
   protected function tearDown()
  {
      echo 'pre reduce memory usage: '.sprintf('%.2fM', memory_get_usage(true)/1024/1024);

      // reduce memory usage
 
      // get all properties of self
      $refl = new \ReflectionObject($this);
      foreach ($refl->getProperties() as $prop) {
          // if not phpunit related or static
          if (!$prop->isStatic() && 0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) {
              // make accessible and set value to free memory
              $prop->setAccessible(true);
              $prop->setValue($this, null);
          }
      }
      echo 'post reduce memory usage: '.sprintf('%.2fM', memory_get_usage(true)/1024/1024);

      parent::tearDown();
  }
}

Reference
https://stackoverflow.com/questions/13537545/clear-memory-being-used-by-php    

Note: Using unset($this) or unset($var) does not immediately free the variable from memory.  However, setting $this = null or $var = null immediately assigns the value null, which uses less memory than the object, string, or other value that was set.  You could also use the value of 0 or "" or anything really, just null is short and sweet and infers the intent of the value being unset.

Related extra
You can also increase the allowed memory usage in your test.

class YourTestCase extends WebTestCase
{
    public function setUp()
    {
        ini_set('memory_limit', '512M');

        parent::setUp();
    }
}

End of document. Thanks for reading.