I am about to finish a university project that involves Python, and my team has a test case shortage. We need more, and specifically, we need some test cases for the database. This is where mocking comes in, however. We need a Python-specific library that can be used to mock a database, so the test cases do not use SQL or access the real database. We are using MySQL for the real database. It's a bit difficult for me to come across an easy-to-use Python database mocking library. What would be the best one to use for our test cases? Or, is there a better way to test a database in Python without touching it? I would appreciate your advice very much. Thanks :-)
If you absolutely must use mocks rather than the Django stuff others have mentioned, I'd recommend either Fudge or Mock.
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/
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.
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:
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.
Place test_data.json
in the directory {django-app}/fixtures
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With