[Fixed]-Finding a Python Library to Mock a Database

6👍

If you absolutely must use mocks rather than the Django stuff others have mentioned, I’d recommend either Fudge or Mock.

5👍

If you are using django, fixtures can solve your problem. I don’t really know what you mean by mocking library, but they allow you to fill your db with test data. Which you can then interact with for your TestCase. The test data is destroyed after each TestCase.
http://docs.djangoproject.com/en/dev/howto/initial-data/

2👍

Personally I tend to write my unit tests to use a separate test database, so I’ll usually have a testing.conf file containing my database info separate from my regular development.conf and/or production.conf files. This makes my unit tests far more similar to the actual conditions under which the code will be executed in production.

For example, I recently developed a Python library for which the user calls a module-level initialize function, passing in the name(s) of the config file(s). The initialize function then uses the ConfigParser module to parse the config file(s), starts whatever threads it needs to run, creates urllib handlers, establishes database connections, etc.

This kind of setup allows for easy unit testing, since you can simply have your unit tests call into your initialize function before executing, passing in a config that points to your test database.

1👍

Based on some comments, it appears you’re using Django. If that’s the case, then you’re going to want to use a data fixture to populate test data into a test database. An excellent resource on this topic is Karen M. Tracey’s book Django 1.1 Testing and Debugging.

Here’s a summary of what you’re going to want to do:

  1. Enter data into your live/real database using the admin interface.
  2. Dump the data from your live database using:

    python manage.py dumpdata {django-app} --indent 4 >test_data.json
    

    replacing {django-app} with the name of your Django app.

  3. Place test_data.json in the directory {django-app}/fixtures

  4. Specify that your test case should load the fixture data using:

    Class MyTest(TestCase):
    
        fixtures = ['test_data.json']
    
        def testThisCode(self):
            # Test code
    

For more information, in addition to Karen M. Tracey’s book, you might check out Django’s documentation on Fixture Loading

0👍

There are some specific examples on using Mock for database testing here:

http://python-mock.sourceforge.net/#example-usage

Leave a comment