If you've got a database setup in Django, how can you have the TestRunner use the 'live' database (per the DATABASE_* settings in开发者_JS百科 settings.py
) instead of running them on the ephemeral test database.
For example, I'd like to run the following test on the live
database that's specified in settings.py
:
import unittest
from example import models
class DBDriverTest(unittest.TestCase):
db testDriver(self):
"Connect to the live database and drop in sample value."
m = models.MyModel('hello')
m.save() # ... save to the live database from settings.py
At present the above code will save only to the test database that's been constructed. This is very limiting because my application has multiple parallel processes working on the database - and my unit tests will be incomplete (and incoherent) without the ability to pump things over to a 'live' database and see where they stand after a short sleep.
The two potential options I can think of are:
Plug through the Django API to figure out how to 'manually' connect to the database in settings.py
Make a low-level connection to the 'live' database and manually populate it
The prior is problematic because it'd be relying on things beneath Django's public API. The latter is problematic because it foregoes the database-agnostic Django database API and is more manually intensive.
I'm grateful for your thoughts and input.
Brian
You would have to define your own test_runner
tearDown
methods, because every test is run in isolation and database is cleared after every run. You can do, what you are asking for by simply building your own test_runner
, we have done it once (though it wasn't me on the team) with database that was accessed by web services and for some time we didn't have any way to delete anything from there but to manually delete the whole database ;-) This was pretty fun.
Answering your question: create your own test_runner
and prepare to create your own tearDown
methods, in which you will only delete objects, that you created. You must somehow store there primary keys
, so you won't delete anything from the live database.
However, I don't think this is a good way to do. Running tests on live database is asking yourself for a disaster. Sooner or later you'll get into trouble with this. What you should do instead is to dump your live database, prepare fixtures from this data and use them in your tests. This is well documented and easily done. This way you will have live environment without risking your precious data and you don't need to write your own test_runner
. This is the best and safest way to go in my opinion.
精彩评论