gpt4 book ai didi

python - 如何针对 Django 数据迁移运行测试?

转载 作者:行者123 更新时间:2023-12-03 19:36:30 25 4
gpt4 key购买 nike

使用 documentation 中的以下示例:

def combine_names(apps, schema_editor):
Person = apps.get_model("yourappname", "Person")
for person in Person.objects.all():
person.name = "%s %s" % (person.first_name, person.last_name)
person.save()

class Migration(migrations.Migration):
dependencies = [
('yourappname', '0001_initial'),
]
operations = [
migrations.RunPython(combine_names),
]

我将如何针对此迁移创建和运行测试,以确认数据已正确迁移?

最佳答案

我正在做一些谷歌来解决同样的问题,并发现 an article 为我钉在钉子上的锤子,似乎没有现有答案那么笨拙。所以,把它放在这里以防它帮助其他人。

提出了 Django 的 TestCase 的以下子类:

from django.apps import apps
from django.test import TestCase
from django.db.migrations.executor import MigrationExecutor
from django.db import connection


class TestMigrations(TestCase):

@property
def app(self):
return apps.get_containing_app_config(type(self).__module__).name

migrate_from = None
migrate_to = None

def setUp(self):
assert self.migrate_from and self.migrate_to, \
"TestCase '{}' must define migrate_from and migrate_to properties".format(type(self).__name__)
self.migrate_from = [(self.app, self.migrate_from)]
self.migrate_to = [(self.app, self.migrate_to)]
executor = MigrationExecutor(connection)
old_apps = executor.loader.project_state(self.migrate_from).apps

# Reverse to the original migration
executor.migrate(self.migrate_from)

self.setUpBeforeMigration(old_apps)

# Run the migration to test
executor = MigrationExecutor(connection)
executor.loader.build_graph() # reload.
executor.migrate(self.migrate_to)

self.apps = executor.loader.project_state(self.migrate_to).apps

def setUpBeforeMigration(self, apps):
pass

他们提出的一个示例用例是:
class TagsTestCase(TestMigrations):

migrate_from = '0009_previous_migration'
migrate_to = '0010_migration_being_tested'

def setUpBeforeMigration(self, apps):
BlogPost = apps.get_model('blog', 'Post')
self.post_id = BlogPost.objects.create(
title = "A test post with tags",
body = "",
tags = "tag1 tag2",
).id

def test_tags_migrated(self):
BlogPost = self.apps.get_model('blog', 'Post')
post = BlogPost.objects.get(id=self.post_id)

self.assertEqual(post.tags.count(), 2)
self.assertEqual(post.tags.all()[0].name, "tag1")
self.assertEqual(post.tags.all()[1].name, "tag2")

关于python - 如何针对 Django 数据迁移运行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44003620/

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