你如何对 Django RawQuerySets 进行单元测试

How do you unit test Django RawQuerySets

我在 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 时似乎超出了 window。

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

  1. 它包含预期数量的结果
  2. 这组主键值 returned 与您预期的相匹配 return
  3. returned 对象上的注释值符合预期。

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

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
    )