Use PyTest with hug and base_url… here is a solution to the problem.
Use PyTest with hug and base_url
I have an API that uses
settings
import hug
API = hug. API(__name__).http.base_url='/api'
@hug.get('/hello-world', versions=1)
def hello_world(response):
return hug. HTTP_200
I’m trying to test it with PyTest.
I’m trying to use the
test route
import pytest
import hug
from myapi import api
...
def test_hello_world_route(self):
result = hug.test.get(myapp, 'v1/hello-world')
assert result.status == hug. HTTP_200
How do I test a HUG route with http.base_url
configured?
I get a 404
error regardless of the routing path. I tried
/api/v1/hello-world
api/v1/hello-world
v1/hello-world
/v1/hello-world
If I delete hug. API().http.base_url
setup then v1/hello-world
works fine, but my requirement is to have an base_url
setting.
I
looked at the documentation on the official hug github repository and various online resources like ProgramTalk, but I didn’t have much success.
Any suggestions?
Solution
You should send your module (myapp
) as the first argument to hug.test.get().
You can then use the full path /api/v1/hello-world
as the second parameter.
Here is a minimal working example:
# myapp.py
import hug
api = hug. API(__name__).http.base_url='/api'
@hug.get('/hello-world', versions=1)
def hello_world(response):
return hug. HTTP_200
.
# tests.py
import hug
import myapp
def test_hello_world_route():
result = hug.test.get(myapp, '/api/v1/hello-world')
assert result.status == hug. HTTP_200
.
# run in shell
pytest tests.py