[英]Templates when unit testing a Flask application
我正在為Flask應用程序編寫單元測試,該應用程序大致具有以下組織:
/myapplication
runner.py
/myapplication
__init__.py
/special
__init__.py
views.py
models.py
/static
/templates
index.html
/special
index_special.html
/tests
__init__.py
/special
__init__.py
test_special.py
特別是,我想測試special
模塊是否按預期工作。
我已經定義了以下內容:
在special/views.py
:
mod = Blueprint('special', __name__, template_folder="templates") @mod.route('/standard') def info(): return render_template('special/index_special.html')
在myapplication/__init__.py
:
app = Flask(__name__) def register_blueprints(app): from special.views import mod as special_blueprint app.register_blueprint(special_blueprint, url_prefix='/special') register_blueprints(app)
在myapplication/tests/test_special.py
class TestSpecial: @classmethod def create_app(cls): app = Flask(__name__) register_blueprints(app) return app @classmethod def setup_class(cls): cls.app = cls.create_app() cls.client = cls.app.test_client() def test_connect(self): r = self.client.get('/standard') assert r.status_code == 200
雖然應用程序本身工作正常,但test_connect
單元測試失敗並出現TemplateNotFound: special/index_special.html
異常。
我怎么能告訴測試在哪里找到相應的模板? 使用Flask測試繞過模板渲染並不是一個真正的選擇......
您可以將template_folder
傳遞給應用程序對象構造函數:
app = Flask(__name__, template_folder='../templates')
你可能不得不使用絕對路徑,我不確定。
http://flask.pocoo.org/docs/api/#flask.Flask
我主要傾向於使用我的應用程序代碼創建一個create_app
函數,並在我的測試中使用它,這樣應用程序對象就是一致的。 如果我想測試單個藍圖或者單獨的小東西,我只會創建一個單獨的應用程序。
def create_app(conf_obj=BaseSettings, conf_file='/etc/mysettings.cfg'):
app = Flask(__name__)
app.config.from_object(conf_obj)
app.config.from_pyfile(conf_file, silent=True)
.... blueprints etc
return app
然后在我的測試中:
class TestFoo(unittest.TestCase):
def setUp(self):
self.app = create_app(TestSettings)
....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.