在我的项目中使用 i18 时,我遇到了单元测试问题。我的项目使用framewoks i18和webapp2 功能使用i18的翻译。但是当我测试时,我得到了错误——缺少全局变量请求。例如它是:
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
但这不是一个好的解决方案。我如何测试我的功能而不使用 webapp2 等?