Python 如何为flask应用程序设置测试mongo数据库
我有一个工作烧瓶应用程序,其外观如下:Python 如何为flask应用程序设置测试mongo数据库,python,mongodb,flask,chai,Python,Mongodb,Flask,Chai,我有一个工作烧瓶应用程序,其外观如下: import chai from myFolder import app class App(chai.Chai): @classmethod def setUpClass(cls): # this method is called before all testcases os.environ['MONGO_DB'] = 'test_db' # changing the db to test one
import chai
from myFolder import app
class App(chai.Chai):
@classmethod
def setUpClass(cls):
# this method is called before all testcases
os.environ['MONGO_DB'] = 'test_db' # changing the db to test one
@classmethod
def tearDownClass(cls):
# this method is called after all testcases
os.environ['MONGO_DB'] = 'normal' # change db to normal
def test_firstTestCase(self):
client = app.app.test_client()
print client.get('/api/something').data # here is the Problem
我的myFolder/app.py带有:
app = flask.Flask('name')
# and then a lot of routes
@app.route('/api/something', methods=['GET'])
def someName():
return flask.jsonify(somefile.somefunc())
包含函数的文件如下所示:
# initialize database connection
client = pymongo.MongoClient(host=os.environ['MONGO_IP'])
db = client[os.environ['MONGO_DB']]
# and then a lot of functions that uses this global db to CRUD something
def somefunc():
# do something with db
return
它工作得很好,每个人都很开心。但是我想和柴一起写一些测试
我想建立一个测试数据库,用数据填充它,进行一个API调用,断言数据看起来正常 我是这样做的:
import chai
from myFolder import app
class App(chai.Chai):
@classmethod
def setUpClass(cls):
# this method is called before all testcases
os.environ['MONGO_DB'] = 'test_db' # changing the db to test one
@classmethod
def tearDownClass(cls):
# this method is called after all testcases
os.environ['MONGO_DB'] = 'normal' # change db to normal
def test_firstTestCase(self):
client = app.app.test_client()
print client.get('/api/something').data # here is the Problem
让我惊讶的是,最后一次打印实际上是从真实数据库输出结果(我希望它什么也不输出,因为我将数据库名称更改为testing,并且没有填充它)。那么,我应该如何正确设置测试数据库呢?您确定在模拟环境变量后会执行初始化数据库连接代码吗?根据我看到的输出,它不会执行。那么,您在哪里为带有函数的文件设置了
import
s?