在我的app.py中,我有以下代码:
from sanic import Sanic
my_dep = load_production_dep()
app = Sanic()
@app.route("/")
def hello(request):
return my_dep.hello()
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)如何将此my_dep注入我的sanic应用程序实例?使用上面的设置,我不能完全测试我的代码,因为我有依赖于模块中加载的全局依赖项的路由。
换句话说:我如何重构这个简单的应用程序,使其易于测试?
发布于 2019-08-29 16:15:06
我可以用blueprints和应用程序工厂来解决。
# routes.py
from sanic import Blueprint
bp = Blueprint('my_blueprint')
@bp.route("/")
def hello(request):
return my_dep.hello()
# app.py
def make_app():
from sanic import Sanic
from routes import bp
my_dep = load_production_dep()
app = Sanic()
app.blueprint(bp)
return app
# test.py
class MyTest(unittest.TestCase):
def setUp(self):
self.test_app = make_app() # or you can make your own factory for test app specifically
def test_foobar(self):
...https://stackoverflow.com/questions/57661310
复制相似问题