【发布时间】:2016-02-14 13:29:42
【问题描述】:
我正在尝试使用 unittest 测试我的烧瓶应用程序。我想避免烧瓶测试,因为我不喜欢超越自己。
我现在真的一直在努力解决这个单元测试问题。这很令人困惑,因为有请求上下文和应用程序上下文,当我调用 db.create_all() 时,我不知道我需要进入哪一个。
似乎当我添加到数据库时,它会将我的模型添加到我的应用程序模块 (init.py) 文件中指定的数据库中,而不是 setUp(self ) 方法。
我有一些方法必须在每个 test_ 方法之前填充数据库。
如何将我的数据库指向正确的路径?
def setUp(self):
#self.db_gd, app.config['DATABASE'] = tempfile.mkstemp()
app.config['TESTING'] = True
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE']
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
os.path.join(basedir, 'test.db')
db = SQLAlchemy(app)
db.create_all()
#self.app = app.test_client()
#self.app.testing = True
self.create_roles()
self.create_users()
self.create_buildings()
#with app.app_context():
# db.create_all()
# self.create_roles()
# self.create_users()
# self.create_buildings()
def tearDown(self):
#with app.app_context():
#with app.request_context():
db.session.remove()
db.drop_all()
#os.close(self.db_gd)
#os.unlink(app.config['DATABASE'])
这是填充我的数据库的方法之一:
def create_users(self):
#raise ValueError(User.query.all())
new_user = User('Some User Name','xxxxx@gmail.com','admin')
new_user.role_id = 1
new_user.status = 1
new_user.password = generate_password_hash(new_user.password)
db.session.add(new_user)
我看过的地方:
http://kronosapiens.github.io/blog/2014/08/14/understanding-contexts-in-flask.html
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xvi-debugging-testing-and-profiling
【问题讨论】:
标签: python flask sqlalchemy flask-sqlalchemy python-unittest