python - 创建 Pyramid 请求进行测试,以便触发事件

标签 python testing pyramid wsgi

我想测试如下所示的 Pyramid View :

def index(request):
    data = request.some_custom_property.do_something()
    return {'some':data}

some_custom_property 通过这样的事件处理程序添加到请求中:

@subscriber(NewRequest)
    def prepare_event(event):
        event.request.set_property(
            create_some_custom_property,
            'some_custom_property',reify=True
        )

我的问题是:如果我手动创建测试请求,则事件设置不正确,因为没有触发任何事件。因为真正的事件处理程序更复杂并且取决于配置设置,所以我不想在我的测试代码中重现该代码。我想尽可能多地使用 Pyramid 基础设施。我从 earlier question 中学到了如何从 ini 文件设置真正的 Pyramid 应用程序:

from webtest import TestApp
from pyramid.paster import get_app

app = get_app('testing.ini#main')
test_app = TestApp(app)

test_app 工作正常,但我只能取回 html 输出(这是 TestApp 的想法)。我想做的是,在 apptest_app 的上下文中执行 index,但要取回 index 的结果 在发送到渲染器之前。

有什么提示吗?

最佳答案

首先,我认为像这样编写 doctests 是一个非常糟糕的主意。因为它需要大量的初始化工作,这将包含在文档中(记住 doctests)并且不会“记录”任何东西。而且,对我来说,这些测试似乎是单元/集成测试的工作。但如果你真的想要,这里有一种方法可以做到:

import myapp
from pyramid.paster import get_appsettings
from webtest import TestApp
app, conf = myapp.init(get_appsettings('settings.ini#appsection'))
rend = conf.testing_add_renderer('template.pt')
test_app = TestApp(app)
resp = test_app.get('/my/view/url')
rend.assert_(key='val')

其中 myapp.init 是一个与您的应用程序初始化函数执行相同工作的函数,它由 pserve 调用(如 main函数 here 。除了 myapp.init 接受 1 个参数,这是设置字典(而不是 main(global_config, **settings))。并返回应用程序(即 conf.make_wsgi_app()) 和 conf(即 pyramid.config.Configurator 实例)。rend 是一个 pyramid.testing.DummyTemplateRenderer 实例。

附言对不起我的英语,我希望你能理解我的回答。

更新。忘记提及 rend 具有 _received 属性,这是传递给渲染器的值,但我不建议使用它,因为它不在公共(public)接口(interface)中。

关于python - 创建 Pyramid 请求进行测试,以便触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16942230/

相关文章:

file-upload - Pyramid/Pylons : How to check if an uploaded file is complete in a POST request?

python - Docker X11 Forward 得到黑屏

python - 使用 matplotlib 在屏幕上绘制直线和圆圈

codeigniter - 在 codeigniter 中检查 session

testing - 是否可以使用 Watin 查看页面加载后的响应 header 是什么

python - 在 Pyramid 中,如何从 http 重定向到 https?

python - 尝试在column_property中使用float()

python - Python 中有两个条件的 if 语句

python - 用这些字符串的子字符串替换字符串中的字符串

testing - 在 TDD 中,谁编写测试 - 开发人员或 QA/测试人员?