Skip to content

Commit

Permalink
Use coverage report as a primary source of files to mutate
Browse files Browse the repository at this point in the history
This PR is a continuation of infection#1082. Primary goal of this PR is memory optimization. Fixes infection#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 infection#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.
  • Loading branch information
sanmai committed Mar 6, 2020
1 parent 5099b69 commit e73688c
Show file tree
Hide file tree
Showing 21 changed files with 948 additions and 522 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/XmlCoverageParser.php'
message: '#Function realpath is unsafe to use\.#'
count: 1
-
Expand Down
13 changes: 13 additions & 0 deletions src/Configuration/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

use Infection\Configuration\Entry\Logs;
use Infection\Configuration\Entry\PhpUnit;
use Infection\FileSystem\SourceFileFilter;
use Infection\Mutator\Mutator;
use Infection\TestFramework\TestFrameworkTypes;
use Symfony\Component\Finder\SplFileInfo;
Expand All @@ -62,6 +63,7 @@ class Configuration
private $timeout;
private $sourceDirectories;
private $sourceFiles;
private $sourceFileFilter;
private $logs;
private $logVerbosity;
private $tmpDir;
Expand Down Expand Up @@ -92,6 +94,7 @@ public function __construct(
int $timeout,
array $sourceDirectories,
iterable $sourceFiles,
SourceFileFilter $sourceFileFilter,
Logs $logs,
string $logVerbosity,
string $tmpDir,
Expand Down Expand Up @@ -125,6 +128,7 @@ public function __construct(
$this->timeout = $timeout;
$this->sourceDirectories = $sourceDirectories;
$this->sourceFiles = $sourceFiles;
$this->sourceFileFilter = $sourceFileFilter;
$this->logs = $logs;
$this->logVerbosity = $logVerbosity;
$this->tmpDir = $tmpDir;
Expand Down Expand Up @@ -165,9 +169,18 @@ public function getSourceDirectories(): array
*/
public function getSourceFiles(): iterable
{
if ($this->onlyCovered) {
return [];
}

return $this->sourceFiles;
}

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

public function getLogs(): Logs
{
return $this->logs;
Expand Down
8 changes: 7 additions & 1 deletion src/Configuration/ConfigurationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
use Infection\Configuration\Entry\PhpUnit;
use Infection\Configuration\Schema\SchemaConfiguration;
use Infection\FileSystem\SourceFileCollector;
use Infection\FileSystem\SourceFileFilter;
use Infection\FileSystem\TmpDirProvider;
use Infection\Mutator\Mutator;
use Infection\Mutator\MutatorFactory;
Expand Down Expand Up @@ -122,14 +123,19 @@ public function create(
$namespacedTmpDir
);

$sourceFileFilter = new SourceFileFilter(
$filter
);

return new Configuration(
$schema->getTimeout() ?? self::DEFAULT_TIMEOUT,
$schema->getSource()->getDirectories(),
$this->sourceFileCollector->collectFiles(
$schema->getSource()->getDirectories(),
$schema->getSource()->getExcludes(),
$filter
$sourceFileFilter->getFilters()
),
$sourceFileFilter,
$schema->getLogs(),
$logVerbosity,
$namespacedTmpDir,
Expand Down
48 changes: 41 additions & 7 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,11 @@
use Infection\TestFramework\AdapterInstaller;
use Infection\TestFramework\CommandLineBuilder;
use Infection\TestFramework\Config\TestFrameworkConfigLocator;
use Infection\TestFramework\Coverage\CoveredFileDataFactory;
use Infection\TestFramework\Coverage\CoveredFileNameFilter;
use Infection\TestFramework\Coverage\JUnit\JUnitTestFileDataProvider;
use Infection\TestFramework\Coverage\JUnit\MemoizedTestFileDataProvider;
use Infection\TestFramework\Coverage\JUnit\TestFileDataAdder;
use Infection\TestFramework\Coverage\JUnit\TestFileDataProvider;
use Infection\TestFramework\Coverage\LineRangeCalculator;
use Infection\TestFramework\Coverage\XmlReport\FileCodeCoverageProviderFactory;
Expand Down Expand Up @@ -154,11 +157,31 @@ public static function create(): self
IndexXmlCoverageParser::class => static function (self $container): IndexXmlCoverageParser {
return new IndexXmlCoverageParser($container->getConfiguration()->getCoveragePath());
},
CoveredFileDataFactory::class => static function (self $container): CoveredFileDataFactory {
return new CoveredFileDataFactory(
$container->getFileCodeCoverageProviderFactory()->create(
$container->getConfiguration()->getTestFramework()
),
$container->getTestFileDataAdder(),
$container->getCoveredFileNameFilter(),
$container->getConfiguration()->getSourceFiles()
);
},
CoveredFileNameFilter::class => static function (self $container): CoveredFileNameFilter {
return new CoveredFileNameFilter(
$container->getConfiguration()->getSourceFileFilter()
);
},
TestFileDataAdder::class => static function (self $container): TestFileDataAdder {
return new TestFileDataAdder(
$container->getTestFrameworkAdapter(),
$container->getMemoizedTestFileDataProvider()
);
},
FileCodeCoverageProviderFactory::class => static function (self $container): FileCodeCoverageProviderFactory {
return new FileCodeCoverageProviderFactory(
$container->getConfiguration()->getCoveragePath(),
$container->getIndexXmlCoverageParser(),
$container->getMemoizedTestFileDataProvider()
$container->getIndexXmlCoverageParser()
);
},
RootsFileOrDirectoryLocator::class => static function (self $container): RootsFileOrDirectoryLocator {
Expand Down Expand Up @@ -392,11 +415,7 @@ public static function create(): self
$config = $container->getConfiguration();

return new MutationGenerator(
$config->getSourceFiles(),
$container->getFileCodeCoverageProviderFactory()->create(
$config->getTestFramework(),
$container->getTestFrameworkAdapter()
),
$container->getCoveredFileDataFactory(),
$config->getMutators(),
$container->getEventDispatcher(),
$container->getFileMutationGenerator(),
Expand Down Expand Up @@ -542,6 +561,21 @@ public function getIndexXmlCoverageParser(): IndexXmlCoverageParser
return $this->get(IndexXmlCoverageParser::class);
}

public function getCoveredFileDataFactory(): CoveredFileDataFactory
{
return $this->get(CoveredFileDataFactory::class);
}

public function getCoveredFileNameFilter(): CoveredFileNameFilter
{
return $this->get(CoveredFileNameFilter::class);
}

public function getTestFileDataAdder(): TestFileDataAdder
{
return $this->get(TestFileDataAdder::class);
}

public function getFileCodeCoverageProviderFactory(): FileCodeCoverageProviderFactory
{
return $this->get(FileCodeCoverageProviderFactory::class);
Expand Down
6 changes: 3 additions & 3 deletions src/Engine.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
use Infection\Process\Runner\TestRunConstraintChecker;
use Infection\Resource\Memory\MemoryLimiter;
use Infection\TestFramework\Coverage\CoverageDoesNotExistException;
use Infection\TestFramework\Coverage\XmlReport\PhpUnitXmlCoverageFactory;
use Infection\TestFramework\Coverage\XmlReport\PhpUnitXmlCoveredFileDataFactory;
use Infection\TestFramework\IgnoresAdditionalNodes;
use Infection\TestFramework\ProvidesInitialRunOnlyOptions;
use Infection\TestFramework\TestFrameworkExtraOptionsFilter;
Expand Down Expand Up @@ -181,7 +181,7 @@ private function assertCodeCoverageExists(string $testFrameworkKey): void
{
$coverageDir = $this->config->getCoveragePath();

$coverageIndexFilePath = $coverageDir . '/' . PhpUnitXmlCoverageFactory::COVERAGE_INDEX_FILE_NAME;
$coverageIndexFilePath = $coverageDir . '/' . PhpUnitXmlCoveredFileDataFactory::COVERAGE_INDEX_FILE_NAME;

if (!file_exists($coverageIndexFilePath)) {
throw CoverageDoesNotExistException::with(
Expand All @@ -196,7 +196,7 @@ private function assertCodeCoverageProduced(Process $initialTestsProcess, string
{
$coverageDir = $this->config->getCoveragePath();

$coverageIndexFilePath = $coverageDir . '/' . PhpUnitXmlCoverageFactory::COVERAGE_INDEX_FILE_NAME;
$coverageIndexFilePath = $coverageDir . '/' . PhpUnitXmlCoveredFileDataFactory::COVERAGE_INDEX_FILE_NAME;

$processInfo = sprintf(
'%sCommand line: %s%sProcess Output: %s',
Expand Down
17 changes: 4 additions & 13 deletions src/FileSystem/SourceFileCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@

namespace Infection\FileSystem;

use function array_filter;
use function array_map;
use function explode;
use Infection\FileSystem\Finder\FilterableFinder;
use Symfony\Component\Finder\SplFileInfo;

Expand All @@ -51,13 +48,14 @@ class SourceFileCollector
/**
* @param string[] $sourceDirectories
* @param string[] $excludeDirectories
* @param string[] $filter
*
* @return iterable<SplFileInfo>
*/
public function collectFiles(
array $sourceDirectories,
array $excludeDirectories,
string $filter
array $filter
): iterable {
if ([] === $sourceDirectories) {
return [];
Expand All @@ -69,17 +67,10 @@ public function collectFiles(
->files()
;

if ($filter === '') {
if ($filter === []) {
$finder->name('*.php');
} else {
$finder->filterFiles(
array_filter(
array_map(
'trim',
explode(',', $filter)
)
)
);
$finder->filterFiles($filter);
}

return $finder;
Expand Down
111 changes: 111 additions & 0 deletions src/FileSystem/SourceFileFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?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 explode;
use Infection\FileSystem\Finder\Iterator\RealPathFilterIterator;
use Infection\TestFramework\Coverage\CoveredFileData;
use Iterator;
use function Pipeline\take;
use Symfony\Component\Finder\SplFileInfo;

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

/**
* @return iterable<SplFileInfo>
*/
public function __construct(string $filter)
{
$this->filters = take(explode(',', $filter))
->map('trim')
->filter()
->toArray();
}

/**
* @return string[]
*
* @see SourceFileCollector
*/
public function getFilters(): array
{
return $this->filters;
}

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

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

/**
* @param iterable<SplFileInfo&CoveredFileData> $input
*
* @return Iterator<SplFileInfo&CoveredFileData>
*/
private function iterableToIterator(iterable $input)
{
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
return (static function () use ($input): Iterator {
yield from $input;
})();
}
}

0 comments on commit e73688c

Please sign in to comment.