我想创建多个测试数据库,这样我就可以检查我的同步脚本是否正常工作。我把它们添加到Django设置中,像这样:
DATABASES = {
"default": {
"ENGINE": env.str("DB_ENGINE"),
"NAME": env.str("name[1]"),
"USER": env.str("DB_USER"),
"PASSWORD": env.str("DB_PASSWORD"),
"HOST": env.str("DB_HOST"),
"PORT": env.str("DB_PORT"),
"TEST":
{
"NAME": 'name[1]',
}
},
"name[2]": {
"ENGINE": env.str("DB_ENGINE"),
"NAME": "[name1]",
"USER": env.str("DB_USER"),
"PASSWORD": env.str("DB_PASSWORD"),
"HOST": env.str("DB_HOST"),
"PORT": env.str("DB_PORT"),
"TEST":
{
"NAME": "name[2]",
}
},
"name[3]": {
"ENGINE": env.str("DB_ENGINE"),
"NAME": "name[3]",
"USER": env.str("DB_USER"),
"PASSWORD": env.str("DB_PASSWORD"),
"HOST": env.str("DB_HOST"),
"PORT": env.str("DB_PORT"),
"TEST":
{
"NAME": "name[3]",
}
},
}
我的测试是这样的:
class SyncTestCase(TestCase):
def setUp(self) -> None:
self.client = Client()
def test_func_tester_client(self):
bitbucket_db_setup.main()
response = self.client.get("/v1/devices/?name=a", SERVER_PORT=8000)
print(response.content)
self.assertEqual(200, 200)
但是当我运行它时,它只为'默认'别名创建DB:
Creating test database for alias 'default'...
*DB_SMTH是从环境中导入的名称,name[x]只是名称
要在运行测试时创建这些数据库,我们需要从Django设置中添加一组数据库名称。我们应该在TestCase的开头添加那些我们希望在测试时使用的内容:
class SyncTestCase(TestCase):
databases = {'name[1]', 'name[2]', 'name[3]'}
...
Django文档链接:https://docs.djangoproject.com/en/3.2/topics/testing/tools/#testing-multi-db