python 我需要一个带有鼻子的python单元测试sqlalchemy模型的样本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/833626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:56:39  来源:igfitidea点击:

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

pythonunit-testingtestingsqlalchemynose

提问by RobertVa

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

有人可以告诉我如何为我使用鼻子创建的 sqlalchemy 模型编写单元测试吗?

I just need one simple example.

我只需要一个简单的例子。

Thanks.

谢谢。

回答by codeape

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

您可以简单地创建一个内存中的 SQLite 数据库并将您的会话绑定到该数据库。

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()
    # ...

回答by Ben Ford

Check out the fixtureproject. 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!

检查夹具项目。我们使用了nose 来测试它,这也是一种声明性地定义要测试的数据的方法,那里会有一些广泛的示例供您使用!

See also fixture documentation.

另请参阅夹具文档