示例#1
0
 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")
示例#2
0
 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")
示例#3
0
 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')
示例#4
0
 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,), {})
示例#6
0
    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")
示例#7
0
    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')
示例#9
0
    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')
示例#10
0
    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'))
示例#11
0
    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")
示例#12
0
    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"))
示例#13
0
    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)
示例#14
0
    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)
示例#15
0
    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")
示例#16
0
    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')
示例#17
0
    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"))
示例#18
0
    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/')
示例#19
0
    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)
示例#20
0
    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'))
示例#23
0
 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)
示例#24
0
 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 &euro; gespendet:", str(config['activated']))
     if EUR_INCREMENT < 0.01: # 0.001
         self.assertEqual("25.333,33 &euro;", 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 &euro;", 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']))
示例#25
0
文件: tests.py 项目: mentat/restifier
 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ß")
示例#29
0
	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')
示例#30
0
    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)
示例#31
0
 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)
示例#32
0
 def test_build_missing_keyword(self):
     route = Route(r'/<year:\d{4}>', None)
     self.assertRaises(KeyError, route.build, Request.blank('/'), (), {})
示例#33
0
    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)
示例#34
0
 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'))
示例#35
0
 def test_build_invalid_keyword2(self):
     route = Route(r'/<year:\d{4}>', None)
     self.assertRaises(ValueError, route.build, Request.blank('/'), (),
                       dict(year='201a'))
示例#36
0
 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')
示例#37
0
 def test_404(self):
     request = Request.blank('/api/', method='GET')
     response = request.get_response(application)
     self.assertEqual(404, response.status_int)
示例#38
0
 def __create(self):
     request = Request.blank('/api/user', method='POST')
     request.json = {"name": "felipe", "age": 22}
     return MockResponse(request.get_response(application))
示例#39
0
 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/')
示例#40
0
 def test_build_invalid_argument2(self):
     route = Route(r'/<:\d{4}>', None)
     self.assertRaises(ValueError, route.build, Request.blank('/'),
                       ('201a', ), {})
示例#41
0
 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)
示例#42
0
 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)
示例#43
0
    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,), {})
示例#44
0
 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)
示例#45
0
 def test_build_int_variable(self):
     route = Route(r'/<:\d{4}>', None)
     url = route.build(Request.blank('/'), (2010, ), {})
     self.assertEqual(url, '/2010')
示例#46
0
 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')
示例#47
0
 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)