I'm writing a test suite for Django that runs tests in a tree-like fashion. For example, Testcase A might have 2 outcomes, and Testcase B might have 1, and Testcase C might have 3. The tree looks like this
X
/
A-B-C-X
\ \
B X
\ X
\ /
C-X
\
X
For each path in the tree above, the database contents may be different. So at each fork, I'm thinking of creating an in-memory copy of the current state of the database, and then feeding that parameter into the next test.
Anyone have an idea about how to essentially copy the in-memory database to another one, and then get a reference to pass that database around?
Thanks!
解决方案
Alright, after a fun adventure I figured this one out.
from django.db import connections
import sqlite3
# Create a Django database connection for our test database
connections.databases['test'] = {'NAME': ":memory:", 'ENGINE': "django.db.backends.sqlite3"}
# We assume that the database under the source_wrapper hasn't been created
source_wrapper = connections['default'] # put alias of source db here
target_wrapper = connections['test']
# Create the tables for the source database
source_wrapper.creation.create_test_db()
# Dump the database into a single text query
query = "".join(line for line in source_wrapper.connection.iterdump())
# Generate an in-memory sqlite connection
target_wrapper.connection = sqlite3.connect(":memory:")
target_wrapper.connection.executescript(query)
And now the database called test will be a carbon copy of the default database. Use target_wrapper.connection as a reference to the newly created database.