简体   繁体   English

如何通过试用测试扭曲的网络资源?

[英]How to test twisted web resource with trial?

I'm developing a twisted.web server - it consists of some resources that apart from rendering stuff use adbapi to fetch some data and write some data to postgresql database. 我正在开发一个twisted.web服务器 - 它包含一些资源,除了渲染内容之外,还使用adbapi来获取一些数据并将一些数据写入postgresql数据库。 I'm trying to figoure out how to write a trial unittest that would test resource rendering without using net (in other words: that would initialize a resource, produce it a dummy request etc.). 我试图弄清楚如何编写一个试验单元测试来测试资源渲染而不使用网络(换句话说:它会初始化资源,产生虚拟请求等)。

Lets assume the View resource is a simple leaf that in render_GET returns NOT_DONE_YET and tinkers with adbapi to produce simple text as a result. 让我们假设View资源是一个简单的叶子,在render_GET中返回NOT_DONE_YET,并且使用adbapi修饰,以生成简单的文本。 Now, I've written this useless code and I can't come up how to make it actually initialize the resource and produce some sensible response: 现在,我已经编写了这个无用的代码,我无法提出如何让它实际初始化资源并产生一些合理的响应:

from twisted.trial import unittest
from myserv.views import View
from twisted.web.test.test_web import DummyRequest

class ExistingView(unittest.TestCase):
    def test_rendering(self):
        slug = "hello_world"
        view = View(slug)
        request = DummyRequest([''])
        output = view.render_GET(request)
        self.assertEqual(request.responseCode, 200)

The output is... 1. I've also tried such approach: output = request.render(view) but same output = 1. Why? 输出是...... 1.我也尝试过这样的方法:output = request.render(view)但输出= 1.为什么? I'd be very gratefull for some example how to write such unittest! 我会为一些例如如何编写单元测试等非常 gratefull!

Here's a function that will render a request and convert the result into a Deferred that fires when rendering is complete: 这是一个函数,它将呈现一个请求并将结果转换为在渲染完成时触发的Deferred:

def _render(resource, request):
    result = resource.render(request)
    if isinstance(result, str):
        request.write(result)
        request.finish()
        return succeed(None)
    elif result is server.NOT_DONE_YET:
        if request.finished:
            return succeed(None)
        else:
            return request.notifyFinish()
    else:
        raise ValueError("Unexpected return value: %r" % (result,))

It's actually used in Twisted Web's test suite, but it's private because it has no unit tests itself. 它实际上在Twisted Web的测试套件中使用,但它是私有的,因为它本身没有单元测试。 ;) ;)

You can use it to write a test like this: 您可以使用它来编写如下测试:

def test_rendering(self):
    slug = "hello_world"
    view = View(slug)
    request = DummyRequest([''])
    d = _render(view, request)
    def rendered(ignored):
        self.assertEquals(request.responseCode, 200)
        self.assertEquals("".join(request.written), "...")
        ...
    d.addCallback(rendered)
    return d

Here is a DummierRequest class that fixes almost all my problems. 这是一个DummierRequest类,几乎解决了我所有的问题。 Only thing left is it does not set any response code ! 唯一剩下的就是它没有设置任何响应代码 Why? 为什么?

from twisted.web.test.test_web import DummyRequest
from twisted.web import server
from twisted.internet.defer import succeed
from twisted.internet import interfaces, reactor, protocol, address
from twisted.web.http_headers import _DictHeaders, Headers

class DummierRequest(DummyRequest):
    def __init__(self, postpath, session=None):
        DummyRequest.__init__(self, postpath, session)
        self.notifications = []
        self.received_cookies = {}
        self.requestHeaders = Headers()
        self.responseHeaders = Headers()
        self.cookies = [] # outgoing cookies

    def setHost(self, host, port, ssl=0):
        self._forceSSL = ssl
        self.requestHeaders.setRawHeaders("host", [host])
        self.host = address.IPv4Address("TCP", host, port)

    def addCookie(self, k, v, expires=None, domain=None, path=None, max_age=None, comment=None, secure=None):
        """
        Set an outgoing HTTP cookie.

        In general, you should consider using sessions instead of cookies, see
        L{twisted.web.server.Request.getSession} and the
        L{twisted.web.server.Session} class for details.
        """
        cookie = '%s=%s' % (k, v)
        if expires is not None:
            cookie = cookie +"; Expires=%s" % expires
        if domain is not None:
            cookie = cookie +"; Domain=%s" % domain
        if path is not None:
            cookie = cookie +"; Path=%s" % path
        if max_age is not None:
            cookie = cookie +"; Max-Age=%s" % max_age
        if comment is not None:
            cookie = cookie +"; Comment=%s" % comment
        if secure:
            cookie = cookie +"; Secure"
        self.cookies.append(cookie)

    def getCookie(self, key):
        """
        Get a cookie that was sent from the network.
        """
        return self.received_cookies.get(key)

    def getClientIP(self):
        """
        Return the IPv4 address of the client which made this request, if there
        is one, otherwise C{None}.
        """
        return "192.168.1.199"

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

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