简体   繁体   English

扭曲延迟测试

[英]Testing with a twisted deferred

I have been struggling to wrap my head around testing twisted code with deferred's and deferred's in general. 我一直在努力绕过测试延迟和延迟的扭曲代码。

I have a simple test that really should fail, I think. 我认为,我有一个真正应该失败的简单测试。

From my undertstanding in Twisted's test tool Trial, I should be able to return a deferred and when it is finished the test will finish. 从我在Twisted的测试工具试用版中,我应该能够返回延期,当它完成时,测试将完成。

Here is my tidbit of code, maybe someone can help. 这是我的代码,也许有人可以提供帮助。

import unittest, time

from twisted.internet import reactor, defer

class MyTest(unittest.TestCase):

def test_simple_deferred(self):

    print "\nStarting Test"

    my_deferred = defer.Deferred()

    def print_time():
      print time.time()
      self.assertTrue(False)

    my_deferred.addCallback(print_time)

    reactor.callLater(3, my_deferred.callback)

    print time.time()

    return my_deferred

Thanks in advance, I have looked at a lot of examples, but I think I have gotten to the point that I have been looking at this for far too long. 在此先感谢,我已经看了很多例子,但我想我已经到了很长时间以来一直在关注这个问题。

You have two problems. 你有两个问题。

Firstly, to get the special deferred handling, your test case needs to inherit from twisted.trial.unittest.TestCase , not the python standard library version. 首先,要获得特殊的延迟处理,您的测试用例需要继承twisted.trial.unittest.TestCase ,而不是python标准库版本。

Lastly, you are not calling reactor.callLater properly, or rather, you aren't giving it the right arguments for Deferred.callback() ; 最后,您没有正确调用reactor.callLater ,或者更确切地说,您没有为Deferred.callback()提供正确的参数; you need to give the deferred a value . 你需要给延期一个 If you don't care what it is, give it a None . 如果你不在乎它是什么,给它一个None Likewise, the callback needs to take that argument; 同样,回调需要采用该参数; you can safely ignore it. 你可以放心地忽略它。

from twisted.trial import unittest
#^^^^^^^^^^^^^^^^^
import time

from twisted.internet import defer
from twisted.internet import reactor

class MyTest(unittest.TestCase):

    def test_simple_deferred(self):

        print "\nStarting Test"

        my_deferred = defer.Deferred()

        def print_time(dont_care):
        #              ^^^^^^^^^
            print time.time()
            self.assertTrue(False)

        my_deferred.addCallback(print_time)

        reactor.callLater(3, my_deferred.callback, None)
        #                                        ^^^^^^    
        print time.time()

        return my_deferred

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM