gpt4 book ai didi

python - 有人可以解释一下这个 Twisted 单元测试吗?

转载 作者:行者123 更新时间:2023-11-28 21:27:42 25 4
gpt4 key购买 nike

我刚刚继承了一些围绕 Twisted Python 的单元测试,如下所示。

虽然测试有效,但我在概念上不理解它。

给出下面的例子,有人可以解释一下吗?

  • 为什么这个单元测试“返回页面”?
  • 为什么没有对 reactor.start() 的任何调用?
  • 关于这种方法的优点/缺点的任何评论,也许还有我可以考虑的其他方法?

def setUp(self):
self.listening_port = reactor.listenTCP(8118, server.Site(buildSite()))

def tearDown(self):
self.listening_port.stopListening()

def getUrl(self, extension=''):
return 'http://localhost:%s/%s' % (self.listening_port.getHost().port, extension)

def test(self):
url = self.getUrl('foo')
def printResult(result):
print result
page = getPage(url, method='POST').addCallback(printResult)
return page

最佳答案

Why does this unit test 'return page'?

嗯,不是很干净。 Twisted 的 Trial 单元测试期望 Deferred 作为结果,并以断言作为回调。这里的回调是 printResult,因此对于任何非空字符串,它将被评估为 true。我认为更恰当的应该是:

page = getPage(url, method='POST').addCallback(self.assertTrue)

page = getPage(url, method='POST').addCallback(self.assertIsNotNone)

Why aren't there any calls to reactor.start()?

因为 TestCase 类会处理这些。而且它也没有使用标准 react 器。

Since unit tests are avoiding real I/O and real time, they can usually avoid using a real reactor. The only exceptions to this are unit tests for a real reactor implementation. Unit tests for protocol implementations or other application code should not use a reactor. Unit tests for real reactor implementations should not use the global reactor, but should instead use twisted.internet.test.reactormixins.ReactorBuilder so they can be applied to all of the reactor implementations automatically. In no case should new unit tests use the global reactor.

关于python - 有人可以解释一下这个 Twisted 单元测试吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10194793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com