Test Flask render_template() context

前端 未结 4 955
滥情空心
滥情空心 2020-12-24 12:02

I have a Flask route that looks like this:

@app.route(\'/\')                                                                 
def home():                             


        
4条回答
  •  伪装坚强ぢ
    2020-12-24 12:36

    Flask official documentation suggests that you use the template_rendered signal (available since version 0.6) for unit-testing your templates and the variables used to render it.

    For example, here is a helper context manager that can be used in a unittest to determine which templates were rendered and what variables were passed to the template:

    from flask import template_rendered
    from contextlib import contextmanager
    
    @contextmanager
    def captured_templates(app):
        recorded = []
        def record(sender, template, context, **extra):
            recorded.append((template, context))
        template_rendered.connect(record, app)
        try:
            yield recorded
        finally:
            template_rendered.disconnect(record, app)
    

    This can now easily be paired with a test client:

    with captured_templates(app) as templates:
        rv = app.test_client().get('/')
        assert rv.status_code == 200
        assert len(templates) == 1
        template, context = templates[0]
        assert template.name == 'index.html'
        assert len(context['items']) == 10
    

提交回复
热议问题