单元测试中的API完整路径



在测试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和urlpatters设置。

项目结构

可以这样做,然后在setUp中设置相对路径,并从call_api调用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/')

最新更新