Unittest Jinja2 and Webapp2 : template not found

I use Jinja2 with Webapp2 on a GAE project.

I have a base RequestHandler as describe in webapp2_extras.jinja2:

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)

And a view handler as:

class MyHandler(BaseHandler): def get(self): context = {'message': 'Hello, world!'} self.render_response('my_template.html', **context)

My templates are in the default location (templates).

The app works well on dev server, and the template is correctly rendered.

But when I try to unittest MyHandler with

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') raise an exception: TemplateNotFound: my_template.html.

Is there something I missed? Like a jinja2 environment or template loader configuration?


<strong>Problem origin:</strong> Jinja2 default loader searches files in a relative ./templates/ directory. When you run your GAE application on the development server this path is relative to the root of your application. But when you run your unittests this path is relative to your unittest files.

<strong>Solution:</strong> Not really an ideal solution, but here a trick I did to solve my problem.

I updated the jinja2 factory to add a dynamic template path, set in app config:

def jinja2_factory(app): """Set configuration environment for Jinja.""" config = {'template_path': app.config.get('templates_path', 'templates'),} j = jinja2.Jinja2(app, config=config) return j

And I set an absolute path to the templates in the setUp of my unittests:

class MyHandlerTest(unittest.TestCase): def setUp(self): # Set template path for loader start = os.path.dirname(__file__) rel_path = os.path.join(start, '../../templates') # Path to my template abs_path = os.path.realpath(rel_path) application.config.update({'templates_path': abs_path})


  • how to implement comet via gevent's event
  • Flask.session persisting after close browser
  • Flask-SQLAlchemy InvalidRequestError: Object is already attached to session
  • Opening csv file in Python: builtins. AttributeError AttributeError: '_io.BytesIO' object
  • why adding a space after `(.+?)` can completely change the result
  • curl not working for getting a web page content, why?
  • Can TextIO write to prefixes derived from the window maxTimestamp?
  • What should be the grok pattern for thoses logs ? (ingest pipeline for filebeat)
  • Wcf NHibernate Session management
  • How to mount dynamically single file component in Vue.js
  • Angular: Passing data back to my controller from a factory ajax call
  • TypeError: Main.login is not a function
  • autotest and rspec giving different answers
  • Replicating and differentiating portions of a form
  • ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn&
  • get all processes in parallel
  • How to make HttpWebRequest async
  • Converter from SAT to 3-SAT
  • Varnish/Apache Random 503 Errors
  • C# Report Renderer for SRSS 2008 R2 - Missing Parameter
  • Updating Dojo provide
  • Django invalid literal for int() with base 10
  • xtable package: Skipping some rows in the output
  • Should I or shouldn't I use the CachingConnectionFactory with hornetq 2.4.1
  • SplFileObject error failed to open stream: No such file or directory
  • Setting up SourceTree to merge unity3d scenes with UnityYAMLMerge
  • C++ Partial template specialization - design simplification
  • Email format validation in mvc3 view
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • How to add date and time under each post in guestbook in google app engine
  • How can I use Kendo UI with Razor?
  • php design question - will a Helper help here?
  • Is there a mandatory requirement to switch app.yaml?
  • File upload with ng-file-upload throwing error
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • AngularJs get employee from factory
  • coudnt use logback because of log4j
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • Observable and ngFor in Angular 2