Laravel 5.6 updates

Travis config update

Removed HHVM script as Laravel no longer support HHVM after releasing 5.3
This commit is contained in:
Manish Verma
2018-08-06 20:08:55 +05:30
parent 126fbb0255
commit 1ac0f42a58
2464 changed files with 65239 additions and 46734 deletions

View File

@@ -22,42 +22,42 @@ final class ChunkTest extends TestCase
*/
private $chunk;
protected function setUp()
protected function setUp(): void
{
$this->chunk = new Chunk;
}
public function testCanBeCreatedWithoutArguments()
public function testCanBeCreatedWithoutArguments(): void
{
$this->assertInstanceOf(Chunk::class, $this->chunk);
}
public function testStartCanBeRetrieved()
public function testStartCanBeRetrieved(): void
{
$this->assertSame(0, $this->chunk->getStart());
}
public function testStartRangeCanBeRetrieved()
public function testStartRangeCanBeRetrieved(): void
{
$this->assertSame(1, $this->chunk->getStartRange());
}
public function testEndCanBeRetrieved()
public function testEndCanBeRetrieved(): void
{
$this->assertSame(0, $this->chunk->getEnd());
}
public function testEndRangeCanBeRetrieved()
public function testEndRangeCanBeRetrieved(): void
{
$this->assertSame(1, $this->chunk->getEndRange());
}
public function testLinesCanBeRetrieved()
public function testLinesCanBeRetrieved(): void
{
$this->assertSame([], $this->chunk->getLines());
}
public function testLinesCanBeSet()
public function testLinesCanBeSet(): void
{
$this->assertSame([], $this->chunk->getLines());

View File

@@ -19,7 +19,7 @@ use PHPUnit\Framework\TestCase;
*/
final class DiffTest extends TestCase
{
public function testGettersAfterConstructionWithDefault()
public function testGettersAfterConstructionWithDefault(): void
{
$from = 'line1a';
$to = 'line2a';
@@ -30,7 +30,7 @@ final class DiffTest extends TestCase
$this->assertSame([], $diff->getChunks(), 'Expect chunks to be default value "array()".');
}
public function testGettersAfterConstructionWithChunks()
public function testGettersAfterConstructionWithChunks(): void
{
$from = 'line1b';
$to = 'line2b';
@@ -43,7 +43,7 @@ final class DiffTest extends TestCase
$this->assertSame($chunks, $diff->getChunks(), 'Expect chunks to be passed value.');
}
public function testSetChunksAfterConstruction()
public function testSetChunksAfterConstruction(): void
{
$diff = new Diff('line1c', 'line2c');
$this->assertSame([], $diff->getChunks(), 'Expect chunks to be default value "array()".');

File diff suppressed because it is too large Load Diff

View File

@@ -1,83 +0,0 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
use PHPUnit\Framework\TestCase;
/**
* @requires OS Linux
*/
final class DifferTestTest extends TestCase
{
private $fileFrom;
private $filePatch;
protected function setUp()
{
$dir = \realpath(__DIR__ . '/../') . '/';
$this->fileFrom = $dir . 'from.txt';
$this->filePatch = $dir . 'patch.txt';
}
/**
* @dataProvider provideDiffWithLineNumbers
*/
public function testTheTestProvideDiffWithLineNumbers($expected, $from, $to)
{
$this->runThisTest($expected, $from, $to);
}
public function provideDiffWithLineNumbers()
{
require_once __DIR__ . '/DifferTest.php';
$test = new DifferTest();
$tests = $test->provideDiffWithLineNumbers();
$tests = \array_filter(
$tests,
function ($key) {
return !\is_string($key) || false === \strpos($key, 'non_patch_compat');
},
ARRAY_FILTER_USE_KEY
);
return $tests;
}
private function runThisTest(string $expected, string $from, string $to)
{
$expected = \str_replace('--- Original', '--- from.txt', $expected);
$expected = \str_replace('+++ New', '+++ from.txt', $expected);
@\unlink($this->fileFrom);
@\unlink($this->filePatch);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->filePatch, $expected));
$command = \sprintf(
'patch -u --verbose %s < %s', // --posix
\escapeshellarg($this->fileFrom),
\escapeshellarg($this->filePatch)
);
\exec($command, $output, $d);
$this->assertSame(0, $d, \sprintf('%s | %s', $command, \implode("\n", $output)));
$patched = \file_get_contents($this->fileFrom);
$this->assertSame($patched, $to);
@\unlink($this->fileFrom . '.orig');
@\unlink($this->fileFrom);
@\unlink($this->filePatch);
}
}

View File

@@ -0,0 +1,41 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
use PHPUnit\Framework\TestCase;
/**
* @covers SebastianBergmann\Diff\ConfigurationException
*/
final class ConfigurationExceptionTest extends TestCase
{
public function testConstructWithDefaults(): void
{
$e = new ConfigurationException('test', 'A', 'B');
$this->assertSame(0, $e->getCode());
$this->assertNull($e->getPrevious());
$this->assertSame('Option "test" must be A, got "string#B".', $e->getMessage());
}
public function testConstruct(): void
{
$e = new ConfigurationException(
'test',
'integer',
new \SplFileInfo(__FILE__),
789,
new \BadMethodCallException(__METHOD__)
);
$this->assertSame('Option "test" must be integer, got "SplFileInfo".', $e->getMessage());
}
}

View File

@@ -0,0 +1,33 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
use PHPUnit\Framework\TestCase;
/**
* @covers SebastianBergmann\Diff\InvalidArgumentException
*/
final class InvalidArgumentExceptionTest extends TestCase
{
public function testInvalidArgumentException(): void
{
$previousException = new \LogicException();
$message = 'test';
$code = 123;
$exception = new InvalidArgumentException($message, $code, $previousException);
$this->assertInstanceOf(Exception::class, $exception);
$this->assertSame($message, $exception->getMessage());
$this->assertSame($code, $exception->getCode());
$this->assertSame($previousException, $exception->getPrevious());
}
}

View File

@@ -22,22 +22,22 @@ final class LineTest extends TestCase
*/
private $line;
protected function setUp()
protected function setUp(): void
{
$this->line = new Line;
}
public function testCanBeCreatedWithoutArguments()
public function testCanBeCreatedWithoutArguments(): void
{
$this->assertInstanceOf(Line::class, $this->line);
}
public function testTypeCanBeRetrieved()
public function testTypeCanBeRetrieved(): void
{
$this->assertSame(Line::UNCHANGED, $this->line->getType());
}
public function testContentCanBeRetrieved()
public function testContentCanBeRetrieved(): void
{
$this->assertSame('', $this->line->getContent());
}

View File

@@ -32,7 +32,7 @@ abstract class LongestCommonSubsequenceTest extends TestCase
*/
private $stress_sizes = [1, 2, 3, 100, 500, 1000, 2000];
protected function setUp()
protected function setUp(): void
{
$this->memoryLimit = \ini_get('memory_limit');
\ini_set('memory_limit', '256M');
@@ -40,17 +40,12 @@ abstract class LongestCommonSubsequenceTest extends TestCase
$this->implementation = $this->createImplementation();
}
/**
* @return LongestCommonSubsequenceCalculator
*/
abstract protected function createImplementation();
protected function tearDown()
protected function tearDown(): void
{
\ini_set('memory_limit', $this->memoryLimit);
}
public function testBothEmpty()
public function testBothEmpty(): void
{
$from = [];
$to = [];
@@ -59,11 +54,11 @@ abstract class LongestCommonSubsequenceTest extends TestCase
$this->assertSame([], $common);
}
public function testIsStrictComparison()
public function testIsStrictComparison(): void
{
$from = [
false, 0, 0.0, '', null, [],
true, 1, 1.0, 'foo', ['foo', 'bar'], ['foo' => 'bar']
true, 1, 1.0, 'foo', ['foo', 'bar'], ['foo' => 'bar'],
];
$to = $from;
$common = $this->implementation->calculate($from, $to);
@@ -72,7 +67,7 @@ abstract class LongestCommonSubsequenceTest extends TestCase
$to = [
false, false, false, false, false, false,
true, true, true, true, true, true
true, true, true, true, true, true,
];
$expected = [
@@ -85,7 +80,7 @@ abstract class LongestCommonSubsequenceTest extends TestCase
$this->assertSame($expected, $common);
}
public function testEqualSequences()
public function testEqualSequences(): void
{
foreach ($this->stress_sizes as $size) {
$range = \range(1, $size);
@@ -97,7 +92,7 @@ abstract class LongestCommonSubsequenceTest extends TestCase
}
}
public function testDistinctSequences()
public function testDistinctSequences(): void
{
$from = ['A'];
$to = ['B'];
@@ -117,7 +112,7 @@ abstract class LongestCommonSubsequenceTest extends TestCase
}
}
public function testCommonSubsequence()
public function testCommonSubsequence(): void
{
$from = ['A', 'C', 'E', 'F', 'G'];
$to = ['A', 'B', 'D', 'E', 'H'];
@@ -141,7 +136,7 @@ abstract class LongestCommonSubsequenceTest extends TestCase
}
}
public function testSingleElementSubsequenceAtStart()
public function testSingleElementSubsequenceAtStart(): void
{
foreach ($this->stress_sizes as $size) {
$from = \range(1, $size);
@@ -152,7 +147,7 @@ abstract class LongestCommonSubsequenceTest extends TestCase
}
}
public function testSingleElementSubsequenceAtMiddle()
public function testSingleElementSubsequenceAtMiddle(): void
{
foreach ($this->stress_sizes as $size) {
$from = \range(1, $size);
@@ -163,7 +158,7 @@ abstract class LongestCommonSubsequenceTest extends TestCase
}
}
public function testSingleElementSubsequenceAtEnd()
public function testSingleElementSubsequenceAtEnd(): void
{
foreach ($this->stress_sizes as $size) {
$from = \range(1, $size);
@@ -174,7 +169,7 @@ abstract class LongestCommonSubsequenceTest extends TestCase
}
}
public function testReversedSequences()
public function testReversedSequences(): void
{
$from = ['A', 'B'];
$to = ['B', 'A'];
@@ -191,11 +186,16 @@ abstract class LongestCommonSubsequenceTest extends TestCase
}
}
public function testStrictTypeCalculate()
public function testStrictTypeCalculate(): void
{
$diff = $this->implementation->calculate(['5'], ['05']);
$this->assertInternalType('array', $diff);
$this->assertCount(0, $diff);
}
/**
* @return LongestCommonSubsequenceCalculator
*/
abstract protected function createImplementation(): LongestCommonSubsequenceCalculator;
}

View File

@@ -15,7 +15,7 @@ namespace SebastianBergmann\Diff;
*/
final class MemoryEfficientImplementationTest extends LongestCommonSubsequenceTest
{
protected function createImplementation()
protected function createImplementation(): LongestCommonSubsequenceCalculator
{
return new MemoryEfficientLongestCommonSubsequenceCalculator;
}

View File

@@ -0,0 +1,152 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Differ;
/**
* @covers SebastianBergmann\Diff\Output\AbstractChunkOutputBuilder
*
* @uses SebastianBergmann\Diff\Differ
* @uses SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder
* @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
*/
final class AbstractChunkOutputBuilderTest extends TestCase
{
/**
* @param array $expected
* @param string $from
* @param string $to
* @param int $lineThreshold
*
* @dataProvider provideGetCommonChunks
*/
public function testGetCommonChunks(array $expected, string $from, string $to, int $lineThreshold = 5): void
{
$output = new class extends AbstractChunkOutputBuilder {
public function getDiff(array $diff): string
{
return '';
}
public function getChunks(array $diff, $lineThreshold)
{
return $this->getCommonChunks($diff, $lineThreshold);
}
};
$this->assertSame(
$expected,
$output->getChunks((new Differ)->diffToArray($from, $to), $lineThreshold)
);
}
public function provideGetCommonChunks(): array
{
return[
'same (with default threshold)' => [
[],
'A',
'A',
],
'same (threshold 0)' => [
[0 => 0],
'A',
'A',
0,
],
'empty' => [
[],
'',
'',
],
'single line diff' => [
[],
'A',
'B',
],
'below threshold I' => [
[],
"A\nX\nC",
"A\nB\nC",
],
'below threshold II' => [
[],
"A\n\n\n\nX\nC",
"A\n\n\n\nB\nC",
],
'below threshold III' => [
[0 => 5],
"A\n\n\n\n\n\nB",
"A\n\n\n\n\n\nA",
],
'same start' => [
[0 => 5],
"A\n\n\n\n\n\nX\nC",
"A\n\n\n\n\n\nB\nC",
],
'same start long' => [
[0 => 13],
"\n\n\n\n\n\n\n\n\n\n\n\n\n\nA",
"\n\n\n\n\n\n\n\n\n\n\n\n\n\nB",
],
'same part in between' => [
[2 => 8],
"A\n\n\n\n\n\n\nX\nY\nZ\n\n",
"B\n\n\n\n\n\n\nX\nA\nZ\n\n",
],
'same trailing' => [
[2 => 14],
"A\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"B\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
],
'same part in between, same trailing' => [
[2 => 7, 10 => 15],
"A\n\n\n\n\n\n\nA\n\n\n\n\n\n\n",
"B\n\n\n\n\n\n\nB\n\n\n\n\n\n\n",
],
'below custom threshold I' => [
[],
"A\n\nB",
"A\n\nD",
2,
],
'custom threshold I' => [
[0 => 1],
"A\n\nB",
"A\n\nD",
1,
],
'custom threshold II' => [
[],
"A\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"A\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
19,
],
[
[3 => 9],
"a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk",
"a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk",
],
[
[0 => 5, 8 => 13],
"A\nA\nA\nA\nA\nA\nX\nC\nC\nC\nC\nC\nC",
"A\nA\nA\nA\nA\nA\nB\nC\nC\nC\nC\nC\nC",
],
[
[0 => 5, 8 => 13],
"A\nA\nA\nA\nA\nA\nX\nC\nC\nC\nC\nC\nC\nX",
"A\nA\nA\nA\nA\nA\nB\nC\nC\nC\nC\nC\nC\nY",
],
];
}
}

View File

@@ -0,0 +1,76 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Differ;
/**
* @covers SebastianBergmann\Diff\Output\DiffOnlyOutputBuilder
*
* @uses SebastianBergmann\Diff\Differ
* @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
*/
final class DiffOnlyOutputBuilderTest extends TestCase
{
/**
* @param string $expected
* @param string $from
* @param string $to
* @param string $header
*
* @dataProvider textForNoNonDiffLinesProvider
*/
public function testDiffDoNotShowNonDiffLines(string $expected, string $from, string $to, string $header = ''): void
{
$differ = new Differ(new DiffOnlyOutputBuilder($header));
$this->assertSame($expected, $differ->diff($from, $to));
}
public function textForNoNonDiffLinesProvider(): array
{
return [
[
" #Warning: Strings contain different line endings!\n-A\r\n+B\n",
"A\r\n",
"B\n",
],
[
"-A\n+B\n",
"\nA",
"\nB",
],
[
'',
'a',
'a',
],
[
"-A\n+C\n",
"A\n\n\nB",
"C\n\n\nB",
],
[
"header\n",
'a',
'a',
'header',
],
[
"header\n",
'a',
'a',
"header\n",
],
];
}
}

View File

@@ -0,0 +1,299 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Utils\FileUtils;
use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait;
use Symfony\Component\Process\Process;
/**
* @covers SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder
*
* @uses SebastianBergmann\Diff\Differ
* @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
*
* @requires OS Linux
*/
final class StrictUnifiedDiffOutputBuilderIntegrationTest extends TestCase
{
use UnifiedDiffAssertTrait;
private $dir;
private $fileFrom;
private $fileTo;
private $filePatch;
protected function setUp(): void
{
$this->dir = \realpath(__DIR__ . '/../../fixtures/out') . '/';
$this->fileFrom = $this->dir . 'from.txt';
$this->fileTo = $this->dir . 'to.txt';
$this->filePatch = $this->dir . 'diff.patch';
if (!\is_dir($this->dir)) {
throw new \RuntimeException('Integration test working directory not found.');
}
$this->cleanUpTempFiles();
}
protected function tearDown(): void
{
$this->cleanUpTempFiles();
}
/**
* Integration test
*
* - get a file pair
* - create a `diff` between the files
* - test applying the diff using `git apply`
* - test applying the diff using `patch`
*
* @param string $fileFrom
* @param string $fileTo
*
* @dataProvider provideFilePairs
*/
public function testIntegrationUsingPHPFileInVendorGitApply(string $fileFrom, string $fileTo): void
{
$from = FileUtils::getFileContent($fileFrom);
$to = FileUtils::getFileContent($fileTo);
$diff = (new Differ(new StrictUnifiedDiffOutputBuilder(['fromFile' => 'Original', 'toFile' => 'New'])))->diff($from, $to);
if ('' === $diff && $from === $to) {
// odd case: test after executing as it is more efficient than to read the files and check the contents every time
$this->addToAssertionCount(1);
return;
}
$this->doIntegrationTestGitApply($diff, $from, $to);
}
/**
* Integration test
*
* - get a file pair
* - create a `diff` between the files
* - test applying the diff using `git apply`
* - test applying the diff using `patch`
*
* @param string $fileFrom
* @param string $fileTo
*
* @dataProvider provideFilePairs
*/
public function testIntegrationUsingPHPFileInVendorPatch(string $fileFrom, string $fileTo): void
{
$from = FileUtils::getFileContent($fileFrom);
$to = FileUtils::getFileContent($fileTo);
$diff = (new Differ(new StrictUnifiedDiffOutputBuilder(['fromFile' => 'Original', 'toFile' => 'New'])))->diff($from, $to);
if ('' === $diff && $from === $to) {
// odd case: test after executing as it is more efficient than to read the files and check the contents every time
$this->addToAssertionCount(1);
return;
}
$this->doIntegrationTestPatch($diff, $from, $to);
}
/**
* @param string $expected
* @param string $from
* @param string $to
*
* @dataProvider provideOutputBuildingCases
* @dataProvider provideSample
* @dataProvider provideBasicDiffGeneration
*/
public function testIntegrationOfUnitTestCasesGitApply(string $expected, string $from, string $to): void
{
$this->doIntegrationTestGitApply($expected, $from, $to);
}
/**
* @param string $expected
* @param string $from
* @param string $to
*
* @dataProvider provideOutputBuildingCases
* @dataProvider provideSample
* @dataProvider provideBasicDiffGeneration
*/
public function testIntegrationOfUnitTestCasesPatch(string $expected, string $from, string $to): void
{
$this->doIntegrationTestPatch($expected, $from, $to);
}
public function provideOutputBuildingCases(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideOutputBuildingCases();
}
public function provideSample(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideSample();
}
public function provideBasicDiffGeneration(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideBasicDiffGeneration();
}
public function provideFilePairs(): array
{
$cases = [];
$fromFile = __FILE__;
$vendorDir = \realpath(__DIR__ . '/../../../vendor');
$fileIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($vendorDir, \RecursiveDirectoryIterator::SKIP_DOTS));
/** @var \SplFileInfo $file */
foreach ($fileIterator as $file) {
if ('php' !== $file->getExtension()) {
continue;
}
$toFile = $file->getPathname();
$cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \realpath($fromFile), \realpath($toFile))] = [$fromFile, $toFile];
$fromFile = $toFile;
}
return $cases;
}
/**
* Compare diff create by builder and against one create by `diff` command.
*
* @param string $diff
* @param string $from
* @param string $to
*
* @dataProvider provideBasicDiffGeneration
*/
public function testIntegrationDiffOutputBuilderVersusDiffCommand(string $diff, string $from, string $to): void
{
$this->assertNotSame('', $diff);
$this->assertValidUnifiedDiffFormat($diff);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->fileTo, $to));
$p = new Process(\sprintf('diff -u %s %s', \escapeshellarg($this->fileFrom), \escapeshellarg($this->fileTo)));
$p->run();
$this->assertSame(1, $p->getExitCode()); // note: Process assumes exit code 0 for `isSuccessful`, however `diff` uses the exit code `1` for success with diff
$output = $p->getOutput();
$diffLines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $this->fileFrom, $diffLines[0], 1);
$diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $this->fileFrom, $diffLines[1], 1);
$diff = \implode('', $diffLines);
$outputLines = \preg_split('/(.*\R)/', $output, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$outputLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $this->fileFrom, $outputLines[0], 1);
$outputLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $this->fileFrom, $outputLines[1], 1);
$output = \implode('', $outputLines);
$this->assertSame($diff, $output);
}
private function doIntegrationTestGitApply(string $diff, string $from, string $to): void
{
$this->assertNotSame('', $diff);
$this->assertValidUnifiedDiffFormat($diff);
$diff = self::setDiffFileHeader($diff, $this->fileFrom);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->filePatch, $diff));
$p = new Process(\sprintf(
'git --git-dir %s apply --check -v --unsafe-paths --ignore-whitespace %s',
\escapeshellarg($this->dir),
\escapeshellarg($this->filePatch)
));
$p->run();
$this->assertProcessSuccessful($p);
}
private function doIntegrationTestPatch(string $diff, string $from, string $to): void
{
$this->assertNotSame('', $diff);
$this->assertValidUnifiedDiffFormat($diff);
$diff = self::setDiffFileHeader($diff, $this->fileFrom);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->filePatch, $diff));
$command = \sprintf(
'patch -u --verbose --posix %s < %s',
\escapeshellarg($this->fileFrom),
\escapeshellarg($this->filePatch)
);
$p = new Process($command);
$p->run();
$this->assertProcessSuccessful($p);
$this->assertStringEqualsFile(
$this->fileFrom,
$to,
\sprintf('Patch command "%s".', $command)
);
}
private function assertProcessSuccessful(Process $p): void
{
$this->assertTrue(
$p->isSuccessful(),
\sprintf(
"Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n",
$p->getCommandLine(),
$p->getOutput(),
$p->getErrorOutput(),
$p->getExitCode()
)
);
}
private function cleanUpTempFiles(): void
{
@\unlink($this->fileFrom . '.orig');
@\unlink($this->fileFrom . '.rej');
@\unlink($this->fileFrom);
@\unlink($this->fileTo);
@\unlink($this->filePatch);
}
private static function setDiffFileHeader(string $diff, string $file): string
{
$diffLines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $file, $diffLines[0], 1);
$diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $file, $diffLines[1], 1);
return \implode('', $diffLines);
}
}

View File

@@ -0,0 +1,163 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait;
use Symfony\Component\Process\Process;
/**
* @covers SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder
*
* @uses SebastianBergmann\Diff\Differ
* @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
*
* @requires OS Linux
*/
final class UnifiedDiffOutputBuilderIntegrationTest extends TestCase
{
use UnifiedDiffAssertTrait;
private $dir;
private $fileFrom;
private $filePatch;
protected function setUp(): void
{
$this->dir = \realpath(__DIR__ . '/../../fixtures/out/') . '/';
$this->fileFrom = $this->dir . 'from.txt';
$this->filePatch = $this->dir . 'patch.txt';
$this->cleanUpTempFiles();
}
protected function tearDown(): void
{
$this->cleanUpTempFiles();
}
/**
* @dataProvider provideDiffWithLineNumbers
*
* @param mixed $expected
* @param mixed $from
* @param mixed $to
*/
public function testDiffWithLineNumbersPath($expected, $from, $to): void
{
$this->doIntegrationTestPatch($expected, $from, $to);
}
/**
* @dataProvider provideDiffWithLineNumbers
*
* @param mixed $expected
* @param mixed $from
* @param mixed $to
*/
public function testDiffWithLineNumbersGitApply($expected, $from, $to): void
{
$this->doIntegrationTestGitApply($expected, $from, $to);
}
public function provideDiffWithLineNumbers()
{
return \array_filter(
UnifiedDiffOutputBuilderDataProvider::provideDiffWithLineNumbers(),
static function ($key) {
return !\is_string($key) || false === \strpos($key, 'non_patch_compat');
},
ARRAY_FILTER_USE_KEY
);
}
private function doIntegrationTestPatch(string $diff, string $from, string $to): void
{
$this->assertNotSame('', $diff);
$this->assertValidUnifiedDiffFormat($diff);
$diff = self::setDiffFileHeader($diff, $this->fileFrom);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->filePatch, $diff));
$command = \sprintf(
'patch -u --verbose --posix %s < %s', // --posix
\escapeshellarg($this->fileFrom),
\escapeshellarg($this->filePatch)
);
$p = new Process($command);
$p->run();
$this->assertProcessSuccessful($p);
$this->assertStringEqualsFile(
$this->fileFrom,
$to,
\sprintf('Patch command "%s".', $command)
);
}
private function doIntegrationTestGitApply(string $diff, string $from, string $to): void
{
$this->assertNotSame('', $diff);
$this->assertValidUnifiedDiffFormat($diff);
$diff = self::setDiffFileHeader($diff, $this->fileFrom);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->filePatch, $diff));
$command = \sprintf(
'git --git-dir %s apply --check -v --unsafe-paths --ignore-whitespace %s',
\escapeshellarg($this->dir),
\escapeshellarg($this->filePatch)
);
$p = new Process($command);
$p->run();
$this->assertProcessSuccessful($p);
}
private function assertProcessSuccessful(Process $p): void
{
$this->assertTrue(
$p->isSuccessful(),
\sprintf(
"Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n",
$p->getCommandLine(),
$p->getOutput(),
$p->getErrorOutput(),
$p->getExitCode()
)
);
}
private function cleanUpTempFiles(): void
{
@\unlink($this->fileFrom . '.orig');
@\unlink($this->fileFrom);
@\unlink($this->filePatch);
}
private static function setDiffFileHeader(string $diff, string $file): string
{
$diffLines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $file, $diffLines[0], 1);
$diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $file, $diffLines[1], 1);
return \implode('', $diffLines);
}
}

View File

@@ -0,0 +1,189 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
final class StrictUnifiedDiffOutputBuilderDataProvider
{
public static function provideOutputBuildingCases(): array
{
return [
[
'--- input.txt
+++ output.txt
@@ -1,3 +1,4 @@
+b
' . '
' . '
' . '
@@ -16,5 +17,4 @@
' . '
' . '
' . '
-
-B
+A
',
"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nB\n",
"b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nA\n",
[
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
],
],
[
'--- ' . __FILE__ . "\t2017-10-02 17:38:11.586413675 +0100
+++ output1.txt\t2017-10-03 12:09:43.086719482 +0100
@@ -1,1 +1,1 @@
-B
+X
",
"B\n",
"X\n",
[
'fromFile' => __FILE__,
'fromFileDate' => '2017-10-02 17:38:11.586413675 +0100',
'toFile' => 'output1.txt',
'toFileDate' => '2017-10-03 12:09:43.086719482 +0100',
'collapseRanges' => false,
],
],
[
'--- input.txt
+++ output.txt
@@ -1 +1 @@
-B
+X
',
"B\n",
"X\n",
[
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
'collapseRanges' => true,
],
],
];
}
public static function provideSample(): array
{
return [
[
'--- input.txt
+++ output.txt
@@ -1,6 +1,6 @@
1
2
3
-4
+X
5
6
',
"1\n2\n3\n4\n5\n6\n",
"1\n2\n3\nX\n5\n6\n",
[
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
],
],
];
}
public static function provideBasicDiffGeneration(): array
{
return [
[
"--- input.txt
+++ output.txt
@@ -1,2 +1 @@
-A
-B
+A\rB
",
"A\nB\n",
"A\rB\n",
],
[
"--- input.txt
+++ output.txt
@@ -1 +1 @@
-
+\r
\\ No newline at end of file
",
"\n",
"\r",
],
[
"--- input.txt
+++ output.txt
@@ -1 +1 @@
-\r
\\ No newline at end of file
+
",
"\r",
"\n",
],
[
'--- input.txt
+++ output.txt
@@ -1,3 +1,3 @@
X
A
-A
+B
',
"X\nA\nA\n",
"X\nA\nB\n",
],
[
'--- input.txt
+++ output.txt
@@ -1,3 +1,3 @@
X
A
-A
\ No newline at end of file
+B
',
"X\nA\nA",
"X\nA\nB\n",
],
[
'--- input.txt
+++ output.txt
@@ -1,3 +1,3 @@
A
A
-A
+B
\ No newline at end of file
',
"A\nA\nA\n",
"A\nA\nB",
],
[
'--- input.txt
+++ output.txt
@@ -1 +1 @@
-A
\ No newline at end of file
+B
\ No newline at end of file
',
'A',
'B',
],
];
}
}

View File

@@ -0,0 +1,684 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\ConfigurationException;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait;
/**
* @covers SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder
*
* @uses SebastianBergmann\Diff\Differ
*/
final class StrictUnifiedDiffOutputBuilderTest extends TestCase
{
use UnifiedDiffAssertTrait;
/**
* @param string $expected
* @param string $from
* @param string $to
* @param array $options
*
* @dataProvider provideOutputBuildingCases
*/
public function testOutputBuilding(string $expected, string $from, string $to, array $options): void
{
$diff = $this->getDiffer($options)->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
/**
* @param string $expected
* @param string $from
* @param string $to
* @param array $options
*
* @dataProvider provideSample
*/
public function testSample(string $expected, string $from, string $to, array $options): void
{
$diff = $this->getDiffer($options)->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
/**
* {@inheritdoc}
*/
public function assertValidDiffFormat(string $diff): void
{
$this->assertValidUnifiedDiffFormat($diff);
}
/**
* {@inheritdoc}
*/
public function provideOutputBuildingCases(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideOutputBuildingCases();
}
/**
* {@inheritdoc}
*/
public function provideSample(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideSample();
}
/**
* @param string $expected
* @param string $from
* @param string $to
*
* @dataProvider provideBasicDiffGeneration
*/
public function testBasicDiffGeneration(string $expected, string $from, string $to): void
{
$diff = $this->getDiffer([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
])->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
public function provideBasicDiffGeneration(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideBasicDiffGeneration();
}
/**
* @param string $expected
* @param string $from
* @param string $to
* @param array $config
*
* @dataProvider provideConfiguredDiffGeneration
*/
public function testConfiguredDiffGeneration(string $expected, string $from, string $to, array $config = []): void
{
$diff = $this->getDiffer(\array_merge([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
], $config))->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
public function provideConfiguredDiffGeneration(): array
{
return [
[
'--- input.txt
+++ output.txt
@@ -1 +1 @@
-a
\ No newline at end of file
+b
\ No newline at end of file
',
'a',
'b',
],
[
'',
"1\n2",
"1\n2",
],
[
'',
"1\n",
"1\n",
],
[
'--- input.txt
+++ output.txt
@@ -4 +4 @@
-X
+4
',
"1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
[
'contextLines' => 0,
],
],
[
'--- input.txt
+++ output.txt
@@ -3,3 +3,3 @@
3
-X
+4
5
',
"1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
[
'contextLines' => 1,
],
],
[
'--- input.txt
+++ output.txt
@@ -1,10 +1,10 @@
1
2
3
-X
+4
5
6
7
8
9
0
',
"1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
[
'contextLines' => 999,
],
],
[
'--- input.txt
+++ output.txt
@@ -1,0 +1,2 @@
+
+A
',
'',
"\nA\n",
],
[
'--- input.txt
+++ output.txt
@@ -1,2 +1,0 @@
-
-A
',
"\nA\n",
'',
],
[
'--- input.txt
+++ output.txt
@@ -1,5 +1,5 @@
1
-X
+2
3
-Y
+4
5
@@ -8,3 +8,3 @@
8
-X
+9
0
',
"1\nX\n3\nY\n5\n6\n7\n8\nX\n0\n",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
[
'commonLineThreshold' => 2,
'contextLines' => 1,
],
],
[
'--- input.txt
+++ output.txt
@@ -2 +2 @@
-X
+2
@@ -4 +4 @@
-Y
+4
@@ -9 +9 @@
-X
+9
',
"1\nX\n3\nY\n5\n6\n7\n8\nX\n0\n",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
[
'commonLineThreshold' => 1,
'contextLines' => 0,
],
],
];
}
public function testReUseBuilder(): void
{
$differ = $this->getDiffer([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
]);
$diff = $differ->diff("A\nB\n", "A\nX\n");
$this->assertSame(
'--- input.txt
+++ output.txt
@@ -1,2 +1,2 @@
A
-B
+X
',
$diff
);
$diff = $differ->diff("A\n", "A\n");
$this->assertSame(
'',
$diff
);
}
public function testEmptyDiff(): void
{
$builder = new StrictUnifiedDiffOutputBuilder([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
]);
$this->assertSame(
'',
$builder->getDiff([])
);
}
/**
* @param array $options
* @param string $message
*
* @dataProvider provideInvalidConfiguration
*/
public function testInvalidConfiguration(array $options, string $message): void
{
$this->expectException(ConfigurationException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote($message, '#')));
new StrictUnifiedDiffOutputBuilder($options);
}
public function provideInvalidConfiguration(): array
{
$time = \time();
return [
[
['collapseRanges' => 1],
'Option "collapseRanges" must be a bool, got "integer#1".',
],
[
['contextLines' => 'a'],
'Option "contextLines" must be an int >= 0, got "string#a".',
],
[
['commonLineThreshold' => -2],
'Option "commonLineThreshold" must be an int > 0, got "integer#-2".',
],
[
['commonLineThreshold' => 0],
'Option "commonLineThreshold" must be an int > 0, got "integer#0".',
],
[
['fromFile' => new \SplFileInfo(__FILE__)],
'Option "fromFile" must be a string, got "SplFileInfo".',
],
[
['fromFile' => null],
'Option "fromFile" must be a string, got "<null>".',
],
[
[
'fromFile' => __FILE__,
'toFile' => 1,
],
'Option "toFile" must be a string, got "integer#1".',
],
[
[
'fromFile' => __FILE__,
'toFile' => __FILE__,
'toFileDate' => $time,
],
'Option "toFileDate" must be a string or <null>, got "integer#' . $time . '".',
],
[
[],
'Option "fromFile" must be a string, got "<null>".',
],
];
}
/**
* @param string $expected
* @param string $from
* @param string $to
* @param int $threshold
*
* @dataProvider provideCommonLineThresholdCases
*/
public function testCommonLineThreshold(string $expected, string $from, string $to, int $threshold): void
{
$diff = $this->getDiffer([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
'commonLineThreshold' => $threshold,
'contextLines' => 0,
])->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
public function provideCommonLineThresholdCases(): array
{
return [
[
'--- input.txt
+++ output.txt
@@ -2,3 +2,3 @@
-X
+B
C12
-Y
+D
@@ -7 +7 @@
-X
+Z
',
"A\nX\nC12\nY\nA\nA\nX\n",
"A\nB\nC12\nD\nA\nA\nZ\n",
2,
],
[
'--- input.txt
+++ output.txt
@@ -2 +2 @@
-X
+B
@@ -4 +4 @@
-Y
+D
',
"A\nX\nV\nY\n",
"A\nB\nV\nD\n",
1,
],
];
}
/**
* @param string $expected
* @param string $from
* @param string $to
* @param int $contextLines
* @param int $commonLineThreshold
*
* @dataProvider provideContextLineConfigurationCases
*/
public function testContextLineConfiguration(string $expected, string $from, string $to, int $contextLines, int $commonLineThreshold = 6): void
{
$diff = $this->getDiffer([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
'contextLines' => $contextLines,
'commonLineThreshold' => $commonLineThreshold,
])->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
public function provideContextLineConfigurationCases(): array
{
$from = "A\nB\nC\nD\nE\nF\nX\nG\nH\nI\nJ\nK\nL\nM\n";
$to = "A\nB\nC\nD\nE\nF\nY\nG\nH\nI\nJ\nK\nL\nM\n";
return [
'EOF 0' => [
"--- input.txt\n+++ output.txt\n@@ -3 +3 @@
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
"A\nB\nX",
"A\nB\nY",
0,
],
'EOF 1' => [
"--- input.txt\n+++ output.txt\n@@ -2,2 +2,2 @@
B
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
"A\nB\nX",
"A\nB\nY",
1,
],
'EOF 2' => [
"--- input.txt\n+++ output.txt\n@@ -1,3 +1,3 @@
A
B
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
"A\nB\nX",
"A\nB\nY",
2,
],
'EOF 200' => [
"--- input.txt\n+++ output.txt\n@@ -1,3 +1,3 @@
A
B
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
"A\nB\nX",
"A\nB\nY",
200,
],
'n/a 0' => [
"--- input.txt\n+++ output.txt\n@@ -7 +7 @@\n-X\n+Y\n",
$from,
$to,
0,
],
'G' => [
"--- input.txt\n+++ output.txt\n@@ -6,3 +6,3 @@\n F\n-X\n+Y\n G\n",
$from,
$to,
1,
],
'H' => [
"--- input.txt\n+++ output.txt\n@@ -5,5 +5,5 @@\n E\n F\n-X\n+Y\n G\n H\n",
$from,
$to,
2,
],
'I' => [
"--- input.txt\n+++ output.txt\n@@ -4,7 +4,7 @@\n D\n E\n F\n-X\n+Y\n G\n H\n I\n",
$from,
$to,
3,
],
'J' => [
"--- input.txt\n+++ output.txt\n@@ -3,9 +3,9 @@\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n",
$from,
$to,
4,
],
'K' => [
"--- input.txt\n+++ output.txt\n@@ -2,11 +2,11 @@\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n",
$from,
$to,
5,
],
'L' => [
"--- input.txt\n+++ output.txt\n@@ -1,13 +1,13 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n",
$from,
$to,
6,
],
'M' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
$from,
$to,
7,
],
'M no linebreak EOF .1' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n-M\n+M\n\\ No newline at end of file\n",
$from,
\substr($to, 0, -1),
7,
],
'M no linebreak EOF .2' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n-M\n\\ No newline at end of file\n+M\n",
\substr($from, 0, -1),
$to,
7,
],
'M no linebreak EOF .3' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
\substr($from, 0, -1),
\substr($to, 0, -1),
7,
],
'M no linebreak EOF .4' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n\\ No newline at end of file\n",
\substr($from, 0, -1),
\substr($to, 0, -1),
10000,
10000,
],
'M+1' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
$from,
$to,
8,
],
'M+100' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
$from,
$to,
107,
],
'0 II' => [
"--- input.txt\n+++ output.txt\n@@ -12 +12 @@\n-X\n+Y\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
0,
999,
],
'0\' II' => [
"--- input.txt\n+++ output.txt\n@@ -12 +12 @@\n-X\n+Y\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\nA\nA\nA\nA\nA\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\nA\nA\nA\nA\nA\n",
0,
999,
],
'0\'\' II' => [
"--- input.txt\n+++ output.txt\n@@ -12,2 +12,2 @@\n-X\n-M\n\\ No newline at end of file\n+Y\n+M\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
0,
],
'0\'\'\' II' => [
"--- input.txt\n+++ output.txt\n@@ -12,2 +12,2 @@\n-X\n-X1\n+Y\n+Y2\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nX1\nM\nA\nA\nA\nA\nA\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nY2\nM\nA\nA\nA\nA\nA\n",
0,
999,
],
'1 II' => [
"--- input.txt\n+++ output.txt\n@@ -11,3 +11,3 @@\n K\n-X\n+Y\n M\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
1,
],
'5 II' => [
"--- input.txt\n+++ output.txt\n@@ -7,7 +7,7 @@\n G\n H\n I\n J\n K\n-X\n+Y\n M\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
5,
],
[
'--- input.txt
+++ output.txt
@@ -1,28 +1,28 @@
A
-X
+B
V
-Y
+D
1
A
2
A
3
A
4
A
8
A
9
A
5
A
A
A
A
A
A
A
A
A
A
A
',
"A\nX\nV\nY\n1\nA\n2\nA\n3\nA\n4\nA\n8\nA\n9\nA\n5\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\n",
"A\nB\nV\nD\n1\nA\n2\nA\n3\nA\n4\nA\n8\nA\n9\nA\n5\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\n",
9999,
99999,
],
];
}
/**
* Returns a new instance of a Differ with a new instance of the class (DiffOutputBuilderInterface) under test.
*
* @param array $options
*
* @return Differ
*/
private function getDiffer(array $options = []): Differ
{
return new Differ(new StrictUnifiedDiffOutputBuilder($options));
}
}

View File

@@ -0,0 +1,396 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
final class UnifiedDiffOutputBuilderDataProvider
{
public static function provideDiffWithLineNumbers(): array
{
return [
'diff line 1 non_patch_compat' => [
'--- Original
+++ New
@@ -1 +1 @@
-AA
+BA
',
'AA',
'BA',
],
'diff line +1 non_patch_compat' => [
'--- Original
+++ New
@@ -1 +1,2 @@
-AZ
+
+B
',
'AZ',
"\nB",
],
'diff line -1 non_patch_compat' => [
'--- Original
+++ New
@@ -1,2 +1 @@
-
-AF
+B
',
"\nAF",
'B',
],
'II non_patch_compat' => [
'--- Original
+++ New
@@ -1,4 +1,2 @@
-
-
A
1
',
"\n\nA\n1",
"A\n1",
],
'diff last line II - no trailing linebreak non_patch_compat' => [
'--- Original
+++ New
@@ -5,4 +5,4 @@
' . '
' . '
' . '
-E
+B
',
"A\n\n\n\n\n\n\nE",
"A\n\n\n\n\n\n\nB",
],
[
"--- Original\n+++ New\n@@ -1,2 +1 @@\n \n-\n",
"\n\n",
"\n",
],
'diff line endings non_patch_compat' => [
"--- Original\n+++ New\n@@ -1 +1 @@\n #Warning: Strings contain different line endings!\n-<?php\r\n+<?php\n",
"<?php\r\n",
"<?php\n",
],
'same non_patch_compat' => [
'--- Original
+++ New
',
"AT\n",
"AT\n",
],
[
'--- Original
+++ New
@@ -1,4 +1,4 @@
-b
+a
' . '
' . '
' . '
',
"b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"a\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
],
'diff line @1' => [
'--- Original
+++ New
@@ -1,2 +1,2 @@
' . '
-AG
+B
',
"\nAG\n",
"\nB\n",
],
'same multiple lines' => [
'--- Original
+++ New
@@ -1,4 +1,4 @@
' . '
' . '
-V
+B
C213
',
"\n\nV\nC213",
"\n\nB\nC213",
],
'diff last line I' => [
'--- Original
+++ New
@@ -5,4 +5,4 @@
' . '
' . '
' . '
-E
+B
',
"A\n\n\n\n\n\n\nE\n",
"A\n\n\n\n\n\n\nB\n",
],
'diff line middle' => [
'--- Original
+++ New
@@ -5,7 +5,7 @@
' . '
' . '
' . '
-X
+Z
' . '
' . '
' . '
',
"A\n\n\n\n\n\n\nX\n\n\n\n\n\n\nAY",
"A\n\n\n\n\n\n\nZ\n\n\n\n\n\n\nAY",
],
'diff last line III' => [
'--- Original
+++ New
@@ -12,4 +12,4 @@
' . '
' . '
' . '
-A
+B
',
"A\n\n\n\n\n\n\nA\n\n\n\n\n\n\nA\n",
"A\n\n\n\n\n\n\nA\n\n\n\n\n\n\nB\n",
],
[
'--- Original
+++ New
@@ -1,8 +1,8 @@
A
-B
+B1
D
E
EE
F
-G
+G1
H
',
"A\nB\nD\nE\nEE\nF\nG\nH",
"A\nB1\nD\nE\nEE\nF\nG1\nH",
],
[
'--- Original
+++ New
@@ -1,4 +1,5 @@
Z
+
a
b
c
@@ -7,5 +8,5 @@
f
g
h
-i
+x
j
',
'Z
a
b
c
d
e
f
g
h
i
j
',
'Z
a
b
c
d
e
f
g
h
x
j
',
],
[
'--- Original
+++ New
@@ -1,7 +1,5 @@
-
-a
+b
A
-X
-
+Y
' . '
A
',
"\na\nA\nX\n\n\nA\n",
"b\nA\nY\n\nA\n",
],
[
<<<EOF
--- Original
+++ New
@@ -1,7 +1,5 @@
-
-
a
-b
+p
c
d
e
@@ -9,5 +7,5 @@
g
h
i
-j
+w
k
EOF
,
"\n\na\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n",
"a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk\n",
],
[
'--- Original
+++ New
@@ -8,7 +8,7 @@
' . '
' . '
' . '
-A
+C
' . '
' . '
' . '
',
"E\n\n\n\n\nB\n\n\n\n\nA\n\n\n\n\n\n\n\n\nD1",
"E\n\n\n\n\nB\n\n\n\n\nC\n\n\n\n\n\n\n\n\nD1",
],
[
'--- Original
+++ New
@@ -5,7 +5,7 @@
' . '
' . '
' . '
-Z
+U
' . '
' . '
' . '
@@ -12,7 +12,7 @@
' . '
' . '
' . '
-X
+V
' . '
' . '
' . '
@@ -19,7 +19,7 @@
' . '
' . '
' . '
-Y
+W
' . '
' . '
' . '
@@ -26,7 +26,7 @@
' . '
' . '
' . '
-W
+X
' . '
' . '
' . '
@@ -33,7 +33,7 @@
' . '
' . '
' . '
-V
+Y
' . '
' . '
' . '
@@ -40,4 +40,4 @@
' . '
' . '
' . '
-U
+Z
',
"\n\n\n\n\n\n\nZ\n\n\n\n\n\n\nX\n\n\n\n\n\n\nY\n\n\n\n\n\n\nW\n\n\n\n\n\n\nV\n\n\n\n\n\n\nU\n",
"\n\n\n\n\n\n\nU\n\n\n\n\n\n\nV\n\n\n\n\n\n\nW\n\n\n\n\n\n\nX\n\n\n\n\n\n\nY\n\n\n\n\n\n\nZ\n",
],
[
<<<EOF
--- Original
+++ New
@@ -1,5 +1,5 @@
a
-b
+p
c
d
e
@@ -7,5 +7,5 @@
g
h
i
-j
+w
k
EOF
,
"a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n",
"a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk\n",
],
[
<<<EOF
--- Original
+++ New
@@ -1,4 +1,4 @@
-A
+B
1
2
3
EOF
,
"A\n1\n2\n3\n4\n5\n6\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1",
"B\n1\n2\n3\n4\n5\n6\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1",
],
[
"--- Original\n+++ New\n@@ -4,7 +4,7 @@\n D\n E\n F\n-X\n+Y\n G\n H\n I\n",
"A\nB\nC\nD\nE\nF\nX\nG\nH\nI\nJ\nK\nL\nM\n",
"A\nB\nC\nD\nE\nF\nY\nG\nH\nI\nJ\nK\nL\nM\n",
],
];
}
}

View File

@@ -0,0 +1,90 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Differ;
/**
* @covers SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder
*
* @uses SebastianBergmann\Diff\Differ
* @uses SebastianBergmann\Diff\Output\AbstractChunkOutputBuilder
* @uses SebastianBergmann\Diff\TimeEfficientLongestCommonSubsequenceCalculator
*/
final class UnifiedDiffOutputBuilderTest extends TestCase
{
/**
* @param string $expected
* @param string $from
* @param string $to
* @param string $header
*
* @dataProvider headerProvider
*/
public function testCustomHeaderCanBeUsed(string $expected, string $from, string $to, string $header): void
{
$differ = new Differ(new UnifiedDiffOutputBuilder($header));
$this->assertSame(
$expected,
$differ->diff($from, $to)
);
}
public function headerProvider(): array
{
return [
[
"CUSTOM HEADER\n@@ @@\n-a\n+b\n",
'a',
'b',
'CUSTOM HEADER',
],
[
"CUSTOM HEADER\n@@ @@\n-a\n+b\n",
'a',
'b',
"CUSTOM HEADER\n",
],
[
"CUSTOM HEADER\n\n@@ @@\n-a\n+b\n",
'a',
'b',
"CUSTOM HEADER\n\n",
],
[
"@@ @@\n-a\n+b\n",
'a',
'b',
'',
],
];
}
/**
* @param string $expected
* @param string $from
* @param string $to
*
* @dataProvider provideDiffWithLineNumbers
*/
public function testDiffWithLineNumbers($expected, $from, $to): void
{
$differ = new Differ(new UnifiedDiffOutputBuilder("--- Original\n+++ New\n", true));
$this->assertSame($expected, $differ->diff($from, $to));
}
public function provideDiffWithLineNumbers(): array
{
return UnifiedDiffOutputBuilderDataProvider::provideDiffWithLineNumbers();
}
}

View File

@@ -11,6 +11,7 @@
namespace SebastianBergmann\Diff;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Utils\FileUtils;
/**
* @covers SebastianBergmann\Diff\Parser
@@ -26,14 +27,14 @@ final class ParserTest extends TestCase
*/
private $parser;
protected function setUp()
protected function setUp(): void
{
$this->parser = new Parser;
}
public function testParse()
public function testParse(): void
{
$content = \file_get_contents(__DIR__ . '/fixtures/patch.txt');
$content = FileUtils::getFileContent(__DIR__ . '/fixtures/patch.txt');
$diffs = $this->parser->parse($content);
@@ -52,9 +53,9 @@ final class ParserTest extends TestCase
$this->assertCount(4, $chunks[0]->getLines());
}
public function testParseWithMultipleChunks()
public function testParseWithMultipleChunks(): void
{
$content = \file_get_contents(__DIR__ . '/fixtures/patch2.txt');
$content = FileUtils::getFileContent(__DIR__ . '/fixtures/patch2.txt');
$diffs = $this->parser->parse($content);
@@ -72,9 +73,9 @@ final class ParserTest extends TestCase
$this->assertCount(4, $chunks[2]->getLines());
}
public function testParseWithRemovedLines()
public function testParseWithRemovedLines(): void
{
$content = <<<A
$content = <<<END
diff --git a/Test.txt b/Test.txt
index abcdefg..abcdefh 100644
--- a/Test.txt
@@ -82,7 +83,7 @@ index abcdefg..abcdefh 100644
@@ -49,9 +49,8 @@
A
-B
A;
END;
$diffs = $this->parser->parse($content);
$this->assertInternalType('array', $diffs);
$this->assertContainsOnlyInstancesOf(Diff::class, $diffs);
@@ -115,9 +116,9 @@ A;
$this->assertSame(Line::REMOVED, $line->getType());
}
public function testParseDiffForMulitpleFiles()
public function testParseDiffForMulitpleFiles(): void
{
$content = <<<A
$content = <<<END
diff --git a/Test.txt b/Test.txt
index abcdefg..abcdefh 100644
--- a/Test.txt
@@ -133,7 +134,7 @@ index abcdefg..abcdefh 100644
@@ -1,2 +1,3 @@
A
+B
A;
END;
$diffs = $this->parser->parse($content);
$this->assertCount(2, $diffs);
@@ -148,4 +149,27 @@ A;
$this->assertSame('b/Test2.txt', $diff->getTo());
$this->assertCount(1, $diff->getChunks());
}
/**
* @param string $diff
* @param Diff[] $expected
*
* @dataProvider diffProvider
*/
public function testParser(string $diff, array $expected): void
{
$result = $this->parser->parse($diff);
$this->assertEquals($expected, $result);
}
public function diffProvider(): array
{
return [
[
"--- old.txt 2014-11-04 08:51:02.661868729 +0300\n+++ new.txt 2014-11-04 08:51:02.665868730 +0300\n@@ -1,3 +1,4 @@\n+2222111\n 1111111\n 1111111\n 1111111\n@@ -5,10 +6,8 @@\n 1111111\n 1111111\n 1111111\n +1121211\n 1111111\n -1111111\n -1111111\n -2222222\n 2222222\n 2222222\n 2222222\n@@ -17,5 +16,6 @@\n 2222222\n 2222222\n 2222222\n +2122212\n 2222222\n 2222222\n",
\unserialize(FileUtils::getFileContent(__DIR__ . '/fixtures/serialized_diff.bin')),
],
];
}
}

View File

@@ -15,7 +15,7 @@ namespace SebastianBergmann\Diff;
*/
final class TimeEfficientImplementationTest extends LongestCommonSubsequenceTest
{
protected function createImplementation()
protected function createImplementation(): LongestCommonSubsequenceCalculator
{
return new TimeEfficientLongestCommonSubsequenceCalculator;
}

View File

@@ -0,0 +1,31 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Utils;
final class FileUtils
{
public static function getFileContent(string $file): string
{
$content = @\file_get_contents($file);
if (false === $content) {
$error = \error_get_last();
throw new \RuntimeException(\sprintf(
'Failed to read content of file "%s".%s',
$file,
$error ? ' ' . $error['message'] : ''
));
}
return $content;
}
}

View File

@@ -0,0 +1,277 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Utils;
trait UnifiedDiffAssertTrait
{
/**
* @param string $diff
*
* @throws \UnexpectedValueException
*/
public function assertValidUnifiedDiffFormat(string $diff): void
{
if ('' === $diff) {
$this->addToAssertionCount(1);
return;
}
// test diff ends with a line break
$last = \substr($diff, -1);
if ("\n" !== $last && "\r" !== $last) {
throw new \UnexpectedValueException(\sprintf('Expected diff to end with a line break, got "%s".', $last));
}
$lines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$lineCount = \count($lines);
$lineNumber = $diffLineFromNumber = $diffLineToNumber = 1;
$fromStart = $fromTillOffset = $toStart = $toTillOffset = -1;
$expectHunkHeader = true;
// check for header
if ($lineCount > 1) {
$this->unifiedDiffAssertLinePrefix($lines[0], 'Line 1.');
$this->unifiedDiffAssertLinePrefix($lines[1], 'Line 2.');
if ('---' === \substr($lines[0], 0, 3)) {
if ('+++' !== \substr($lines[1], 0, 3)) {
throw new \UnexpectedValueException(\sprintf("Line 1 indicates a header, so line 2 must start with \"+++\".\nLine 1: \"%s\"\nLine 2: \"%s\".", $lines[0], $lines[1]));
}
$this->unifiedDiffAssertHeaderLine($lines[0], '--- ', 'Line 1.');
$this->unifiedDiffAssertHeaderLine($lines[1], '+++ ', 'Line 2.');
$lineNumber = 3;
}
}
$endOfLineTypes = [];
$diffClosed = false;
// assert format of lines, get all hunks, test the line numbers
for (; $lineNumber <= $lineCount; ++$lineNumber) {
if ($diffClosed) {
throw new \UnexpectedValueException(\sprintf('Unexpected line as 2 "No newline" markers have found, ". Line %d.', $lineNumber));
}
$line = $lines[$lineNumber - 1]; // line numbers start by 1, array index at 0
$type = $this->unifiedDiffAssertLinePrefix($line, \sprintf('Line %d.', $lineNumber));
if ($expectHunkHeader && '@' !== $type && '\\' !== $type) {
throw new \UnexpectedValueException(\sprintf('Expected hunk start (\'@\'), got "%s". Line %d.', $type, $lineNumber));
}
if ('@' === $type) {
if (!$expectHunkHeader) {
throw new \UnexpectedValueException(\sprintf('Unexpected hunk start (\'@\'). Line %d.', $lineNumber));
}
$previousHunkFromEnd = $fromStart + $fromTillOffset;
$previousHunkTillEnd = $toStart + $toTillOffset;
[$fromStart, $fromTillOffset, $toStart, $toTillOffset] = $this->unifiedDiffAssertHunkHeader($line, \sprintf('Line %d.', $lineNumber));
// detect overlapping hunks
if ($fromStart < $previousHunkFromEnd) {
throw new \UnexpectedValueException(\sprintf('Unexpected new hunk; "from" (\'-\') start overlaps previous hunk. Line %d.', $lineNumber));
}
if ($toStart < $previousHunkTillEnd) {
throw new \UnexpectedValueException(\sprintf('Unexpected new hunk; "to" (\'+\') start overlaps previous hunk. Line %d.', $lineNumber));
}
/* valid states; hunks touches against each other:
$fromStart === $previousHunkFromEnd
$toStart === $previousHunkTillEnd
*/
$diffLineFromNumber = $fromStart;
$diffLineToNumber = $toStart;
$expectHunkHeader = false;
continue;
}
if ('-' === $type) {
if (isset($endOfLineTypes['-'])) {
throw new \UnexpectedValueException(\sprintf('Not expected from (\'-\'), already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
}
++$diffLineFromNumber;
} elseif ('+' === $type) {
if (isset($endOfLineTypes['+'])) {
throw new \UnexpectedValueException(\sprintf('Not expected to (\'+\'), already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
}
++$diffLineToNumber;
} elseif (' ' === $type) {
if (isset($endOfLineTypes['-'])) {
throw new \UnexpectedValueException(\sprintf('Not expected same (\' \'), \'-\' already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
}
if (isset($endOfLineTypes['+'])) {
throw new \UnexpectedValueException(\sprintf('Not expected same (\' \'), \'+\' already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
}
++$diffLineFromNumber;
++$diffLineToNumber;
} elseif ('\\' === $type) {
if (!isset($lines[$lineNumber - 2])) {
throw new \UnexpectedValueException(\sprintf('Unexpected "\\ No newline at end of file", it must be preceded by \'+\' or \'-\' line. Line %d.', $lineNumber));
}
$previousType = $this->unifiedDiffAssertLinePrefix($lines[$lineNumber - 2], \sprintf('Preceding line of "\\ No newline at end of file" of unexpected format. Line %d.', $lineNumber));
if (isset($endOfLineTypes[$previousType])) {
throw new \UnexpectedValueException(\sprintf('Unexpected "\\ No newline at end of file", "%s" was already closed. Line %d.', $type, $lineNumber));
}
$endOfLineTypes[$previousType] = true;
$diffClosed = \count($endOfLineTypes) > 1;
} else {
// internal state error
throw new \RuntimeException(\sprintf('Unexpected line type "%s" Line %d.', $type, $lineNumber));
}
$expectHunkHeader =
$diffLineFromNumber === ($fromStart + $fromTillOffset)
&& $diffLineToNumber === ($toStart + $toTillOffset)
;
}
if (
$diffLineFromNumber !== ($fromStart + $fromTillOffset)
&& $diffLineToNumber !== ($toStart + $toTillOffset)
) {
throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "from" (\'-\')) and "to" (\'+\') mismatched. Line %d.', $lineNumber));
}
if ($diffLineFromNumber !== ($fromStart + $fromTillOffset)) {
throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "from" (\'-\')) mismatched. Line %d.', $lineNumber));
}
if ($diffLineToNumber !== ($toStart + $toTillOffset)) {
throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "to" (\'+\')) mismatched. Line %d.', $lineNumber));
}
$this->addToAssertionCount(1);
}
/**
* @param string $line
* @param string $message
*
* @return string '+', '-', '@', ' ' or '\'
*/
private function unifiedDiffAssertLinePrefix(string $line, string $message): string
{
$this->unifiedDiffAssertStrLength($line, 2, $message); // 2: line type indicator ('+', '-', ' ' or '\') and a line break
$firstChar = $line[0];
if ('+' === $firstChar || '-' === $firstChar || '@' === $firstChar || ' ' === $firstChar) {
return $firstChar;
}
if ("\\ No newline at end of file\n" === $line) {
return '\\';
}
throw new \UnexpectedValueException(\sprintf('Expected line to start with \'@\', \'-\' or \'+\', got "%s". %s', $line, $message));
}
private function unifiedDiffAssertStrLength(string $line, int $min, string $message): void
{
$length = \strlen($line);
if ($length < $min) {
throw new \UnexpectedValueException(\sprintf('Expected string length of minimal %d, got %d. %s', $min, $length, $message));
}
}
/**
* Assert valid unified diff header line
*
* Samples:
* - "+++ from1.txt\t2017-08-24 19:51:29.383985722 +0200"
* - "+++ from1.txt"
*
* @param string $line
* @param string $start
* @param string $message
*/
private function unifiedDiffAssertHeaderLine(string $line, string $start, string $message): void
{
if (0 !== \strpos($line, $start)) {
throw new \UnexpectedValueException(\sprintf('Expected header line to start with "%s", got "%s". %s', $start . ' ', $line, $message));
}
// sample "+++ from1.txt\t2017-08-24 19:51:29.383985722 +0200\n"
$match = \preg_match(
"/^([^\t]*)(?:[\t]([\\S].*[\\S]))?\n$/",
\substr($line, 4), // 4 === string length of "+++ " / "--- "
$matches
);
if (1 !== $match) {
throw new \UnexpectedValueException(\sprintf('Header line does not match expected pattern, got "%s". %s', $line, $message));
}
// $file = $matches[1];
if (\count($matches) > 2) {
$this->unifiedDiffAssertHeaderDate($matches[2], $message);
}
}
private function unifiedDiffAssertHeaderDate(string $date, string $message): void
{
// sample "2017-08-24 19:51:29.383985722 +0200"
$match = \preg_match(
'/^([\d]{4})-([01]?[\d])-([0123]?[\d])(:? [\d]{1,2}:[\d]{1,2}(?::[\d]{1,2}(:?\.[\d]+)?)?(?: ([\+\-][\d]{4}))?)?$/',
$date,
$matches
);
if (1 !== $match || ($matchesCount = \count($matches)) < 4) {
throw new \UnexpectedValueException(\sprintf('Date of header line does not match expected pattern, got "%s". %s', $date, $message));
}
// [$full, $year, $month, $day, $time] = $matches;
}
/**
* @param string $line
* @param string $message
*
* @return int[]
*/
private function unifiedDiffAssertHunkHeader(string $line, string $message): array
{
if (1 !== \preg_match('#^@@ -([\d]+)((?:,[\d]+)?) \+([\d]+)((?:,[\d]+)?) @@\n$#', $line, $matches)) {
throw new \UnexpectedValueException(
\sprintf(
'Hunk header line does not match expected pattern, got "%s". %s',
$line,
$message
)
);
}
return [
(int) $matches[1],
empty($matches[2]) ? 1 : (int) \substr($matches[2], 1),
(int) $matches[3],
empty($matches[4]) ? 1 : (int) \substr($matches[4], 1),
];
}
}

View File

@@ -0,0 +1,129 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Utils;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Process;
/**
* @requires OS Linux
*
* @coversNothing
*/
final class UnifiedDiffAssertTraitIntegrationTest extends TestCase
{
use UnifiedDiffAssertTrait;
private $filePatch;
protected function setUp(): void
{
$this->filePatch = __DIR__ . '/../fixtures/out/patch.txt';
$this->cleanUpTempFiles();
}
protected function tearDown(): void
{
$this->cleanUpTempFiles();
}
/**
* @param string $fileFrom
* @param string $fileTo
*
* @dataProvider provideFilePairsCases
*/
public function testValidPatches(string $fileFrom, string $fileTo): void
{
$command = \sprintf(
'diff -u %s %s > %s',
\escapeshellarg(\realpath($fileFrom)),
\escapeshellarg(\realpath($fileTo)),
\escapeshellarg($this->filePatch)
);
$p = new Process($command);
$p->run();
$exitCode = $p->getExitCode();
if (0 === $exitCode) {
// odd case when two files have the same content. Test after executing as it is more efficient than to read the files and check the contents every time.
$this->addToAssertionCount(1);
return;
}
$this->assertSame(
1, // means `diff` found a diff between the files we gave it
$exitCode,
\sprintf(
"Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n",
$command,
$p->getOutput(),
$p->getErrorOutput(),
$p->getExitCode()
)
);
$this->assertValidUnifiedDiffFormat(FileUtils::getFileContent($this->filePatch));
}
/**
* @return array<string, array<string, string>>
*/
public function provideFilePairsCases(): array
{
$cases = [];
// created cases based on dedicated fixtures
$dir = \realpath(__DIR__ . '/../fixtures/UnifiedDiffAssertTraitIntegrationTest');
$dirLength = \strlen($dir);
for ($i = 1;; ++$i) {
$fromFile = \sprintf('%s/%d_a.txt', $dir, $i);
$toFile = \sprintf('%s/%d_b.txt', $dir, $i);
if (!\file_exists($fromFile)) {
break;
}
$this->assertFileExists($toFile);
$cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \substr(\realpath($fromFile), $dirLength), \substr(\realpath($toFile), $dirLength))] = [$fromFile, $toFile];
}
// create cases based on PHP files within the vendor directory for integration testing
$dir = \realpath(__DIR__ . '/../../vendor');
$dirLength = \strlen($dir);
$fileIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS));
$fromFile = __FILE__;
/** @var \SplFileInfo $file */
foreach ($fileIterator as $file) {
if ('php' !== $file->getExtension()) {
continue;
}
$toFile = $file->getPathname();
$cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \substr(\realpath($fromFile), $dirLength), \substr(\realpath($toFile), $dirLength))] = [$fromFile, $toFile];
$fromFile = $toFile;
}
return $cases;
}
private function cleanUpTempFiles(): void
{
@\unlink($this->filePatch);
}
}

View File

@@ -0,0 +1,434 @@
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Utils;
use PHPUnit\Framework\TestCase;
/**
* @covers SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait
*/
final class UnifiedDiffAssertTraitTest extends TestCase
{
use UnifiedDiffAssertTrait;
/**
* @param string $diff
*
* @dataProvider provideValidCases
*/
public function testValidCases(string $diff): void
{
$this->assertValidUnifiedDiffFormat($diff);
}
public function provideValidCases(): array
{
return [
[
'--- Original
+++ New
@@ -8 +8 @@
-Z
+U
',
],
[
'--- Original
+++ New
@@ -8 +8 @@
-Z
+U
@@ -15 +15 @@
-X
+V
',
],
'empty diff. is valid' => [
'',
],
];
}
public function testNoLinebreakEnd(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected diff to end with a line break, got "C".', '#')));
$this->assertValidUnifiedDiffFormat("A\nB\nC");
}
public function testInvalidStartWithoutHeader(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected line to start with '@', '-' or '+', got \"A\n\". Line 1.", '#')));
$this->assertValidUnifiedDiffFormat("A\n");
}
public function testInvalidStartHeader1(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Line 1 indicates a header, so line 2 must start with \"+++\".\nLine 1: \"--- A\n\"\nLine 2: \"+ 1\n\".", '#')));
$this->assertValidUnifiedDiffFormat("--- A\n+ 1\n");
}
public function testInvalidStartHeader2(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Header line does not match expected pattern, got \"+++ file X\n\". Line 2.", '#')));
$this->assertValidUnifiedDiffFormat("--- A\n+++ file\tX\n");
}
public function testInvalidStartHeader3(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Date of header line does not match expected pattern, got "[invalid date]". Line 1.', '#')));
$this->assertValidUnifiedDiffFormat(
"--- Original\t[invalid date]
+++ New
@@ -1,2 +1,2 @@
-A
+B
" . '
'
);
}
public function testInvalidStartHeader4(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected header line to start with \"+++ \", got \"+++INVALID\n\". Line 2.", '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++INVALID
@@ -1,2 +1,2 @@
-A
+B
' . '
'
);
}
public function testInvalidLine1(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected line to start with '@', '-' or '+', got \"1\n\". Line 5.", '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
-Z
1
+U
'
);
}
public function testInvalidLine2(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected string length of minimal 2, got 1. Line 4.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
'
);
}
public function testHunkInvalidFormat(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Hunk header line does not match expected pattern, got \"@@ INVALID -1,1 +1,1 @@\n\". Line 3.", '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ INVALID -1,1 +1,1 @@
-Z
+U
'
);
}
public function testHunkOverlapFrom(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected new hunk; "from" (\'-\') start overlaps previous hunk. Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,1 +8,1 @@
-Z
+U
@@ -7,1 +9,1 @@
-Z
+U
'
);
}
public function testHunkOverlapTo(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected new hunk; "to" (\'+\') start overlaps previous hunk. Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,1 +8,1 @@
-Z
+U
@@ -17,1 +7,1 @@
-Z
+U
'
);
}
public function testExpectHunk1(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected hunk start (\'@\'), got "+". Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
-Z
+U
+O
'
);
}
public function testExpectHunk2(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected hunk start (\'@\'). Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
' . '
' . '
@@ -38,12 +48,12 @@
'
);
}
public function testMisplacedLineAfterComments1(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 8.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
-Z
\ No newline at end of file
+U
\ No newline at end of file
+A
'
);
}
public function testMisplacedLineAfterComments2(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 7.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
+U
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
'
);
}
public function testMisplacedLineAfterComments3(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 7.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
+U
\ No newline at end of file
\ No newline at end of file
+A
'
);
}
public function testMisplacedComment(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected "\ No newline at end of file", it must be preceded by \'+\' or \'-\' line. Line 1.', '#')));
$this->assertValidUnifiedDiffFormat(
'\ No newline at end of file
'
);
}
public function testUnexpectedDuplicateNoNewLineEOF(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected "\\ No newline at end of file", "\\" was already closed. Line 8.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
' . '
' . '
\ No newline at end of file
' . '
\ No newline at end of file
'
);
}
public function testFromAfterClose(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected from (\'-\'), already closed by "\ No newline at end of file". Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
-A
\ No newline at end of file
-A
\ No newline at end of file
'
);
}
public function testSameAfterFromClose(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected same (\' \'), \'-\' already closed by "\ No newline at end of file". Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
-A
\ No newline at end of file
A
\ No newline at end of file
'
);
}
public function testToAfterClose(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected to (\'+\'), already closed by "\ No newline at end of file". Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
+A
\ No newline at end of file
+A
\ No newline at end of file
'
);
}
public function testSameAfterToClose(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected same (\' \'), \'+\' already closed by "\ No newline at end of file". Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
+A
\ No newline at end of file
A
\ No newline at end of file
'
);
}
public function testUnexpectedEOFFromMissingLines(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "from" (\'-\')) mismatched. Line 7.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,19 +7,2 @@
-A
+B
' . '
'
);
}
public function testUnexpectedEOFToMissingLines(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "to" (\'+\')) mismatched. Line 7.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,2 +7,3 @@
-A
+B
' . '
'
);
}
public function testUnexpectedEOFBothFromAndToMissingLines(): void
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "from" (\'-\')) and "to" (\'+\') mismatched. Line 7.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -1,12 +1,14 @@
-A
+B
' . '
'
);
}
}

View File

@@ -0,0 +1 @@
root = true

View File

@@ -0,0 +1,35 @@
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a
a

View File

@@ -0,0 +1,18 @@
a
a
a
a
a
a
a
a
a
a
b
a
a
a
a
a
a
c

View File

@@ -0,0 +1 @@
root = true

View File

@@ -0,0 +1,2 @@
# reset all ignore rules to create sandbox for integration test
!/**

Binary file not shown.