• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python service_log.error函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中support.service_log.error函数的典型用法代码示例。如果您正苦于以下问题:Python error函数的具体用法?Python error怎么用?Python error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了error函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __getattr__

    def __getattr__(self, item):
        if item in self.find_prefixes_shell():
            #global prefix_ssh
            values_authentication = dict()
            try:
                values_authentication = {
                    "shell_host": configs.config["env_info"][item + "_host"],
                    "shell_port": configs.config["env_info"][item + "_port"],
                    "shell_user": configs.config["env_info"][item + "_user"],
                    "shell_type": item[:3],  # TODO: при добавалении новых типов shell изменить
                }

                if item + "_passwd" in configs.config["env_info"]:
                    # есть пароль, используем пароль
                    # "shell_passwd": configs.config["env_info"][item + "_passwd"],
                    values_authentication.update({"shell_passwd": configs.config["env_info"][item + "_passwd"]})
                elif item + "_keyfile" in configs.config["env_info"]:
                    # используем ключ, указываем путь до ключа
                    values_authentication.update({"shell_keyfile": configs.config["env_info"][item + "_keyfile"]})
                else:
                    raise AssertionError("Not found password or keyfile for shell.")

            except Exception, tx:
                service_log.error("Not found mark in env.cfg: %s" % str(tx))
            return ClassShellWork(**values_authentication)
开发者ID:Maksim1988,项目名称:test,代码行数:25,代码来源:shell.py


示例2: get_response_by_WebServer

def get_response_by_WebServer(serv, count=1):
    """ Получаем данные от Веб-сервера.
    Метод вернёт управление по таймауту сервера или при получении всех данных
    :param serv: объект сервера
    :param count: количество принятых пакетов
    :return: информация о полученном пакете.
    """
    full_answer = None
    run_time = int(configs.config["system_settings"]["sys_timeout_listen_port"])
    start_timer = int(time.time())
    while True:
        try:
            full_answer = serv.info_requests
            if len(full_answer) >= count or ('Disconnect' or 'Error') in full_answer[0].keys():
                serv.stop_server = True
                #serv.setDaemon(True) # вырубить демон
                return serv.info_requests
            elif "Error" in full_answer[0]:
                raise AssertionError("Server return error: %s" % str(full_answer[0]["Error"]))
            elif full_answer[0]['Disconnect']:
                break
        except IndexError:
            pass
        except KeyError:
            pass

        # прерывание цикла
        if int(time.time()) - start_timer > run_time:
            service_log.error("Timeout!")
            break
    p_error = str(full_answer[0]["Disconnect"]) if len(full_answer) != 0 else ""
    raise AssertionError("Server return error: %s" % p_error)
开发者ID:senchuk,项目名称:letotest,代码行数:32,代码来源:webserver.py


示例3: execute

    def execute(self, req, parameters=None):
        """ Выполнить запрос.
        :param req: сql-запрос
        :return: результат операции
        """

        session = None
        try:
            session = self.connect_plain_auth(user_name=self.user, password=self.passwd, port=self.port,
                                              key_space=self.name, contacts_point=self.host)
            if parameters is not None:
                # вариант с предварительной привязкой параметров, для работы с BLOB
                prepare_params = session.prepare(req)
                bound_params = prepare_params.bind(parameters)
                result = session.execute(bound_params)
            else:
                result = session.execute(req)
            service_log.put("Response from cassandra.")
            if isinstance(result, list):
                if len(result) > 0:
                    return [dict(index.__dict__) for index in result]
                else:
                    return None
            else:
                return result
        except Exception, tx:
            service_log.error(str(tx))
            raise AssertionError(str(tx))
开发者ID:senchuk,项目名称:letotest,代码行数:28,代码来源:db_cassandra.py


示例4: __getattr__

 def __getattr__(self, item):
     """ Делаем привязку к сервису.
     :param item: наименование префикса
     :return: возвращаем значение переменной из env_info.cfg или вызываем Exception
     """
     if item in self.array_all_prefix:
         global prefix_serv
         prefix_serv = item
         return GetVariableThrift(self.cfg)
     elif item in self.array_thrift_var:
         if item in self.array_thrift_var1:
             # проверка, что нужна переменная импорта
             return self.dict_thrift_var[prefix_serv + "_" + item]
         elif item in self.array_thrift_var2:
             # проверка, что нужна одна из переменных в thrift_variables
             return self.cfg["thrift_variables"][prefix_serv + "_" + item]
     elif item == "imports" and prefix_serv in self.array_user_prefix:
         # только импорты определённого воркера
         res = dict([name, path] for name, path in self.dict_thrift_var.iteritems() if name.find(prefix_serv) != -1)
         return res
     elif item == "workers" and prefix_serv is GetVariableThrift.main_prefix:
         # список названий воркеров
         return self.array_user_prefix
     elif item == "imports" and prefix_serv is GetVariableThrift.main_prefix:
         # список всех импортов для Thrift
         return self.dict_thrift_var
     else:
         msg_pref = "Unknown prefix=%s in env.cfg" % item
         service_log.error(msg_pref)
         raise AssertionError(msg_pref)
开发者ID:senchuk,项目名称:letotest,代码行数:30,代码来源:variables.py


示例5: execute

 def execute(self, req, fetch="all"):
     """ Выполнить запрос.
     :param req: sql-запрос
     :param fetch: тип выборки строк запроса
     :return: результат операции
     """
     try:
         self.cursor_now = self.connect()
         self.cursor_now.execute(req)
         if fetch == "all":
             result = rows_to_dict_list(self.cursor_now)
             service_log.put("Fetchall rows.")
             return result
         elif fetch == "one":
             result = self.cursor_now.fetchone()
             service_log.put("Fetchone rows.")
             return result
         elif fetch == "update" or fetch == "insert":
             service_log.put("No fetch rows. Operation by UPDATE.")
             self.conn.commit()
             service_log.put("Commit operation UPDATE.")
             return None
     except Exception, tx:
         service_log.error(str(tx))
         raise AssertionError(str(tx))
开发者ID:senchuk,项目名称:letotest,代码行数:25,代码来源:db_oracle.py


示例6: sudo_command_execution

    def sudo_command_execution(self, cls, passwd=None):
        """
        Make a remote command execution with sudo by ssh
        Return result
        :param cls: remote command to run
        """
        client = self.connect()
        channel = None
        try:
            service_log.put("Open SSH chanel.")
            channel = client.get_transport().open_session()
            service_log.put("Open SSH chanel success.")

            channel.get_pty()
            channel.settimeout(5)

            service_log.put("Execute: %s." % cls)
            #self.channel.exec_command('sudo -i')
            channel.exec_command('sudo %s' % cls)
            if passwd is not None:
                channel.send(self.passwd+'\n')
            data = channel.recv(1024)
            service_log.put("Execute success. Output: %s" % str(data))
            return data
        except Exception, tx:
            service_log.error(str(tx))
            raise AssertionError(str(tx))
开发者ID:senchuk,项目名称:letotest,代码行数:27,代码来源:ssh_client.py


示例7: command_execution

 def command_execution(self, cls, flag_output=True):
     """ Выполнить оперцию на удалённой консоли.
     :param client: ссылка на удалённую консоль
     :param cls: команда, которую необходимо запустить
     :param flag_output: если флаг False, то результат не возвращаем
     :return: Результат выполненной операции, либо ничего
     """
     if self.passwd is not None:
         client = self.connect_by_user_password()
     elif self.keyfile is not None:
         client = self.connect_by_key_file()
     else:
         msg_error = "Not found password or keyfile for connect!"
         service_log.error(msg_error)
         raise AssertionError(msg_error)
     try:
         service_log.put("Execute: %s." % cls)
         if flag_output is True:
             stdin, stdout, stderr = client.exec_command("""%s""" % cls)
             data = dict(stdout=stdout.read(), stderr=stderr.read())
             if data["stderr"] != '':
                 service_log.put("Return. Output: %s" % str(stderr))
                 service_log.put("Execute success. Output: %s" % str(data))
                 raise AssertionError("Return error: %s" % str(stderr))
             service_log.put("Execute success. Output: %s" % str(data))
             return data
         else:
             client.exec_command("""%s""" % cls)
             service_log.put("Execute success.")
             return None
     except Exception, tx:
         service_log.error(str(tx))
         raise AssertionError(str(tx))
开发者ID:senchuk,项目名称:letotest,代码行数:33,代码来源:ssh_client.py


示例8: __init__

    def __init__(self, cfg):
        """ Инициализация переменных различных сервисов.
        :param cfg: ссылка на конфигурацию
        """

        self.cfg = cfg

        try:
            # Ключевые слова, которые не являются префиксами
            #__kwords = ("host", "port", "name", "login", "passwd")
            __kwords = ()

            env_info = self.cfg["env_info"].keys()

            # определяем дополнительные функции для выборки префиксов сервисов
            num_pref = lambda a: a.rfind("_") if a.rfind("_") != -1 else False
            get_pref = lambda p: p[num_pref(p)+1:]
            get_name = lambda n: n[:num_pref(n)]
            no_kwords = lambda w, f: f(w) not in __kwords

            # Находим все префиксы сервисов
            self.array_var = set(get_pref(word) for word in env_info if num_pref(word) and no_kwords(word, get_pref))
            self.array_prefix = set(get_name(word) for word in env_info if num_pref(word) and no_kwords(word, get_name))
        except:
            msg_any_pref = "Unknown any prefix in env.cfg"
            service_log.error(msg_any_pref)
            raise AssertionError(msg_any_pref)
开发者ID:senchuk,项目名称:letotest,代码行数:27,代码来源:variables.py


示例9: add_users_strategy

    def add_users_strategy(link_db, mode='all'):
        """

        :param driver:
        :param count:
        :param mode:
        :return:
        """
        users_list = list()
        criteria = "account_status = 'ENABLED' AND id in (%s) AND phone like '7%s' AND length(phone)=11 AND " \
                   "display_name is not NULL"
        if mode == 'all':
            users_list = link_db.accounting.get_user_by_role('1,2,3,4', '100')
            value_list = [str(value["account_details_id"]) for value in users_list]
            string = ','.join(value_list)
            users_list = link_db.accounting.get_user_by_criteria_only(criteria % (string, '%'))
        elif mode == 'buyer':
            users_list = link_db.accounting.get_user_by_role('1', '2,3,4')
            value_list = [str(value["account_details_id"]) for value in users_list]
            string = ','.join(value_list)
            users_list = link_db.accounting.get_user_by_criteria_only(criteria % (string, '%'))
        elif mode == 'seller':
            users_list = link_db.accounting.get_user_by_role('2', '3,4')
            value_list = [str(value["account_details_id"]) for value in users_list]
            string = ','.join(value_list)
            users_list = link_db.accounting.get_user_by_criteria_only(criteria % (string, '%'))
        elif mode == 'disabled':
            users_list = link_db.accounting.get_accounts_by_criteria(criteria="account_status='DISABLED'")
        else:
            service_log.error("Undefined mode='%s'" % mode)
        return users_list
开发者ID:Maksim1988,项目名称:test,代码行数:31,代码来源:class_user_contacts.py


示例10: find_prefixes_shell

 def find_prefixes_shell():
     bases_val = [key for key in configs.config["env_info"].keys() if key[:3] in ClassShellWork.prefix_shell]
     prefixes = set([index[:index.find("_")] for index in bases_val])
     if len(prefixes) != 0:
         return prefixes
     else:
         msg_error = "Not found prefix for connect with shell!"
         service_log.error(msg_error)
         raise AssertionError(msg_error)
开发者ID:Maksim1988,项目名称:test,代码行数:9,代码来源:shell.py


示例11: find_prefixes_databases

 def find_prefixes_databases():
     bases_val = [key for key in configs.config["env_info"].keys() if key[:2] == ClassDatabasesWork.prefix_selenium]
     prefixes = set([index[:index.find("_")] for index in bases_val])
     if len(prefixes) != 0:
         return prefixes
     else:
         msg_error = "Not found prefix databases!"
         service_log.error(msg_error)
         raise AssertionError(msg_error)
开发者ID:Maksim1988,项目名称:test,代码行数:9,代码来源:selenium.py


示例12: generate_context_data

 def generate_context_data(context_type):
     if context_type == "auth":
         return SessionMethods.generate_auth_data_context()
     elif context_type == "agent":
         return SessionMethods.generate_agent_data_context()
     else:
         msg = "Unknown context type %s!" % str(context_type)
         service_log.error(msg)
         raise AssertionError(msg)
开发者ID:Maksim1988,项目名称:test,代码行数:9,代码来源:class_session.py


示例13: go_main

    def go_main(driver, phone=None, email=None, passwd=None, flag_auth=True, flag_api=True):
        """ Универсальный переход на главную страницу.
        :param driver: ссылка на драйвер
        :param phone: номер телефона
        :param email: электронная почта
        :param passwd: пароль
        :param flag_auth: флаг авторизации
        """
        from support.utils.variables import EVariable
        env_base_url = EVariable.front_base.url.strip()

        # авторизоваться через API
        if flag_auth:
            service_log.put("To authorization via API")
            if flag_api:
                if email is None and phone is not None:
                    HelpAuthMethods.set_authorization_by_phone(driver, phone, passwd)
                elif email is not None and phone is None:
                    # TODO
                    pass
                else:
                    msg_error = "Not correct params."
                    service_log.error(msg_error)
                    assert AssertionError(msg_error)
            else:
                if email is None and phone is not None:
                    HelpNavigateCheckMethods.get_page(driver, HelpNavigateCheckMethods.path_auth.PATH_AUTH)
                    obj_phone, obj_password, obj_submit_button = HelpAuthCheckMethods.get_data_authorization(driver)

                    # Вводим данные на авторизацию
                    l = lambda e, p:e if p is None else p
                    HelpAuthCheckMethods.send_phone(phone_object=obj_phone, phone_number=l(email, phone))
                    HelpAuthCheckMethods.send_password(password_object=obj_password, password_number=passwd)
                    # Нажатие на кнопку авторизации
                    HelpNavigateCheckMethods.element_click(driver, obj_submit_button, change_page_url=True)
                    time.sleep(HelpNavigateCheckMethods.time_sleep)
                elif email is not None and phone is None:
                    # TODO
                    pass
                else:
                    msg_error = "Not correct params."
                    service_log.error(msg_error)
                    assert AssertionError(msg_error)
            service_log.put("To authorization via API - success.")

        service_log.put("Get page: %s" % env_base_url)
        do_get_work = time.time()
        driver.get(env_base_url)
        work_get_time = HelpNavigateCheckMethods.work_time(do_get_work)
        service_log.put("Onload event time: [%s]" % work_get_time)
        HelpNavigateCheckMethods.progress(driver)
        work_load_time = HelpNavigateCheckMethods.work_time(do_get_work)
        service_log.put("Page received: %s" % env_base_url)
        service_log.put("Page received time: %s" % work_load_time)
        time.sleep(3)
开发者ID:Maksim1988,项目名称:test,代码行数:55,代码来源:class_front.py


示例14: check_err_msg

 def check_err_msg(self, driver, xpath_err_msg):
     tx1 = None
     tx2 = None
     service_log.put("STEP: CHECK ERROR MESSAGE")
     try:
         service_log.put("...Start find abstract warning message.")
         driver.find_element_by_xpath(self.check_good.ERR_NEED_STOCK_ABSTRACT)
         service_log.put("...Success! Abstract warning message is found.")
     except Exception, tx1:
         service_log.error("...Abstract warning message is not found.")
         self.assertIsNone(tx1, "Warning message '%s' is not found." % xpath_err_msg)
开发者ID:Maksim1988,项目名称:test,代码行数:11,代码来源:class_chat_and_deals.py


示例15: save_wares_data

 def save_wares_data(data):
     """ Сохранить список данных товаров.
     :param data: данные товаров
     :return: True
     """
     if isinstance(data, list):
         WarehouseMethods.SAVED_WARE = data
         service_log.put("Save the data in a single ware.")
         return True
     else:
         service_log.error("Data is not list.")
         assert AssertionError("Data is not list.")
开发者ID:Maksim1988,项目名称:test,代码行数:12,代码来源:class_warehouse.py


示例16: NoneToInt

def NoneToInt(val):
    """ Если значение None, конвертим его в 0.
    :param val: значение
    :return: 0 или число
    """
    if val is None:
        return 0
    elif isinstance(val, int):
        return val
    else:
        service_log.error("Value is not int or None")
        assert AssertionError("Value is not int or None")
开发者ID:Maksim1988,项目名称:test,代码行数:12,代码来源:common_utils.py


示例17: import_libs

 def import_libs(self, name_prefix):
     try:
         # Производим динамический импорт сгенериррованных файлов для Thrift
         path = TVariables.thrift.imports[name_prefix + "_worker"]
         service_log.put("Get path by worker: %s" % path)
         get_lib = lambda path_lib: path_lib[path_lib.rfind(".")+1:]
         self.worker = __import__(path, fromlist=[get_lib(path)])
         service_log.put("Import libs worker: path=%s, name=%s" % (path, get_lib(path)))
         return name_prefix
     except ImportError, tx:
         error_message = "Import lib for worker - %s" % tx
         service_log.error(error_message)
         raise AssertionError(error_message)
开发者ID:Maksim1988,项目名称:test,代码行数:13,代码来源:thrift4req.py


示例18: modify

 def modify(*args, **kwargs):
     try:
         service_log.put("Params for %s: %s, %s" % (func.func_name, str(args[1:]), str(kwargs)))
         link_func = unittest.TestCase.__dict__[func.func_name]
         return link_func(*args, **kwargs)
     except Exception, tx:
         limit_print_exc = 10
         msg_line = "#" + ("-"*100)
         service_log.error(tx)
         service_log.put("\n%s\n%s\n%s" % (msg_line, traceback.format_exc(limit_print_exc), msg_line))
         trace_stack_log = funcy.join(traceback.format_stack(limit=limit_print_exc))
         service_log.put("Traceback stack:\n%s\n%s" % (str(trace_stack_log), msg_line))
         raise AssertionError(tx)
开发者ID:Maksim1988,项目名称:test,代码行数:13,代码来源:MainClass.py


示例19: check_not_found

 def check_not_found(self, func, *args, **kwargs):
     """ Перехватываем исключение, если элемент не найден и говорим, что так и должно быть.
     :param func: результат поиска элемента
     :return: True
     """
     try:
         func(*args, **kwargs)
         msg = "Find element!"
         service_log.error(msg)
         raise AssertionError("Error: %s" % msg)
     except NoSuchElementException, tx:
         service_log.put("Success! Element not found.")
         return True
开发者ID:Maksim1988,项目名称:test,代码行数:13,代码来源:test_ware_life_cycle.py


示例20: modify

 def modify(*args, **kwargs):
     try:
         platform_name = CmdWork.get_platform()
         link_func = None
         if platform_name == "windows":
             link_func = CmdWindows.__dict__[func.func_name]
         elif platform_name == "linux":
             link_func = CmdLinux.__dict__[func.func_name]
         else:
             raise AssertionError("Not found name platform!")
         return link_func(*args, **kwargs)
     except Exception, tx:
         service_log.error(tx)
         raise AssertionError(tx)
开发者ID:senchuk,项目名称:letotest,代码行数:14,代码来源:exec_cmd.py



注:本文中的support.service_log.error函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python service_log.preparing_env函数代码示例发布时间:2022-05-27
下一篇:
Python service_log.end函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap