有没有办法在 Django 的单元测试中获取 Client() 的默认域?

Is there any way to get the default domain of Client() in unittest of Django?

我想在 Django unittests 中获取 Client() 的默认域名。我看到了一种更改默认方法的方法。但是没有找到获取默认域名的方法。

Django 测试客户端的默认域名是testserverRequestFactory 基数 class 中的 hardcoded

如果你想为特定请求更改域,你可以将它作为 kwarg 传递:

self.client.get('/some-path', SERVER_NAME="anotherdomain.com")

我刚试过https://docs.djangoproject.com/en/1.9/topics/testing/tools/#liveservertestcase

默认测试 URL 将是 http://localhost:8082 我们可以在 运行 测试时请求相同的测试。它对我有用。

这是您正在寻找的 (pytest) 答案吗?

@pytest.fixture()
def client() -> "django.test.client.Client":
    """like the default pytest client with a new domain name."""
    skip_if_no_django()
    return Client(SERVER_NAME = 'my-server.com')