在PhantomJS + GhostDriver + WebDriver客户端配置中为每个测试清除cookie

时间:2013-09-25 14:59:20

标签: cookies selenium-webdriver automated-tests phantomjs

如何在PhantomJS + GhostDriver + Selenium WebDriver + WebDriver客户端系统中清除每个测试的Cookie?

我的测试过程如下:

  1. 以hub角色启动selenium-web-driver-standalone。
  2. 在webdriver模式下启动phantomjs并将其附加到selenium 的webdriver。
  3. 启动shell脚本,迭代测试套件并启动每个脚本。
  4. 每个测试使用webdriver客户端并与浏览器通信 连接到selenium web driver。
  5. 当我使用firefox浏览器而不是phantomjs时,所有测试都通过了。但是当我切换到使用phantomjs作为浏览器时,所有检查注册失败的测试都因为cookie在第一次测试执行后已经设置。我可以在每次测试启动时清除所有cookie吗?或者我应该在每个单独的测试中重新启动phantomjs进程(因为这是使用firefox和selenium webdriver而不是hub角色)?

3 个答案:

答案 0 :(得分:2)

也许是一些offtopic,因为作者标记他使用php来运行测试。

但如果您来自谷歌并对C#解决方案感兴趣以清除所有Cookie,请查看以下内容:

// driver is fully initialized PhantomJS instance
driver.Manage().Cookies.DeleteAllCookies();

需要NuGetPackages:

  

PhantomJS 2.0.0

     

Selenium.Support 2.48.2

     

Selenium.WebDriver 2.48.2

使用.NETFramework v4.5.2进行测试

答案 1 :(得分:1)

您可以使用以下方法删除特定的Cookie:

webDriver.manage().deleteCookieNamed("smSession");

使用以下命令删除所有Cookie:

webDriver.manage().deleteAllCookies();

答案 2 :(得分:1)

我遇到类似的问题,GhostDriver无法清除localStorage。试试这些建议:

在你的网页driver.get(URL)之后,你可以执行javascript 它来自webdriver,像这样

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};
  

没有100%的解决方案可以删除浏览器Cookie。

     

问题在于,cookie不仅仅是由唯一标识   他们的关键"名称"还有他们的"域名"和"路径"。

     

不知道"域"和"路径"一个cookie,你不能   可靠地删除它。此信息无法通过   JavaScript的document.cookie。它不能通过HTTP获得   Cookie标题也是!

     

但是,如果你知道cookie的名称,路径和域名,那么你   可以通过设置一个带有失效日期的空cookie来清除它   过去

资源:

  1. https://sqa.stackexchange.com/a/10468
  2. https://stackoverflow.com/a/2421786/572348