def test_json(self): """ Test json response :return: void """ helper = ResponseHelper() rule = '/' + self.rand_str(20) key1 = self.rand_str(20) value1 = self.rand_str(20) key2 = self.rand_str(20) value2 = self.rand_str(20) with self.app.test_request_context(rule): # Empty json response response = helper.json() # Check self.assert_is_instance(response, Response) self.assert_is_instance(response, FlaskResponse) self.assert_equal('{}', Encoding.normalize(response.response[0])) # Assign helper.assign(key1, value1) helper.assign(key2, value2) # Json response response = helper.json() # Check self.assert_is_instance(response, Response) self.assert_is_instance(response, FlaskResponse) response_json = Encoding.normalize(json.loads(response.response[0])) self.assert_equal(2, len(response_json)) self.assert_in(key1, response_json) self.assert_equal(value1, response_json[key1]) self.assert_in(key2, response_json) self.assert_equal(value2, response_json[key2])
def test_file_input(self): """ Test file input :return: void """ file_arguments = [ ('file_argument_1', Encoding.normalize('')), ('file_argument_2', self.rand_str(5)), ('file_argument_3', self.rand_str(10)), ] rule = '/' + self.rand_str(20) # Make post data data = dict() for key, value in file_arguments: if sys.version_info < (3, 0): value = StringIO(value) else: value = BytesIO(value.encode()) data[key] = (value, key + '.txt') # Call route with self.app.test_request_context(rule, method='POST', data=data): input = Input(request) self.assert_equal(len(file_arguments), len(input)) for key, value in file_arguments: self.assert_in(key, input) self.assert_is_instance(input[key], FileStorage) self.assert_equal(key + '.txt', Encoding.normalize(input[key].filename)) self.assert_equal(value, Encoding.normalize(input[key].stream.read()))
def test_render(self): """ Test render :return: void """ helper = ResponseHelper() rule = '/' + self.rand_str(20) value1 = self.rand_str(20) value2 = self.rand_str(20) value3 = self.rand_str(20) incomplete_result = '%s %s' % (value1, value3) alternate_result = '%s %s %s' % (value1, value2, value3) with self.app.test_request_context(rule): # Assign normal way helper.assign('value1', value1) helper.assign('value3', value3) # Fetch response response = helper.render(self.template) # Check self.assert_is_instance(response, Response) self.assert_is_instance(response, FlaskResponse) self.assert_equal(1, len(response.response)) self.assert_equal(incomplete_result, Encoding.normalize(response.response[0])) # Fetch response with extra assign response = helper.render(self.template, {'value2': value2}) # Check self.assert_is_instance(response, Response) self.assert_is_instance(response, FlaskResponse) self.assert_equal(1, len(response.response)) self.assert_equal(alternate_result, Encoding.normalize(response.response[0]))
def test_get_text_type(self): """ Test get text type :return: void """ if sys.version_info < (3, 0): self.assert_equal(unicode, Encoding.get_text_type()) else: self.assert_equal(str, Encoding.get_text_type())
def test_authorized(self): """ Test auth :return: void """ rule = '/' + self.rand_str(20) self.write_config(self.valid_config) DatabaseManager._sql_alchemy_instance = None app = self.create_application() self.init_database(app) # Add route @app.route(rule, middleware=[TokenAuthMiddleware]) def handle_route(): return '' # Call route with app.test_client() as c: data = json.dumps({ 'email': self.user_email, 'password': self.user_password }) headers = {'content-type': 'application/json'} token_response = c.post('/login', data=data, headers=headers) token = json.loads(Encoding.normalize(token_response.data) )['response']['user']['authentication_token'] headers = {'Authentication-Token': token} rv = c.get(rule, headers=headers) self.assert_equal(200, rv.status_code, msg=rv.data)
def test_authorized(self): """ Test auth :return: void """ rule = '/' + self.rand_str(20) self.write_config(self.valid_config) DatabaseManager._sql_alchemy_instance = None app = self.create_application() self.init_database(app) # Add route @app.route(rule, middleware=[BasicAuthMiddleware]) def handle_route(): return '' # Call route with app.test_client() as c: user_pass_b64 = '%s:%s' % (self.user_email, self.user_password) user_pass_b64 = user_pass_b64.encode() user_pass_b64 = Encoding.normalize(b64encode(user_pass_b64)) headers = {'Authorization': 'Basic %s' % user_pass_b64} rv = c.get(rule, headers=headers) self.assert_equal(200, rv.status_code, msg=rv.data)
def test_to_unicode(self): """ Test to unicode function :return: void """ value = { u'key1': 'value1'.encode('ascii'), 'key2': u'value2', 'key3'.encode('ascii'): [ 'listvalue1', 'listvalue2'.encode('ascii'), u'listvalue3', ] } expected = { u'key1': u'value1', u'key2': u'value2', u'key3': [ u'listvalue1', u'listvalue2', u'listvalue3', ] } self.assert_equal_deep(expected, Encoding.to_unicode(value))
def test_post_input(self): """ Test post input :return: void """ post_arguments = [ ('post_argument_string_1', ''), ('post_argument_string_2', self.rand_str(5)), ('post_argument_string_3', self.rand_str(10)), ('post_argument_integer_1', 0), ('post_argument_integer_2', self.rand_int(1, 10)), ('post_argument_integer_3', self.rand_int(20, 100)), ] rule = '/' + self.rand_str(20) # Make post data data = dict() for key, value in post_arguments: data[key] = value # Call route with self.app.test_request_context(rule, method='POST', data=data): input = Input(request) self.assert_equal(len(post_arguments), len(input)) for key, value in post_arguments: self.assert_in(key, input) self.assert_equal(str(value), Encoding.normalize(input[key]))
def test_file(self): """ Test file :return: void """ helper = ResponseHelper() rule = '/' + self.rand_str(20) with self.app.test_request_context(rule): # Redirect response response = helper.file(os.path.dirname(self.template_file), os.path.basename(self.template_file)) # Check self.assert_is_instance(response, Response) self.assert_is_instance(response, FlaskResponse) self.assert_is_instance(response.response, FileWrapper) if sys.version_info < (3, 0): self.assert_is_instance(response.response.file, file) self.assert_in(self.template_source, response.response.file) else: self.assert_is_instance(response.response.file, io.BufferedReader) self.assert_in(self.template_source, Encoding.normalize(response.response.file.read())) self.assert_equal(self.template_file, response.response.file.name) response.close()
def test_get_input(self): """ Test get input :return: void """ get_arguments = [ ('get_argument_string_1', ''), ('get_argument_string_2', self.rand_str(5)), ('get_argument_string_3', self.rand_str(10)), ('get_argument_integer_1', 0), ('get_argument_integer_2', self.rand_int(1, 10)), ('get_argument_integer_3', self.rand_int(20, 100)), ] rule = self._get_url_with_arguments('/' + self.rand_str(20), get_arguments) # Call route with self.app.test_request_context(rule): input = Input(request) self.assert_equal(len(get_arguments), len(input)) for key, value in get_arguments: self.assert_in(key, input) self.assert_equal(str(value), Encoding.normalize(input[key]))
def random_str(length): """ Get a random string :param length: Length of the random string :type length: int :return: Random string :rtype: str """ return Encoding.normalize(''.join( random.choice(string.ascii_lowercase + string.digits) for _ in range(length)))
def get_response(self, client, rule, email, password): """ Get response :param client: The client :param rule: The rule :param email: The email to log in with :param password: The password :return: The response """ user_pass_b64 = '%s:%s' % (email, password) user_pass_b64 = user_pass_b64.encode() user_pass_b64 = Encoding.normalize(b64encode(user_pass_b64)) headers = {'Authorization': 'Basic %s' % user_pass_b64} return client.get(rule, headers=headers)
def test_redirect(self): """ Test redirect :return: void """ helper = ResponseHelper() rule = '/' + self.rand_str(20) with self.app.test_request_context(rule): # Redirect response response = helper.redirect(rule) # Check self.assert_is_instance(response, Response) self.assert_is_instance(response, FlaskResponse) self.assert_in(rule, Encoding.normalize(response.response[0]))
def test_raw(self): """ Test raw :return: void """ helper = ResponseHelper() rule = '/' + self.rand_str(20) with self.app.test_request_context(rule): response = helper.raw(self.template_source) self.assert_is_instance(response, Response) self.assert_is_instance(response, FlaskResponse) self.assert_equal(1, len(response.response)) self.assert_equal(self.template_source, Encoding.normalize(response.response[0]))
def test_date(self): """ Test date :return: void """ locale = Locale.parse('nl_BE', sep='_') time_zone = get_timezone('Europe/Brussels') time_obj = Time(locale=locale, time_zone=time_zone) data = [ ('9/05/92', date(1992, 5, 9), Time.SHORT), ('3 apr. 2004', date(2004, 4, 3), Time.MEDIUM), ('18 februari 2016', date(2016, 2, 18), Time.LONG), ('zondag 30 juli 2017', date(2017, 7, 30), Time.FULL), ] for expected, given_date, given_format in data: self.assert_equal( expected, Encoding.normalize(time_obj.date(given_date, given_format)))
def test_normalize(self): """ Test normalize function :return: void """ value = { u'key1': 'value1'.encode('ascii'), 'key2': u'value2', 'key3'.encode('ascii'): [ 'listvalue1', 'listvalue2'.encode('ascii'), u'listvalue3', ] } if sys.version_info < (3, 0): expected = { 'key1'.encode('ascii'): 'value1'.encode('ascii'), 'key2'.encode('ascii'): 'value2'.encode('ascii'), 'key3'.encode('ascii'): [ 'listvalue1'.encode('ascii'), 'listvalue2'.encode('ascii'), 'listvalue3'.encode('ascii'), ] } else: expected = { u'key1': u'value1', u'key2': u'value2', u'key3': [ u'listvalue1', u'listvalue2', u'listvalue3', ] } self.assert_equal_deep(expected, Encoding.normalize(value))
def test_time(self): """ Test time :return: void """ locale = Locale.parse('nl_BE', sep='_') time_zone = get_timezone('Europe/Brussels') time_obj = Time(locale=locale, time_zone=time_zone) data = [ ('05:26', time(5, 26, 13), Time.SHORT), ('05:06:07', time(5, 6, 7), Time.MEDIUM), ('14:26:57 CET', time(14, 26, 57), Time.LONG), ('01:02:03 Midden-Europese standaardtijd', time(1, 2, 3), Time.FULL), ] for expected, given_time, given_format in data: self.assert_equal( expected, Encoding.normalize(time_obj.time(given_time, given_format)))
def test_interval(self): """ Test interval :return: void """ locale = Locale.parse('nl_BE', sep='_') time_zone = get_timezone('Europe/Brussels') time_obj = Time(locale=locale, time_zone=time_zone) data = [ ('09:05:23 - 14:05:06', time(9, 5, 23), time(14, 5, 6)), ('3 apr. 2004 07:06:07 - 30 jul. 2017 03:02:03', datetime(2004, 4, 3, 5, 6, 7), datetime(2017, 7, 30, 1, 2, 3)), ('18 feb. 2016 15:26:57 - 30 jul. 2017 02:00:00', datetime(2016, 2, 18, 14, 26, 57), date(2017, 7, 30)), ('9 mei 1992 - 30 jul. 2017', date(1992, 5, 9), date(2017, 7, 30)), ] for expected, given_start, given_end in data: self.assert_equal( expected, Encoding.normalize(time_obj.interval(given_start, given_end)))
def test_datetime(self): """ Test datetime :return: void """ locale = Locale.parse('nl_BE', sep='_') time_zone = get_timezone('Europe/Brussels') time_obj = Time(locale=locale, time_zone=time_zone) data = [ ('9/05/92 07:26', datetime(1992, 5, 9, 5, 26, 13), Time.SHORT), ('3 apr. 2004 07:06:07', datetime(2004, 4, 3, 5, 6, 7), Time.MEDIUM), ('18 februari 2016 15:26:57 CET', datetime(2016, 2, 18, 14, 26, 57), Time.LONG), ('zondag 30 juli 2017 03:02:03 Midden-Europese zomertijd', datetime(2017, 7, 30, 1, 2, 3), Time.FULL), ] for expected, given_datetime, given_format in data: self.assert_equal( expected, Encoding.normalize( time_obj.datetime(given_datetime, given_format)))
def test_combined_input(self): """ Test combined input :return: void """ get_arguments = [ ('get_argument_string_1', ''), ('get_argument_string_2', self.rand_str(5)), ('get_argument_string_3', self.rand_str(10)), ('get_argument_integer_1', 0), ('get_argument_integer_2', self.rand_int(1, 10)), ('get_argument_integer_3', self.rand_int(20, 100)), ] post_arguments = [ ('post_argument_string_1', ''), ('post_argument_string_2', self.rand_str(5)), ('post_argument_string_3', self.rand_str(10)), ('post_argument_integer_1', 0), ('post_argument_integer_2', self.rand_int(1, 10)), ('post_argument_integer_3', self.rand_int(20, 100)), ] file_arguments = [ ('file_argument_1', ''), ('file_argument_2', self.rand_str(5)), ('file_argument_3', self.rand_str(10)), ] rule = self._get_url_with_arguments('/' + self.rand_str(20), get_arguments) # Make post data data = dict() for key, value in post_arguments: data[key] = value for key, value in file_arguments: if sys.version_info < (3, 0): value = StringIO(value) else: value = BytesIO(value.encode()) data[key] = (value, key + '.txt') # Call route with self.app.test_request_context(rule, method='POST', data=data): input = Input(request) self.assert_equal( len(get_arguments) + len(post_arguments) + len(file_arguments), len(input)) for key, value in get_arguments: self.assert_in(key, input) self.assert_equal(str(value), Encoding.normalize(input[key])) for key, value in post_arguments: self.assert_in(key, input) self.assert_equal(str(value), Encoding.normalize(input[key])) for key, value in file_arguments: self.assert_in(key, input) self.assert_is_instance(input[key], FileStorage) self.assert_equal(key + '.txt', Encoding.normalize(input[key].filename)) self.assert_equal(value, Encoding.normalize(input[key].stream.read()))
def insights(self, ip): """ Get insights in ip :param ip: The ip :return: Insights :rtype: geoip2.models.City """ if request.remote_addr != ip: raise RuntimeError( "Can only use GoogleAppEngine-location-driver for looking up location of request-ip (=%s) (lookup=%s)" % (request.remote_addr, ip)) raw_response = {} # Country country_iso = request.headers[ 'X-AppEngine-Country'] if 'X-AppEngine-Country' in request.headers else None country_iso = country_iso if country_iso and country_iso != 'ZZ' else None if country_iso: country_iso = Encoding.normalize(country_iso) raw_response['country'] = {'iso_code': country_iso} raw_response['registered_country'] = raw_response['country'] raw_response['represented_country'] = raw_response['country'] # Region region_iso = request.headers[ 'X-AppEngine-Region'] if 'X-AppEngine-Region' in request.headers else None region_iso = region_iso if region_iso else None if region_iso: region_iso = Encoding.normalize(region_iso) raw_response['subdivisions'] = [{'iso_code': region_iso}] # City city = request.headers[ 'X-AppEngine-City'] if 'X-AppEngine-City' in request.headers else None city = city if city else None if city: city = Encoding.normalize(city) raw_response['city'] = {'names': {'en': city}} # Location city_lat_long = request.headers[ 'X-AppEngine-CityLatLong'] if 'X-AppEngine-CityLatLong' in request.headers else None city_lat_long = city_lat_long if city_lat_long else None latitude, longitude = city_lat_long.split(',') if city_lat_long else ( None, None) if latitude and longitude: latitude = float(Encoding.normalize(latitude)) longitude = float(Encoding.normalize(longitude)) raw_response['location'] = { 'latitude': latitude, 'longitude': longitude, } timezone_finder = TimezoneFinder() timezone = timezone_finder.timezone_at(lat=latitude, lng=longitude) timezone = timezone if timezone else None if timezone: raw_response['location']['time_zone'] = timezone return City(raw_response)