我是 Python 的新手,正在尝试为 API 端点编写一些测试。我在下面 mock 小狗对象的方式安全吗?在我的测试中,它按照我期望的方式工作。我是否会冒着测试相互踩踏的风险,我认为我正在测试的对象的值实际上是在引用内存中的旧值?
我应该使用不同的策略吗?
class PuppyTest(APITestCase):
""" Test module for Puppy model """
def mock_puppy(self):
return {
"name": "Max",
"age": 3,
"breed": "Bulldog"
}
def test_create_puppy_with_null_breed(self):
"""
Ensure we can create a new puppy object with a null "breed" value
"""
url = reverse('puppy')
data = self.mock_puppy()
data['breed'] = None # Updating breed value
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_create_puppy(self):
"""
Ensure we can create a new puppy object.
"""
url = reverse('puppy')
data = self.mock_puppy() # returns original "breed" value "Bulldog"
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
最佳答案
Is the way that I'm mocking the puppy object safe below?
是
Do I run the risk in the future of the tests stepping on each other and the object's value that I think I'm testing, actually be referencing an older value in memory?
没有
Should I be using a different strategy?
您的方法没问题,每次测试都会创建一个新的字典。但是,由于您使用的是 pytest,因此将该数据放入 fixture 中可能更为典型。而不是一种方法。
关于Python 测试——这是一种安全的编写测试的方法,可以避免在每个测试函数中重复长字典吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54889887/