python - 如何使用 url dispatch 在 View 测试中自动调用上下文工厂

标签 python testing pyramid

我有一个使用 url dispatch 的现有 Pyramid 应用程序。它具有“/kind1/{id1}/kind2/{id2}.../action”形式的 url。所以遍历本来是理想的,但没有被使用。

在每个 View 中都有一个从 url 中获取实例的函数调用。例如,可能会有这样的调用 thingy_instance = get_thingy_from_url(request)

现在我需要为 View 添加权限。所以我将上下文工厂添加到路由配置中。类似于:config.add_route('thingy_action','/kind1/{id1}/kind2/{id2}.../action', factory='ThingyContext')

现在让 ThingyContext 获取事物是有意义的,这样我就可以在 View 本身中做 thingy_instance = request.context.thingy_instance 之类的事情,而不是 thingy_instance = get_thingy_from_url(请求)

到目前为止,这是非常直接和可行的。但是它破坏了所有直接测试 View 的单元测试,因为请求上下文没有被填充。

例如,像这样的测试:

def test_thingy_action_scenario(self):
    stuff...
    x = thingy_action(request)

会给我一个异常(exception):

Traceback (most recent call last):
  File "/home/sheena/Workspace/Waxed/waxed_backend/waxed_backend/concerns/accountable_basics/tests/view_tests.py", line 72, in test_alles
    self.assertRaises(UserNotFound,lambda:get_user(request))
  File "/usr/lib/python2.7/unittest/case.py", line 473, in assertRaises
    callableObj(*args, **kwargs)
  File "/home/sheena/Workspace/Waxed/waxed_backend/waxed_backend/concerns/accountable_basics/tests/view_tests.py", line 72, in <lambda>
    self.assertRaises(UserNotFound,lambda:get_user(request))
  File "/home/sheena/Workspace/Waxed/waxed_backend/waxed_backend/concerns/accountable_basics/views.py", line 69, in get_user
    oUser = request.context.oUser
AttributeError: 'NoneType' object has no attribute 'thingy_instance'

简而言之。在测试中,request.context 为 None。但是当通过他们的 url 访问 View 时,一切正常。

例如:这种东西适用于新设置 curl -X POST --header 'Accept: application/json' 'http://stuff/kind1/{id1}/kind2/{id2} .../ Action /'

那么处理这个问题的优雅方式是什么?我想在 View 中使用上下文,并让测试通过。

最佳答案

您正在寻找功能测试而不是单元测试。在 Pyramid 中, View 本身“只是功能”,不会做任何事情来填充上下文等。在所有这些其他事情发生后,它们由 Pyramid 的路由器调用。但是您没有在这些测试中使用路由器,所以这些事情都没有发生。

如果您只想在单元测试中测试 View 函数本身,那么您可以让您的测试集 request.context = ThingyContext(...) 并且您的 View 应该很满意。

如果你想测试的东西更像是像 curl 这样的客户端会如何测试它,你想使用 webtest。

from webtest import TestApp

app = config.make_wsgi_app()
testapp = TestApp(app)
response = testapp.get('/')

这将需要一个完整的应用程序,而不仅仅是 View 函数。

关于python - 如何使用 url dispatch 在 View 测试中自动调用上下文工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41223664/

相关文章:

python - Pyramid View 重定向

python - 使用 "with"语句打印矩阵时出现 __enter__ 错误

python - 在requirements.txt中包含python版本吗?

javascript - 使用 $httpBackend 进行 AngularJS 测试 - 服务未被调用

ruby-on-rails - Rails Controller 测试 : Does database state change persist after success of test?

javascript - 等同于 rspec =~ 对于 Chai 中的数组

python - 在 python 中重定向 robots.run 的机器人输出

python - 如何使用 Python 遍历给定编码中的每个字符?

javascript - 在 window.location 重定向后预选 html 选择选项

python - 在皇帝模式下在 uWSGI 下运行 Pyramid 应用程序时日志记录不起作用