【问题标题】:Getting current route in pyramid view test在金字塔视图测试中获取当前路线
【发布时间】:2020-12-27 20:08:58
【问题描述】:

我正在尝试在金字塔中测试使用request.current_route_path() 的视图。

我将使用基本的测试设置,几乎直接来自文档:

from ..views.auth import signup
...
class ....:
    def test_signup_view(self):
        with testing.testConfig():
            signup(testing.DummyRequest(self.session))

我正在使用类似于https://docs.pylonsproject.org/projects/pyramid/en/latest/tutorials/wiki2/tests.html的配置:

class BaseTest(unittest.TestCase):
    def setUp(self) -> None:
        self.config = testing.setUp(settings={
            'sqlalchemy.url': self.postgresql.url().replace("postgresql", "postgresql+pg8000", 1)
        })
        self.config.include('..models')
        self.config.include('..routes')
        ...

但这会导致ValueError: Current request matches no route

我将path="/signup" 参数添加到DummyRequest,但最终出现相同的错误。

我的路由是基于uris的,不是基于资源的,所以测试的具体路由是:

def includeme(config):
    ...
    config.add_route('signup', '/signup')
    ...

我该如何解决这个问题?

【问题讨论】:

标签: python testing pyramid


【解决方案1】:

通过DummyRequest 模拟current_route_path 并不容易,因为它依赖于一个附加到它的IRoute 对象,名为matched_route,因为它正在执行request.matched_route.name 来获取路由名称,从而获取生成所需的元数据路线。当请求实际匹配到路由时,路由器通常会附加此对象。

我认为你有 3 个选择:

  1. 完全使用current_route_path 的版本模拟请求对象上的函数,该版本返回您想要的内容。例如request.current_route_path = lambda *a, **kw: '/path'。如果它不是您测试的重点,那就太好了。

  2. 从自省器中提取IRoute 对象并将其附加到虚拟请求。这需要学习 introspector api 并将其从那里拉出来并将其设置为request.matched_route = iroute_object

  3. 使用通过路由器的功能测试,此时 Pyramid 将为您正确设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2017-05-07
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2017-10-19
    相关资源
    最近更新 更多