0

我试图在测试数据库中设置一些模型,然后张贴到包含文件上传的自定义窗体。Django测试客户端,不创建模型(--keepdb选项正在使用)

在数据库中似乎没有任何东西存在,我不确定为什么执行POST时的测试正在发回200响应?跟着= 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', '[email protected]', 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) 

回答

2

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

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

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

+0

在test_csv_import方法中发出发布请求后,为什么没有看到任何正在创建的数据库记录?我想测试文件是否正确上传,然后使用特定方式处理文件。而且,200的回答是否正确? –

+0

在'test_csv_import method'中发出post请求之后,您需要在**方法中检查对象创建** - 一旦方法运行完毕,事务就会回滚,任何创建的对象都会消失。 200响应并不意味着该对象已创建 - 响应可能是一个错误,说明发布数据无效。 – Alasdair

相关问题