py。test不会从数据库中提取数据

时间:2021-10-21 06:17:53

Good afternoon.

下午好。

I'm testing api based on django-rest-framework using pytest. As far as I knew at the beginning of the test, py.test creates a duplicate database with the prefix test_. But the pattern during writing tests noticed that it is not receiving data from the database. That is a duplicate of this supposedly empty. A simple example:

我正在使用pytest测试基于django rest-framework的api。就我在测试开始时所知道的,py。test使用前缀test_创建一个重复的数据库。但是编写测试时的模式注意到它没有从数据库接收数据。这是这个假设为空的东西的复制品。一个简单的例子:

@pytest.mark.django_db
def test_db():
    qs = Category.objects.get(id=4)
    assert qs['id'] = 4

Its returns this error below, but in a database, object with id=4 exists.

它返回下面的错误,但是在数据库中,id=4的对象存在。

>       assert qs['id'] == 4
E       assert [] == 4

I am new to testing, may miss something, help please.

我是新手,可能会错过一些东西,请帮忙。

1 个解决方案

#1


2  

Like Daniel commented, test DB is initially empty. You can add any data you want for testing by using one of two methods:

正如Daniel所说,测试DB最初是空的。您可以使用以下两种方法之一添加您想要测试的任何数据:

  1. Django Fixtures - You can add data using a JSON file just like initial data.
  2. Django fixture——可以使用JSON文件添加数据,就像初始数据一样。
  3. Mock data using a library such as django dynamic fixture during run time.
  4. 在运行时使用库(如django动态夹具)的模拟数据。

These are your best bets.

这是你最好的选择。

#1


2  

Like Daniel commented, test DB is initially empty. You can add any data you want for testing by using one of two methods:

正如Daniel所说,测试DB最初是空的。您可以使用以下两种方法之一添加您想要测试的任何数据:

  1. Django Fixtures - You can add data using a JSON file just like initial data.
  2. Django fixture——可以使用JSON文件添加数据,就像初始数据一样。
  3. Mock data using a library such as django dynamic fixture during run time.
  4. 在运行时使用库(如django动态夹具)的模拟数据。

These are your best bets.

这是你最好的选择。