Code Monkey home page Code Monkey logo

phpunit-speedtrap's Introduction

phpunit-speedtrap

Integrate

SpeedTrap reports on slow-running PHPUnit tests right in the console.

Many factors affect test execution time. A test not properly isolated from variable latency (database, network, etc.) and even basic load on the test machine will cause test execution times to fluctuate.

SpeedTrap helps identify slow tests but cannot explain why those tests are slow. Consider using Blackfire.io to profile the test suite to specifically identify slow code.

Screenshot of terminal using SpeedTrap

Installation

SpeedTrap is installed using Composer. Add it as a require-dev dependency:

composer require --dev johnkary/phpunit-speedtrap

Usage

Enable with all defaults by adding the following code to your project's phpunit.xml file:

<phpunit bootstrap="vendor/autoload.php">
...
    <extensions>
        <extension class="JohnKary\PHPUnit\Extension\SpeedTrap" />
    </extensions>
</phpunit>

Now run the test suite. If one or more test executions exceed the slowness threshold (500ms by default), SpeedTrap will report on those tests in the console after all tests have completed.

Config Parameters

SpeedTrap also supports these parameters:

  • slowThreshold - Number of milliseconds when a test is considered "slow" (Default: 500ms)
  • reportLength - Number of slow tests included in the report (Default: 10 tests)

Each parameter is set in phpunit.xml:

<phpunit bootstrap="vendor/autoload.php">
    <!-- ... other suite configuration here ... -->

    <extensions>
        <extension class="JohnKary\PHPUnit\Extension\SpeedTrap">
            <arguments>
                <array>
                    <element key="slowThreshold">
                        <integer>500</integer>
                    </element>
                    <element key="reportLength">
                        <integer>10</integer>
                    </element>
                </array>
            </arguments>
        </extension>
    </extensions>
</phpunit>

Custom slowness threshold per-test case

Some projects have a few complex tests that take a long time to run. It is possible to set a different slowness threshold for individual test cases.

The annotation @slowThreshold can set a custom slowness threshold for each test case. This number may be higher or lower than the default threshold and is used instead of the default threshold for that specific test.

class SomeTestCase extends PHPUnit\Framework\TestCase
{
    /**
     * @slowThreshold 5000
     */
    public function testLongRunningProcess()
    {
        // Code that takes a longer time to execute
    }
}

Setting @slowThreshold 0 will never report that test as slow.

Disable slowness profiling using an environment variable

SpeedTrap profiles for slow tests when enabled in phpunit.xml. But using an environment variable named PHPUNIT_SPEEDTRAP can enable or disable the extension:

$ PHPUNIT_SPEEDTRAP="disabled" ./vendor/bin/phpunit

Use case: Disable profiling in development, but profile with Travis CI

Travis CI is popular for running tests in the cloud after pushing new code to a repository.

Step 1) Enable SpeedTrap in phpunit.xml, but set PHPUNIT_SPEEDTRAP="disabled" to disable profiling when running tests.

<phpunit bootstrap="vendor/autoload.php">
...
    <php>
        <env name="PHPUNIT_SPEEDTRAP" value="disabled" />
    </php>

    <extensions>
        <extension class="JohnKary\PHPUnit\Extension\SpeedTrap" />
    </extensions>
</phpunit>

Step 2) Configure .travis.yml with PHPUNIT_SPEEDTRAP="enabled" to profile for slow tests when running on Travis CI:

language: php

php:
  - 7.3

env:
  - PHPUNIT_SPEEDTRAP="enabled"

Step 3) View the Travis CI build output and read the slowness report printed in the console.

Travis CI Documentation - Environment Variables

Use case: Enable profiling in development, but disable with Travis CI

Step 1) Enable SpeedTrap in phpunit.xml. The slowness report will output during all test suite executions.

<phpunit bootstrap="vendor/autoload.php">
...
    <extensions>
        <extension class="JohnKary\PHPUnit\Extension\SpeedTrap" />
    </extensions>
</phpunit>

Step 2) Configure .travis.yml with PHPUNIT_SPEEDTRAP="disabled" to turn off profiling when running on Travis CI:

language: php

php:
  - 7.3

env:
  - PHPUNIT_SPEEDTRAP="disabled"

Step 3) View the Travis CI build output and confirm the slowness report is not printed in the console.

Use case: Only enable SpeedTrap on demand via command-line

Useful when you only want to profile slow tests once in a while.

Step 1) Setup phpunit.xml to enable SpeedTrap, but disable slowness profiling by setting PHPUNIT_SPEEDTRAP="disabled" like this:

<phpunit bootstrap="vendor/autoload.php">
...
    <php>
        <env name="PHPUNIT_SPEEDTRAP" value="disabled" />
    </php>

    <extensions>
        <extension class="JohnKary\PHPUnit\Extension\SpeedTrap" />
    </extensions>
</phpunit>

Step 2) When executing phpunit from the command-line, enable slowness profiling only for this run by passing the environment variable PHPUNIT_SPEEDTRAP="enabled" like this:

$ PHPUNIT_SPEEDTRAP=enabled ./vendor/bin/phpunit

Using with Symfony Framework

Symfony Framework comes with package symfony/phpunit-bridge that installs its own version of PHPUnit and ignores what is defined in your project's composer.json or composer.lock file. See the PHPUnit versions it installs with command ls vendor/bin/.phpunit/

symfony/phpunit-bridge allows environment variable SYMFONY_PHPUNIT_REQUIRE to define additional dependencies while installing phpunit.

The easiest way to set environment variables for the script simple-phpunit is via phpunit.xml.dist:

<phpunit bootstrap="vendor/autoload.php">
    <php>
        <env name="SYMFONY_PHPUNIT_REQUIRE" value="johnkary/phpunit-speedtrap:^4"/>
        <env name="SYMFONY_PHPUNIT_VERSION" value="9"/>
    </php>

    <extensions>
        <extension class="JohnKary\PHPUnit\Extension\SpeedTrap" />
    </extensions>
</phpunit>

Using the above example, running vendor/bin/simple-phpunit will now install the latest PHPUnit 9 and require the latest phpunit-speedtrap v4.

Development

Follow these steps to add new features or develop your own fork:

# Get source code (or replace with your fork URL)
$ git checkout https://github.com/johnkary/phpunit-speedtrap.git phpunit-speedtrap

# Install dev dependencies
$ cd phpunit-speedtrap
$ composer install

# Run test suite to verify code runs as expected
$ vendor/bin/phpunit

Inspiration

SpeedTrap was inspired by RSpec's --profile option that displays feedback about slow tests.

License

phpunit-speedtrap is available under the MIT License.

phpunit-speedtrap's People

Contributors

carusogabriel avatar daimona avatar duncan3dc avatar dxops avatar engerim avatar fain182 avatar grahamcampbell avatar hkdobrev avatar jakeasmith avatar jeroendedauw avatar johnkary avatar keradus avatar localheinz avatar luispabon avatar mgatner avatar mihaeu avatar mvorisek avatar pascalthesing avatar pscheit avatar samnela avatar sergeyz avatar vincentlaurier 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpunit-speedtrap's Issues

How to Fail Slow Tests?

I enabled the stopOnSlow setting, which appears to halt execution of PHPUnit, and yield a successful response.

Is there a different setting that would cause either the test or the execution of PHPUnit to fail on a slow test? I'd like to enforce our pipeline to straight up not allow slow tests, but I can't seem to find a way to do that out of the box with this package.

Replace Travis CI with GitHub Actions

This library should move to running its test suite using GitHub Actions.

If anyone is familiar with Actions, a PR would be greatly appreciated!

  • PHPUnit test suite runs after new commits are pushed to GitHub
  • Replace Travis CI badge in README

Feature request > format tests times for easier readability

Hello,

I would like to propose adding an option to make easier to read the test times.

So instead of having something like this:

You should really fix these slow tests (>2000ms)...

  1. 18859ms to run x
  2. 16441ms to run y
  3. 12352ms to run z
  4. 2352ms to run z

We could have something like:

You should really fix these slow tests (>2000ms)...

  1. 18.8s to run x
  2. 16.4s to run y
  3. 12.3s to run z
  4. 2352ms to run z

Something similar to Carbon::diffForHumans().

Great job btw!

Use speedtrap as printer

Hey, this is more of a question then a issue, sorry.

I'm trying to configure speedtrap from the command line instead of from the config file.

Mainly since I want it to be a option per run not per every run.

this option doesen't seam to work.

--printer <printer>       TestListener implementation to use.
Could not use "JohnKary\PHPUnit\Listener\SpeedTrapListener" as printer.

Support for PHPUnit 6 and up

Hello,

I would like to have this running on PHPUnit 6.0.8, is it possible to add support for that?

Regards
Steff

Documentation usage example

On the GitHub repository main page currently is the example under "Usage" section:

<phpunit bootstrap="vendor/autoload.php">
...
    <extensions>
        <extension class="JohnKary\PHPUnit\Extension\SpeedTrap" />
    </extensions>
</phpunit>

I tried this code and failed. But this one is worked:

    <listeners>
        <listener class="JohnKary\PHPUnit\Listener\SpeedTrapListener" />
    </listeners>

Can you add support for PHPUnit > 6?

I was trying to install this extension into my project, but I stumbled into this problem

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Conclusion: don't install phpunit/phpunit 6.3.0
- johnkary/phpunit-speedtrap 1.1.x-dev requires phpunit/phpunit >=4.7,<6.0 -> satisfiable by phpunit/phpunit[4.7.x-dev, 4.8.x-dev, 5.0.x-dev, 5.1.x-dev, 5.2.x-dev, 5.3.x-dev, 5.4.x-dev, 5.5.x-dev, 5.6.x-dev, 5.7.x-dev].
- johnkary/phpunit-speedtrap v1.1.0 requires phpunit/phpunit >=4.7,<6.0 -> satisfiable by phpunit/phpunit[4.7.x-dev, 4.8.x-dev, 5.0.x-dev, 5.1.x-dev, 5.2.x-dev, 5.3.x-dev, 5.4.x-dev, 5.5.x-dev, 5.6.x-dev, 5.7.x-dev].
- Can only install one of: phpunit/phpunit[4.8.x-dev, 6.3.0].
- Can only install one of: phpunit/phpunit[5.6.x-dev, 6.3.0].
- Can only install one of: phpunit/phpunit[5.7.x-dev, 6.3.0].
- Can only install one of: phpunit/phpunit[4.7.x-dev, 6.3.0].
- Can only install one of: phpunit/phpunit[5.0.x-dev, 6.3.0].
- Can only install one of: phpunit/phpunit[5.1.x-dev, 6.3.0].
- Can only install one of: phpunit/phpunit[5.2.x-dev, 6.3.0].
- Can only install one of: phpunit/phpunit[5.3.x-dev, 6.3.0].
- Can only install one of: phpunit/phpunit[5.4.x-dev, 6.3.0].
- Can only install one of: phpunit/phpunit[5.5.x-dev, 6.3.0].
- Installation request for phpunit/phpunit (locked at 6.3.0, required as ~6.1) -> satisfiable by phpunit/phpunit[6.3.0].
- Installation request for johnkary/phpunit-speedtrap ^1.1 -> satisfiable by johnkary/phpunit-speedtrap[1.1.x-dev, v1.1.0].

Please tag a version

Using a branch (even aliased with 1.0) leads to cloning this repository instead of downloading a version.
Tagging the current state will allow people to make use of this work easier. If you fear you are not ready yet, use an alpha tag like "1.0.0-alpha.1". This would even allow incompatible changes according to semver.org:

A pre-release version MAY be denoted by appending a hyphen and a series of dot separated identifiers immediately following the patch version. Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes. Pre-release versions have a lower precedence than the associated normal version. A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version. Examples: 1.0.0-alpha, 1.0.0-alpha.1, 1.0.0-0.3.7, 1.0.0-x.7.z.92.

PHPUnit 6.0.10 not working with 1.0.2

Hello,

I guess that 1.0.2 was a patch release to support PHPUnit 6.x so I tried it while migrating.

However, it throws an fatal error:

PHP Fatal error: Interface 'PHPUnit_Framework_TestListener' not found in /home/.../redaxscript/vendor/johnkary/phpunit-speedtrap/src/JohnKary/PHPUnit/Listener/SpeedTrapListener.php on line 9
Warning: Command failed: vendor/bin/phpunit --configuration=phpunit.xml

After that I used "dev-master" for speedtrap and the testing suite worked again.

Updating dependencies (including require-dev)

  • Updating johnkary/phpunit-speedtrap (v1.0.2 => dev-master cbd785f)
    Checking out cbd785f

Slow tests not correctly identified with HHVM

With HHVM 3.12.0:

........                                                            8 / 8 (100%)

You should really fix these slow tests (>50ms)...
 1. 3436ms to run PiHostTest:testCreatesContainer
 2. 45ms to run PiHostTest:testMessageFactoryIsSet
 3. 41ms to run PiHostTest:testAssertHostProviderInstanceIsSet
 4. 41ms to run PiHostTest:testCanRegisterPlugin
 5. 34ms to run PiHostTest:testSetAndGetCacheProvider
 6. 34ms to run PiHostTest:testEventManagerIsCreated
 7. 31ms to run PiHostTest:testAppSettingsIsRegistered
 8. 15ms to run PiHostTest:testExecuteRequestAndWriteResponse

Time: 22.49 seconds, Memory: 19.13Mb

OK (8 tests, 9 assertions)

If i set the limit to 50ms the only slow test from the above report shouldn't be the first?

I know that HHVM support isn't reference but i wanted to be sure as at this moment i'm in doubt if it's reporting the extra execution time from 50ms (50+3436, 50+45, etc) instead of the execution time itself.

Argument example doesn't work

Hey John, thanks for this awesome listener!

I've just stumbled upon a problem that I think I didn't have before (newer PHPUnit version maybe).

Using the following example from your README:

<listener class="JohnKary\PHPUnit\Listener\SpeedTrapListener">
    <arguments>
        <array>
            <element key="slowThreshold"> <!-- Slowness threshold in ms -->
                <integer>500</integer>
            </element>
            <element key="reportLength"> <!-- Number of slow tests to report on -->
                <integer>5</integer>
            </element>
        </array>
    </arguments>
</listener>

I get the following problem

PHP Catchable fatal error:  Argument 1 passed to PHPUnit_Util_XML::xmlToVariable() must be an instance of DOMElement, instance of DOMComment given, called in /opt/lampp/htdocs/movie-manager/vendor/phpunit/phpunit/src/Util/XML.php on line 251 and defined in /opt/lampp/htdocs/movie-manager/vendor/phpunit/phpunit/src/Util/XML.php on line 242

The solution is to simply remove the comments from the example:

<arguments>
    <array>
        <element key="slowThreshold">
            <integer>500</integer>
        </element>
        <element key="reportLength">
            <integer>5</integer>
        </element>
    </array>
</arguments>

So either ignore the comments in your Listener or just remove the comments from the README to avoid this problem when copy & pasting.

Only output slowness report when explicitly enabled

PHPUnit may be configured with runtime options that alter its output or generated reports, such as --coverage-html or --log-junit or --testdox-html

Currently the slowness report is output on every test suite execution when SpeedTrapListener is enabled in phpunit.xml. This may not be desired when running PHPUnit with other options. For example, generating code coverage via --coverage-html is an opt-in runtime option. SpeedTrap should behave similarly.

Instead, the slowness report should only output when at least one of the following is true:

  1. Providing runtime command-line argument: --speedtrap
  2. PHP environment variable PHPUNIT_SPEEDTRAP has a string value of "enabled"

PHP environment variables can be set in php.ini or any method supported by PHP.

PHP environment variables can also be set using phpunit.xml:

<phpunit>
    <php>
        <env name="PHPUNIT_SPEEDTRAP" value="enabled" />
    </php>
</phpunit>

Feedback requested

  1. Are there any other ways we should support opt-in slowness reporting?
  2. What do you think of the name --speedtrap for runtime option? I'm not sure if/how this option's presence can be detected by the listener, but it can probably be done.
  3. What do you think of the name PHPUNIT_SPEEDTRAP for the environment variable? This name scopes it into a fake namespace (PHPUNIT) and specific to this library (SPEEDTRAP).
  4. Suggestions for PHPUNIT_SPEEDTRAP variable value to declare the listener should be enabled? I proposed string "enabled" because: 1) environment variables should always assume to be strings; 2) using a word prevents accidental type casting (i.e. "true" could become a boolean, "1" could be come an int or boolean; 3) the word definition of "enabled" declares exactly its effect on the listener behavior.

Disable on a test suite?

I know you can add the annotation to increase the timeout on a per test basis but is there a way to do it on a per test suite basis, for instance I know my integration tests are going to be slow because they tear down and recreate a database between tests

Compatibility with PHPUnit 9

PHPUnit 9 is expected to be released in the next weeks. There's already a deprecation warning shown when running tests with PHPUnit 8.5:

The "JohnKary\PHPUnit\Listener\SpeedTrapListener" class implements "PHPUnit\Framework\TestListener" that is deprecated Use the TestHook interfaces instead.

Annotations for higher thresholds

Overall we want a low threshold, but we have a few tests that run longer and we're okay with that. I don't want to bump up the threshold across the board, but I don't want to get used to seeing slow tests either.

Would it be possible to add a custom annotation for changing the threshold on specific tests?

Can't get it to work ...

Installed via Composer and added listener in phpunit.xml.dist, but no output is printed to console when tests are run. (I tried lowering the threshold to a ridiculously low number and also added a sleep(1) call in one of the tests.)

My phpunit.xml.dist file:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
  backupStaticAttributes="false"
  bootstrap="tests/bootstrap.php"
  colors="true"
  convertErrorsToExceptions="true"
  convertNoticesToExceptions="true"
  convertWarningsToExceptions="true"
  processIsolation="false"
  stopOnFailure="false"
  syntaxCheck="false">
  <testsuites>
    <testsuite name="My Test Suite">
      <directory>./tests/</directory>
    </testsuite>
  </testsuites>

  <logging>
    <log type="coverage-html" target="build/coverage" title="my-project"
      charset="UTF-8" yui="true" highlight="true"
      lowUpperBound="35" highLowerBound="70"/>
    <log type="coverage-clover" target="build/logs/clover.xml"/>
    <log type="junit" target="build/logs/junit.xml" logIncompleteSkipped="false"/>
  </logging>

  <filter>
    <whitelist addUncoveredFilesFromWhitelist="true">
      <directory suffix=".php">src</directory>
    </whitelist>
  </filter>

  <listeners>
    <listener class="JohnKary\PHPUnit\Listener\SpeedTrapListener"/>
    <listener class="Mockery\Adapter\Phpunit\TestListener"/>
  </listeners>
</phpunit>

My environment is Ubuntu 13.10 with PHP 5.5.3 and PHPUnit 3.7.37, if that helps.

Automatically annotate slow tests

Once we've found the slow tests, it might be handy to have them all annotated. That would let us find them again later, and also would let us configure PHPUnit to run them separately from the the fast tests - e.g. we might want to run fast tests before commit and slow tests only before deployment.

I'm not sure if the functionality to edit test code would necessarily belong inside this tool - maybe it would be better to implement this a recommendation of another tool that can do the annotations (assuming it exists) and an option to output the list of test cases in a suitable machine readable format - probably something like you get by piping the existing output through grep -o '\S*::\S*'

First test always report a lot of time

First test report allways like a slowly test

For example

class GeneralTest extends IlluminateTestCase
{
    public function testCool(): void
    {
        $this->assertTrue(true);
    }

    public function testNotCool(): void
    {
        usleep(300000);
        $this->assertTrue(true);
    }
}

You should really fix these slow tests (>80ms)...

  1. 489ms to run Tests\GeneralTest:testCool
  2. 312ms to run Tests\GeneralTest:testNotCool

Any ideas? testCool() has only a simple assert :/

I'm using v3.0.0

Add Travis CI build against PHPUnit dev-master

phpunit-speedtrap depends on PHPUnit features that sometimes change when new versions are released. Currently phpunit-speedtrap maintainers manually check for compatibility when official PHPUnit versions are released (or when helpful users report issues on GitHub :) )

Is it possible to add a canary build for phpunit-speedtrap Travis CI build matrix that tests against the latest PHPUnit dev-master on a nightly or weekly schedule? The build should be allowed to fail.

Sebastian Bergmann and all PHPUnit contributors do an amazing job maintaining PHPUnit by frequently releasing new versions to fix bugs, add new minor features and occasionally introduce backwards-incompatible features.

Due to PHPUnit's rapid release pace, a canary build would more quickly indicate BC breaks in phpunit-speedtrap, allowing maintainers to more quickly update the library before new major PHPUnit versions are available.

Exception in setUpBeforeClass

With my current configuration, SpeedTrapListener fails with an unhelpful Exception, if setUpBeforeClass throws an Exception.

SpeedTrapListener::endTest is called with $test as instance of PHPUnit_Framework_TestSuite,
which causes an E_RECOVERABLE_ERROR because SpeedTrapListener::getSlowThreshold expects PHPUnit_Framework_TestCase to be passed.

current result:

PHP Fatal error:  Uncaught exception 'RuntimeException' with message 'There should be an error triggered while test run
E_RECOVERABLE_ERROR: Argument 1 passed to JohnKary\PHPUnit\Listener\SpeedTrapListener::getSlowThreshold() must be an instance of PHPUnit_Framework_TestCase, instance of PHPUnit_Framework_TestSuite given, called in /vagrant/vendor/johnkary/phpunit-speedtrap/src/JohnKary/PHPUnit/Listener/SpeedTrapListener.php on line 128 and defined
         at 0  /vagrant/Tests/phpunit/bootstrap.php (line 64) -> getDebugAsString()
         at 1  /vagrant/vendor/johnkary/phpunit-speedtrap/src/JohnKary/PHPUnit/Listener/SpeedTrapListener.php (line 309) -> user_error_handler()
         at 2  /vagrant/vendor/johnkary/phpunit-speedtrap/src/JohnKary/PHPUnit/Listener/SpeedTrapListener.php (line 128) -> getSlowThreshold()
         at 3  /vagrant/vendor/phpunit/phpunit/src/Framework/TestResult.php (line 344) -> endTest()
         at 4  /vagrant/vendor/phpunit/phpunit/src/Framework/TestSuite.php (line 695) -> endTest()
         at 5  /vagrant/vendor/phpunit/phpunit/src/TextUI/Te in /vagrant/Tests/phpunit/bootstrap.php on line 71

expected result:

There was 1 error:

1) TestsPhpunitSpeedtrapTest
exception 'Exception' with message 'I am broken' in /vagrant/Tests/phpunit/speedtrap_test.php:11

Suggestion to fix this:

add if ( $test instanceof \PHPUnit_Framework_TestCase ) { to SpeedTrapListener::endTest

TestCase to reproduce the problem:

class TestsPhpunitSpeedtrapTest extends PHPUnit_Framework_TestCase
{
    public static function setUpBeforeClass()
    {
        throw new Exception("I am broken");
    }

    public function test()
    {
        $this->assertTrue(true);
    }
}
PHPUnit 4.4.5 by Sebastian Bergmann.
PHP 5.4.36-0+deb7u3 (cli) (built: Jan  9 2015 08:07:06) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies
    with XCache v2.0.0, Copyright (c) 2005-2012, by mOo
    with Xdebug v2.2.1, Copyright (c) 2002-2012, by Derick Rethans

Report should display exceeded slowness threshold for each test

Individual tests may set slowness thresholds independent of the configured test-suite threshold.

/**
 * This test's runtime would normally be under the suite's threshold, but
 * this annotation sets a lower threshold, causing it to be considered slow
 * and reported on in the test output.
 *
 * @slowThreshold 5
 */
public function testCanSetLowerSlowThreshold()
{
    $this->extendTime(10);
    $this->assertTrue(true);
}

But when these per-test slowness thresholds are exceeded, the report displays only the configured test-suite threshold is printed. This makes the report appear incorrect at first glance.

.SI.........                                                      12 / 12 (100%)

You should really fix these slow tests (>500ms)...
 1. 805ms to run JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testWithDataProvider with data set "Rock"
 2. 705ms to run JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testWithDataProvider with data set "Chalk"
 3. 601ms to run JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testWithDataProvider with data set "Jayhawk"
 4. 503ms to run JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testAnotherSlowTests
 5. 501ms to run JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testLongEndToEndTest
 6. 13ms to run JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testCanSetLowerSlowThreshold

In the above example, the default slowness threshold 500ms is set. But the last test runs in 13ms, which is not greater than the reported 500ms. This can be confusing.

Possible Solution 1

Remove the slowness thresholds from the report output. This removes the inaccuracy and the report simply contains a list of slow tests and their execution time. It remains easy to see which tests would benefit from investigating why they are slow.

Possible Solution 2

In addition to Solution 1, each slow test could output its slowness threshold along with execution time. For example:

.SI.........                                                      12 / 12 (100%)

You should really fix these slow tests...
 1. 805ms > 500ms running JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testWithDataProvider with data set "Rock"
 2. 705ms > 500ms running JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testWithDataProvider with data set "Chalk"
 3. 601ms > 500ms running JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testWithDataProvider with data set "Jayhawk"
 4. 503ms > 500ms running JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testAnotherSlowTests
 5. 501ms > 500ms running JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testLongEndToEndTest
 6. 13ms > 5ms running JohnKary\PHPUnit\Listener\Tests\SomeSlowTest:testCanSetLowerSlowThreshold

Any other ideas for improving the report output format?

Prints out stats mixed with testdox output

When running phpunit with --testdox then it is posible to get a output which mixes speedtraps output with the dox.

<lots of tests above>
Name/Space/Here

You should really fix these slow tests (>500ms)...
 1. 5610ms to run <cut>
 2. 3332ms to run <cut>
 3. 3260ms to run <cut>
 4. 3059ms to run <cut>
 5. 2826ms to run <cut>
 6. 1473ms to run <cut>
 7. 1416ms to run <cut>
 8. 969ms to run <cut>
 9. 948ms to run <cut>
 10. 947ms to run <cut>
...and there are 29 more above your threshold hidden from view [x] Prefix
 [x] Is utf 8

All tests seem to have passed successfully!

Fatal error with Symfony 3.4 and symfony/phpunit-bridge

Hello, when running my suite after adding the listener a fatal error occurs:

./vendor/bin/simple-phpunit                      
PHP Fatal error:  Declaration of Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV7::addError(PHPUnit\Framework\Test $test, Throwable $t, float $time): void must be compatible with PHPUnit\Framework\TestListener::addError(PHPUnit\Framework\Test $test, Exception $e, $time) in /home/luca/Sites/ciudadania/vendor/symfony/phpunit-bridge/Legacy/SymfonyTestsListenerForV7.php on line 27

My phpunit.xml.dist file is like this:


<!-- https://phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.8/phpunit.xsd"
         backupGlobals="false"
         colors="true"
         bootstrap="vendor/autoload.php"
>
    <php>
        <ini name="error_reporting" value="-1" />
        <server name="KERNEL_CLASS" value="AppKernel" />
    </php>

    <testsuites>
        <testsuite name="Project Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>src</directory>
            <exclude>
                <directory>src/*Bundle/Resources</directory>
                <directory>src/*/*Bundle/Resources</directory>
                <directory>src/*/Bundle/*Bundle/Resources</directory>
            </exclude>
        </whitelist>
    </filter>

    <listeners>
        <listener class="JohnKary\PHPUnit\Listener\SpeedTrapListener" />
    </listeners>
</phpunit>

Output total time taken by slow tests

I think it would be really handy to see the total time taken by all the slow tests, to get a good idea of how useful it would be to speed them up or move them out of the main test suite.

I haven't looked at the implementation of phpunit-speedtrap but if this is a desired feature I think I'd be happy to have a go at implementing it.

PhpUnit 4.* SpeedTrapListener should implement addRiskyTest() method

When running tests under PhpUnit 4.* it shows an error. In order to fix this you need to implement the following method:

/**
* Risky test.
*
* @param PHPUnit_Framework_Test $test
* @param Exception $e
* @param float $time
* @since Method available since Release 4.0.0
*/
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time)
{
// TODO: Implement addRiskyTest() method.
}

Switch over to using hooks instead of implementing deprecated TestListener

To allow compatibility with phpunit/phpunit:^9.0.0, for which the TestListener interface will have been removed, an implementation using hooks need to be developed.

For reference, see

I took a stab at this earlier, but it appears there's a bit of a challenge as the hooks only receive the name of the test, rather than the TestCase. That is, from the name of the test the test class and test need to be derived in order to introspect its annotations for determining whether the test is configured for a different threshold then the basic setting in phpunit.xml.

Request: please tag v2.0.0 final

I've been using speedtrap v2.0.0-BETA1 on php 7.2 and phpunit 6.5 for a while now, with zero problems. I reckon this is good to go as-is.

It's the only non-stable dependency I have around my projects at the moment.

Display @dataProvider parameters

Hello, when using tests with parameters it could be useful to actually show the parameters' values.

You should really fix these slow tests (>50ms)...
 1. 309ms to run Tests\AppBundle\Admin\AdminTest:testAdminRoutes with data set #0
 2. 276ms to run Tests\AppBundle\Admin\AdminTest:testAdminRoutes with data set #57
 3. 165ms to run Tests\AppBundle\Admin\AdminTest:testAdminRoutes with data set #1
 4. 122ms to run Tests\AppBundle\Admin\AdminTest:testAdminRoutes with data set #34
 5. 121ms to run Tests\AppBundle\Admin\AdminTest:testAdminRoutes with data set #54

Thanks!

Improve UX

- You should really speed up these slow tests (>500ms)...
+ You should really speed up these slow tests (>500 ms)...
- 1. 84059ms to run Atk4\Data\Tests\ReferenceSqlTest:testHasOneTitleSet
+ 1. 84_059 ms to run Atk4\Data\Tests\ReferenceSqlTest:testHasOneTitleSet
- 2. 58549ms to run Atk4\Data\Tests\Util\DeepCopyTest:testBasic
+ 2. 58_549 ms to run Atk4\Data\Tests\Util\DeepCopyTest:testBasic

to make large values easier to read, also, there should be a space between value and unit

Output could contain convenient way to run/view slow test using a profiler

After a developer discovers a slow test using SpeedTrap, they want to discover why the test is slow, and eventually change the code to run faster. SpeedTrap cannot profile code deeper than the start and stop time of each test. But SpeedTrap might make it easier for a developer to use another tool to discover why their test is slow.

What if the PHPUnit SpeedTrap report contained output that conveniently let the reader run or view a PHP profiler's analysis of the slow test?

For example, as a developer, I run my test suite locally on my development machine with SpeedTrap enabled. The test output shows the test UserLoginTest::testLoginWorkflow() takes 6 seconds to execute. I am curious why this test is so slow! A profiler would allow me to see clock time, wall time, CPU usage, memory usage, etc. of this code's execution path. How could SpeedTrap help me more quickly profile this slow test?

Blackfire.io is likely the most feature-rich PHP profiler available. It can run on a developer's local machine. This is important so the profiling occurs under the same conditions as the slow test run found with SpeedTrap.

  • Could SpeedTrap detect that Blackfire is available to use?
  • If yes to above, could the test output display a CLI command to re-execute the slow test wrapped in a Blackfire profiler session?
  • Could SpeedTrap web link to a previous Blackfire run that executed the slow test? (Is that even useful?)

Please use the comments for any additional ideas, questions or answers to how this feature might work.

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.