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:
JavaScript
x
21
21
1
from unittest import TestCase, main
2
from webapp2_extras.i18n import lazy_gettext as _
3
4
def Hello(a):
5
if a > 0:
6
message = _('My great message!11 a > 0')
7
else:
8
message = _('My great message!11 a =< 0')
9
return message
10
11
class TestHandler(TestCase):
12
13
def testHello0(self):
14
self.assertEqual(Hello(0), 'My great message!11 a =< 0')
15
16
def testHello3(self):
17
self.assertEqual(Hello(3), 'My great message!11 a > 0')
18
19
if __name__ == '__main__':
20
main()
21
and I have message:
JavaScript
1
7
1
FAIL: testHello0 (text3.TestHandler)
2
----------------------------------------------------------------------
3
Traceback (most recent call last):
4
File "/home/text3.py", line 14, in testHello0
5
self.assertEqual(Hello(0), 'My great message!11 a =< 0')
6
AssertionError: Request global variable is not set.
7
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
JavaScript
1
45
45
1
from unittest import TestCase, main
2
from webapp2_extras.i18n import lazy_gettext as _
3
import webapp2
4
5
def Hello(a):
6
if a > 0:
7
message = _('My great message!11 a > 0')
8
else:
9
message = _('My great message!11 a =< 0')
10
return message
11
12
13
class OneHandler(webapp2.RequestHandler):
14
def get(self):
15
myNumber = self.request.get('myNumber')
16
myNumber = int(myNumber)
17
message = Hello(myNumber)
18
self.response.write(message)
19
20
21
routes = [('/One', OneHandler)]
22
app = webapp2.WSGIApplication(routes = routes)
23
24
class TestHandler(TestCase):
25
26
def testHello0(self):
27
myNumber = 0
28
URL = '/One?myNumber=%s' % myNumber
29
30
self.response = app.get_response(URL)
31
self.mess = self.response.body
32
self.assertEqual(self.mess, 'My great message!11 a =< 0')
33
34
def testHello3(self):
35
myNumber = 3
36
URL = '/One?myNumber=%s' % myNumber
37
38
self.response = app.get_response(URL)
39
self.mess = self.response.body
40
self.assertEqual(self.mess, 'My great message!11 a > 0')
41
42
43
if __name__ == '__main__':
44
main()
45
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
JavaScript
1
13
13
1
from unittest import TestCase
2
import fudge
3
4
from path.to import fun
5
# def fun(msg):
6
# return _lazy("foo %s") % msg
7
8
class TestHandler(TestCase):
9
@fudge.patch("path.to._lazy")
10
def test_foo(self, fake_lazy)
11
fake_lazy.is_callable().calls(lambda s, **kw: s)
12
self.assertEqual(fun("bar"), "foo bar")
13