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

标签 python python-3.x pytest

我是 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/

相关文章:

javascript - 使用 Mechanize 将 HTML 注入(inject)页面

python - 如何使用 slack-apipins.add 方法

python-3.x - 如何使用pyplot填充阶梯曲线下的区域?

python - 如何告诉 pytest-xdist 按顺序从一个文件夹运行测试,并并行运行其余文件夹?

python - 从 EXPLOSM.net 漫画脚本下载 [Python]

python - PyMySQL 变量在一个数据库中使用 GRANT ALL PRIVILEGES

python - 如何在Python中比较两个不同.csv文件中的列?

python - cx_freeze 后的 subprocess.Popen 行为

python - Pytest:模拟具有不同 side_effect 的相同方法的多次调用

python - Django py.test 在真实数据库上运行?