API 单元测试中的完整路径

API full path in unit tests

当我测试 API 时,有什么方法可以为 url 指定完整路径。现在我是这样做的:

def test_product_types_retrieve(self):
    self.relative_path = '/api/api_product/'
    response = self.client.get(self.relative_path + 'product_types/')

我应该在每个请求中添加 relative_path 部分,但我想设置它,例如在 setUp 函数中。没有 self.relative_path 我会得到 http://localhost:8000/product_types/ 而不是 http://localhost:8000/api/api_product/product_types/

我的项目结构如下,每个 api 都有自己的 urls.py 和 url 模式设置。

Project structure

你可以这样做,然后在 setUp 中设置相对路径并从 call_api 调用 api 可以通过它传递 args 和 kwargs。

然后,如果在测试中您需要不同的 relative_path,您可以在该测试中设置它并仍然调用 call_api。

class ExampleTestCase(TestCase):
    def setUp(self):
        self.relative_path = '/api/api_product/'

    def call_api(self, endpoint):
        return self.client.get(self.relative_path + endpoint)

    def test_product_types_retrieve(self):
        response = self.call_api('product_types/')

    def test_requires_different_path(self):
        self.relative_path = '/api/api_product/v1/'
        response = self.call_api('product_types/')