Der*_*wok 32 python django unit-testing
我有一个托管= False的模型.
class SampleModel(models.Model):
apple = models.CharField(max_length=30)
orange = models.CharField(max_length=30)
class Meta:
managed = False
Run Code Online (Sandbox Code Playgroud)
我有一个单元测试,它创建了一个SampleModel,但是当我运行测试时,我得到:
DatabaseError: no such table: SAMPLE_SAMPLE_MODEL
Run Code Online (Sandbox Code Playgroud)
django文档 - https://docs.djangoproject.com/en/dev/ref/models/options/#managed记录以下内容:
对于涉及托管= False的模型的测试,由您来确保在测试设置中创建正确的表.
如何在测试设置期间实际"创建"表格?或者,我怎样才能使它在运行测试时,在测试期间该模型具有"managed = True"?
在实际应用程序中,此模型实际上由数据库中的视图支持.但是对于测试期间,我想将其视为一个表,并能够在那里插入测试数据.
Mar*_*vin 14
看看这篇博客文章:http://www.caktusgroup.com/blog/2010/09/24/simplifying-the-testing-of-unmanaged-database-models-in-django/它详细描述了一个创建非管理型号的测试运行器.
ill*_*nan 10
您可以在方法中使用SchemaEditor以TestCase.setUp使用managed = False.
# models.py
from django.db import models
class Unmanaged(models.Model):
foo = models.TextField()
class Meta:
# This model is not managed by Django
managed = False
db_table = 'unmanaged_table'
Run Code Online (Sandbox Code Playgroud)
在你的测试中:
# tests.py
from django.db import connection
from django.test import TestCase
from myapp.models import Unmanaged
class ModelsTestCase(TestCase):
def setUp(self):
super().setUp()
with connection.schema_editor() as schema_editor:
schema_editor.create_model(Unmanaged)
if Unmanaged._meta.db_table not in connection.introspection.table_names():
raise ValueError("Table `{table_name}` is missing in test database.".format(table_name=Unmanaged._meta.db_table))
def tearDown(self):
super().tearDown()
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(Unmanaged)
def test_unmanaged_model(self):
with self.assertNumQueries(num=3):
self.assertEqual(0, Unmanaged.objects.all().count())
Unmanaged.objects.create()
self.assertEqual(1, Unmanaged.objects.all().count())
Run Code Online (Sandbox Code Playgroud)
执行原始SQL以在测试设置中创建表:
from django.db import connection
class MyTest(unittest.TestCase):
def setUp(self):
connection.cursor().execute("CREATE TABLE ...")
def tearDown(self):
connection.cursor().execute("DROP TABLE ...")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8928 次 |
| 最近记录: |