how to unittest the template variables passed to jinja2 template from webapp2 request handler

后端 未结 2 526
醉梦人生
醉梦人生 2021-01-02 05:29

I\'m trying to test my webapp2 handlers. To do this, I thought it would be a good idea to send a request to the handler e.g.:

request = webapp2.Request.blank(         


        
2条回答
  •  -上瘾入骨i
    2021-01-02 05:59

    Thanks to proppy's suggestion I ended up using a mock.

    http://www.voidspace.org.uk/python/mock/

    (mock is included as part or unittest.mock in python 3)

    So here is my main.py code which is similar to what I have in webapp2:

    note instead of BaseHandler.render_template i have BaseHandler.say_yo

    __author__ = 'Robert'
    
    print "hello from main"
    
    class BaseHandler():
        def say_yo(self,some_number=99):
            print "yo"
            return "sup"
    
    class TheHandler(BaseHandler):
        def get(self, my_number=42):
            print "in TheHandler's get()"
            print self.say_yo(my_number)
            return "TheHandler's return string"
    

    and atest.py:

    __author__ = 'Robert'
    
    import unittest
    import main
    from mock import patch
    
    class DemoTestCase(unittest.TestCase):
        def setUp(self):
            pass
    
        def tearDown(self):
            pass
    
        def testNothing(self):
            self.assertEqual(42, 21 + 21)
    
        def testSomeRequests(self):
            print "hi"
            bh = main.BaseHandler()
            print bh.say_yo()
    
            print "1111111"
    
            with patch('main.BaseHandler.say_yo') as patched_bh:
                print dir(patched_bh)
                patched_bh.return_value = 'double_sup'
                bh2 = main.BaseHandler()
                print bh2.say_yo()
                print "222222"
    
            bh3 = main.BaseHandler()
            print bh3.say_yo()
    
            print "3333"
    
            th = main.TheHandler()
            print th.get()
    
            print "44444"
            with patch('main.BaseHandler.say_yo') as patched_bh:
                patched_bh.return_value = 'last_sup'
                th = main.TheHandler()
                print th.get()
                print th.get(123)
                print "---"
                print patched_bh.called
                print patched_bh.call_args_list
                print "555555"
    
    
    
    if __name__ == '__main__':
        unittest.main()
    

    this code gives lots of output, here is a sample:

    44444
    in TheHandler's get()
    last_sup
    TheHandler's return string
    in TheHandler's get()
    last_sup
    TheHandler's return string
    ---
    True
    [call(42), call(123)]
    555555
    

提交回复
热议问题