def test_build_extra_keyword(self): route = Route(r"/<year:\d{4}>", None) url = route.build(Request.blank("/"), (), dict(year="2010", foo="bar")) self.assertEqual(url, "/2010?foo=bar") # Arguments are sorted. url = route.build(Request.blank("/"), (), dict(year="2010", foo="bar", baz="ding")) self.assertEqual(url, "/2010?baz=ding&foo=bar")
def test_expr_variable(self): route = Route(r"/<year:\d{4}>", None) self.assertEqual(route.match(Request.blank("/bar")), None) self.assertEqual(route.match(Request.blank("/2010")), (None, (), {"year": "2010"})) self.assertEqual(route.match(Request.blank("/1900")), (None, (), {"year": "1900"})) url = route.build(Request.blank("/"), (), dict(year="2010")) self.assertEqual(url, "/2010")
def test_build_extra_keyword(self): route = Route(r'/<year:\d{4}>', None) url = route.build(Request.blank('/'), (), dict(year='2010', foo='bar')) self.assertEqual(url, '/2010?foo=bar') # Arguments are sorted. url = route.build(Request.blank('/'), (), dict(year='2010', foo='bar', baz='ding')) self.assertEqual(url, '/2010?baz=ding&foo=bar')
def test_expr_variable(self): route = Route(r'/<year:\d{4}>', None) self.assertEqual(route.match(Request.blank('/bar')), None) self.assertEqual(route.match(Request.blank('/2010')), (None, (), {'year': '2010'})) self.assertEqual(route.match(Request.blank('/1900')), (None, (), {'year': '1900'})) url = route.build(Request.blank('/'), (), dict(year='2010')) self.assertEqual(url, '/2010')
def test_build_missing_argument(self): route = Route(r'/<:\d{4}>', None) self.assertRaises(KeyError, route.build, Request.blank('/'), (), {}) route = Route(r'/<:\d{4}>/<:\d{2}>', None) self.assertRaises( KeyError, route.build, Request.blank('/'), (2010,), {})
def test_build_default_keyword(self): route = Route(r"/<year:\d{4}>/<month:\d{2}>", None, defaults={"month": 10}) url = route.build(Request.blank("/"), (), dict(year="2010")) self.assertEqual(url, "/2010/10") route = Route(r"/<year:\d{4}>/<month:\d{2}>", None, defaults={"year": 1900}) url = route.build(Request.blank("/"), (), dict(month="07")) self.assertEqual(url, "/1900/07")
def test_build_with_unnamed_variable(self): route = Route(r'/<:\d{4}>/<month:\d{2}>', None) url = route.build(Request.blank('/'), (2010,), dict(month=10)) self.assertEqual(url, '/2010/10') url = route.build(Request.blank('/'), ('1999',), dict(month='07')) self.assertEqual(url, '/1999/07')
def test_simple_variable(self): route = Route(r'/<foo>', None) self.assertEqual( route.match(Request.blank('/bar')), (route, (), {'foo': 'bar'}) ) url = route.build(Request.blank('/'), (), dict(foo='baz')) self.assertEqual(url, '/baz')
def test_build_extra_positional_keyword(self): route = Route(r'/<year:\d{4}>/<:\d{2}>', None) url = route.build(Request.blank('/'), ('08', 'i-should-be-ignored', 'me-too'), dict(year='2010', foo='bar')) self.assertEqual(url, '/2010/08?foo=bar') url = route.build(Request.blank('/'), ('08', 'i-should-be-ignored', 'me-too'), dict(year='2010', foo='bar', baz='ding')) self.assertEqual(url, '/2010/08?baz=ding&foo=bar')
def test_router_build_error(self): router = Router() router.add(Route('/<year:\d{4}>', None, name='year-page')) url = router.build('year-page', Request.blank('/'), (), dict(year='2010')) self.assertEqual(url, '/2010') self.assertRaises(KeyError, router.build, 'i-dont-exist', Request.blank('/'), (), dict(year='2010'))
def test_build_with_unnamed_variable(self): route = Route(r"/<:\d{4}>/<month:\d{2}>", None) url = route.build(Request.blank("/"), (2010,), dict(month=10)) self.assertEqual(url, "/2010/10") url = route.build(Request.blank("/"), ("1999",), dict(month="07")) self.assertEqual(url, "/1999/07")
def test_router_build_error(self): router = Router(None) router.add(Route("/<year:\d{4}>", None, name="year-page")) url = router.build("year-page", Request.blank("/"), (), dict(year="2010")) self.assertEqual(url, "/2010") self.assertRaises(KeyError, router.build, "i-dont-exist", Request.blank("/"), (), dict(year="2010"))
def test_repetition_operator(self): route = Route(r"/<:\d>", None) self.assertEqual(route.match(Request.blank("/1")), (None, ("1",), {})) self.assertEqual(route.match(Request.blank("/2")), (None, ("2",), {})) route = Route(r"/<:\d{2,3}>", None) self.assertEqual(route.match(Request.blank("/11")), (None, ("11",), {})) self.assertEqual(route.match(Request.blank("/111")), (None, ("111",), {})) self.assertEqual(route.match(Request.blank("/1111")), None)
def test_repetition_operator(self): route = Route(r'/<:\d>', None) self.assertEqual(route.match(Request.blank('/1')), (None, ('1',), {})) self.assertEqual(route.match(Request.blank('/2')), (None, ('2',), {})) route = Route(r'/<:\d{2,3}>', None) self.assertEqual(route.match(Request.blank('/11')), (None, ('11',), {})) self.assertEqual(route.match(Request.blank('/111')), (None, ('111',), {})) self.assertEqual(route.match(Request.blank('/1111')), None)
def test_build_extra_positional_keyword(self): route = Route(r"/<year:\d{4}>/<:\d{2}>", None) url = route.build(Request.blank("/"), ("08", "i-should-be-ignored", "me-too"), dict(year="2010", foo="bar")) self.assertEqual(url, "/2010/08?foo=bar") url = route.build( Request.blank("/"), ("08", "i-should-be-ignored", "me-too"), dict(year="2010", foo="bar", baz="ding") ) self.assertEqual(url, "/2010/08?baz=ding&foo=bar")
def test_build_default_keyword(self): route = Route(r'/<year:\d{4}>/<month:\d{2}>', None, defaults={'month': 10}) url = route.build(Request.blank('/'), (), dict(year='2010')) self.assertEqual(url, '/2010/10') route = Route(r'/<year:\d{4}>/<month:\d{2}>', None, defaults={'year': 1900}) url = route.build(Request.blank('/'), (), dict(month='07')) self.assertEqual(url, '/1900/07')
def test_c_post_count(self): self._create_config() memcache.set('already_donated', 0) memcache.set('already_clicked', 0) memcache.set('eur_goal', 1) # all values should still be 0 after request from inside uri = '/c?domain=' + self.domain + '&from=inside' body = '{"clicks":0, "donated":0.0, "unlocked": 0.0, "percent":0.0, "increment": %f}' % EUR_INCREMENT self._test_c_post(uri, body) # from == outside, no previous visit, with current timestamp increases counter now = int(time.time() * 1000) current_time = "%d" % now uri = '/c?domain=' + self.domain + '&from=outside&pt=&ct=' + current_time body = '{"clicks":1, "donated":0.0, "unlocked": %f, "percent":%f, "increment": %f}' % (EUR_INCREMENT, EUR_INCREMENT, EUR_INCREMENT) self._test_c_post(uri, body) # from == outside, previous visit 1 second before current timestamp does not increase counter uri = '/c?domain=' + self.domain + '&from=outside&pt=' + ("%s" % (now - 1)) + '&ct=' + current_time self._test_c_post(uri, body) # from == outside, previous visit before current timestamp increases counter uri = '/c?domain=' + self.domain + '&from=outside&pt=' + ( "%s" % (now - COUNT_THRESHOLD)) + '&ct=' + current_time body = '{"clicks":2, "donated":0.0, "unlocked": %f, "percent":%f, "increment": %f}' % (2 * EUR_INCREMENT, 2 * EUR_INCREMENT, EUR_INCREMENT) self._test_c_post(uri, body) self.assertEquals(2, memcache.get('clicks_total')) d = models.Domain() d.name = self.domain self.assertEquals(2, memcache.get(jobs.get_cache_key(d))) # Pre-cron domain = models.Domain.query(models.Domain.name == str(self.domain)).get() self.assertEquals(0, domain.clickcount) count = models.ClickcountDate.query().get() self.assertTrue(count is None) # Execute memcount cron request = Request.blank('/task/counter/persist', headers=[('X-AppEngine-Cron', 'true')]) request.method = 'GET' request.get_response(application) domain = models.Domain.query(models.Domain.name == str(self.domain)).get() self.assertEquals(2, domain.clickcount) # Execute total cron request = Request.blank('/task/total/persist', headers=[('X-AppEngine-Cron', 'true')]) request.method = 'GET' request.get_response(application) count = models.ClickcountDate.query().get() self.assertEquals(2, count.clickcount) self.assertEquals(datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S"), count.time.strftime("%Y-%m-%dT%H:%M:%S"))
def test_no_variable(self): route = Route(r'/hello', None) handler, args, kwargs = route.match(Request.blank('/hello')) self.assertEqual(kwargs, {}) url = route.build(Request.blank('/'), (), {}) self.assertEqual(url, '/hello') route = Route(r'/hello/world/', None) handler, args, kwargs = route.match(Request.blank('/hello/world/')) self.assertEqual(kwargs, {}) url = route.build(Request.blank('/'), (), {}) self.assertEqual(url, '/hello/world/')
def test_schemes(self): route = Route(r'/', schemes=['http']) req = Request.blank('http://mydomain.com/') self.assertTrue(route.match(req) is not None) req = Request.blank('https://mydomain.com/') self.assertTrue(route.match(req) is None) route = Route(r'/', schemes=['https']) req = Request.blank('https://mydomain.com/') self.assertTrue(route.match(req) is not None) req = Request.blank('http://mydomain.com/') self.assertTrue(route.match(req) is None)
def test_no_variable(self): route = Route(r"/hello", None) handler, args, kwargs = route.match(Request.blank("/hello")) self.assertEqual(kwargs, {}) url = route.build(Request.blank("/"), (), {}) self.assertEqual(url, "/hello") route = Route(r"/hello/world/", None) handler, args, kwargs = route.match(Request.blank("/hello/world/")) self.assertEqual(kwargs, {}) url = route.build(Request.blank("/"), (), {}) self.assertEqual(url, "/hello/world/")
def testRequestParser_type_is_bool(self): import decimal parser = RequestParser() parser.add_argument("foo", type=bool) args = parser.parse_args(Request.blank('/stam?foo=true')) self.assertEquals(args['foo'], True) args = parser.parse_args(Request.blank('/stam?foo=True')) self.assertEquals(args['foo'], True) args = parser.parse_args(Request.blank('/stam?foo=t')) self.assertEquals(args['foo'], True) args = parser.parse_args(Request.blank('/stam?foo=1')) self.assertEquals(args['foo'], True) args = parser.parse_args(Request.blank('/stam?foo=f')) self.assertEquals(args['foo'], False) args = parser.parse_args(Request.blank('/stam?foo=0')) self.assertEquals(args['foo'], False) args = parser.parse_args(Request.blank('/stam?foo=false')) self.assertEquals(args['foo'], False) args = parser.parse_args(Request.blank('/stam?foo=False')) self.assertEquals(args['foo'], False)
def test_int_range_choice_types(self): parser = RequestParser() parser.add_argument("foo", type=int, choices=range(100), location='json') req = Request.blank('/stam', POST=json.dumps(dict(foo=101)), environ={ 'CONTENT_TYPE': 'application/json;"', }) self.assertRaises(InvalidParameterValue, parser.parse_args, req) req = Request.blank('/stam', POST=json.dumps(dict(foo=99)), environ={ 'CONTENT_TYPE': 'application/json;"', }) args = parser.parse_args(req) self.assertEqual(99, args.get('foo'))
def _test_c_post(self, uri, body): """Helper to actually test posting to /c, depending on uri and body.""" request = Request.blank(uri, headers=[self.auth_header]) request.method = 'POST' response = request.get_response(application) self.assertEqual(response.status_int, 200) self.assertEqual(response.body, body)
def test_config_replacement(self): d = 25000 memcache.set('already_clicked', d * 1000) memcache.set('clicks_total', d * 1000 + 333333) memcache.set('already_donated', d) memcache.set('eur_goal', 50000) memcache.set('eur_increment', EUR_INCREMENT) self._create_config( '{"firstvisit":"center","secondvisit":"top","default_locale":"en","strings":{' + '"en":{"heading":"Thanks!","subheading":"Every click is worth %increment%","about":"More about the <strong>dotHIV</strong> initiative","activated":"Already %donated% contributed:","money":"%unlocked%","clickcount":"%clicks% clicks"},' + '"de":{"heading":"Danke!","subheading":"Jeder Klick hilft mit %increment%","about":"Mehr über die <strong>dotHIV</strong> Initiative","activated":"Bereits %donated% gespendet:","money":"%unlocked%","clickcount":"%clicks% Klicks"}}}' ) uri = '/c?domain=' + self.domain + '&from=inside' request = Request.blank(uri, headers=[('Accept-Language', 'de,en-US;q=0.5,en;q=0.6')]) request.method = 'POST' response = request.get_response(application) config = json.decode(response.body) self.assertEqual("Bereits 25.000 € gespendet:", str(config['activated'])) if EUR_INCREMENT < 0.01: # 0.001 self.assertEqual("25.333,33 €", str(config['money'])) self.assertEqual("Jeder Klick hilft mit 0,1 ct", str(config['subheading'])) self.assertEqual(round(25333.33 / 50000, 3), round(config['percent'], 3)) else: # 0.01 self.assertEqual("28.333,33 €", str(config['money'])) self.assertEqual("Jeder Klick hilft mit 1 ct", str(config['subheading'])) self.assertEqual(round(28333.33 / 50000, 3), round(config['percent'], 3)) self.assertEqual("25.333.333 Klicks", str(config['clickcount']))
def test_document(self): from webapp2 import WSGIApplication, RequestHandler, Request class HelloMessage(Message): greeting = StringProperty(description="The greating.", validators=[regex(re.compile('^[A-Za-z]+$')), required()]) class HelloResponseMessage(Message): salutation = StringProperty(description="The response.") tags = StringProperty(repeated=True) request = StructuredProperty(HelloMessage) class HelloHandler(RequestHandler): @api(input=HelloMessage, output=HelloResponseMessage) def post(self, obj): return {'salutation':'You are the best.'} routes = [ ('/api/v1/hello', HelloHandler) ] app = DocumentedMiddleware( WSGIApplication(routes), api_base="/api/v1", api_overview="This is a super important API that does a lot of stuff." ) request = Request.blank('/api/v1', headers={'Content-Type':'application/json'}) response = request.get_response(app)
def testRequestParser_choices(self): req = Request.blank("/bubble?foo=bar") parser = RequestParser() parser.add_argument("foo", choices=["bat"]), self.assertRaises(InvalidParameterValue, lambda: parser.parse_args(req))
def testRequestParser_choices_sensitive(self): req = Request.blank("/bubble?foo=BAT") parser = RequestParser() parser.add_argument("foo", choices=["bat"], case_sensitive=True), self.assertRaises(InvalidParameterValue, lambda: parser.parse_args(req))
def testRequestParser_parse_unicode(self): req = Request.blank("/bubble?foo=barß") parser = RequestParser() parser.add_argument("foo") args = parser.parse_args(req) self.assertEquals(args['foo'], u"barß")
def testFormWithPOSTData(self): request = Request.blank('/', POST={'id_twitter_user':'******', 'id_delicious_user':'******','id_delicious_password':'******'}) form = self.UserSettingsForm(request.POST) formContents = form.render() self.assertTrue(form.clean_data['twitter_user'], 'twitter_user_value') self.assertTrue(form.clean_data['delicious_user'], 'delicious_user_value')
def test_positions(self): template = '/<:\d+>' * 98 args = tuple(str(i) for i in range(98)) url_res = '/' + '/'.join(args) route = Route(template, None) self.assertEqual(route.match(Request.blank(url_res)), (None, args, {})) url = route.build(Request.blank('/'), args, {}) self.assertEqual(url_res, url) args = [str(i) for i in range(1000)] random.shuffle(args) args = tuple(args[:98]) url_res = '/' + '/'.join(args) self.assertEqual(route.match(Request.blank(url_res)), (None, args, {})) url = route.build(Request.blank('/'), args, {}) self.assertEqual(url_res, url)
def test_action_without_model(self): request = Request.blank('/api/any/123/activate', method='POST') response = request.get_response(application) self.assertEqual(404, response.status_int)
def test_build_missing_keyword(self): route = Route(r'/<year:\d{4}>', None) self.assertRaises(KeyError, route.build, Request.blank('/'), (), {})
def test_get_all(self): self.__create() request = Request.blank('/api/user', method='GET') response = MockResponse(request.get_response(application)) self.assertEqual(200, response.status_int)
def test_build_missing_keyword2(self): route = Route(r'/<year:\d{4}>/<month:\d{2}>', None) self.assertRaises(KeyError, route.build, Request.blank('/'), (), dict(year='2010'))
def test_build_invalid_keyword2(self): route = Route(r'/<year:\d{4}>', None) self.assertRaises(ValueError, route.build, Request.blank('/'), (), dict(year='201a'))
def test_build_int_keyword(self): route = Route(r'/<year:\d{4}>', None) url = route.build(Request.blank('/'), (), dict(year=2010)) self.assertEqual(url, '/2010')
def test_404(self): request = Request.blank('/api/', method='GET') response = request.get_response(application) self.assertEqual(404, response.status_int)
def __create(self): request = Request.blank('/api/user', method='POST') request.json = {"name": "felipe", "age": 22} return MockResponse(request.get_response(application))
def test_expr_variable2(self): route = Route(r'/<year:\d{4}>/foo/', None) url = route.build(Request.blank('/'), (), dict(year='2010')) self.assertEqual(url, '/2010/foo/')
def test_build_invalid_argument2(self): route = Route(r'/<:\d{4}>', None) self.assertRaises(ValueError, route.build, Request.blank('/'), ('201a', ), {})
def test_get(self): uuid_created = '1245' request = Request.blank('/api/user/' + uuid_created, method='GET') response = MockResponse(request.get_response(application)) self.assertEqual(200, response.status_int)
def test_delete(self): uuid_created = '1245' request = Request.blank('/api/user/' + uuid_created, method='DELETE') response = request.get_response(application) self.assertEqual(200, response.status_int)
def test_build_missing_argument(self): route = Route(r'/<:\d{4}>', None) self.assertRaises(KeyError, route.build, Request.blank('/'), (), {}) route = Route(r'/<:\d{4}>/<:\d{2}>', None) self.assertRaises(KeyError, route.build, Request.blank('/'), (2010,), {})
def test_action_url_404(self): request = Request.blank('/api/user/123/dontexists', method='POST') response = request.get_response(application) self.assertEqual(404, response.status_int)
def test_build_int_variable(self): route = Route(r'/<:\d{4}>', None) url = route.build(Request.blank('/'), (2010, ), {}) self.assertEqual(url, '/2010')
def test_simple_variable(self): route = Route(r'/<foo>', None) self.assertEqual(route.match(Request.blank('/bar')), (route, (), {'foo': 'bar'})) url = route.build(Request.blank('/'), (), dict(foo='baz')) self.assertEqual(url, '/baz')
def test_put(self): uuid_created = '1245' request = Request.blank('/api/user/' + uuid_created, method='PUT') request.json = {"name": "ray", 'uuid': uuid_created} response = request.get_response(application) self.assertEqual(200, response.status_int)