Search code examples
pythonpytesthug

Using PyTest with hug and base_url


I have a an api that is setup with

import hug
API = hug.API(__name__).http.base_url='/api'

@hug.get('/hello-world', versions=1)
def hello_world(response):
    return hug.HTTP_200

and I'm trying to test it with PyTest.

I'm trying to test the route with

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 can I test hug routes that have http.base_url configured?

I get a 404 errors regardless of the route path. I've tried

  • /api/v1/hello-world
  • api/v1/hello-world
  • v1/hello-world
  • /v1/hello-world

If I remove the hug.API().http.base_url setting then v1/hello-world works fine but my requirement is to have a base_url setup.

I've reviewed the documentation on the official hug github repo and various online sources such as ProgramTalk but I haven't had much success.

any recommendations?


Solution

  • You should send your module (myapp) as the first argument to hug.test.get().

    Then you can use the full path /api/v1/hello-world as the second argument.

    Here's 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