Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need a sample of python unit testing sqlalchemy model with nose

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

I just need one simple example.

Thanks.

like image 654
RobertVa Avatar asked May 07 '09 09:05

RobertVa


2 Answers

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()
    # ...
like image 170
codeape Avatar answered Nov 07 '22 19:11

codeape


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.

like image 2
Ben Ford Avatar answered Nov 07 '22 18:11

Ben Ford