【发布时间】:2017-02-09 04:27:15
【问题描述】:
我有一系列集成级别的测试,它们在我的 Django 项目中作为管理命令运行。这些测试正在验证从外部来源摄取到我的数据库中的大量天气数据的完整性。因为我有如此大量的数据,所以我真的必须针对我的生产数据库进行测试才能使测试有意义。我想弄清楚的是如何定义特定于该命令或连接对象的只读数据库连接。我还应该补充一点,这些测试不能通过 ORM,所以我需要执行原始 SQL。
我的测试结构是这样的
class Command(BaseCommand):
help = 'Runs Integration Tests and Query Tests against Prod Database'
def handle(self,*args, **options):
suite = unittest.TestLoader().loadTestsFromTestCase(TestWeatherModel)
ret = unittest.TextTestRunner().run(suite)
if(len(ret.failures) != 0):
sys.exit(1)
else:
sys.exit(0)
class TestWeatherModel(unittest.TestCase):
def testCollectWeatherDataHist(self):
wm = WeatherManager()
wm.CollectWeatherData()
self.assertTrue(wm.weatherData is not None)
WeatherManager.CollectWeatherData() 方法如下所示:
def CollecWeatherData(self):
cur = connection.cursor()
cur.execute(<Raw SQL Query>)
wm.WeatherData = cur.fetchall()
cur.close()
我想以某种方式证明这一点,以免其他人(或我)稍后出现并意外编写会修改生产数据库的测试。
【问题讨论】:
-
根据我的经验,这是在数据库端完成的。换句话说,测试应该使用特定于测试的只读用户凭据连接到数据库。您的测试也可能不必访问实时数据库,但这是一个更大的架构问题。
-
我知道我不应该让这些测试影响生产数据库,我最终会将所有摄取和验证移至暂存数据库,然后同步到生产数据库,但我还没搞定。
标签: python django django-testing django-database django-postgresql