在 Mac OS X 上使用 Selenium 进行测试时如何强制 Firefox 成为前台应用程序
我们最近开始使用 Selenium 测试基于 Django 的应用程序。测试在 Linux 上运行良好,但有些在 Mac OS X 上失败。在这两种情况下,我们都使用 Firefox 作为浏览器,我们花了一段时间(还有一些运气)才弄清楚这两种情况之间的重要区别在于是否FF 作为前台应用程序或后台窗口运行。 Linux 上发生的情况如下:
- Selenium 告诉 Firefox 转到用户注册页面。
- Selenium 填写用户名和无效电子邮件地址。
- Selenium 将焦点从电子邮件地址字段更改为同一页面上的另一个字段(它恰好是搜索框,但这并不重要——重要的是焦点更改事件)。
- 网页中的 Javascript 验证代码会注意到电子邮件地址无效,并在页面中插入一条错误消息。
- Selenium 检测到该错误消息并将测试标记为通过。
然而,当我们在 Mac OS X 上运行时,步骤 #4 不会发生除非我们在测试运行时手动将 Firefox 窗口置于前台 — 如果我们将其保留在后台(这就是默认情况下会出现),浏览器中的 Javascript 不会获取焦点更改事件,因此错误消息永远不会插入到页面的 DOM 中,因此 Selenium 等待超时,测试失败。
我们能否在测试运行时强制 Selenium 将浏览器置于前台,以便我们的 Javascript 能够按照我们想要的方式获取事件?如果是这样,怎么办?
We recently started testing our Django-based application using Selenium. Tests run fine on Linux, but some fail on Mac OS X. We're using Firefox as the browser in both cases, and it took us a while (and some luck) to figure out that the important difference between the two cases is whether FF is running as the foreground application or as a background window. Here's what happens on Linux:
- Selenium tells Firefox to go to a user registration page.
- Selenium fills in the user name and an invalid email address.
- Selenium changes focus from the email address field to another field on the same page (it happens to be the search box, but that's not important---all that matters is the change-of-focus event).
- The Javascript validation code in the web page notices that the email address is invalid and inserts an error message in the page.
- Selenium detects that error message and marks the test as passed.
When we run on Mac OS X, however, step #4 doesn't happen unless we manually foreground the Firefox window while the test is running---if we leave it in the background (which is where it comes up by default), the Javascript in the browser doesn't get the change-of-focus event, so the error message is never inserted in the page's DOM, so Selenium times out waiting for it, and the test fails.
Can we force Selenium to foreground the browser when tests run, so that our Javascript will get events as we want it to? If so, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Selenium 通过 Javascript 驱动浏览器。没有办法通过JS控制浏览器窗口。一般来说,在 Selenium 中测试 'onfocus' 和 'onblur' 事件是非常困难的。
您可以在输入无效的电子邮件地址后,使用 Selenium 的“runScript”或“getEval”方法进行 JS 评估,尝试自行触发此事件。这不是“纯粹的”黑盒测试,即如果验证的实现发生更改,您的测试也需要更改,但这是执行此测试的最可行的方法。
Selenium drives the browser through Javascript. There is no way to control browser window through JS. In general, testing the 'onfocus' and 'onblur' events in Selenium is very difficult.
You can try firing this event yourself by doing a JS evaluation using either the 'runScript' or the 'getEval' methods of Selenium after entering the invalid email address. This is not "pure" black box testing i.e. your test needs to be changed if the implementation of the validation is changed, but this is the most feasible way to carry out this test.