【问题标题】:write unit test for web.py application by using pytest使用 pytest 为 web.py 应用程序编写单元测试
【发布时间】:2019-05-03 06:12:46
【问题描述】:

我想使用 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 requests 模块来完成,当我们运行web.py服务时,它会运行http://localhost:8080/。然后导入 requests 模块并使用 get 方法,在响应对象中,您可以验证结果。没关系。

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

pytest 中是否有类似 paste 和 nose 选项的解决方案。

【问题讨论】:

    标签: python unit-testing pytest web.py


    【解决方案1】:

    是的。实际上,来自 web.py 配方 Testing with Paste and Nose 的代码几乎可以与 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))
    

    【讨论】:

    • 感谢您的回复,将尝试此解决方案并让您知道结果
    猜你喜欢
    • 2021-12-19
    • 2021-03-27
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2021-11-05
    • 2022-01-12
    相关资源
    最近更新 更多