def export(self, ids): """ Экспортирование шаблонов """ dictionaries = {} for dict_id in ids: dictionaries[dict_id] = {} suite = self.fetch(dict_id) dictionaries[dict_id][ "name"] = suite["code"] or suite.dictionary_id # noqa dictionaries[dict_id]["content"] = suite["content"] result = post_request(url=PROCESSOR_HOST, headers=None, request_data=get_create_request( method="task.create", script="scripts.dictionaries.export_run", type=TYPE, args={"dictionaries": dictionaries})) result = result["result"] if result["status"]: return result["response"] raise ApiError(code="UNHANDLED", message=result["errors"]["message"])
def inner(replica): params = { "inf_id": inf_id, "session_id": session_id, "replica": replica, } try: req = requests.post(url=urljoin(NLAB_ARM_ENGINE_SERVICE_HOST, "send_request"), params=params, headers=HEADERS) except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.Timeout, requests.exceptions.RequestException): raise ApiError(code="INF_ENGINE_ERROR", message="Inf engine session initialization error.") req = req.json() if req["status"]: return req["data"]["text"] return None
def change(self, id, action, profile_id): if action not in ("add", "remove"): raise ValueError("Invalid action: %s" % action) with self.create_session() as session: complect_model = self.complect.get(id, session=session) if not complect_model: raise ApiError(code="NOT_EXISTS", message="Can't find complect with id=%r" % id) save = False in_ = profile_id in complect_model.profile_ids if action == "add": if not in_: profile_ids = copy.deepcopy(complect_model.profile_ids) profile_ids.append(profile_id) complect_model.profile_ids = profile_ids save = True else: if in_: profile_ids = copy.deepcopy(complect_model.profile_ids) profile_ids.remove(profile_id) complect_model.profile_ids = profile_ids save = True if save: session.add(complect_model) session.commit() return complect_model.to_dict()
def remove(self, id): try: result = self.dictionary.remove(id) return result except VersionNoObject as e: raise ApiError(code="NOT_EXISTS", message=e.args[0]) from e
def run(ids, testcases, profile_info): """ Запуск тесткейсов """ result = [] inf_id = profile_info["engine_id"] if not inf_id: raise ApiError(code="INF_ENGINE_ERROR", message="Inf engine_id is null.") inf_name = profile_info["code"] or NLAB_ARM_TEST_TESTCASE_INF_NAME if not init_session( inf_id=inf_id, inf_name=inf_name, session_id=SESSION_ID): raise ApiError(code="INF_ENGINE_ERROR", message="Inf engine session initialization error.") send_replica_request = send_request(inf_id=inf_id, session_id=SESSION_ID) testcases_dict = {} for tc in testcases: testcases_dict[tc["id"]] = tc for id in ids: item = {"id": id, "dialogue": []} try: testcase = testcases_dict[id] except KeyError: item["error"] = { "message": "Can't find testcase with id=%r" % id, "code": "NOT_EXISTS" } result.append(item) continue for replica in testcase["replicas"]: response = send_replica_request(replica) item["dialogue"].append({"request": replica, "response": response}) result.append(item) return {"dialogues": result}
def _store(self, id=None, name=None, state=None, profile_ids=None, meta=None, is_enabled=None, code=None, action=None, compiler_target=None, debug_target=None, deploy_target=None, session=None): if action == 'update': complect_model = self.complect.get(id, session=session) if not complect_model: raise ApiError(code="NOT_EXISTS", message="Can't find complect with id=%r" % id) else: complect_model = Complect( created=datetime.now(), version=0, ) if name is not None: complect_model.name = name if state is not None: complect_model.state = state if profile_ids is not None: complect_model.profile_ids = profile_ids if meta is not None: complect_model.meta = meta if is_enabled is not None: complect_model.is_enabled = is_enabled if code is not None: complect_model.code = code if compiler_target is not None: complect_model.compiler_target = compiler_target if debug_target is not None: complect_model.debug_target = debug_target if deploy_target is not None: complect_model.deploy_target = deploy_target complect_model.version += 1 session.add(complect_model) session.flush() return complect_model.to_dict()
def fetch(self, id): with self.create_session() as session: complect_model = self.complect.get(id, session=session) if not complect_model: raise ApiError(code="NOT_EXISTS", message="Can't find complect with id=%r" % id) return complect_model.to_dict()
def info(self, task_id): """Получение задачи""" with self.create_session() as session: task_model = self.task.get(task_id, session=session) if not task_model: raise ApiError(code="NOT_EXISTS", message="Can't find task_id with id=%r" % task_id) return task_model.to_dict()
def _fetch(self, id): """Получение""" with self.create_session() as session: testcase_model = self.testcase.get(id, session=session) if not testcase_model: raise ApiError( code="NOT_EXISTS", message="Can't find testcase with id=%r" % id ) return testcase_model.to_dict()
def _update_one(instance, session, kwargs): # TODO: some components have more complex primary_key if kwargs.get("id") is None: raise ApiError( code="ID_REQUIRED", message="Must be id in update operation", ) kwargs['action'] = 'update' kwargs['session'] = session return instance._store(**kwargs)
def fetch(self, id): """ Returns complect revision model by id """ with self.create_session() as session: complect_revision_model = self.complect_revision.get( id, session=session) if not complect_revision_model: raise ApiError( code="NOT_EXISTS", message="Can't find complect revision with id=%r" % id) return complect_revision_model.to_dict()
def fetch(self, id, _process=None): with self.create_session() as session: profile_model = self.dictionary.get(id, session=session) if not profile_model: raise ApiError(code="NOT_EXISTS", message="Can't find profile with id=%r" % id) item = profile_model.to_dict() if _process: item = _process_dictionary_inplace(item) return item
def remove(self, id): try: with self.create_session() as session: if not isinstance(id, list): id = [id] for iid in id: template_model = self.template.get(iid, session=session) self._update_parent(template_model, session=session) return self.template.remove(id, session) except VersionNoObject as e: raise ApiError(code="NOT_EXISTS", message=e.args[0]) from e
def result(task_id): """ Получение результата по задаче """ result = post_request( url=PROCESSOR_HOST, headers=None, request_data=get_info_request(method="task.info", task_id=task_id) ) result = result["result"] if result["status"]: return result["response"] raise ApiError( code="PROCESSOR_SERVICE", message=result["errors"]["message"] )
def result_list(offset=None, limit=None): """ Получение списка задача/статус """ result = post_request( url=PROCESSOR_HOST, headers=None, request_data=get_info_request( method="task.list", type=TYPE, offset=offset, limit=limit ) ) result = result["result"] if result["status"]: return result["response"] raise ApiError(code="NOT_EXISTS", message=result["errors"]["message"])
def _calculate_template_position(self, *, position: int, position_before: str, position_after: str, suite_id: str, do_insert: bool, session): """ Calculates position for template in insert or update operation. :param position: Set position :param position_before: Position before template uuid or "last" :param position_after: Position after template uuid or "first" :param suite_id: Suite id :param do_insert: Do insert or update :param session: Database session :return: new position or None if not changes """ position_arguments_exist = sum( int(arg is not None) for arg in (position, position_before, position_after)) if position_arguments_exist > 1: raise ApiError(code="INVALID_POSITION", message="Only one of `position`, `position_before` " "and `position_after` arguments must be given!") fetch_position = position_before or position_after or None if fetch_position not in ("first", "last", None): # fetch_position is Template uuid fetch_template = (session.query(Template).filter_by( template_id=fetch_position).scalar()) set_position = fetch_template.position if position_after: set_position += 1 elif fetch_position == "first": set_position = 1 elif position is not None: set_position = position elif do_insert or fetch_position == "last": # Get max template position in suite max_position = (session.query(func.max( Template.position)).filter_by(suite_id=suite_id).scalar()) set_position = (max_position or 0) + 1 else: # Do nothing set_position = None return set_position
def run(self, profile_id, ids): """ Запуск """ if len(ids) > MAX_COUNT_TESTCASE_TO_RUN: raise ApiError( code="COUNT_TESTCASES", message="Количество тесткейсов превышает допустимое количество" " {} для одного запуска".format( MAX_COUNT_TESTCASE_TO_RUN ) ) def form_items(items): res = [] for item, _ in items: res.append(item.to_short_dict()) return res filter_q = [ Testcase.profile_id == profile_id, Testcase.testcase_id.in_(ids) ] testcases, _ = self.testcase.filter( filter_q=filter_q, limit=len(ids), form_items=form_items # TODO: ? Так оно точно работает? ) profile = ProfileRpc( tracer=self.tracer, create_session=self.create_session ) profile_info = profile.fetch(profile_id) result = post_request( url=PROCESSOR_HOST, headers=None, request_data=get_create_request( method="task.create", script="scripts.testcase.run", type=TYPE, args={ "ids": ids, "testcases": testcases, "profile_info": profile_info } ) ) return result["result"]["response"]
def import_file(profile_ids, file_name, data): """ Импортирование словарей из файла """ result = post_request(url=PROCESSOR_HOST, headers=None, request_data=get_create_request( method="task.create", script="scripts.dictionary.import_run", type=TYPE, args={ "profile_ids": profile_ids, "file_name": file_name, "data": data, })) result = result["result"] if result["status"]: return result["response"] raise ApiError(code="UNHANDLED", message=result["errors"]["message"])
def init_session(inf_id, inf_name, session_id): """ Инициализация сессии """ params = { "inf_id": inf_id, "session_id": session_id, "inf_name": inf_name, } try: result = requests.post(url=urljoin(NLAB_ARM_ENGINE_SERVICE_HOST, "init_session"), params=params, headers=HEADERS) except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.Timeout, requests.exceptions.RequestException): raise ApiError(code="INF_ENGINE_ERROR", message="Inf engine session initialization error.") return result.json()["status"]
def _store(self, id=None, profile_id=False, title=None, description=None, replicas=None, is_common=None, author=None, action=None, session=None): if action == "update": testcase_model = self.testcase.get(id, session=session) if not testcase_model: raise ApiError( code="NOT_EXISTS", message="Can't find testcase with id=%r" % id ) else: testcase_model = Testcase(created=datetime.now(), ) if profile_id is not False: # False, потому что клиент может отправлять None # для очистки profile_id testcase_model.profile_id = profile_id if title is not None: testcase_model.title = title if description is not None: testcase_model.description = description if replicas is not None: testcase_model.replicas = replicas if is_common is not None: testcase_model.is_common = is_common if author is not None: testcase_model.author = author session.add(testcase_model) session.flush() return testcase_model.to_dict()
def remove(self, id): """Удаление""" try: return self.testcase.remove(id) except VersionNoObject as e: raise ApiError(code="NOT_EXISTS", message=e.args[0]) from e
def remove(self, id): try: return self.complect.remove(id) except VersionNoObject as e: raise ApiError(code="NOT_EXISTS", message=e.args[0]) from e
def _store(self, *, content=None, suite_id=None, id=None, is_enabled=None, is_compilable=None, meta=None, position=None, position_before=None, position_after=None, action=None): with self.create_session() as session: set_position = self._calculate_template_position( position=position, position_before=position_before, position_after=position_after, suite_id=suite_id, do_insert=not id, session=session) if action == "update": template_model = self.template.get(id, session=session) if not template_model: raise ApiError(code="NOT_EXISTS", message="Can't find template with id=%r" % id) else: if suite_id is None: raise ApiError( code="MISSING_SUITE_ID", message="suite_id must be given for creating template") if set_position is None: # Если позиция не указана, ставим в конец. max_position = session.query(func.max( Template.position)).filter_by( suite_id=suite_id).scalar() set_position = (max_position or 0) + 1 template_model = Template( template_id=id, suite_id=suite_id, created=datetime.now(), version=0, ) if content is not None: template_model.content = content if is_enabled is not None: template_model.is_enabled = is_enabled if is_compilable is not None: template_model.is_compilable = is_compilable if meta is not None: template_model.meta = meta if set_position is not None: self._move_positions_slow_method(template_model, set_position, session=session) # template_model.updated = datetime.now() template_model.version += 1 session.add(template_model) self._update_parent(template_model, session) template = template_model.to_dict() del template["stats"] session.commit() return template_model.to_dict()
def _store(self, id=None, code=None, description=None, content=None, common=None, state=None, meta=None, profile_ids=None, is_enabled=None, hidden=None, action=None, kind=None, parts=None, session=None): if action == 'update': dictionary_model = self.dictionary.get(id, session=session) if not dictionary_model: raise ApiError(code="NOT_EXISTS", message="Can't find dictionary with id=%r" % id) else: dictionary_model = Dictionary( created=datetime.now(), version=0, ) if code is not None: dictionary_model.code = code if description is not None: dictionary_model.description = description if content is not None: dictionary_model.content = content if common is not None: dictionary_model.common = common if kind is not None: dictionary_model.kind = kind if state is not None: dictionary_model.state = state if meta is not None: dictionary_model.meta = meta if profile_ids is not None: dictionary_model.profile_ids = profile_ids if is_enabled is not None: dictionary_model.is_enabled = is_enabled if hidden is not None: dictionary_model.hidden = hidden if parts is not None: dictionary_model.parts = parts dictionary_model.version += 1 session.add(dictionary_model) session.flush() data = dictionary_model.to_dict() return data