在金字塔视图测试中获取当前路线
Getting current route in pyramid view test
我正在尝试测试金字塔中使用 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')
...
我该如何解决这个问题?
通过 DummyRequest
模拟 current_route_path
并不是很容易,因为它依赖于附加到它的名为 matched_route
的 IRoute
对象,因为它正在做 request.matched_route.name
获取路由名称,从而获取生成路由所需的元数据。当请求实际匹配到路由时,该对象通常由路由器附加。
我认为你有 3 个选择:
完全使用 returns 您想要的 current_route_path
版本模拟请求对象上的函数。例如 request.current_route_path = lambda *a, **kw: '/path'
。如果这不是您测试的重点,那就太好了。
从内省器中拉取 IRoute
对象并将其附加到虚拟请求。这需要学习内省器 api 并将其从那里拉出来并将其设置为 request.matched_route = iroute_object
.
使用通过路由器的功能测试,此时 Pyramid 将为您正确设置。
我正在尝试测试金字塔中使用 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')
...
我该如何解决这个问题?
通过 DummyRequest
模拟 current_route_path
并不是很容易,因为它依赖于附加到它的名为 matched_route
的 IRoute
对象,因为它正在做 request.matched_route.name
获取路由名称,从而获取生成路由所需的元数据。当请求实际匹配到路由时,该对象通常由路由器附加。
我认为你有 3 个选择:
完全使用 returns 您想要的
current_route_path
版本模拟请求对象上的函数。例如request.current_route_path = lambda *a, **kw: '/path'
。如果这不是您测试的重点,那就太好了。从内省器中拉取
IRoute
对象并将其附加到虚拟请求。这需要学习内省器 api 并将其从那里拉出来并将其设置为request.matched_route = iroute_object
.使用通过路由器的功能测试,此时 Pyramid 将为您正确设置。