模拟SQLite数据库调用DJango ORM pytest

2024-06-26 14:33:33 发布

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

下面是我的一个django视图中的代码,该视图使用django ORM获取数据,但是从pytest运行相同的代码会产生错误:

FAILED tests/test_views.py::TestViews::test_trendchart_view - AttributeError: 'NoneType' object has no attribute 'metricname'

metrics = Metrics.objects.all()
metric = metrics.filter(metricid=metric_id).first()
metric_name = metric.metricname

从错误的角度看,这个指标似乎是零。知道我如何模拟这个调用来返回一些虚拟对象吗

以下是我的测试案例供参考:

@pytest.mark.django_db

class TestViews:
    def test_trendchart_view(self):
        kwargs={'event_id':1, 'ar_id':1, 'tcid':1, 'activemenu_id':1, 'metric_id':1}
        path = reverse('trendchart', kwargs=kwargs)
        request = RequestFactory().get(path)
        response = treandchartsummary(request,None,**kwargs)
        assert response.status_code == 200

Tags: pathdjango代码testview视图idpytest