Skip to main content
 首页 » 编程设计

python之Django:跨多个文件拆分测试,但共享同一个数据库

2025年05月04日38lidabo

我正在使用 Django 1.8。我一直在一个名为 test_api.py 的长文件中为我的 Django API 编写测试。文件结构如下:

def setUpModule(): 
  management.call_command('loaddata', 'frontend/fixtures/data.json', 
                        verbosity=0) 
  management.call_command('my_custom_command') 
 
def tearDownModule(): 
  management.call_command('flush', verbosity=0, interactive=False) 
 
 
class TestAPIBNFViews(TestCase): 
  def test_api_view_list_all(self): 
    url = '/api/1.0/bnf_code' 
    # do testing 
 
def test_api_view_query(self): 
    # more testint 

fixtures 和管理命令在所有测试运行之前加载一次,到目前为止效果很好。

但是现在文件变得又长又笨重,我想将它拆分成多个文件。我创建了多个名为 test_list 和 test_query 的文件,并为每个文件分配了一个 setUpModule 部分,如上所示。

但是,首先这不是 DRY,其次当我运行 python manage.py test 时,许多测试失败并出现重复的外键错误,例如:

ProgrammingError: relation "frontend_sha_id" already exists 

我想这并不奇怪,因为测试会多次尝试创建测试数据库。

但是,如果我从除第一个测试(按文件名字母顺序列出)之外的所有测试中删除 setUpModule,其他测试将失败,因为它们看不到任何数据。

如何在所有测试运行之前运行一次 setUpModule,并且为了方便仍然将测试保存在单独的文件中?

请您参考如下方法:

您可以在每个 TestCase 类中使用一次 setUpTestData,而不是对两个测试类都使用全局 setUpModule。来自 Django documentation: Testing tools :

The class-level atomic block ... allows the creation of initial data at the class level, once for the whole TestCase.