Houman
Houman

Reputation: 66380

How to unit test view_func in url rule?

I have the following routing url rule defined and would like to test it.

app.add_url_rule('/api/v1.0/worker/bbc-stage-0', 'stage0', view_func=BBCStage0TaskView.as_view('bbc_stage0_taskview'))

The following tests if the path is correct:

def test_url_to_view_stage0_exists(self):
        self.assertEqual(api.app.url_map._rules_by_endpoint['stage0'][0].rule, '/api/v1.0/worker/bbc-stage-0')

I haven't found a way to test if view_func is pointing to the right class. Is there a way to test that?

Upvotes: 2

Views: 337

Answers (1)

davidism
davidism

Reputation: 127330

Werkzeug's Map maps paths to endpoints. The Flask app maps these endpoints to view functions in app.view_functions, which is used during app.dispatch_request. So to check what view has been connected to an endpoint, simply get it from that map. Since you're using a class based View, the real view function will be different every instantiation, so you instead test that the view_class is the same.

self.assertEqual(api.app.view_functions['stage0'].view_class, BBCStage0Task)

This is sort of a meaningless test, as you're basically testing Flask internals, which are already tested by Flask. Your own tests would be much more useful by simply using the test client to see if a request to a url returns what you expect.

with api.app.test_client() as client:
    rv = client.get('/api/v1.0/worker/bbc-stage-0')

# assert something about the response, such as 'expected string' in rv.data

Upvotes: 1

Related Questions