gpt4 book ai didi

rest-assured - 使用 REST Assured 检查 HTML 文档

转载 作者:行者123 更新时间:2023-12-03 01:23:59 25 4
gpt4 key购买 nike

我正在尝试使用 REST Assured检查我的服务器返回的 HTML 文档的一些属性。安SSCCE问题的证明如下:

import static com.jayway.restassured.path.xml.config.XmlPathConfig.xmlPathConfig;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Test;

import com.jayway.restassured.path.xml.XmlPath;

public class HtmlDocumentTest {

@Test
public void titleShouldBeHelloWorld() {
final XmlPath xml = new XmlPath("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ "<head><title>Hello world</title></head><body></body></html>")
.using(xmlPathConfig().with().feature("http://apache.org/xml/features/disallow-doctype-decl", false));
assertThat(xml.get("//title[text()]"), is("Hello world"));
}
}

现在,这次尝试以 com.jayway.restassured.path.xml.exception.XmlPathException: Failed to parse the XML document 结束由所有可能的错误引起,java.net.ConnectException: Connection timed out大约 30 秒后!

如果我删除带有 xmlPathConfig().with().feature(...) 的行由于DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.,测试立即失败。

如果我从文档中删除 doctype 行,则解析会成功,但测试会因断言错误“Expected: is "Hello world" but: was <Hello worldnull>”而失败——但是,显然这是一个不同的问题(但请随意给出有关该问题的说明,也...)。无论如何,删除文档类型对我来说不是一个选择。

那么问题来了:如何使用 REST Assured 检查具有文档类型的 HTML 文档的属性?它说in the documentationREST Assured 提供商预定义了 HTML、XML 和 JSON 等解析器。”,但我似乎找不到任何有关如何准确激活和使用该 HTML 解析器的示例!没有像 HtmlPath 这样的“XmlPath ”类比如说,那个超时异常就很让人费解……

最佳答案

我检查了你的代码。问题是 Resassured 的 XmlPath 不是 Xpath,而是使用属性访问语法。如果您将正文内容添加到示例 HTML,您将发现您的 XPath 没有做太多事情。查询语言的实际名称是 GPath 。以下示例有效,另请注意 CompatibilityMode.HTML 的使用,它具有适合您需要的正确配置:

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.jayway.restassured.path.xml.XmlPath;
import com.jayway.restassured.path.xml.XmlPath.CompatibilityMode;

public class HtmlDocumentTest {

@Test
public void titleShouldBeHelloWorld() {
XmlPath doc = new XmlPath(
CompatibilityMode.HTML,
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ "<head><title>Hello world</title></head>"
+ "<body>some body"
+ "<div class=\"content\">wrapped</div>"
+ "<div class=\"content\">wrapped2</div>"
+ "</body></html>");

String title = doc.getString("html.head.title");
String content = doc.getString("html.body.div.find { it.@class == 'content' }");
String content2 = doc.getString("**.findAll { it.@class == 'content' }[1]");

assertEquals("Hello world", title);
assertEquals("wrapped", content);
assertEquals("wrapped2", content2);
}
}

关于rest-assured - 使用 REST Assured 检查 HTML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33167541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com