Тестирование с помощью Twisted и inlineCallbacks - PullRequest
2 голосов
/ 23 февраля 2012

Вот мое определение функции:

@defer.inlineCallbacks
def get_order(order_id):
    # do some db operations...
    defer.returnValue(order_details)

Что я хочу сделать, это протестировать эту функцию, используя пробную версию Twisted:

from twisted.trial import unittest
from twisted.internet import defer

class OrderTest(unittest.TestCase):
    @defer.inlineCallbacks  
    def test_order(self):
        order = yield get_order(5)
        raise Exception('FAIL FAIL!!') # this should fail, but never does
        self.assertEqual(order.id, 6)

Я очень смущен .. Я красныйвсе документы, которые я мог найти о Twisted и пробной версии, но не мог найти, как заставить это работать.

Ответы [ 3 ]

8 голосов
/ 23 февраля 2012

Вот рабочие тесты с @ defer.inlineCallbacks и выводом.Я поставил твой тест в конце.Возникает исключение.

from twisted.trial import unittest
from twisted.internet import defer
from twisted.internet import reactor

@defer.inlineCallbacks
def get_order(order_id):   
    d = defer.Deferred()
    reactor.callLater(2, d.callback, order_id)
    result = yield d # yielded deferreds will pause the generator

    # after 2 sec
    defer.returnValue(result) # the result of the deferred, which is order_id

class OrderTest(unittest.TestCase):
    def test_order(self):
        return get_order(6).addCallback(self.assertEqual, 6)

# This works
class OrderTestYourWay(unittest.TestCase):
    @defer.inlineCallbacks
    def test_order(self):
        order_id = yield get_order(6)
        defer.returnValue(self.assertEqual(order_id, 6))

# this fails, cause 6 != 5
class OrderTestYourWayWithFailure(unittest.TestCase):
    @defer.inlineCallbacks
    def test_order(self):
        order_id = yield get_order(6)
        defer.returnValue(self.assertEqual(order_id, 5))

# This is your test
# It raises an exception, which produces an error in the test
class OrderTestRaisingException(unittest.TestCase):
    @defer.inlineCallbacks  
    def test_order(self):
        order_id = yield get_order(5)
        raise Exception('FAIL FAIL!!') # this should fail, but never does
        self.assertEqual(order_id, 6)

yavor@yavor-pc:~/src/tvstream/Misc/src/var$ trial OrderTest.py 

OrderTest

  OrderTest

    test_order ...                                                         [OK]

  OrderTestRaisingException

    test_order ...                                                      [ERROR]

  OrderTestYourWay

    test_order ...                                                         [OK]

  OrderTestYourWayWithFailure

    test_order ...                                                       [FAIL]

===============================================================================

[FAIL]

Traceback (most recent call last):

  File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1020, in _inlineCallbacks

    result = g.send(result)

  File "/home/yavor/src/tvstream/Misc/src/var/OrderTest.py", line 34, in test_order

    defer.returnValue(self.assertEqual(order_id, 5))

twisted.trial.unittest.FailTest: not equal:

a = 6

b = 5


OrderTest.OrderTestYourWayWithFailure.test_order

===============================================================================

[ERROR]

Traceback (most recent call last):

  File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1020, in _inlineCallbacks

    result = g.send(result)

  File "/home/yavor/src/tvstream/Misc/src/var/OrderTest.py", line 40, in test_order

    raise Exception('FAIL FAIL!!') # this should fail, but never does

exceptions.Exception: FAIL FAIL!!

OrderTest.OrderTestRaisingException.test_order

-------------------------------------------------------------------------------

Ran 4 tests in 8.016s

FAILED (failures=1, errors=1, successes=2)
4 голосов
/ 23 февраля 2012

Но это так:

$ trial test_example.py 
test_example
  OrderTest
    test_order ...                                                      [ERROR]

===============================================================================
[ERROR]
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1020, in _inlineCallbacks
    result = g.send(result)
  File "/tmp/test_example.py", line 11, in test_order
    raise Exception('FAIL FAIL!!') # this should fail, but never does
exceptions.Exception: FAIL FAIL!!

test_example.OrderTest.test_order
-------------------------------------------------------------------------------
Ran 1 tests in 0.009s

FAILED (errors=1)
$

Возможно, настоящая проблема заключается в реализации get_order (который вы пропустили).

0 голосов
/ 31 июля 2013

Ваша функция get_order должна вернуть экземпляр Deferred или DeferredList из twisted.internet.defer.

...