GAE 프로젝트에서 Webapp2와 함께 Jinja2를 사용합니다.Unittest Jinja2 및 Webapp2 : 템플릿을 찾을 수 없음
class MyHandler(BaseHandler):
def get(self):
context = {'message': 'Hello, world!'}
self.render_response('my_template.html', **context)
내 템플릿을 기본 위치 (templates
)에 있습니다로
import webapp2
from webapp2_extras import jinja2
def jinja2_factory(app):
"""Set configuration environment for Jinja."""
config = {my config...}
j = jinja2.Jinja2(app, config=config)
return j
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(factory=jinja2_factory, app=self.app)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)
을 그리고보기 처리기 : webapp2_extras.jinja2
에 설명으로
나는 기본 RequestHandler
있습니다.
응용 프로그램은 dev 서버에서 잘 작동하며 템플릿이 올바르게 렌더링됩니다.
하지만
import unittest
import webapp2
import webstest
class MyHandlerTest(unittest.TestCase):
def setUp(self):
application = webapp2.WSGIApplication([('/', MyHandler)])
self.testapp = webtest.TestApp(application)
def test_response(self):
response = application.get_response('/')
...
application.get_response('/my-view')
인상 예외로 MyHandler
을 유닛 테스트 할 때 : TemplateNotFound: my_template.html
.
내가 놓친 것이 있습니까? jinja2 환경 또는 템플릿 로더 구성과 비슷합니까?
감사! 팩토리 기능을 포함하는 모듈/파일을 기반으로 절대 경로를 생성하여 구성에서 경로를 설정하지 않아도됩니다. 이런 식으로 이미 절대 경로를 생성하고 있습니다. 테스트 세트 업 함수에서 수행하는 것입니다. 팩토리 기능으로 수행하면 설정을 기억할 필요가 없으며 라이브 및 테스트 중일 때 모두 작동합니다. 예를 들어 :'config = { 'template_path': os.path.join (os.path.dirname (__ file__), 'templates /')}''(factory 함수를 포함하는 파일과 템플릿 dir 모두가 프로젝트). – bszom