I encountered a problem with unit tests when use i18 in my project.
My project uses framewoks i18 and webapp2
The function uses the translation by i18. But when I test, I get the error – missing global variable request.
For example it is:
from unittest import TestCase, main from webapp2_extras.i18n import lazy_gettext as _ def Hello(a): if a > 0: message = _('My great message!11 a > 0') else: message = _('My great message!11 a =< 0') return message class TestHandler(TestCase): def testHello0(self): self.assertEqual(Hello(0), 'My great message!11 a =< 0') def testHello3(self): self.assertEqual(Hello(3), 'My great message!11 a > 0') if __name__ == '__main__': main()
and I have message:
FAIL: testHello0 (text3.TestHandler) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/text3.py", line 14, in testHello0 self.assertEqual(Hello(0), 'My great message!11 a =< 0') AssertionError: Request global variable is not set.
I have a solution to this problem, but I do not like it. This is a crutch. How can you test my function without using framewoks on similarity webapp2
from unittest import TestCase, main from webapp2_extras.i18n import lazy_gettext as _ import webapp2 def Hello(a): if a > 0: message = _('My great message!11 a > 0') else: message = _('My great message!11 a =< 0') return message class OneHandler(webapp2.RequestHandler): def get(self): myNumber = self.request.get('myNumber') myNumber = int(myNumber) message = Hello(myNumber) self.response.write(message) routes = [('/One', OneHandler)] app = webapp2.WSGIApplication(routes = routes) class TestHandler(TestCase): def testHello0(self): myNumber = 0 URL = '/One?myNumber=%s' % myNumber self.response = app.get_response(URL) self.mess = self.response.body self.assertEqual(self.mess, 'My great message!11 a =< 0') def testHello3(self): myNumber = 3 URL = '/One?myNumber=%s' % myNumber self.response = app.get_response(URL) self.mess = self.response.body self.assertEqual(self.mess, 'My great message!11 a > 0') if __name__ == '__main__': main()
and well done!
Ran 2 tests in 0.047s OK
But it’s not a good solution. How I can testing my function and dont use webapp2, etc?
Advertisement
Answer
just don’t test external code and patch your _lazy function
from unittest import TestCase import fudge from path.to import fun # def fun(msg): # return _lazy("foo %s") % msg class TestHandler(TestCase): @fudge.patch("path.to._lazy") def test_foo(self, fake_lazy) fake_lazy.is_callable().calls(lambda s, **kw: s) self.assertEqual(fun("bar"), "foo bar")