【问题标题】:How do you unit test Django RawQuerySets你如何对 Django RawQuerySets 进行单元测试
【发布时间】:2018-10-09 11:44:54
【问题描述】:

我在 Django 查询中使用 raw()annotate(),需要一些方法来测试它。

这是我的代码的样子(这已大大简化)

query = """SELECT
           table1.id, table1.column1, table1.column2,
           table2.other_column1, table2.other_column2 
           FROM myapp_mymodel as table1 
           JOIN otherapp_othermodel as table2 ON table1.othermodel_id = table2.id"""

return MyModel.objects.annotate(
    other_column1=models.Value('other_column1', models.IntegerField()),
    other_column2=models.Value('other_column2', models.DateField())
).raw(query)

用示例数据填充数据库相对简单,但是检查此代码是否返回数据的最佳方法是什么?

在处理标准查询集时有很多选项,但在处理 RawQuerySets 时似乎会消失。

【问题讨论】:

    标签: django unit-testing django-queryset django-orm python-unittest


    【解决方案1】:

    通常的方法是让测试设置一个相对较小的数据集,其中包含一些查询应该找到的东西,以及一些它不应该找到的东西。然后检查返回的QuerySet 并验证:

    1. 它包含预期数量的结果
    2. 返回的主键值集与您期望返回的值匹配
    3. 返回对象上的注释值是预期的值。

    因此,例如,您可能会执行以下操作:

    def test_custom_query(self):
        # Put whatever code you need here to insert the test data
        results = run_your_query_here()
        self.assertEqual(results.count(), expected_number_of_results)
        self.assertEqual({obj.pk for obj in results}, set_of_expected_primary_keys)
        self.assertEqual(
            [obj.annotated_value for obj in results],
            list_of_expected_annotated_values
        )
    

    【讨论】:

    • RawQuerySet 没有.count()(它不是QuerySet,当涉及到查询与数据库的交互方式时,你自己很漂亮)也没有 len( )。我假设我应该先将其转换为列表以获取计数?
    • 一般模式仍然适用。可以list()结果,然后用长度等操作就行了。
    猜你喜欢
    • 2013-05-08
    • 2010-09-07
    • 2017-06-10
    • 2013-09-29
    • 2012-08-18
    • 1970-01-01
    • 2010-09-20
    • 2010-11-24
    • 2011-02-23
    相关资源
    最近更新 更多