24

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

I just need one simple example.

Thanks.

RobertVa
  • 259
  • 1
  • 2
  • 5
  • 3
    Be more specific: do you need help in how to setup nose? or how to test a model? – van May 28 '09 at 12:59

2 Answers2

38

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()
    # ...
codeape
  • 97,830
  • 24
  • 159
  • 188
  • 1
    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. – van May 28 '09 at 13:03
  • Good points. I updated the example to show a call to create_all. – codeape Jun 02 '09 at 12:18
  • 10
    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. – Michael Robellard Jul 14 '15 at 02:06
  • 1
    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. – codeape Jul 16 '15 at 22:21
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.

codeape
  • 97,830
  • 24
  • 159
  • 188
Ben Ford
  • 2,087
  • 21
  • 26