osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Flask test generator code review?


Hi,

I am writing my first unittests for a Flask app. First modest goal is to test whether a selected subset of the templates return the expected status 200. 
I am using a nose test generator in a class for this. Is the code below the correct way to do this? And is there a way to dynamically set the docstring of test_generator? This would make the nosetests output a bit more understandable. 

Thanks!
Albert-Jan

import os
import sys
from os.path import splitext
from http import HTTPStatus as status

import nose

from MyFabulousApp import app

app.testing = True
template_folder = app.config['TEMPLATE_FOLDER']


class Test_MyFabulousApp_HTTP_Status_OK:

    def __init__(self):
        self.setup()   # with unittest, setUp is called automatically, but not with nose

    def setup(self):
        self.client = app.test_client()
        self.client.post('/login', follow_redirects=True)

    def teardown(self):
        self.client.post('/logout', follow_redirects=True)

    def test_generator(self):
        """Does template return HTTP Status 200?"""
        def the_test(self, template):
            # the following line throws an error: AttributeError: attribute '__doc__' of 'method' objects is not writable
            #self.test_generator.__doc__ = 'Does template "%s" return HTTP Status 200?' % template
            respons = self.client.get('/' + template)
            actual = respons.status_code
            desired = status.OK.value
            assert actual == desired, \
               'Template "%s" returns status code %d' % (template, actual)
        templates = [splitext(item)[0] for item in os.listdir(template_folder)]
        for template in templates:
            yield the_test, self, template


if __name__ == '__main__':
    nose.run(defaultTest=__name__, argv=[sys.argv[0], '__main__', '--verbosity=2'])