viraptor
viraptor

Reputation: 34145

Getting current route in pyramid view test

I'm trying to test a view in pyramid which uses request.current_route_path().

I'm going with the basic test setup, pretty much straight from the doc:

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

I'm using the configuration similar to 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')
        ...

but this results in ValueError: Current request matches no route

I added the path="/signup" param to the DummyRequest, but end up with the same error.

My routes are based on uris, not resource-based, so the specific route for testing is:

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

How do I work around this?

Upvotes: 0

Views: 203

Answers (1)

Michael Merickel
Michael Merickel

Reputation: 23331

It's not super easy to mock current_route_path via DummyRequest because it relies on an IRoute object attached to it named matched_route as it's doing request.matched_route.name to get the route name and thus the metadata required to generate the route. This object is typically attached by the router when the request is actually matched to a route.

I think you have 3 options:

  1. Mock the function on the request object entirely with a version of current_route_path that returns what you want. For example request.current_route_path = lambda *a, **kw: '/path'. This is great if it's not the focus of your test.

  2. Pull the IRoute object from the introspector and attach it to the dummy request. This requires learning the introspector api and pulling it from there and setting it as request.matched_route = iroute_object.

  3. Use a functional test that goes through the router, at which point Pyramid will setup things correctly for you.

Upvotes: 2

Related Questions