我幾年沒有做任何扭曲,並已開始使用客戶端HTTP調用的新型代理風格。使用代理已經可以,但測試讓我感到困惑(畢竟它是扭曲的)。單元測試twisted.web.client.Agent的沒有網絡
我已經通過了https://twistedmatrix.com/documents/current/core/howto/trial.html文檔以及試用工具和代理本身的API。還有大量的搜索。
我已經去僞造代理,因爲我不需要測試它。但是由於處理代理請求的處理和響應的步驟,我的測試代碼變得非常糟糕,實現了代理,協議等的嵌套層。我應該在哪裏畫線,並且有一些我避難的utils找不到?
這裏有一個小例子(幼稚實現SUT的):
from twisted.web.client import Agent, readBody
from twisted.internet import reactor
import json
class SystemUnderTest(object):
def __init__(self, url):
self.url = url
def action(self):
d = self._makeAgent().request("GET", self.url)
d.addCallback(self._cbSuccess)
return d
def _makeAgent(self):
''' It's own method so can be overridden in tests '''
return Agent(reactor)
def _cbSuccess(self, response):
d = readBody(response)
d.addCallback(self._cbParse)
return d
def _cbParse(self, data):
self.result = json.loads(data)
print self.result
與測試模塊:
from twisted.trial import unittest
from sut import SystemUnderTest
from twisted.internet import defer
from twisted.test import proto_helpers
class Test(unittest.TestCase):
def test1(self):
s_u_t = ExtendedSystemUnderTest(None)
d = s_u_t.action()
d.addCallback(self._checks, s_u_t)
return d
def _checks(self, result, s_u_t):
print result
self.assertEqual({'one':1}, s_u_t.result)
class ExtendedSystemUnderTest(SystemUnderTest):
def _makeAgent(self):
return FakeSuccessfulAgent("{'one':1}")
## Getting ridiculous below here...
class FakeReason(object):
def check(self, _):
return False
def __str__(self):
return "It's my reason"
class FakeResponse(object):
''' Implementation of IResponse '''
def __init__(self, content):
self.content = content
self.prot = proto_helpers.StringTransport()
self.code = 200
self.phrase = ''
def deliverBody(self, prot):
prot.makeConnection(self.prot)
prot.dataReceived(self.content)
# reason = FakeReason()
# prot.connectionLost(reason)
class FakeSuccessfulAgent(object):
''' Implementation of IAgent '''
def __init__(self, response):
self.response = response
def request(self, method, url):
return defer.succeed(FakeResponse(self.response))
非常感謝讓 - 保羅。很高興聽到有這張票,因爲它確實覺得它缺少。 請注意,如果這是運行然後它掛起。似乎協議正在等待dataReceived()之後的某個東西(這就是爲什麼我有註釋掉的斷開連接)。任何線索,以什麼是缺少完成?謝謝 –
即使'connectionLost'調用沒有被註釋掉,它也會掛起? –
不,在這種情況下,它與我的理由錯誤。我如何讓它成功完成? PS感謝風格的提示,我做了這些變化 –