开发者

Testing Django models with Lettuce?

Lettuce seems like a pretty good BDD testing framework for Django apps; however, I haven't found any examples or documentation how to test models w开发者_开发知识库ith it. Is there anything available?


well I was looking for the same, but couldn't find any proper documentation or a tutorial for this. Just to test the validations on models and checking the sanity of relationships i tried putting and fetching the values from the scenarios and and validate them. Thats much of the validations one can require to validate from a model i guess.


Seems this post was made some time ago, though it was top of the results for me so here's my findings.

Lettuce has @before.runserver and @after.runserver decorators for Django, which can be used to implement a test database in your terrain.py file.

I'm using an SQLite database for this example and I also use South [:(] so I have an additional test to ensure SOUTH_TESTS_MIGRATE has been set to False. I have a local_settings_test.py file, which overrides settings with the ones specific to my test case and call with the harvest command like so:

python manage.py harvest --settings=local_settings_test

Here's my set-up and destruction calls. Of course you can implement these with other decorators if you'd prefer to reset the database upon every feature, scenario or step, for example. Refer to http://lettuce.it/reference/terrain.html for more information on what's available to you.

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)

Once you've added these steps in your terrain file, you can call the models in your steps as you would in your unit tests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜