From cb63d29ace83919be4dad1df29168f26e6a2898f Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Thu, 17 Oct 2024 21:17:20 +0800 Subject: [PATCH] MDL-83468 phpunit: Add back deprecated assertTag --- lib/phpunit/classes/base_testcase.php | 53 ++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/lib/phpunit/classes/base_testcase.php b/lib/phpunit/classes/base_testcase.php index b6a2e88655d..d28ea05f43f 100644 --- a/lib/phpunit/classes/base_testcase.php +++ b/lib/phpunit/classes/base_testcase.php @@ -55,12 +55,57 @@ abstract class base_testcase extends PHPUnit\Framework\TestCase { * @deprecated 3.0 */ public static function assertTag($matcher, $actual, $message = '', $ishtml = true) { - $dom = (new PHPUnit\Util\Xml\Loader)->load($actual, $ishtml); + if ($ishtml) { + $dom = self::loadHTML($actual); + } else { + $dom = (new PHPUnit\Util\Xml\Loader)->load($actual); + } $tags = self::findNodes($dom, $matcher, $ishtml); $matched = (is_array($tags) && count($tags) > 0) && $tags[0] instanceof DOMNode; self::assertTrue($matched, $message); } + /** + * Load HTML into a DomDocument. + * + * Note: THis is a replacement for functionality removed from PHPUnit 10. + * + * @param string $actual + * @throws \PHPUnit\Util\Xml\XmlException + * @return DOMDocument + */ + public static function loadHTML(string $actual): DOMDocument { + if ($actual === '') { + throw new \PHPUnit\Util\Xml\XmlException('Could not load XML from empty string'); + } + + $document = new DOMDocument; + $document->preserveWhiteSpace = false; + + $internal = libxml_use_internal_errors(true); + $message = ''; + $reporting = error_reporting(0); + + $loaded = $document->loadHTML($actual); + + foreach (libxml_get_errors() as $error) { + $message .= "\n" . $error->message; + } + + libxml_use_internal_errors($internal); + error_reporting($reporting); + + if ($loaded === false) { + if ($message === '') { + $message = 'Could not load XML for unknown reason'; + } + + throw new \PHPUnit\Util\Xml\XmlException($message); + } + + return $document; + } + /** * Note: we are overriding this method to remove the deprecated error * @see https://tracker.moodle.org/browse/MDL-47129 @@ -73,7 +118,11 @@ abstract class base_testcase extends PHPUnit\Framework\TestCase { * @deprecated 3.0 */ public static function assertNotTag($matcher, $actual, $message = '', $ishtml = true) { - $dom = (new PHPUnit\Util\Xml\Loader)->load($actual, $ishtml); + if ($ishtml) { + $dom = self::loadHTML($actual); + } else { + $dom = (new PHPUnit\Util\Xml\Loader)->load($actual); + } $tags = self::findNodes($dom, $matcher, $ishtml); $matched = (is_array($tags) && count($tags) > 0) && $tags[0] instanceof DOMNode; self::assertFalse($matched, $message);