Skip to content

Commit

Permalink
Use coverage report as a primary source of files to mutate (#1106)
Browse files Browse the repository at this point in the history
* Use coverage report as a primary source of files to mutate

This PR is a continuation of #1082. Primary goal of this PR is memory optimization. Fixes #705.

With big projects with huge coverage reports Infection still has a lot of difficulty. Major part of this problem stems from the fact that Infection loads virtually all PHPUnit coverage reports at the start, and then goes one by one over source files looking up each file in the reports to understand if it need mutating, where, how, and so on. Not only it is expensive to load all reports at once, but also working with them isn't fast. Basically, it is one big hash table, where Infection tries to access rows from here and from there.

- Yes, it may worth adding a cache, because, say, methods of XMLLineCodeCoverage are called sequentially over data for the same file, but this isn't what I want to propose.
- Yes, with some careful ArrayAccess application you can make the $coverage array clever to load data only as needed, and neither this is what I want to propose.

What's the idea?

If you'd look at the PHPUnit coverage reports, and how we parse them, you would notice that the coverage reports have the same file names we need. Therefore, instead of iterating over files on disk, we can iterate over coverage reports, parsing them one by one, and discarding them once we finish mutating a file.

There are some problems:

- We not only consider these reports, we also consider JUnit reports, joining them together. This procedure had to be split into two. First we load coverage files, select files we want to be mutated (covered, uncovered, filtered), and only then we add JUnit timings, proceeding with mutation.
- For BC reasons we have to consider files outside of coverage reports, therefore we collect them too, adding missing files at the end, but only if needed. Suffice to say if we'd went half-way towards proposal #1064, this part could be removed from our pipeline, chances are together with the configuration step where user enters source paths.
- Overall I had to reshuffle a lot of things, while trying to not to rename them too much. E.g. old tests for the new parser should probably work, and so on.

* Bring back FileCodeCoverageProvider

* s/createFor/provideFor/ as in #1107

* Integrate FileCodeCoverageProvider

* PhpUnitXmlCoveredFileDataFactory -> Provider

* Configuration/ConfigurationTest

* ConfigurationFactoryTest

* Fix for updated configuration

* Fix PhpUnitXmlCoveredFileDataProviderTest

* FileCodeCoverageProviderFactoryTest

* FileMutationGeneratorTest

* Add stubs for new tests

* Fix MutationGeneratorTest

* Fix CoverageChecker

* WIP

* FileCodeCoverageProviderTest

* Update XmlCoverageParser

* Update src/FileSystem/SourceFileFilter.php

Co-Authored-By: Théo FIDRY <theo.fidry@gmail.com>

* CS

* CS

* SourceFileFilterTest

* TestFileDataAdderTest

* CoveredFileNameFilterTest

* Use parse() instead of parseLazy(), LegacyXmlCoverageParser

* CoveredFileDataTest

* Introduce SourceFileInfoProvider

* CS

* CoveredFileDataFactoryTest

* SourceFileInfoProviderTest

* Update XmlCoverageFixtures

* Update SourceFileInfoProviderTest

* XmlCoverageParserTest

* CS

* XmlCoverageParserTest

* CoveredFileDataFactoryTest

* Bump MSI

* CS

* CS

* CS

* CS

* XPathFactory

* Update ProjectCodeProvider

* Simplify XmlCoverageParser

* Fix ProjectCodeProvider

* Revert change

* Update XmlCoverageParserTest

* Simplify XmlCoverageParser

* Remove @see

* Update src/TestFramework/Coverage/CoveredFileData.php

* CS

* SourceFileFilter: comment

* Make testExecutionInfoAdder a Generator

* Update src/FileSystem/SourceFileFilter.php

Co-Authored-By: Théo FIDRY <theo.fidry@gmail.com>

* Update tests/phpunit/FileSystem/SourceFileFilterTest.php

Co-Authored-By: Théo FIDRY <theo.fidry@gmail.com>

* Update src/TestFramework/PhpUnit/Coverage/IndexXmlCoverageParser.php

Co-Authored-By: Théo FIDRY <theo.fidry@gmail.com>

* CS

* CoverageFileData -> CoverageReport

* s/seenFiles/filesSeen/g

* s/TestFileDataAdder/JUnitTestExecutionInfoAdder/

* CS

* Update tests/phpunit/FileSystem/SourceFileFilterTest.php

Co-Authored-By: Théo FIDRY <theo.fidry@gmail.com>

* CS

* s/assertFilter/assertCanFilterInput/g

* SourceFileFilterTest

* FileMutationGenerator

* CoveredFileData -> SourceFileData

* s/coveredFileData/sourceFileData/g

* MutationGenerator

* Document MutationGenerator

* Remove CoveredFileNameFilter

* s/coverageFileData/coverageReport/g

* MutationGenerator: just files

* ->getSourceFilesFilter()

* SourceFileFilter: missing imports

* SourceFileFilter: notes

* CS

* SourceFileData: remove getRealPath

* Add TODOs

* Update src/TestFramework/Coverage/SourceFileDataProvider.php

* Update src/TestFramework/Coverage/SourceFileDataFactory.php

* Revert "SourceFileData: remove getRealPath"

This reverts commit 26a0c4e.

* SourceFileData

* $testFrameworkKey can now be removed since it's no longer in use

* CS

Co-authored-by: Théo FIDRY <theo.fidry@gmail.com>
  • Loading branch information
sanmai and theofidry committed Mar 10, 2020
1 parent 7b5d5f4 commit 42b7223
Show file tree
Hide file tree
Showing 48 changed files with 2,727 additions and 754 deletions.
2 changes: 1 addition & 1 deletion devTools/phpstan-src.neon
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ parameters:
message: '#Parameter \#1 \$argument of class ReflectionClass constructor expects class\-string\<T of object\>\|T of object\, string given\.#'
count: 1
-
path: '../src/TestFramework/PhpUnit/Coverage/IndexXmlCoverageParser.php'
path: '../src/TestFramework/PhpUnit/Coverage/SourceFileInfoProvider.php'
message: '#Function realpath is unsafe to use\.#'
count: 1
-
Expand Down
6 changes: 1 addition & 5 deletions devTools/phpstan-tests.neon
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,12 @@ parameters:
inferPrivatePropertyTypeFromConstructor: true
ignoreErrors:
- '#Return type \(void\) of method .*(Visitor|Traverser).* should be compatible with return type .* of method PhpParser\\Node.*#'
- '#^Cannot call method willReturn\(\) on iterable<Infection\\Mutation\\Mutation>\.$#'
- '#^Cannot call method (willReturn|shouldBeCalledTimes)\(\) on iterable<Infection\\Mutation\\Mutation>\.$#'
- '#^PHPDoc tag @var for variable \$sourceFilesCollectorProphecy contains unresolvable type#'
-
path: '../tests/phpunit/PhpParser/Visitor/MutationsCollectorVisitorTest.php'
message: '#Call to method PHPUnit\\Framework\\Assert::assertSame\(\)#'
count: 2
-
path: '../tests/phpunit/TestFramework/Coverage/XmlReport/FileCodeCoverageTest.php'
message: '#Call to method PHPUnit\\Framework\\Assert::assertSame\(\)#'
count: 2
-
path: '../tests/phpunit/TestFramework/PhpUnit/Config/Builder/InitialConfigBuilderTest.php'
message: '#Function simplexml_load_string is unsafe to use#'
Expand Down
8 changes: 8 additions & 0 deletions src/Configuration/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ class Configuration
private $timeout;
private $sourceDirectories;
private $sourceFiles;
private $sourceFilesFilter;
private $logs;
private $logVerbosity;
private $tmpDir;
Expand Down Expand Up @@ -92,6 +93,7 @@ public function __construct(
int $timeout,
array $sourceDirectories,
iterable $sourceFiles,
string $sourceFilesFilter,
Logs $logs,
string $logVerbosity,
string $tmpDir,
Expand Down Expand Up @@ -125,6 +127,7 @@ public function __construct(
$this->timeout = $timeout;
$this->sourceDirectories = $sourceDirectories;
$this->sourceFiles = $sourceFiles;
$this->sourceFilesFilter = $sourceFilesFilter;
$this->logs = $logs;
$this->logVerbosity = $logVerbosity;
$this->tmpDir = $tmpDir;
Expand Down Expand Up @@ -168,6 +171,11 @@ public function getSourceFiles(): iterable
return $this->sourceFiles;
}

public function getSourceFilesFilter(): string
{
return $this->sourceFilesFilter;
}

public function getLogs(): Logs
{
return $this->logs;
Expand Down
1 change: 1 addition & 0 deletions src/Configuration/ConfigurationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ public function create(
$schema->getSource()->getExcludes(),
$filter
),
$filter,
$schema->getLogs(),
$logVerbosity,
$namespacedTmpDir,
Expand Down
57 changes: 50 additions & 7 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
use Infection\FileSystem\Locator\RootsFileLocator;
use Infection\FileSystem\Locator\RootsFileOrDirectoryLocator;
use Infection\FileSystem\SourceFileCollector;
use Infection\FileSystem\SourceFileFilter;
use Infection\FileSystem\TmpDirProvider;
use Infection\Logger\LoggerFactory;
use Infection\Mutant\MetricsCalculator;
Expand Down Expand Up @@ -88,10 +89,13 @@
use Infection\TestFramework\CommandLineBuilder;
use Infection\TestFramework\Config\TestFrameworkConfigLocator;
use Infection\TestFramework\Coverage\CoverageChecker;
use Infection\TestFramework\Coverage\JUnit\JUnitTestExecutionInfoAdder;
use Infection\TestFramework\Coverage\JUnit\JUnitTestFileDataProvider;
use Infection\TestFramework\Coverage\JUnit\MemoizedTestFileDataProvider;
use Infection\TestFramework\Coverage\JUnit\TestFileDataProvider;
use Infection\TestFramework\Coverage\LineRangeCalculator;
use Infection\TestFramework\Coverage\SourceFileDataFactory;
use Infection\TestFramework\Coverage\XmlReport\FileCodeCoverageProvider;
use Infection\TestFramework\Coverage\XmlReport\FileCodeCoverageProviderFactory;
use Infection\TestFramework\Factory;
use Infection\TestFramework\PhpUnit\Config\Path\PathReplacer;
Expand Down Expand Up @@ -154,13 +158,35 @@ public static function create(): self
IndexXmlCoverageParser::class => static function (self $container): IndexXmlCoverageParser {
return new IndexXmlCoverageParser($container->getConfiguration()->getCoveragePath());
},
SourceFileDataFactory::class => static function (self $container): SourceFileDataFactory {
return new SourceFileDataFactory(
$container->getFileCodeCoverageProviderFactory()->create(),
$container->getJUnitTestExecutionInfoAdder(),
$container->getSourceFileFilter(),
$container->getConfiguration()->getSourceFiles(),
$container->getConfiguration()->mutateOnlyCoveredCode()
);
},
SourceFileFilter::class => static function (self $container): SourceFileFilter {
return new SourceFileFilter(
$container->getConfiguration()->getSourceFilesFilter()
);
},
JUnitTestExecutionInfoAdder::class => static function (self $container): JUnitTestExecutionInfoAdder {
return new JUnitTestExecutionInfoAdder(
$container->getTestFrameworkAdapter(),
$container->getMemoizedTestFileDataProvider()
);
},
FileCodeCoverageProviderFactory::class => static function (self $container): FileCodeCoverageProviderFactory {
return new FileCodeCoverageProviderFactory(
$container->getConfiguration()->getCoveragePath(),
$container->getIndexXmlCoverageParser(),
$container->getMemoizedTestFileDataProvider()
$container->getIndexXmlCoverageParser()
);
},
FileCodeCoverageProvider::class => static function (self $container): FileCodeCoverageProvider {
return new FileCodeCoverageProvider();
},
RootsFileOrDirectoryLocator::class => static function (self $container): RootsFileOrDirectoryLocator {
return new RootsFileOrDirectoryLocator(
[$container->getProjectDir()],
Expand Down Expand Up @@ -398,11 +424,8 @@ public static function create(): self
$config = $container->getConfiguration();

return new MutationGenerator(
$config->getSourceFiles(),
$container->getFileCodeCoverageProviderFactory()->create(
$config->getTestFramework(),
$container->getTestFrameworkAdapter()
),
$container->getSourceFileDataFactory(),
$container->getFileCodeCoverageProvider(),
$config->getMutators(),
$container->getEventDispatcher(),
$container->getFileMutationGenerator(),
Expand Down Expand Up @@ -549,11 +572,31 @@ public function getIndexXmlCoverageParser(): IndexXmlCoverageParser
return $this->get(IndexXmlCoverageParser::class);
}

public function getSourceFileDataFactory(): SourceFileDataFactory
{
return $this->get(SourceFileDataFactory::class);
}

public function getSourceFileFilter(): SourceFileFilter
{
return $this->get(SourceFileFilter::class);
}

public function getJUnitTestExecutionInfoAdder(): JUnitTestExecutionInfoAdder
{
return $this->get(JUnitTestExecutionInfoAdder::class);
}

public function getFileCodeCoverageProviderFactory(): FileCodeCoverageProviderFactory
{
return $this->get(FileCodeCoverageProviderFactory::class);
}

public function getFileCodeCoverageProvider(): FileCodeCoverageProvider
{
return $this->get(FileCodeCoverageProvider::class);
}

public function getRootsFileOrDirectoryLocator(): RootsFileOrDirectoryLocator
{
return $this->get(RootsFileOrDirectoryLocator::class);
Expand Down
121 changes: 121 additions & 0 deletions src/FileSystem/SourceFileFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
<?php
/**
* This code is licensed under the BSD 3-Clause License.
*
* Copyright (c) 2017, Maks Rafalko
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

declare(strict_types=1);

namespace Infection\FileSystem;

use function array_filter;
use function array_map;
use function explode;
use Infection\FileSystem\Finder\Iterator\RealPathFilterIterator;
use Infection\TestFramework\Coverage\SourceFileData;
use Iterator;
use Symfony\Component\Finder\SplFileInfo;

/**
* @internal
* @final
*/
class SourceFileFilter
{
/**
* @var string[]
*/
private $filters;

public function __construct(string $filter)
{
$this->filters = array_filter(array_map(
'trim',
explode(',', $filter)
));
}

/**
* Returns a filter array to be used in tests.
*
* TODO Good candidate to be refactored into a class.
*
* @return string[]
*/
public function getFilters(): array
{
return $this->filters;
}

/**
* @param iterable<SplFileInfo&SourceFileData> $input
*
* @return iterable<SplFileInfo&SourceFileData>
*/
public function filter(iterable $input): iterable
{
if ($this->filters === []) {
return $input;
}

return new RealPathFilterIterator(
$this->iterableToIterator($input),
$this->filters,
[]
);
}

/**
* @param iterable<SplFileInfo&SourceFileData> $input
*
* @return Iterator<SplFileInfo&SourceFileData>
*/
private function iterableToIterator(iterable $input): Iterator
{
if ($input instanceof Iterator) {
// Generator is an iterator, means most of the time we're done right here.
return $input;
}

/*
* Clause for all other cases, e.g. when testing.
*
* RealPathFilterIterator wants an iterator, not just any iterable or traversable.
* But not any Traversable is an Iterator. But since we know most of the time we're
* dealing with Generators, which are instances of an Iterator, we can jump them
* through. But we may want to use other types of iterables, e.g. arrays in tests,
* and that last clause is to covert them, or any other non-Iterator object, to
* a Generator which is an Iterator. Traversable types are complicated, right.
*/
return (static function () use ($input): Iterator {
yield from $input;
})();
}
}
13 changes: 5 additions & 8 deletions src/Mutation/FileMutationGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
use Infection\PhpParser\Visitor\MutationsCollectorVisitor;
use Infection\TestFramework\Coverage\LineCodeCoverage;
use Infection\TestFramework\Coverage\LineRangeCalculator;
use Symfony\Component\Finder\SplFileInfo;
use Infection\TestFramework\Coverage\SourceFileData;
use Webmozart\Assert\Assert;

/**
Expand Down Expand Up @@ -76,7 +76,7 @@ public function __construct(
* @return iterable<Mutation>
*/
public function generate(
SplFileInfo $fileInfo,
SourceFileData $fileData,
bool $onlyCovered,
LineCodeCoverage $codeCoverage,
array $mutators,
Expand All @@ -85,21 +85,18 @@ public function generate(
Assert::allIsInstanceOf($mutators, Mutator::class);
Assert::allIsInstanceOf($nodeIgnorers, NodeIgnorer::class);

$filePath = $fileInfo->getRealPath() === false
? $fileInfo->getPathname()
: $fileInfo->getRealPath()
;

if ($onlyCovered && !$codeCoverage->hasTests()) {
return;
}

$fileInfo = $fileData->getSplFileInfo();

$initialStatements = $this->parser->parse($fileInfo);

$mutationsCollectorVisitor = new MutationsCollectorVisitor(
new NodeMutationGenerator(
$mutators,
$filePath,
$fileInfo->getPathname(),
$initialStatements,
$codeCoverage,
$onlyCovered,
Expand Down
1 change: 0 additions & 1 deletion src/Mutation/Mutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ public function __construct(
array $tests
) {
Assert::oneOf($mutatorName, array_keys(ProfileList::ALL_MUTATORS));
Assert::allIsInstanceOf($tests, CoverageLineData::class);

foreach (self::ATTRIBUTE_KEYS as $key) {
Assert::keyExists($attributes, $key);
Expand Down

0 comments on commit 42b7223

Please sign in to comment.