当前位置: 首页>>代码示例>>Python>>正文


Python BuiltIn.get_variable_value方法代码示例

本文整理汇总了Python中robot.libraries.BuiltIn.BuiltIn.get_variable_value方法的典型用法代码示例。如果您正苦于以下问题:Python BuiltIn.get_variable_value方法的具体用法?Python BuiltIn.get_variable_value怎么用?Python BuiltIn.get_variable_value使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在robot.libraries.BuiltIn.BuiltIn的用法示例。


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

示例1: _init_logger

# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import get_variable_value [as 别名]
 def _init_logger(self):
     robotLogLevels = {'TRACE': logging.DEBUG/2,
              'DEBUG': logging.DEBUG,
              'INFO': logging.INFO,
              'HTML': logging.INFO,
              'WARN': logging.WARN}
     builtIn = BuiltIn()
     handler = logging.StreamHandler(sys.stdout)
     formatter = logging.Formatter('%(message)s')
     handler.setFormatter(formatter)
     logger = logging.getLogger('SikuliLibraryLogger')
     logger.addHandler(handler)
     level = logging.DEBUG
     try:
         logLevel = builtIn.get_variable_value('${LOG_LEVEL}')
         level = robotLogLevels[logLevel]
     except Exception, err:
         pass
开发者ID:bluesummerbreeze,项目名称:robotframework-SikuliLibrary,代码行数:20,代码来源:sikuli.py

示例2: LogGrabber

# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import get_variable_value [as 别名]

#.........这里部分代码省略.........

    """
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LISTENER_API_VERSION = 2
    
    def __init__(self):
        # загрузка встроенных библиотек
        self.bi=BuiltIn()
        self.ssh=SSHLibrary()
        self.adv_log=AdvancedLogging()
 
        # словарь с подготовленными логами
        self.prepared_logs = dict()

    def start_suite(self, name, attrs):
        self.set_connections()

    def start_test(self, name, attrs):
        self.prepare_logs()

    def end_test(self, name, attrs):
        if attrs['status'] != 'PASS':
            self.download_logs()

    def end_suite(self, name, attrs):
        self.close_connections()

    def set_connections(self):
        """
        SSH-соединение с удаленными серверами
        """
        
        # Получаем информацию о логах подсистем
        self.logs=self.bi.get_variable_value('${server_logs}')
        # Системный разделитель для платформы запуска тестов
        self.sys_separator=self.bi.get_variable_value('${/}')
        # Разделитель в unix
        self.nix_separator = '/'

        # перебираем сервера из словаря настройки
        # для каждого сервера создаем одтельное ssh-соединение,
        # которое будет жить в течение всего suite
        # дописываем alias в словарь для каждого сервера
        for _, server in enumerate(self.logs["servers"]):
            hostname = server["hostname"]
            port = server["port"]
            username = server["username"]
            password = server["password"]
            ssh_alias = str(self.bi.get_time('epoch'))
            # создаем ssh-соединение - alias = epoch timestamp
            self.ssh.open_connection(hostname, ssh_alias, port)
            self.ssh.login(username, password)
            server["ssh_alias"] = ssh_alias
    
    def prepare_logs(self):
        """
        Подготовка логов.
        В результате для каждого лога, удовлетворяющего настройке,
        записывается номер послнедней строки.

        """

        # структура с описанием серверов, подсистем и логов
        self.prepared_logs["servers"] = []
        # перебираем сервера из конфигурации
        for server in self.logs["servers"]:
开发者ID:JASON0916,项目名称:robot-framework-library,代码行数:70,代码来源:LogGrabber.py

示例3: BuiltIn

# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import get_variable_value [as 别名]
from robot.libraries.OperatingSystem import OperatingSystem
from robot.libraries.Process import Process
from systemTestUtils import _blockUntilConditionMet

builtIn = BuiltIn()  # type: BuiltIn
process = builtIn.get_library_instance('Process')  # type: Process
opSys = builtIn.get_library_instance('OperatingSystem')  # type: OperatingSystem

spyServerPort = 8270  # is `registered by IANA` for remote server usage. Two ASCII values:'RF'
spyServerURI = 'http://127.0.0.1:{}'.format(spyServerPort)
spyAlias = "nvdaSpy"

# robot is expected to be run from the NVDA repo root directory. We want all repo specific
# paths to be relative to this. This would allow us to change where it is run from if we decided to.
repoRoot = _abspath("./")
whichNVDA = builtIn.get_variable_value("${whichNVDA}", "source")
if whichNVDA == "source":
	NVDACommandPathToCheckExists = _pJoin(repoRoot, "source/nvda.pyw")
	baseNVDACommandline = "pythonw "+NVDACommandPathToCheckExists
elif whichNVDA == "installed":
	NVDACommandPathToCheckExists = _pJoin(_expandvars('%PROGRAMFILES%'),'nvda','nvda.exe')
	baseNVDACommandline='"%s"' % NVDACommandPathToCheckExists
else:
	raise AssertionError("robot should be given argument `-v whichNVDA [source|installed]")

# Paths
systemTestSourceDir = _pJoin(repoRoot, "tests", "system")
tempDir = tempfile.gettempdir()
opSys.directory_should_exist(tempDir)
nvdaProfileWorkingDir = _pJoin(tempDir, "nvdaProfile")
nvdaLogFilePath = _pJoin(nvdaProfileWorkingDir, 'nvda.log')
开发者ID:ehollig,项目名称:nvda,代码行数:33,代码来源:nvdaRobotLib.py

示例4: AdvancedLogging

# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import get_variable_value [as 别名]
class AdvancedLogging(object):
    """
    Creating additional logs when testing.
    If during the test you want to add any additional information in the file, then this library
    provide a hierarchy of folders and files for logging.
    Folder hierarchy is created as follows: output_dir/test_log_folder_name/Test_Suite/Test_Suite/Test_Case/file.log
    Log files and folders are not removed before the test, and overwritten of new files.
    
     == Dependency: ==
    | robot framework | http://robotframework.org |
    -------
    
    When initializing the library, you can define two optional arguments
    | *Argument Name*      |  *Default value*  | *Description*                                                 |
    | output_dir           |  ${OUTPUT_DIR}    | The directory in which create the folder with additional logs |
    | test_log_folder_name |  Advanced_Logs    | Name of the folder from which to build a hierarchy of logs    |
    -------
    
    == Example: ==
    | *Settings*  |  *Value*           | *Value*  |  *Value*        |
    | Library     |  AdvancedLogging   | C:/Temp  |   LogFromServer |
    | Library     |  SSHLibrary        |          |                 |
    
    | *Test cases*              | *Action*                  | *Argument*             |  *Argument*            |
    | Example_TestCase          | ${out}=                   | Execute Command        |  grep error output.log |
    |                           | Write advanced testlog    | error.log              |  ${out}                |
    =>\n
    File C:/Temp/LogFromServer/TestSuite name/Example_TestCase/error.log  with content from variable ${out}
    """

    ROBOT_LIBRARY_SCOPE='TEST SUITE'

    def __init__(self, output_dir = None, test_log_folder_name = 'Advanced_Logs'):
        self.os=OperatingSystem()
        self.bi=BuiltIn()

        self.output_dir=output_dir
        self.test_log_folder_name=test_log_folder_name
        self.sep='/'

    @property
    def _suite_folder (self):
        """
        Define variables that are initialized by a call 'TestSuite'
        """


        if self.output_dir==None :
            self.output_dir=self.bi.get_variable_value('${OUTPUT_DIR}')

        suite_name=self.bi.get_variable_value('${SUITE_NAME}')
        suite_name=suite_name.replace('.', self.sep)
        self.output_dir=os.path.normpath(self.output_dir)
        self.test_log_folder_name=os.path.normpath(self.test_log_folder_name)

        suite_folder=self.output_dir+self.sep+self.test_log_folder_name+self.sep+suite_name
        return os.path.normpath(suite_folder)

    def Write_Advanced_Testlog (self, filename, content):
        """ 
        Inclusion content in additional log file
        
        Return: path to filename
        
        Example:
        | Write advanced testlog   | log_for_test.log  |  test message |
        =>\n
        File ${OUTPUT_DIR}/Advanced_Logs/<TestSuite name>/<TestCase name>/log_for_test.log with content 'test message'
        """

        test_name=BuiltIn().get_variable_value('${TEST_NAME}')

        if not test_name:
            log_folder=self._suite_folder+self.sep
        else:
            log_folder=self._suite_folder+self.sep+test_name

        self.os.create_file(log_folder+self.sep+filename, content)

        return os.path.normpath(log_folder+self.sep+filename)

    def Create_Advanced_Logdir (self):
        """  
        Creating a folder hierarchy for TestSuite
        
        Return: path to folder
        
        Example:
        | *Settings* | *Value* |
        | Library    |        AdvancedLogging |
        | Library    |       OperatingSystem |
        
        | *Test Cases* | *Action* | *Argument* |
        | ${ADV_LOGS_DIR}=   | Create advanced logdir            |                |
        | Create file        | ${ADV_LOGS_DIR}/log_for_suite.log |   test message |
        =>\n
        File ${OUTPUT_DIR}/Advanced_Logs/<TestSuite name>/log_for_suite.log with content 'test message'
        """

        test_name=self.bi.get_variable_value('${TEST_NAME}')
#.........这里部分代码省略.........
开发者ID:JASON0916,项目名称:robot-framework-library,代码行数:103,代码来源:AdvancedLogging.py

示例5: keywords

# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import get_variable_value [as 别名]
class keywords (object):
    
    def __init__(self, rootDir, envVarDir, templateDir):
        self.robotBuiltIn = BuiltIn()
        self.ybLib = YamlVariablesLibrary.keywords(rootDir, envVarDir)
        self.rootDir = rootDir
        self.envVarDir = envVarDir
        self.templateDir = templateDir
        self.envTemplates = Environment(loader=FileSystemLoader
                                        (templateDir))
        

    def linux_config_check_files(self, environments, applicationGroup=None):
        
        patternRFVar = re.compile(r'''\${(.*?)}''', re.UNICODE|re.VERBOSE|re.S)
        if patternRFVar.search(environments):
            environments = self.robotBuiltIn.get_variable_value(environments)
            environmentList = environments.split(":")
            
            for environment in environmentList:
                _checkerFile.ConfigFileChecker().main(self.rootDir, self.envVarDir, self.templateDir, environment, applicationGroup)
        else:
            _checkerFile.ConfigFileChecker().main(self.rootDir, self.envVarDir, self.templateDir, environments, applicationGroup)
        
    def linux_config_set_variables(self, envConfigFile):

        
        self.envData = (yvLibKeywords._open_yaml_file(os.path.join(self.rootDir, self.envVarDir, envConfigFile)))
        
        self.envGeneratedFilesPath = self._setup_output_folders(os.path.join(GLOBAL_VARIABLES['${OUTPUTDIR}'], "%s_generatedFiles" % envConfigFile))
        self.envServerFilesPath = self._setup_output_folders(os.path.join(GLOBAL_VARIABLES['${OUTPUTDIR}'],"%s_serverFiles" % envConfigFile))
        self.resultFileName = ("%s_result.csv" % envConfigFile)
        self.resultFile = self._setup_output_folders(os.path.join(GLOBAL_VARIABLES['${OUTPUTDIR}'], self.resultFileName))

        os.makedirs(self.envServerFilesPath)
        os.makedirs(self.envGeneratedFilesPath)
        #Global Variables
        #self.envConf = self._set_generic_variables(self.envData['environment']['configuration'])
        #self.envUser = self._set_generic_variables(self.envData['environment']['user'])
        #self.envHomeDir = self._set_generic_variables(self.envData['environment']['homeDir'])
        self.auditUsername = self._set_generic_variables(self.envData['environment']['auditUsername'])       
        self.id = envConfigFile

    def check_environment(self):
        for applicationGroup in self.envData['applicationGroups']:
            self.check_linux_server_commands(applicationGroup)
            for configFileTemplate in self.envData['applicationGroups'][applicationGroup]['configurationFiles']:
                self.check_configuration_file(applicationGroup, configFileTemplate)
        
        self._result_reporter()
        
    def _setup_output_folders(self, path):
        if os.path.exists(path) and os.path.isdir(path):
            shutil.rmtree(path)
        elif os.path.exists(path) and not os.path.isdir(path):
            os.remove(path)
        return path
            
             
    def _set_generic_variables(self,data):
        try:
            value = data
        except Exception, e:
            self.BuiltIn.log(data,e)
        return value
开发者ID:jbarnes007,项目名称:robotframework-linuxcfgtestlibrary,代码行数:67,代码来源:_keywords.py

示例6: keywords

# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import get_variable_value [as 别名]
class keywords (object):

    def __init__(self, baseDir, envDir=None):
        # Get the base working directory
        self.baseDir = baseDir.replace("\\", "/")

        # Get the directory that stores the test environment resources
        if envDir != None:
            self.envDir = envDir.replace("\\", "/")

        # Get an instances of the RF BuildIn Functions
        self.robotBuiltIn = BuiltIn()

    def get_data(self, environments=None):
        # Gets the full location on this file
        self.me = os.path.abspath(__file__)[:-1].replace("\\", "/")
        self.robotBuiltIn.log("File Path: %s" % self.me)

        # Gets the current test suite source
        suiteSource = self.robotBuiltIn.get_variable_value('${SUITE SOURCE}').replace("\\", "/")
        charPos = len(suiteSource) - suiteSource.rfind("/")
        # Removes the last \\ from the suite source
        suiteSourceDir = suiteSource[:-charPos]
        self.robotBuiltIn.log("Suite Directory: %s" % suiteSourceDir)

        # Gets the current test name
        testCaseName = self.robotBuiltIn.get_variable_value('${TEST_NAME}')
        suiteKey = self._get_suite_key()

        # If testCaseName is none, then set suite and environment variables
        if testCaseName == None:
            self.robotBuiltIn.log("Test Case Name is None")

            # Gets the environment level variables
            if environments != None:
                self.robotBuiltIn.log("Environment variable has been passed")

                # Get the environment value if a RF variable has been passed
                patternRFVar = re.compile(r'''\${(.*?)}''', re.UNICODE |
                                                            re.VERBOSE |
                                                            re.S)
                if patternRFVar.search(environments):
                    self.robotBuiltIn.log("Environment variable is a RF variable")
                    environments = self.robotBuiltIn.get_variable_value(environments)

                # Split the env string to get each env that was passed
                envList = environments.split(":")

                # Read the contents of each env yaml and create the variables
                for envFile in envList:
                    self.robotBuiltIn.log("Importing Environment Variables for: %s" % envFile)
                    varFile = os.path.join(self.baseDir, self.envDir, envFile).replace("\\", "/")
                    self.robotBuiltIn.import_variables(self.me, varFile, "env")

            # Gets the suite test data variables and imports variables
            varFile = os.path.join(suiteSourceDir, suiteKey).replace("\\", "/")
            if suiteKey != None:
                self.robotBuiltIn.log("Trying to import suite variables: %s" % varFile)
                if os.path.isfile(varFile + ".yaml"):
                    self.robotBuiltIn.log("File found, importing.")
                    self.robotBuiltIn.import_variables(self.me, varFile)
                else:
                    self.robotBuiltIn.log("File not found. Not importing.")

        # if testCaseName is not none, then set test case variables
        if testCaseName != None:

            # Gets the test case data variables and imports variables
            testKey = self._get_test_key()
            #varFile = (suiteSourceDir + "/" + suiteKey + "-" + testKey)
            varFile = (suiteSourceDir + "/" + testKey)
            print varFile
            if testKey != None:
                if os.path.isfile(varFile + ".yaml"):
                    self.robotBuiltIn.import_variables(self.me, varFile)

    def get_data_service(self, keyword):
        keywordArray = keyword.split("|")
        print keywordArray
        keywordArrayLen = len(keywordArray)
        #print keywordArrayLen
        if keywordArrayLen == 1:
            runKeyword = keywordArray[0]
        else:
            runKeyword = keywordArray.pop(0)

        result = self.robotBuiltIn.run_keyword_and_ignore_error('Keyword Should Exist', runKeyword)
        if result[0] == 'PASS':
            if keywordArrayLen == 1:
                # Gets the return value from the keyword
                testData = self.robotBuiltIn.run_keyword_and_ignore_error(runKeyword)
            else:
                # Gets the return value from the keyword
                testData = self.robotBuiltIn.run_keyword_and_ignore_error(runKeyword, *keywordArray)

        # Run if the keyword runs to PASS and has returned values
        if testData[0] == 'PASS' and testData[1] != None:
            for key, value in testData[1].items():
                variableName = ("${%s}" % key)
                # If the variable is not set the set the variable
#.........这里部分代码省略.........
开发者ID:jbarnes007,项目名称:robotframework-yamlvariableslibrary,代码行数:103,代码来源:_keywords.py

示例7: get_variables

# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import get_variable_value [as 别名]
def get_variables(testDataFile, testDataFileType="local"):
    robotBuiltIn = BuiltIn()
    #oraConnection = OracleLibrary.keywords()

    robotBuiltIn.log("Importing Data File: %s" % testDataFile)

    if testDataFileType == "env":
        envData = _open_yaml_file(testDataFile)
        variables = {}

        # Following Code adds the servers from each group to the Global Variables DICT
        if "applicationGroups" in envData:
            for applicationGroup in envData['applicationGroups'].keys():
                variables["LIST__" + applicationGroup] = envData['applicationGroups'][applicationGroup]['servers'].keys()
                for value, server in enumerate(envData['applicationGroups'][applicationGroup]['servers'].keys()):
                    variables[applicationGroup + str(value)] = server

        # The following Code will parse for environment variables and it them to the Global Variables DICT
        if "environment" in envData:
            for envVarKey, envVarValue in envData['environment'].items():
                if isinstance(envVarValue, basestring) or isinstance(envVarValue, dict):
                    variables[envVarKey] = envVarValue
                if isinstance(envVarValue, list):
                    variables["LIST__" + envVarKey] = envVarValue

    else:
        variables = _open_yaml_file(testDataFile)
        patternSQL = re.compile(r'''^SELECT(.+?)WHERE''', re.UNICODE |
                                                          re.VERBOSE)

        patternRFVar = re.compile(r'''\${(.*?)}''', re.UNICODE |
                                                    re.VERBOSE |
                                                    re.S)

        patternRFKeyword = re.compile(r'''\Get.Data''', re.UNICODE |
                                                        re.VERBOSE)

        for key, item in variables.items():

            """
            THIS CODE IS USED FOR SQL EXECUTION.
            DUE TO CROSS PLATFORM ISSUES THIS HAS BEEN DISABLED.

            if isinstance(item, list):
                dbName = item[0]
                dbQuery = item[1]

                if patternSQL.match(dbQuery): # If an SQL pattern is found, then run it to get the data
                    if patternRFVar.search(dbQuery):
                        for match in patternRFVar.finditer(dbQuery):
                            rfVarValue = robotBuiltIn.get_variable_value(match.group(0))
                            dbQuery = dbQuery.replace(match.group(0), rfVarValue)

                    result = oraConnection.ora_execute_sql(dbQuery, dbName)

                    if isinstance(result, basestring):
                        variables[key] = result

                    if isinstance(result, list):
                        del variables[key] # Delete the key from the dict
                        listKey = "LIST__" + key # Create a new key with LIST__ at the front

                        # The returned result set from the oracle query is not in the correct format
                        # The below code corrects the format.
                        resultList = []
                        for resultLine in result:
                            for resultLineItem in resultLine:
                                resultList.append(resultLineItem)

                        variables[listKey] = resultList # Updates the dict with the results and new key value
            """
            if isinstance(item, basestring):
                if patternRFVar.search(item):
                    rfVar = patternRFVar.search(item).group()
                    rfVarValue = robotBuiltIn.get_variable_value(rfVar)
                    variables[key] = item.replace(rfVar, rfVarValue)
                    item = variables[key]

                if patternRFKeyword.match(item):
                    itemList = item.split("|")
                    keywordName = itemList[0]
                    itemList.pop(0)
                    itemListLen = len(itemList)

                    if itemListLen == 0:
                        results = robotBuiltIn.run_keyword(keywordName)
                    else:
                        results = robotBuiltIn.run_keyword(keywordName, *itemList)

                    if isinstance(results, basestring):
                        variables[key] = results

                    if isinstance(results, list):
                        del variables[key]
                        listKey = "LIST__" + key
                        variables[listKey] = results

    return variables
开发者ID:jbarnes007,项目名称:robotframework-yamlvariableslibrary,代码行数:100,代码来源:_keywords.py

示例8: keywords

# 需要导入模块: from robot.libraries.BuiltIn import BuiltIn [as 别名]
# 或者: from robot.libraries.BuiltIn.BuiltIn import get_variable_value [as 别名]
class keywords(object):

    def __init__(self):
        """
        """
        self._connection = None
        self._default_log_level = 'INFO'
        self._bexception = False
        self.robotBuiltIn = BuiltIn()

    def _ora_connect(self, dbName):
        """
        """   
        connectionSettings = self.robotBuiltIn.get_variable_value("${" + dbName + "}")
    
        if connectionSettings == None:
            self.robotBuiltIn.log((("No database connection configured for %s") % (dbName)), "WARN")
            return 99
        else:
            if connectionSettings["dbConnectionType"].upper() == "SID":
                dbTns = DB.makedsn(connectionSettings["dbServerName"], 
                                   connectionSettings["dbServerPort"],
                                   connectionSettings["dbServerId"])
                
            elif connectionSettings["dbConnectionType"].upper() == "SERVICE":
                dbTns = (("%s:%s/%s") % (connectionSettings["dbServerName"], 
                                         connectionSettings["dbServerPort"],
                                         connectionSettings["dbServerId"]))                
            else:
                self.robotBuiltIn.fail((("Unknown connection type configured for %s. Only SID & SERVICE types are supported.") % (dbName)))
                
            connString = (("%s/%[email protected]%s") % (connectionSettings["dbUsername"], 
                                          connectionSettings["dbPassword"], 
                                          dbTns))
            
            return self.ora_make_connection(connString)
        
        
    def ora_make_connection(self, sConnString):
        """
        """
        sConn = None
        try:
            sConn = DB.connect(sConnString )
        except Exception:
            self._bexception = True
            print 'Connection for database has failed', Exception, sConnString
            raise 
        finally:
            self._connection = sConn
        
        return sConn

    def ora_execute_sql (self, sSql=None, sServerId=None):
        """
        """
        if sServerId <> None:
            self._ora_connect(sServerId)
            
        sOut = None
        sCursor = None
        sConn = self._connection
        print sConn
        
        if (sConn == None) :
            return sOut
        else:
            try:
                sCursor = sConn.cursor()
                sCursor.execute(sSql)
                sOut = sCursor.fetchall()                   
                return sOut
            
            except Exception, err:
                raise Exception (('Query execution failed. %s') % (err))
            finally:
开发者ID:jbarnes007,项目名称:robotframework-oraclelibrary,代码行数:78,代码来源:_keywords.py


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