gpt4 book ai didi

python - 如何设置和拆卸用于单元测试的临时 Django 数据库?

转载 作者:太空狗 更新时间:2023-10-29 20:13:15 25 4
gpt4 key购买 nike

我想要一个 python 模块,其中包含一些我可以传递给 hg bisect --command 的单元测试。

单元测试正在测试 Django 应用程序的某些功能,但我认为我不能使用 hg bisect --command manage.py test mytestapp 因为 mytestapp必须在 settings.py 中启用,并且当 hg bisect 更新工作目录时,对 settings.py 的编辑将被破坏。

因此,我想知道下面的方法是否是最好的方法:

import functools, os, sys, unittest

sys.path.append(path_to_myproject)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'


def with_test_db(func):
"""Decorator to setup and teardown test db."""
@functools.wraps
def wrapper(*args, **kwargs):
try:
# Set up temporary django db
func(*args, **kwargs)
finally:
# Tear down temporary django db


class TestCase(unittest.TestCase):

@with_test_db
def test(self):
# Do some tests using the temporary django db
self.fail('Mark this revision as bad.')


if '__main__' == __name__:
unittest.main()

如果您能提供建议,我将不胜感激:

  1. 如果有更简单的方法,也许子类化 django.test.TestCase 但不编辑 settings.py 或者,如果没有;
  2. 上面说“设置临时 django 数据库”和“拆除临时 django 数据库”的行应该是什么?

最佳答案

破解了。我现在有一个完全独立于任何可以使用测试数据库运行单元测试的 django 应用程序的 python 文件:

#!/usr/bin/env python
"""Run a unit test and return result.

This can be used with `hg bisect`.
It is assumed that this file resides in the same dir as settings.py

"""

import os
from os.path import abspath, dirname
import sys
import unittest

# Set up django
project_dir = abspath(dirname(dirname(__file__)))
sys.path.insert(0, project_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

from django.db import connection
from django.test import TestCase
from django.test.utils import setup_test_environment, teardown_test_environment

from myproject import settings
from myproject.myapp.models import MyModel


class MyTestCase(TestCase):

def test_something(self):
# A failed assertion will make unittest.main() return non-zero
# which if used with `hg bisect` will mark the revision as bad
self.assertEqual(0, len(MyModel.objects.all())) # and so on


if '__main__' == __name__:
try:
setup_test_environment()
settings.DEBUG = False
verbosity = 0
old_database_name = settings.DATABASE_NAME
connection.creation.create_test_db(verbosity)
unittest.main()
finally:
connection.creation.destroy_test_db(old_database_name, verbosity)
teardown_test_environment()

关于python - 如何设置和拆卸用于单元测试的临时 Django 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2533457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com