Django 测试客户端,不创建模型(使用--keepdb 选项)

Django test client, not creating models (--keepdb option being used)

我正在尝试在测试数据库中设置一些模型,然后 post 到包含文件上传的自定义表单。

数据库中似乎没有任何内容,我不确定为什么执行 POST 时的测试会发回 200 响应? follow=False,不应该是302吗?

此外,当我尝试在数据库中查找模型时,它什么也没找到。

当我使用 --keepdb 选项查看数据库时,也什么都没有?

我做错了什么?

class ImportTestCase(TestCase):
    remote_data_url = "http://test_data.csv"
    local_data_path = "test_data.csv"
    c = Client()
    password = "password"

    def setUp(self):
        utils.download_file_if_not_exists(self.remote_data_url, self.local_data_path)
        self.my_admin = User.objects.create_superuser('jonny', 'jonny@testclient.com', self.password)
        self.c.login(username=self.my_admin.username, password=self.password)

    def test_create_organisation(self):
        self.o = Organization.objects.create(**{'name': 'TEST ORG'})

    def test_create_station(self):
        self.s = Station.objects.create(**{'name': 'Player', 'organization_id': 1})

    def test_create_window(self):
        self.w = Window.objects.create(**{'station_id': 1})

    def test_create_component(self):
        self.c = Component.objects.create(**{
            'type': 'Player',
            'window_id': 1,
            'start': datetime.datetime.now(),
            'end': datetime.datetime.now(),
            'json': "",
            'layer': 0}
                                          )

    def test_csv_import(self):
        """Testing that standard csv imports work"""
        self.assertTrue(os.path.exists(self.local_data_path))
        with open(self.local_data_path) as fp:
            response = self.c.post('/schedule/schedule-import/create/', {
                'component': self.c,
                'csv': fp,
                'date_from': datetime.datetime.now(),
                'date_to': datetime.datetime.now()
            }, follow=False)

        self.assertEqual(response.status_code, 200)

    def test_record_exists(self):
        new_component = Component.objects.all()
        self.assertTrue(len(new_component) > 0)

以及测试结果

Using existing test database for alias 'default'...
.....[]
F
======================================================================
FAIL: test_record_exists (schedule.tests.ImportTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests.py", line 64, in test_record_exists
    self.assertTrue(len(new_component) > 0)
AssertionError: False is not true

----------------------------------------------------------------------
Ran 6 tests in 1.250s

FAILED (failures=1)

--keepdb选项表示保留数据库。这意味着再次 运行 测试会更快,因为您不必重新创建 table.s

但是,TestCase class 中的每个测试方法都是 运行 在方法完成后回滚的事务中。使用 --keepdb 不会改变这一点。

这意味着您在 test_create_component 中创建的对象不会被 test_record_exists 测试看到。您可以在 test_record_exists 方法、setUp 方法或 setUpTestData class 方法中创建对象。