def test_argument_repr(self): arg = Argument('foo') try: # Python 2.6 compatibility self.assertIn('foo', arg.__repr__()) except AttributeError: self.assertTrue('foo' in arg.__repr__()) self.assertTrue(arg.__repr__().startswith("Argument('foo'"))
def test_source(self): req = Mock(['args', 'headers', 'values']) req.args = {'foo': 'bar'} req.headers = {'baz': 'bat'} arg = Argument('foo', location=['args']) self.assertEquals(arg.source(req), req.args) arg = Argument('foo', location=['headers']) self.assertEquals(arg.source(req), req.headers)
def test_source(self): req = Mock(["args", "headers", "values"]) req.args = {"foo": "bar"} req.headers = {"baz": "bat"} arg = Argument("foo", location=["args"]) self.assertEquals(arg.source(req), req.args) arg = Argument("foo", location=["headers"]) self.assertEquals(arg.source(req), req.headers)
def put(self, deployment_id, **kwargs): """ Create a deployment """ request_schema = self.create_request_schema() request_dict = get_json_and_verify_params(request_schema) blueprint_id = request_dict['blueprint_id'] bypass_maintenance = is_bypass_maintenance_mode() args = get_args_and_verify_arguments( [Argument('private_resource', type=types.boolean, default=False)] ) deployment = get_resource_manager().create_deployment( blueprint_id, deployment_id, inputs=request_dict.get('inputs', {}), bypass_maintenance=bypass_maintenance, private_resource=args.private_resource, skip_plugins_validation=self.get_skip_plugin_validation_flag( request_dict) ) return deployment, 201
def delete(self, deployment_id, **kwargs): """ Delete deployment by id """ args = get_args_and_verify_arguments( [Argument('ignore_live_nodes', type=types.boolean, default=False)]) bypass_maintenance = is_bypass_maintenance_mode() deployment = get_resource_manager().delete_deployment( deployment_id, bypass_maintenance, args.ignore_live_nodes) # Delete deployment resources from file server deployment_folder = os.path.join(config.instance.file_server_root, FILE_SERVER_DEPLOYMENTS_FOLDER, utils.current_tenant.name, deployment.id) if os.path.exists(deployment_folder): shutil.rmtree(deployment_folder) return deployment, 200
def post(self, **kwargs): """ Create provider context """ request_dict = get_json_and_verify_params({'context', 'name'}) args = get_args_and_verify_arguments( [Argument('update', type=types.boolean, default=False)] ) update = args['update'] context = dict( id=PROVIDER_CONTEXT_ID, name=request_dict['name'], context=request_dict['context'] ) status_code = 200 if update else 201 try: get_resource_manager().update_provider_context(update, context) return dict(status='ok'), status_code except dsl_parser_utils.ResolverInstantiationError, ex: raise manager_exceptions.ResolverInstantiationError(str(ex))
class CreateVehicleFeeApiParser(BaseRequestParser): vehicle_type_id = Argument( 'vehicle_type_id', required=True, nullable=False, type=int, location=('json', 'form')) company_id = Argument( 'company_id', required=True, nullable=False, type=int, location=('json', 'form')) unit_price = Argument( 'unit_price', required=True, nullable=False, type=float, location=('json', 'form')) start_time = Argument( 'start_time', required=True, nullable=False, location=('json', 'form')) end_time = Argument( 'end_time', required=True, nullable=False, location=('json', 'form')) confirm_person = Argument( 'confirm_person', required=True, nullable=False, type=int, location=('json', 'form')) attachment_hash = Argument( 'attachment_hash', required=True, nullable=False, location=('json', 'form'))
def receive_uploaded_data(self, data_id=None, **kwargs): blueprint_url = None # avoid clashing with existing blueprint names blueprint_id = data_id + uuid.uuid4().hex[:16] args = get_args_and_verify_arguments( [Argument('application_file_name', default='')]) # Handle importing blueprint through url if self._get_data_url_key() in request.args: if request.data or \ 'Transfer-Encoding' in request.headers or \ 'blueprint_archive' in request.files: raise manager_exceptions.BadParametersError( "Can pass {0} as only one of: URL via query parameters, " "request body, multi-form or " "chunked.".format(self._get_kind())) blueprint_url = request.args[self._get_data_url_key()] self._prepare_and_process_doc( blueprint_id, blueprint_url, application_file_name=args.application_file_name) return "", 204
def put(self, deployment_id, **kwargs): """ Create a deployment """ rest_utils.validate_inputs({'deployment_id': deployment_id}) request_schema = self.create_request_schema() request_dict = rest_utils.get_json_and_verify_params(request_schema) blueprint_id = request_dict['blueprint_id'] bypass_maintenance = is_bypass_maintenance_mode() args = rest_utils.get_args_and_verify_arguments( [Argument('private_resource', type=boolean)]) visibility = rest_utils.get_visibility_parameter( optional=True, valid_values=VisibilityState.STATES) deployment = get_resource_manager().create_deployment( blueprint_id, deployment_id, inputs=request_dict.get('inputs', {}), bypass_maintenance=bypass_maintenance, private_resource=args.private_resource, visibility=visibility, skip_plugins_validation=self.get_skip_plugin_validation_flag( request_dict)) return deployment, 201
class CreateShopFeeApiParser(BaseRequestParser): ACCOUNT_PERIOD = Enum( ('NOW', 1, u'现结'), ('MONTH', 2, u'月结'), ) ACCOUNT_WAY = Enum( ('CASH', 1, u'现金'), ('CHECK', 2, u'支票'), ('TRANSFER', 3, u'转账'), ) shop_id = Argument('shop_id', type=int, required=True, nullable=False) fee_person = Argument('fee_person', type=float, required=True, nullable=False) company_ratio = Argument('company_ratio', type=float, required=True, nullable=False) tour_guide_ratio = Argument( 'tour_guide_ratio', type=float, required=True, nullable=False) account_period = Argument( 'account_period', type=int, choices=ACCOUNT_PERIOD.values(), required=True, nullable=False) account_way = Argument( 'account_way', type=int, choices=ACCOUNT_WAY.values(), required=True, nullable=False) note = Argument('note')
def post(self, id, phase): """ Supports two stages of a plugin update. Phases: 1. (PHASES.INITIAL) Creates a temporary blueprint and executes a deployment update (will update only the plugins) for all the deployments of the given blueprint. 2. (PHASES.FINAL) Updates the original blueprint plan and deletes the temp one. :param id: the blueprint ID to update it's deployments' plugins if phase == PHASES.INITIAL, otherwise (phase == PHASES.FINAL) the plugin update ID. :param phase: either PHASES.INITIAL or PHASES.FINAL (internal). """ if phase == PHASES.INITIAL: args = rest_utils.get_args_and_verify_arguments([ Argument('force', type=boolean, required=False, default=False) ]) return get_plugins_updates_manager().initiate_plugins_update( blueprint_id=id, force=args.get('force')) elif phase == PHASES.FINAL: return get_plugins_updates_manager().finalize( plugins_update_id=id)
def _prepare_and_submit_blueprint(cls, file_server_root, app_dir, blueprint_id, visibility): args = get_args_and_verify_arguments([ Argument('application_file_name', default='')]) app_file_name = cls._extract_application_file( file_server_root, app_dir, args.application_file_name) # add to blueprints manager (will also dsl_parse it) try: get_resource_manager().validate_blueprint( app_dir, app_file_name, file_server_root ) except manager_exceptions.DslParseException as ex: raise manager_exceptions.InvalidBlueprintError( 'Invalid blueprint - {0}'.format(ex)) return {}
class AchievementResources(Resource): """ Verbs relative to the users """ @staticmethod def get(**_kwargs): """ Return an user key information based on his name """ return render_resource(AchievementRepository.all()) @staticmethod @parse_params( Argument("name", required=True, help="Name of the achievement", location="json"), Argument("short_description", required=True, help="Short description of the achievement", location="json"), Argument("long_description", required=True, help="Long description of the achievement", location="json"), Argument("difficulty", required=True, type=int, help="Difficulty of the achievement", location="json"), Argument("image_src", required=True, help="Image of the achievement", location="json"), Argument("bg_image_src", required=True, help="Bg image of the achievement", location="json"), ) def post(name, short_description, long_description, difficulty, image_src, bg_image_src, **_kwargs): return render_resource( AchievementRepository.create(name, short_description, long_description, difficulty, image_src, bg_image_src))
class InspectionsResource(Resource): @staticmethod @jwt_required def get(): inspections = InspectionRepository.all() return [u.json for u in inspections] @staticmethod @parse_params( Argument("city", location="json", required=True, help="Missing parameter"), Argument("street", location="json", required=True, help="Missing parameter"), Argument("street_number", location="json", required=True, help="Missing parameter"), Argument("staircases", location="json", required=True, help="Missing parameter"), Argument("employee", location="json", required=True, help="Missing parameter"), Argument("flat_count", location="json", required=True, help="Missing parameter"), ) @jwt_required def post(city: str, street: str, street_number: str, staircases: str, employee: str, flat_count: int): inspection = InspectionRepository.create(city, street, street_number, staircases, employee, flat_count) return inspection.json
class CreateVehicleTypeApiParser(BaseRequestParser): VEHICLE_TYPE = Enum( ('CAR', 1, u'轿车'), ('VAN', 2, u'货车'), ('BIG_VAN', 3, u'大货车'), ('MINI_COATCH', 4, u'迷你大巴'), ('COATCH', 5, u'大巴'), ('LONG_COATCH', 6, u'加长大巴'), ('OTHER', 7, u'其他'), ) vehicle_type = Argument( 'vehicle_type', type=int, choices=VEHICLE_TYPE.values(), required=True, nullable=False) brand = Argument('brand', required=True, nullable=False) seat = Argument('seat', type=int, required=True, nullable=False) available_seat = Argument( 'available_seat', type=int, required=True, nullable=False) passenger_count = Argument( 'passenger_count', type=int, required=True, nullable=False) note = Argument('note')
class MovieResource(Resource): """ Verbs relative to the movies """ @staticmethod @swag_from("../swagger/movie/GET.yml") def get(title): """ Return a movie key information based on the title """ movie = MovieRepository.get(title=title) return jsonify({"movie": movie.json}) @staticmethod @parse_params( Argument("producer", location="json", required=True, help="The producer of the movie."), Argument("date", location="json", required=True, help="The date of the movie."), Argument("actor", location="json", required=True, help="The main actor in the movie.") ) @swag_from("../swagger/movie/POST.yml") def post(title, producer, date, actor): """ Create a movie based on the sent information """ movie = MovieRepository.create( title=title, producer=producer, date=date, actor=actor ) return jsonify({"movie": movie.json}) @staticmethod @parse_params( Argument("producer", location="json", required=True, help="The producer of the movie."), Argument("date", location="json", required=True, help="The date of the movie."), Argument("actor", location="json", required=True, help="The main actor in the movie.") ) @swag_from("../swagger/movie/PUT.yml") def put(title, producer, date, actor): """ Update a movie based on the sent information """ repository = MovieRepository() movie = repository.update(title=title, producer=producer, date=date, actor=actor) return jsonify({"movie": movie.json})
def test_source_bad_location(self): req = Mock(['values']) arg = Argument('foo', location=['foo']) self.assertTrue(len( arg.source(req)) == 0) # yes, basically you don't find it
def test_convert_with_null_input_when_not_nullable(self): arg = Argument('foo', nullable=False) self.assertRaises(ValueError, lambda: arg.convert(None, None))
def test_convert_default_type_with_null_input(self): arg = Argument('foo') self.assertEquals(arg.convert(None, None), None)
def test_location_json(self): arg = Argument("foo", location="json") self.assertEquals(arg.location, "json")
def test_location_url_list(self): arg = Argument("foo", location=["url"]) self.assertEquals(arg.location, ["url"])
def test_dest(self): arg = Argument("foo", dest="foobar") self.assertEquals(arg.dest, "foobar")
def test_source_default_location(self): req = Mock(['values']) req._get_child_mock = lambda **kwargs: NonCallableMock(**kwargs) arg = Argument('foo') self.assertEquals(arg.source(req), req.values)
def test_convert_default_type_with_null_input(self): """convert() should properly handle case where input is None""" arg = Argument('foo') self.assertEquals(arg.convert(None, None), None)
class MovieResource(Resource): """ Verbs relative to the movies """ @staticmethod @swag_from("../swagger/movie/GET.yml") def get(name): """ Return an movie key information based on his name """ m = MovieRepository.get(name=name) d = {} d['name'] = m.name d['year'] = m.year d['genre'] = m.genre d['notes'] = 0 d['affiche'] = m.affiche t = [] for l in m.notes: t.append(l.note) if len(t) != 0: d['notes'] = sum(t) / len(t) else: d['notes'] = -1 return (jsonify(d)) @staticmethod @parse_params( Argument("genre", location="json", required=True, help="The genre of the movie."), Argument("year", location="json", required=True, help="The year of the movie."), Argument("affiche", location="json", required=True, help="The affiche of the movie.")) @swag_from("../swagger/movie/POST.yml") def post(name, genre, year, affiche): """ Create an movie based on the sent information """ movie = MovieRepository.create(name=name, genre=genre, year=year, affiche=affiche) return jsonify({"movie": movie.json}) @staticmethod @parse_params( Argument("genre", location="json", required=True, help="The genre of the movie."), Argument("year", location="json", required=True, help="The year of the movie."), Argument("affiche", location="json", required=True, help="The affiche of the movie.")) @swag_from("../swagger/movie/PUT.yml") def put(name, genre, year, affiche): """ Update an movie based on the sent information """ repository = MovieRepository() movie = repository.update(name=name, genre=genre, year=year, affiche=affiche) return jsonify({"movie": movie.json})
def test_source_default_location(self): req = Mock(['values']) req._get_child_mock = lambda **kwargs: MultiDict() arg = Argument('foo') self.assertEquals(arg.source(req), req.values)
def test_name(self): arg = Argument("foo") self.assertEquals(arg.name, "foo")
def test_ignore_default(self): arg = Argument("foo") self.assertEquals(arg.ignore, False)
def test_location_url(self): arg = Argument("foo", location="url") self.assertEquals(arg.location, "url")
def test_action_default(self): arg = Argument("foo") self.assertEquals(arg.action, u"store")
def test_location_header(self): arg = Argument("foo", location="headers") self.assertEquals(arg.location, "headers")
def test_choices_default(self): arg = Argument("foo") self.assertEquals(len(arg.choices), 0)
def test_source_default_location(self): req = Mock(['values']) arg = Argument('foo') self.assertEquals(arg.source(req), req.values)
def test_source_default_location(self): req = Mock(["values"]) arg = Argument("foo") self.assertEquals(arg.source(req), req.values)
def test_default_type(self, mock_six): arg = Argument("foo") sentinel = object() arg.type(sentinel) mock_six.text_type.assert_called_with(sentinel)
def test_default_default(self): arg = Argument("foo") self.assertEquals(arg.default, None)
def test_source_bad_location(self): req = Mock(['values']) arg = Argument('foo', location=['foo']) self.assertTrue(len(arg.source(req)) == 0) # yes, basically you don't find it
def test_required_default(self): arg = Argument("foo") self.assertEquals(arg.required, False)
class SubmitAnswerResources(Resource): """ Verbs relative to the users """ @staticmethod @parse_params( Argument("answer_id", location="json", type=int, required=True, help="Answer id"), Argument("question_id", location="json", type=int, required=True, help="Question id"), ) @with_auth def post(answer_id, trivia_id, question_id, user, **_kwargs): """ Return an user key information based on his name """ answer = SubmittedAnswer( answer_id=answer_id, trivia_id=trivia_id, user_id=user.oid, question_id=question_id ).save() trivia = Trivia.query.filter_by(id=trivia_id).one() achievement = AchievementRepository.get(trivia.achievement_id) if achievement: if len(trivia.submitted_answers) == len(achievement.questions): trivia.completed = True trivia.save() achieved = True for answer in trivia.submitted_answers: if not answer.answer.is_right: achieved = False break if achieved: user.achievements_rate = user.achievements_rate + 50 user.save() try: UserRepository.obtain(user, achievement) except sqlalchemy.orm.exc.FlushError: pass elif len(trivia.submitted_answers) == len(trivia.questions) * 2: trivia.completed = True trivia.save() players_score = {trivia.user_id: 0, trivia.second_player_id: 0} answers_checked = [] for answer in trivia.submitted_answers: if answer.id in answers_checked: continue for aanswer in trivia.submitted_answers: if aanswer.id in answers_checked: continue if aanswer.id == answer.id: continue if aanswer.question_id != answer.question_id: continue if aanswer.answer.is_right and answer.answer.is_right: if aanswer.created_at < answer.created_at: players_score[aanswer.user_id] += 1 else: players_score[answer.user_id] += 1 elif aanswer.answer.is_right: players_score[aanswer.user_id] += 1 elif answer.answer.is_right: players_score[answer.user_id] += 1 answers_checked.append(answer.id) answers_checked.append(aanswer.id) first_player_id, first_player_score = players_score.popitem() second_player_id, second_player_score = players_score.popitem() if trivia.user_id != first_player_id: first_player_id, first_player_score, second_player_id, second_player_score = ( second_player_id, second_player_score, first_player_id, first_player_score ) if first_player_score == second_player_score: user = UserRepository.get(first_player_id) user.trivia_rate = user.trivia_rate + 20 user.save() user = UserRepository.get(second_player_id) user.trivia_rate = user.trivia_rate + 20 user.save() trivia.first_player_score = 20 trivia.second_player_score = 20 trivia.save() elif first_player_score > second_player_score: user = UserRepository.get(first_player_id) user.trivia_rate = user.trivia_rate + 45 user.save() trivia.first_player_score = 45 trivia.second_player_score = 0 trivia.save() else: user = UserRepository.get(second_player_id) user.trivia_rate = user.trivia_rate + 45 user.save() trivia.first_player_score = 0 trivia.second_player_score = 45 trivia.save() return render_resource(answer)
def test_source_default_location(self): req = Mock(["values"]) req._get_child_mock = lambda **kwargs: MultiDict() arg = Argument("foo") self.assertEquals(arg.source(req), req.values)