【问题标题】:python nose and twisted蟒蛇鼻子和扭曲
【发布时间】:2010-10-05 11:56:08
【问题描述】:

我正在为一个函数编写一个测试,该函数使用 Twisted 从一个 url 下载数据(我知道 twisted.web.client.getPage,但是这个增加了一些额外的功能)。无论哪种方式,我都想使用nosetests,因为我在整个项目中都在使用它,而且仅将Twisted Trial 用于这个特定的测试看起来并不合适。 所以我想做的是:

from nose.twistedtools import deferred

@deferred()
def test_download(self):
    url = 'http://localhost:8000'

    d = getPage(url)

    def callback(data):
        assert len(data) != 0

    d.addCallback(callback)
    return d

在 localhost:8000 上监听一个测试服务器。问题是我总是得到twisted.internet.error.DNSLookupError

DNSLookupError: DNS lookup failed: address 'localhost:8000' not found: [Errno -5] No address associated with hostname.

有什么办法可以解决这个问题吗?有人真的使用nose.twistedtools 吗?

更新:更完整的追溯

Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/nose-0.11.2-py2.6.egg/nose/twistedtools.py", line 138, in errback
failure.raiseException()
File "/usr/local/lib/python2.6/dist-packages/Twisted-9.0.0-py2.6-linux-x86_64.egg/twisted/python/failure.py", line 326, in raiseException
raise self.type, self.value, self.tb
DNSLookupError: DNS lookup failed: address 'localhost:8000' not found: [Errno -5] No address associated with hostname.

更新 2

我的不好,似乎在 getPage 的实现中,我正在做类似的事情:

obj = urlparse.urlparse(url) netloc = obj.netloc 并在我应该通过 netloc.split(':')[0]

时将 netloc 传递给工厂

【问题讨论】:

  • 你也知道twisted.web.client.Agent吗?
  • 不,我快速浏览了一下。我的getPage 实现在没有收到UA 标头时不会发送默认用户代理,而且,在返回延迟时,如果先前设置了编码gzip 标头,它会解压缩结果。感谢您指向 t.w.c.Agent

标签: python twisted nose


【解决方案1】:

您确定您的 getPage 函数正确解析了 URL 吗?该错误消息似乎表明它在进行 dns 查找时同时使用了主机名和端口。

你说你的getPage 类似于twisted.web.client.getPage,但是当我在这个完整的脚本中使用它时,这对我来说很好:

#!/usr/bin/env python
from nose.twistedtools import deferred
from twisted.web import client
import nose

@deferred()
def test_download():
    url = 'http://localhost:8000'

    d = client.getPage(url)

    def callback(data):
        assert len(data) != 0

    d.addCallback(callback)
    return d

if __name__ == "__main__":
    args = ['--verbosity=2', __file__]
    nose.run(argv=args)

在我的主目录中运行一个简单的 http 服务器:

$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...

鼻子测试给出以下输出:

.
----------------------------------------------------------------------
Ran 1 test in 0.019s

OK

【讨论】:

  • 你是对的,看起来它同时使用主机名和端口来进行查找,但我没有要求这个。我没有在 getPage 中进行任何查找,堆栈跟踪来自鼻子。
  • @hyperboreean 好吧,URL 被传递给 getPage,它大概使用它以某种方式连接到服务器。您的 getPage 对给出的 URL 做了什么?
  • 啊,我看到你编辑了这个问题......认为它可能是这样的。很高兴你把它修好了;)