检查 Selenium 中的 HTTP 状态代码

发布于 2024-08-23 11:37:44 字数 175 浏览 3 评论 0原文

如何在Selenium中获取HTTP状态码?

例如,我可以测试如果浏览器请求 /user/27 并且不存在 ID=27 的用户,则返回 HTTP 404?

我的主要兴趣是 Selenium RC,但如果有人知道“正常”selenium 的答案,我可能可以轻松地将其转换为 RC。

/皮特

How to get the HTTP status code in Selenium?

E.g. so I can test that if the browser requests /user/27 and no user with ID=27 exists, an HTTP 404 is returned?

My primary interest is Selenium RC, but if someone knows the answer for "normal" selenium, I can probably easily translate it into RC.

/Pete

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

卸妝后依然美 2024-08-30 11:37:44

对于此类测试,这可能不是 Selenium 的最佳用途。 当您可以执行并运行更快的测试时,无需加载浏览器, Selenium 可以检查最终页面是否符合您的预期。

[Test]
[ExpectedException(typeof(WebException), UserMessage = "The remote server returned an error: (404) Not Found")]
public void ShouldThrowA404()
{
    HttpWebRequest task; //For Calling the page
    HttpWebResponse taskresponse = null; //Response returned
    task = (HttpWebRequest)WebRequest.Create("http://foo.bar/thiswontexistevenifiwishedonedayitwould.html");
    taskresponse = (HttpWebResponse)task.GetResponse();
}

如果您的测试在 404 期间重定向到另一个页面,那么

This might not be the best use of Selenium for this type of test. There is unnecessary need to load a browser when you could do and have a faster running test

[Test]
[ExpectedException(typeof(WebException), UserMessage = "The remote server returned an error: (404) Not Found")]
public void ShouldThrowA404()
{
    HttpWebRequest task; //For Calling the page
    HttpWebResponse taskresponse = null; //Response returned
    task = (HttpWebRequest)WebRequest.Create("http://foo.bar/thiswontexistevenifiwishedonedayitwould.html");
    taskresponse = (HttpWebResponse)task.GetResponse();
}

If your test is redirecting to another page during a 404 Selenium could check the final page has what you expect.

倾`听者〃 2024-08-30 11:37:44

我知道这是一个令人震惊的黑客攻击,但这就是我所做的:

    protected void AssertNotYellowScreen()
    {
        var selenium = Selenium;

        if (selenium.GetBodyText().Contains("Server Error in '/' Application."))
        {
            string errorTitle = selenium.GetTitle();

            Assert.Fail("Yellow Screen of Death: {0}", errorTitle);
        }
    }

它在我需要的情况下完成了工作,尽管我承认这并不理想......

I know this is a shocking hack, but this is what I've done:

    protected void AssertNotYellowScreen()
    {
        var selenium = Selenium;

        if (selenium.GetBodyText().Contains("Server Error in '/' Application."))
        {
            string errorTitle = selenium.GetTitle();

            Assert.Fail("Yellow Screen of Death: {0}", errorTitle);
        }
    }

It gets the job done in the situation I needed it for, although I accept it's not ideal...

只等公子 2024-08-30 11:37:44

由于 Selenium 2 包含 HtmlUnit,因此您可以利用它来直接访问响应。

public static int getStatusCode(long appUserId) throws IOException {
    WebClient webClient = new WebClient();
    int code = webClient.getPage(
            "http://your.url/123/"
    ).getWebResponse().getStatusCode();
    webClient.closeAllWindows();
    return code;
}

Since Selenium 2 includes HtmlUnit, you can utilize it in order to get access to the response directly.

public static int getStatusCode(long appUserId) throws IOException {
    WebClient webClient = new WebClient();
    int code = webClient.getPage(
            "http://your.url/123/"
    ).getWebResponse().getStatusCode();
    webClient.closeAllWindows();
    return code;
}
纵性 2024-08-30 11:37:44

您可能想查看 captureNetworkTraffic() 调用。目前,它只能在 Firefox 上可靠地工作,除非您手动设置 IE/Safari/etc 通过端口 4444 代理流量。

要使用它,只需调用 selenium.start("captureNetworkTraffic=true"),然后在脚本中调用您可以调用 selenium.captureNetworkTraffic("...") ,其中“...”是“plain”、“xml”或“json”。

You probably want to check out the captureNetworkTraffic() call. Right now it only works reliably with Firefox, unless you manually set up IE/Safari/etc to proxy traffic through port 4444.

To use it, just call selenium.start("captureNetworkTraffic=true"), and then later on in your script you can call selenium.captureNetworkTraffic("...") where "..." is "plain", "xml", or "json".

温柔嚣张 2024-08-30 11:37:44

我还没有尝试过,但如果您不介意将自己限制在 Firefox 上,并安装 Firebug 和 Netexport,那么 Selenium 就可以访问页面状态代码(以及 Firebug 的 Net 面板中的其他所有内容): http://selenium.polteq.com/en/using-netexport-to -export-firebugs-net-panel/

I haven't tried it, but if you don't mind limiting yourself to Firefox, and installing Firebug and Netexport, then Selenium can get access to the page status code (and everything else in Firebug's Net panel): http://selenium.polteq.com/en/using-netexport-to-export-firebugs-net-panel/

时光礼记 2024-08-30 11:37:44

试试这个,人们

WebClient wc = new WebClient();
int countRepeats = 120; // one wait = 0.5 sec, total 1 minute after this code
boolean haveResult = false;
try {
    HtmlPage pageHndl = wc.getPage(Urls);
    for(int iter=0; iter<countRepeats; iter++){
        int pageCode = pageHndl.getWebResponse().getStatusCode();
        System.out.println("Page status "+pageCode);
        if(pageCode == 200){
            haveResult = true;
            break;
        }
        else{
            Thread.sleep(500);
        }
    }
} catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
} catch (InterruptedException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}

Try this, people

WebClient wc = new WebClient();
int countRepeats = 120; // one wait = 0.5 sec, total 1 minute after this code
boolean haveResult = false;
try {
    HtmlPage pageHndl = wc.getPage(Urls);
    for(int iter=0; iter<countRepeats; iter++){
        int pageCode = pageHndl.getWebResponse().getStatusCode();
        System.out.println("Page status "+pageCode);
        if(pageCode == 200){
            haveResult = true;
            break;
        }
        else{
            Thread.sleep(500);
        }
    }
} catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
} catch (InterruptedException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}
雨轻弹 2024-08-30 11:37:44

如果所有其他方法都失败,您可以在测试期间调整服务器端代码,以将页面中的 HTTP 状态作为元素输出:

例如,在我的 403 Permission Denied 页面上,我有:

   <h1 id="web_403">403 Access Denied</h1>

可以通过 WebDriver API 轻松检查:

    public boolean is403(WebDriver driver) {
        try {
            driver.findElement(By.id("web_403"));
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

https://rogerkeays.com/how-获取selenium-webdriver中的http-status-code

If all else fails you could adapt your server side code, during testing, to output the HTTP status in the page as an element:

For example, on my 403 Permission Denied page, I have:

   <h1 id="web_403">403 Access Denied</h1>

which can be easily checked via the WebDriver API:

    public boolean is403(WebDriver driver) {
        try {
            driver.findElement(By.id("web_403"));
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

https://rogerkeays.com/how-to-get-the-http-status-code-in-selenium-webdriver

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文