新聞中心
測試主/副配置
如果你使用主/副本(某些數(shù)據(jù)庫稱為主/從)復(fù)制來測試多數(shù)據(jù)庫配置,那么這種創(chuàng)建測試數(shù)據(jù)庫的策略會帶來問題。當(dāng)創(chuàng)建測試數(shù)據(jù)庫時,不會有任何復(fù)制,因此,在主服務(wù)器上創(chuàng)建的數(shù)據(jù)在副本上看不到。
為了彌補這一點,Django 允許你定義一個數(shù)據(jù)庫是 測試鏡像??紤]以下(簡化的)數(shù)據(jù)庫配置示例:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myproject',
'HOST': 'dbprimary',
# ... plus some other settings
},
'replica': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myproject',
'HOST': 'dbreplica',
'TEST': {
'MIRROR': 'default',
},
# ... plus some other settings
}
}在這個設(shè)置中,我們有兩個數(shù)據(jù)庫服務(wù)器。?dbprimary?,用數(shù)據(jù)庫別名 ?default ?描述,?dbreplica ?用別名 ?replica ?描述。正如你所期望的那樣,?dbreplica ?被數(shù)據(jù)庫管理員配置為 ?dbprimary ?的讀副本,因此在正常活動中,對 ?default ?的任何寫入都會出現(xiàn)在 ?replica ?上。
如果 Django 創(chuàng)建了兩個獨立的測試數(shù)據(jù)庫,就會破壞任何期望復(fù)制發(fā)生的測試。然而,?replica ?數(shù)據(jù)庫已經(jīng)被配置為測試鏡像(使用 ?MIRROR ?測試設(shè)置),表明在測試中,?replica? 應(yīng)該被當(dāng)作 ?default ?的鏡像。
在配置測試環(huán)境時,?replica ?的測試版本將不會被創(chuàng)建。相反,與?replica?的連接將被重定向為指向 ?default?。因此,對 ?default ?的寫入將出現(xiàn)在 ?replica ?上——但這是因為它們實際上是同一個數(shù)據(jù)庫,而不是因為兩個數(shù)據(jù)庫之間有數(shù)據(jù)復(fù)制。
控制測試數(shù)據(jù)庫的創(chuàng)建順序
默認(rèn)情況下,Django 會假設(shè)所有的數(shù)據(jù)庫都依賴于 ?default ?數(shù)據(jù)庫,因此總是先創(chuàng)建 ?default ?數(shù)據(jù)庫。但是,我們不保證測試配置中其他數(shù)據(jù)庫的創(chuàng)建順序。
如果你的數(shù)據(jù)庫配置需要特定的創(chuàng)建順序,你可以使用 ?DEPENDENCIES ?測試設(shè)置指定存在的依賴關(guān)系??紤]以下(簡化的)數(shù)據(jù)庫配置示例:
DATABASES = {
'default': {
# ... db settings
'TEST': {
'DEPENDENCIES': ['diamonds'],
},
},
'diamonds': {
# ... db settings
'TEST': {
'DEPENDENCIES': [],
},
},
'clubs': {
# ... db settings
'TEST': {
'DEPENDENCIES': ['diamonds'],
},
},
'spades': {
# ... db settings
'TEST': {
'DEPENDENCIES': ['diamonds', 'hearts'],
},
},
'hearts': {
# ... db settings
'TEST': {
'DEPENDENCIES': ['diamonds', 'clubs'],
},
}
}在這種配置下,將首先創(chuàng)建 ?diamonds ?數(shù)據(jù)庫,因為它是唯一沒有依賴性的數(shù)據(jù)庫。接下來將創(chuàng)建 ?default ?和 ?clubs ?數(shù)據(jù)庫(盡管這兩個數(shù)據(jù)庫的創(chuàng)建順序沒有保證),然后是 ?hearts?,最后是 ?spades?。
如果在 ?DEPENDENCIES ?定義中存在任何循環(huán)依賴關(guān)系,將引發(fā) ?ImproperlyConfigured ?異常。
網(wǎng)站題目:創(chuàng)新互聯(lián)Django4.0教程:Django4.0進階測試主題-測試與多數(shù)據(jù)庫
文章位置:http://www.dlmjj.cn/article/dhjgcoc.html


咨詢
建站咨詢
