View Javadoc
1   /*
2    * Copyright (c) 2002-2025 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit;
16  
17  import java.io.File;
18  import java.nio.charset.StandardCharsets;
19  
20  import org.apache.commons.io.FileUtils;
21  import org.htmlunit.junit.BrowserRunner;
22  import org.junit.Rule;
23  import org.junit.Test;
24  import org.junit.rules.TemporaryFolder;
25  import org.junit.runner.RunWith;
26  
27  /**
28   * Tests for text content.
29   *
30   * @author Ronald Brill
31   */
32  @RunWith(BrowserRunner.class)
33  public class TextPageTest extends WebServerTestCase {
34  
35      /**
36       * Utility for temporary folders.
37       * Has to be public due to JUnit's constraints for @Rule.
38       */
39      @Rule
40      public final TemporaryFolder tmpFolderProvider_ = new TemporaryFolder();
41  
42      /**
43       * @throws Exception if the test fails
44       */
45      @Test
46      public void save() throws Exception {
47          final String response = "HTTP/1.1 200 OK\r\n"
48                  + "Content-Type: text/plain\r\n"
49                  + "\r\n"
50                  + "HtmlUnit Text Response";
51  
52          try (PrimitiveWebServer primitiveWebServer = new PrimitiveWebServer(null, response, null)) {
53              final WebClient client = getWebClient();
54  
55              final TextPage page = client.getPage("http://localhost:" + primitiveWebServer.getPort() + "/" + "text");
56  
57              final File tmpFolder = tmpFolderProvider_.newFolder("hu");
58              final File file = new File(tmpFolder, "hu_txt.plain");
59              page.save(file);
60              assertTrue(file.exists());
61              assertTrue(file.isFile());
62  
63              assertEquals("HtmlUnit Text Response", FileUtils.readFileToString(file, StandardCharsets.UTF_8));
64          }
65      }
66  }