繁体   English   中英

使用pytest为web.py应用程序编写单元测试

[英]write unit test for web.py application by using pytest

我想使用pytest为web.py应用程序编写单元测试。 如何在pytest中调用web.py服务。

码:

import web

urls = (
    '/', 'index'
)

app = web.application(urls, globals()) 

class index:
    def GET(self):
        return "Hello, world!"

if __name__ == "__main__":    
 app.run()

可以使用python请求模块来完成,当我们运行web.py服务时,它将运行http:// localhost:8080 / 然后导入请求模块并使用get方法,并在响应对象中,您可以验证结果。 没关系。

通过使用粘贴和鼻子,我们也可以按照web.py官方文档来实现。 http://webpy.org/docs/0.3/tutorial

在pytest中是否有任何解决方案,例如粘贴和鼻子中的选项。

是。 实际上,来自web.py配方“ 使用粘贴和鼻子进行测试”中的代码几乎可以按原样与py.test一起使用,只是删除了nose.tools导入并适当地更新了断言。

但是,如果您想知道如何以py.test样式为web.py应用程序编写测试,则它们可能看起来像这样:

from paste.fixture import TestApp

# I assume the code from the question is saved in a file named app.py,
# in the same directory as the tests. From this file I'm importing the variable 'app'
from app import app

def test_index():
    middleware = []
    test_app = TestApp(app.wsgifunc(*middleware))
    r = test_app.get('/')
    assert r.status == 200
    assert 'Hello, world!' in r

当您添加更多测试时,您可能会将测试应用的创建重构到固定装置中:

from pytest import fixture # added
from paste.fixture import TestApp
from app import app

def test_index(test_app):
    r = test_app.get('/')
    assert r.status == 200
    assert 'Hello, world!' in r

@fixture()
def test_app():
    middleware = []
    return TestApp(app.wsgifunc(*middleware))

暂无
暂无

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

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