|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Tests for the saveDomDocument() function. |
| 4 | + * |
| 5 | + * @group admin |
| 6 | + * |
| 7 | + * @covers ::saveDomDocument |
| 8 | + */ |
| 9 | +class Tests_saveDomDocument extends WP_UnitTestCase { |
| 10 | + /** |
| 11 | + * Path to the temporary file. |
| 12 | + * |
| 13 | + * @var string |
| 14 | + */ |
| 15 | + private $temp_file; |
| 16 | + |
| 17 | + /** |
| 18 | + * Set up the test environment. |
| 19 | + */ |
| 20 | + public function set_up() { |
| 21 | + parent::set_up(); |
| 22 | + require_once ABSPATH . 'wp-admin/includes/misc.php'; |
| 23 | + $this->temp_file = wp_tempnam( 'saveDomDocument' ); |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * Clean up the test environment. |
| 28 | + */ |
| 29 | + public function tear_down() { |
| 30 | + if ( file_exists( $this->temp_file ) ) { |
| 31 | + unlink( $this->temp_file ); |
| 32 | + } |
| 33 | + parent::tear_down(); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Tests that saveDomDocument() correctly saves a DOMDocument to a file. |
| 38 | + * |
| 39 | + * @ticket 65173 |
| 40 | + */ |
| 41 | + public function test_saveDomDocument_saves_file() { |
| 42 | + $doc = new DOMDocument(); |
| 43 | + $root = $doc->createElement( 'root' ); |
| 44 | + $doc->appendChild( $root ); |
| 45 | + |
| 46 | + saveDomDocument( $doc, $this->temp_file ); |
| 47 | + |
| 48 | + $this->assertFileExists( $this->temp_file, 'The file should be saved.' ); |
| 49 | + $this->assertXmlStringEqualsXmlFile( $this->temp_file, $doc->saveXML(), 'The saved file content should match the XML.' ); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Tests that saveDomDocument() converts LF to CRLF. |
| 54 | + * |
| 55 | + * @ticket 65173 |
| 56 | + */ |
| 57 | + public function test_saveDomDocument_converts_line_endings() { |
| 58 | + $doc = new DOMDocument(); |
| 59 | + // Create a multi-line XML. |
| 60 | + $root = $doc->createElement( 'root' ); |
| 61 | + $child1 = $doc->createElement( 'child', 'one' ); |
| 62 | + $child2 = $doc->createElement( 'child', 'two' ); |
| 63 | + $root->appendChild( $child1 ); |
| 64 | + $root->appendChild( $child2 ); |
| 65 | + $doc->appendChild( $root ); |
| 66 | + $doc->formatOutput = true; |
| 67 | + |
| 68 | + saveDomDocument( $doc, $this->temp_file ); |
| 69 | + |
| 70 | + $content = file_get_contents( $this->temp_file ); |
| 71 | + |
| 72 | + // The function replaces [^\r]\n with \r\n. |
| 73 | + // Note: DOMDocument::saveXML() usually outputs LF on Linux environments where these tests run in Docker. |
| 74 | + |
| 75 | + $this->assertStringContainsString( "\r\n", $content, 'The output should contain CRLF line endings.' ); |
| 76 | + $this->assertStringNotContainsString( "(?<!\r)\n", $content, 'The output should not contain bare LF line endings.' ); |
| 77 | + } |
| 78 | +} |
0 commit comments