Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPunit: Testing memory usage or running time in assert statements

Tags:

phpunit

I know that phpunit provides memory usage and execution time during test, but is there a way to use these data within an assert statement?

For example, say for example I want to assert if the consumed usage is greater than or equal a specified memory or running time. I search the net as well as the phpunit manuals and can' get an exact information.

Thanks for any tips.

like image 687
Emerson Maningo Avatar asked Feb 17 '23 01:02

Emerson Maningo


2 Answers

To run asserts on execution time and used memory you can use phpunit_stopwatch_annotations package. It provides it's own TestCase class, which add support for special annotations (@executionTime and @memoryUsage) for your tests methods.

How to use phpunit_stopwatch_annotations:

  1. Extend your TestCase class from StopwatchAnnotations\TestCase

    class ExampleTest extends \StopwatchAnnotations\TestCase

  2. Start using annotations by writing

    @executionTime time_in_milliseconds

    or

    @memoryUsage memory_in_bytes

    in docblock before your methods. Execution time and memory usage will be asserted automatically after each test.

like image 91
usernam3 Avatar answered Apr 20 '23 01:04

usernam3


Maybe I'm thinking in a wrong direction, but why not try something like this?

class memTest extends PHPUnit_Framework_TestCase {
    public function testMemory() {
        $this->assertGreaterThanOrEqual(4194304, memory_get_usage());
    }
}

Just use your desired assumption specifier (here: assertGreaterThanOrEqual) and check your desired value against memory_get_usage().

In my case the output looks like this:

>phpunit unittests\memtest.php
PHPUnit 3.7.15 
F

Time: 0 seconds, Memory: 1.75Mb

There was 1 failure:

1) memTest::testMemory
Failed asserting that 1503768 is equal to 4194304 or is greater than 4194304.

mypath\memtest.php:5

FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
like image 28
Bjoern Avatar answered Apr 20 '23 01:04

Bjoern