Python测试是编写测试的一种安全方法,可以避免在每个测试函数中重复使用长字典

2024-06-01 01:54:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,正在尝试为API端点编写一些测试。我嘲笑小狗的方式安全吗?在我的测试中,它正以我期望的方式工作。我是否有可能在将来的测试中相互影响,并且我认为我正在测试的对象的值实际上是引用内存中的旧值?你知道吗

我应该使用不同的策略吗?你知道吗

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)

Tags: testselfurldatavalueresponsedefstatus
1条回答
网友
1楼 · 发布于 2024-06-01 01:54:13

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?

你的方法还可以,为每个测试创建一个新的dict。但是,由于您使用的是pytest,因此将数据放入fixture而不是方法可能更为典型。你知道吗

相关问题 更多 >