jazzband / django-hosts

Dynamic and static host resolving for Django. Maps hostnames to URLconfs.
http://django-hosts.rtfd.org
Other
982 stars 106 forks source link

Simple test example #66

Closed stevelacey closed 7 years ago

stevelacey commented 7 years ago

I don't follow how you're meant to write tests for endpoints running via django-hosts – I've attempted overriding settings and passing hostnames... and still the default urlconf is being triggered.

An example of how you intend people to test these routes would be useful. Should I be doing something like setting the test client hostname to api.testserver, is that meant to work?

stevelacey commented 7 years ago

Note they don't even pass if I set the host I am testing as the DEFAULT_HOST

jezdez commented 7 years ago

@stevelacey When using Django's test client, pass in the HTTP_HOST parameter when calling it, e.g. https://github.com/django/djangoproject.com/commit/5e6b76d4d062e205f26779e62da9a5a0aebb07d3

stevelacey commented 7 years ago

Yeah, I figured it was that, both api and api.testserver work, though I hadn't tried the right combination of things – which involved using the custom reverse function too.

I actually ended up putting this in a utils file so that my tests remain generic (i.e. they're not tied to django-hosts directly) / DRYer.

import django_hosts
from rest_framework.test import APITestCase as BaseAPITestCase

class APITestCase(BaseAPITestCase):
    @property
    def client(self):
        return self._client

    @client.setter
    def client(self, value):
        value.defaults.setdefault('SERVER_NAME', 'api.testserver')
        self._client = value

def reverse(*args, **kwargs):
    kwargs.setdefault('host', 'api')
    return django_hosts.resolvers.reverse(*args, **kwargs)