Skip to content

Commit

Permalink
[CLEANUP] Whitespace-agnostic HTML test comparison
Browse files Browse the repository at this point in the history
In tests for `AbstractHtmlProcessor`, ignore whitespace differences in the outer
`<html>` element.

This will help with #831.

Also added test that the `<body>` content passed to `fromHtml()` is preserved
and returned by `render()`.
  • Loading branch information
JakeQZ committed Mar 31, 2020
1 parent 9a1cba2 commit feee440
Showing 1 changed file with 55 additions and 3 deletions.
58 changes: 55 additions & 3 deletions tests/Unit/HtmlProcessor/AbstractHtmlProcessorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,20 @@ public function renderRendersDocumentProvidedToFromDomDocument()
/**
* @test
*/
public function reformatsHtml()
public function renderPreservesBodyContentProvidedToFromHtml()
{
$innerHtml = '<p>Hello world!</p>';
$subject = TestingHtmlProcessor::fromHtml('<html>' . $innerHtml . '</html>');

$html = $subject->render();

self::assertContains($innerHtml, $html);
}

/**
* @test
*/
public function renderPreservesOuterHtmlProvidedToFromHtml()
{
$rawHtml = '<!DOCTYPE HTML>' .
'<html>' .
Expand All @@ -93,8 +106,9 @@ public function reformatsHtml()
"</html>\n";

$subject = TestingHtmlProcessor::fromHtml($rawHtml);
$html = $subject->render();

self::assertSame($formattedHtml, $subject->render());
self::assertEqualsHtml($formattedHtml, $html);
}

/**
Expand Down Expand Up @@ -706,7 +720,7 @@ public function getDomDocumentWithNormalizedHtmlRepresentsTheGivenHtml()

$domDocument = $subject->getDomDocument();

self::assertSame($html, $domDocument->saveHTML());
self::assertEqualsHtml($html, $domDocument->saveHTML());
}

/**
Expand All @@ -732,4 +746,42 @@ public function getDomDocumentVoidElementNotHasChildNodes(string $htmlWithNonXml
self::assertFalse($element->hasChildNodes());
}
}

/**
* Asserts that two HTML strings are equal, allowing for whitespace differences in the HTML element itself (but not
* its descendants) and after its closing tag.
*
* @param string $expected
* @param string $actual
* @param string $message
*/
private static function assertEqualsHtml(string $expected, string $actual, string $message = '')
{
$normalizedExpected = self::normalizeHtml($expected);
$normalizedActual = self::normalizeHtml($actual);

self::assertSame($normalizedExpected, $normalizedActual, $message);
}

/**
* Normalizes whitespace in the HTML element itself (but not its descendants) and after its closing tag, with a
* single newline inserted or replacing whitespace at positions where whitespace may occur but is superfluous.
*
* @param string $html
*
* @return string
*/
private static function normalizeHtml(string $html)
{
return \preg_replace(
[
'%(<html(?=[\\s>])[^>]*+>)\\s*+(<head[\\s>])%',
'%(</head>)\\s*+(<body[\\s>])%',
'%(</body>)\\s*+(</html>)%',
'%(</html>)\\s*+($)%',
],
"$1\n$2",
$html
);
}
}

0 comments on commit feee440

Please sign in to comment.