使用PhantomJS、Python、Selenium和unittest时出现“IOError: [Errno 35] 资源暂时不可用”

3 投票
1 回答
4230 浏览
提问于 2025-04-18 00:01

我在用selenium和PhantomJS驱动运行单元测试时遇到了一些问题。这个问题似乎和PhantomJS进程在处理错误输出和标准输出时的资源争用有关。错误信息是:

$ python -m unittest selenium_failure.SeleniumTestCase
[]
[{u'timestamp': 1395857498698, u'message': u'{"log":{"version":"1.2","creator":{"name":"PhantomJS","version":"1.9.7"},"pages":[{"startedDateTime":"2014-03-26T18:11:38.347Z","id":"https://www.google.com/","title":"Google","pageTimings":{"onLoad":294}}],"entries":[{"startedDateTime":"2014-03-26T18:11:38.344Z","time":127,"request":{"method":"GET","url":"https://www.google.com/","httpVersion":"HTTP/1.1","cookies":[],"headers":[{"name":"User-Agent","value":"Mozilla/5.0 (Macintosh; Intel Mac OS X) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.7 Safari/534.34"},{"name":"Accept","value":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}],"queryString":[],"headersSize":-1,"bodySize":-1},"response":{"status":200,"statusText":"OK","httpVersion":"HTTP/1.1","cookies":[],"headers":[{"name":"Date","value":"Wed, 26 Mar 2014 18:11:37 GMT"},{"name":"Expires","value":"-1"},{"name":"Cache-Control","value":"private, max-age=0"},{"name":"Content-Type","value":"text/html; charset=UTF-8"},{"name":"Set-Cookie",E
======================================================================
ERROR: test_that_something_fails (selenium_failure.SeleniumTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "selenium_failure.py", line 16, in test_that_something_fails
    print repr(self.selenium.get_log('har'))
IOError: [Errno 35] Resource temporarily unavailable

----------------------------------------------------------------------
Ran 1 test in 2.398s

FAILED (errors=1)

更详细的信息可以在这里找到:https://gist.github.com/lucaswiman/9788422

import unittest
import logging
from selenium.webdriver import phantomjs
import sys

class SeleniumTestCase(unittest.TestCase):
    def setUp(self):
        self.selenium = phantomjs.webdriver.WebDriver()
    def tearDown(self):
        self.selenium.quit()
    def test_that_something_fails(self):
        self.selenium.get('https://www.google.com')
        print repr(self.selenium.get_log('browser'))
        print repr(self.selenium.get_log('har'))
        raise AssertionError()

在OS X系统上可以复现这个错误,但在Ubuntu 12.04上却没有。我认为这个问题并不是OS X特有的,因为我在Ubuntu上运行集成测试时也见过类似的错误,不过我还没能在一个独立的环境中复现这个问题。

  • Python版本:2.7.6
  • selenium版本:2.35.0
  • phantomjs版本:1.9.7

1 个回答

2

解决了!一个同事给我指了个相关的问题:http://trac.edgewall.org/ticket/2066#comment:1。我对那里的补丁做了一些修改,让 sys.__stderr__sys.__stdout__ 有了阻塞标志。这样在创建 phantomjs 的 WebDriver 之后立刻调用那个函数,就能把错误信息正确发送到标准错误输出了。

撰写回答