TheDeeno's Blog

DbSnapshot v0.1 Released!

Posted in programming by TheDeeno on August 31, 2009

Last night I finished up work on a small .net library called DbSnapshot. The library helps test database interactions by allowing you to easily save and restore snapshots of your database. Simplicity was the goal, so its increidibly easy to use. Lets see it in action!

public void MyTest()
{
    using (var manager = new SqlSnapshotManager(connectionString, databaseName))
    {
        manager.SaveSnapshot();

        // execute some potentially destructive db commands

        manager.RestoreSnapshot();

        // execute some more destructive db commands

        manager.RestoreSnapshot();
    }
}

You can easily port the above to setup a test fixture (example in nunit):

[TestFixture]
public class MyFixture
{
    IDbSnapshotManager _manager;

    [TestFixtureSetUp]
    public void FixtureSetup()
    {
        _manager = new SqlSnapshotManager(CONNECTION_STRING, TEST_DATABASE_NAME);
        _manager.SaveSnapshot(); // prepare for db tests
    }

    [SetUp]
    public void Setup()
    {
        _manager.RestoreSnapshot(); // put db in an expected state before each test
    }

    // ...
    // DO TONS OF POTENTIALLY DESTRUCTIVE TESTS
    // ...

    [TestFixtureTearDown]
    public void FixtureSetup()
    {
        _manager.Dispose(); // clean up when finished with tests
    }
}

The SqlSnapshotManager works by using SqlServer’s built in backup/restore facilities. It creates a COPY_ONLY backup (so it doesn’t interupt your current backup cycle) and saves it to a file in the “.dbsnapshot” directory under your project’s current directory. It implements IDisposable so make sure to dispose it! Disposal will ensure the database always gets restored and the work files/folders are removed.

Right now it only works with SqlServer but I plan on supporting MySql and others in the future.

If you want to help by creating a snapshot manager for your flavor of database engine, just implement IDbSnapshotManager and send me a patch!

You can get the v0.1 v.02 release here.

The source is on GitHub.

Clone url: git://github.com/thedeeno/DbSnapshot.git

Enjoy!

Tagged with: , , , ,