【问题标题】:Testing Django models with Lettuce?用生菜测试 Django 模型?
【发布时间】:2011-07-31 21:08:50
【问题描述】:

Lettuce 似乎是一个非常好的 Django 应用程序 BDD 测试框架;但是,我还没有找到任何如何使用它测试模型的示例或文档。有什么可用的吗?

【问题讨论】:

    标签: django django-models lettuce


    【解决方案1】:

    好吧,我一直在寻找相同的内容,但找不到任何合适的文档或教程。 只是为了测试模型的验证并检查关系的健全性,我尝试从场景中放置和获取值并验证它们。我猜这就是从模型中验证所需的大部分验证。

    【讨论】:

      【解决方案2】:

      似乎这篇文章是很久以前发布的,虽然它对我来说是最重要的结果,所以这是我的发现。

      Lettuce 具有用于 Django 的 @before.runserver@after.runserver 装饰器,可用于在您的 terrain.py 文件中实现测试数据库。

      我在这个例子中使用了一个 SQLite 数据库,并且我还使用了 South [:(] 所以我有一个额外的测试来确保 SOUTH_TESTS_MIGRATE 已设置为 False。我有一个 local_settings_test.py 文件,它使用特定于我的测试用例的设置覆盖设置,并使用 Harvest 命令调用,如下所示:

      python manage.py harvest --settings=local_settings_test

      这是我的设置和破坏调用。当然,例如,如果您希望在每个功能、场景或步骤上重置数据库,您可以使用其他装饰器来实现这些。请参阅http://lettuce.it/reference/terrain.html 了解更多关于您可以使用的信息。

      from lettuce import *
      from django.conf import settings
      from django.core.management.base import CommandError
      from django.core.management import call_command
      
      
      def assert_test_database():
      
          """
          Raises a CommandError in the event that the database name does not contain
          any reference to testing.
      
          Also checks South settings to ensure migrations are not implemented.
          """
      
          if not '-test' in settings.DATABASES['default']['NAME']:
              raise CommandError('You must run harvest with a test database')
      
          if getattr(settings, 'SOUTH_TESTS_MIGRATE', True):
              raise CommandError('SOUTH_TESTS_MIGRATE should be set to False')
      
      
      @before.runserver
      def create_database(server):
      
          """
          Asserts the database name is correct and creates initial structure, loading
          in any test_data fixtures which may have been created.
          """
      
          assert_test_database()
          call_command('syncdb', interactive=False, verbosity=0)
          call_command('loaddata', 'test_data', interactive=False, verbosity=0)
      
      
      @after.runserver
      def flush_database(server):
      
          """
          Asserts the database name is correct and flushes the database.
          """
      
          assert_test_database()
          call_command('flush', interactive=False, verbosity=0)
      

      在地形文件中添加这些步骤后,您可以在步骤中调用模型,就像在单元测试中一样。

      【讨论】:

        猜你喜欢
        • 2021-01-04
        • 1970-01-01
        • 2012-03-14
        • 2017-12-19
        • 1970-01-01
        • 1970-01-01
        • 2014-12-05
        • 2017-09-06
        • 1970-01-01
        相关资源
        最近更新 更多