Reputation: 10860
Im writing unit tests for an API written in Python with Flask. Specifically, I want to test that the error handling for my routes work properly so I want to deliberately build URLs with missing parameters. I want to avoid hard-coding by using url_for() but that doesn't allow you to have missing parameters, so how to build bad URLs ?
Upvotes: 0
Views: 248
Reputation: 51877
When it comes to url_for
it generates two kinds of urls. If there are named routes, like
@app.route('/favorite/color/<color>')
def favorite_color(color):
return color[::-1]
Then the URL parameters are required:
url_for('favorite_color')
BuildError: Could not build url for endpoint 'favorite_color'. Did you forget to specify values ['color']?
However, any parameter that is not present in the route itself will simply be converted to a querystring parameter:
print(url_for('favorite_color', color='blue', no='yellooooowwww!'))
/favorite/color/blue?no=yellooooowwww%21
So when you ask for a URL with a missing parameter, what you're asking for is a url that has no route. You can't build a URL for that, because flask is trying to build parameters for endpoints that exist.
The best you can do is use parameter values that are out of bounds, e.g.
url_for('favorite_color', color='toaster')
Toaster is not a real color, and thus should return 404
. Missing parameters might also make sense in a different context, so you'll have to account for that.
If you really want to have missing parameters, what you really want to do is use querystring arguments. But if you're dead set on making sure that URLs that don't exist on your server actually don't exist on your server, then you can do something like this:
url_for('favorite_color', color='fnord').replace('/fnord', '')
Upvotes: 2