25

Can someone show me how to write unit tests for sqlalchemy model I created using nose.

I just need one simple example.

Thanks.

1
  • 3
    Be more specific: do you need help in how to setup nose? or how to test a model? Commented May 28, 2009 at 12:59

2 Answers 2

40

You can simply create an in-memory SQLite database and bind your session to that.

Example:


from db import session # probably a contextbound sessionmaker
from db import model

from sqlalchemy import create_engine

def setup():
    engine = create_engine('sqlite:///:memory:')
    session.configure(bind=engine)
    # You probably need to create some tables and 
    # load some test data, do so here.

    # To create tables, you typically do:
    model.metadata.create_all(engine)

def teardown():
    session.remove()


def test_something():
    instances = session.query(model.SomeObj).all()
    eq_(0, len(instances))
    session.add(model.SomeObj())
    session.flush()
    # ...
Sign up to request clarification or add additional context in comments.

4 Comments

Great answer! I think you need to call create_all on the MetaData object to actually create tables. Also if db-vendor specific data types are used, then some of the DDLs may not run.
Good points. I updated the example to show a call to create_all.
This is a horrible answer if SQLLite is not your production database. Never test with a different database than the one you are using in production. They will have lots of differences and you are setting yourself up for a disaster.
You could of course use a Postgresql, MySQL, etc. database server for executing the tests against. The setup and teardown methods above would possibly be a bit different then, you probably would do a CREATE DATABASE in setup and a DROP DATABASE in teardown. I have seldom had any problems by switching DB backends using SQLAlchemy. I routinely do automatic tests against SQLite and run the prod system on Postg, MySQL or MSSQL. One system I developed, we did unit testing against SQLite, integration testing on Linux/Postgres and the production system was Win/MSSQL. No changes in DB access code.
2

Check out the fixture project. We used nose to test that and it's also a way to declaratively define data to test against, there will be some extensive examples for you to use there!

See also fixture documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.