Ejemplo n.º 1
0
    def __init__(self, name, librarys=["SeleniumLibrary"]):
        # 创建测试套件
        self.suite = TestSuite(name)

        # 导入SeleniumLibrary
        for lib in librarys:
            self.suite.resource.imports.library(lib)
Ejemplo n.º 2
0
 def start_suite(self, suite):
     if self.state_tags is None:
         # We don't have Mongo db connection do fatal error
         fail_suite = TestSuite(name='Fatal error')
         tc_fatal_error = fail_suite.tests.create("Fatal MongoDB error")
         tc_fatal_error.keywords.create(
             'Fatal error',
             args=[
                 "RPA Mongodb Server not available or authentication failed. Please check connection parameters."
             ])
         suite.tests.insert(0, tc_fatal_error)
     else:
         # Remove tasks from suite based on RPA status (which was already executed in other robot run)
         filtered_tests = []
         for test in suite.tests:
             remove_test = False
             for tag in self.state_tags:
                 if tag in test.tags:
                     remove_test = True
                     break
             if not remove_test:
                 filtered_tests.append(test)
         suite.tests = filtered_tests
         # Add task to setup robot data in begin of suite
         rpa_suite = TestSuite(name='Rpa data')
         tc_rpa_data = rpa_suite.tests.create("Get data from database")
         tc_rpa_data.keywords.create('Setup data',
                                     args=[self.runid, self.robotname])
         suite.tests.insert(0, tc_rpa_data)
Ejemplo n.º 3
0
def _start_server(interface, server_conf, robot_conf):
    suite = TestSuite('RFServer', rpa=True)
    suite.resource.imports.library('RFServer', args=[interface, server_conf])
    test = suite.tests.create('RFserver Task')

    if version.parse(VERSION) < version.parse('4.0.0'):
        test.keywords.create('RFServer.Main Loop')
    else:
        test.body.create_keyword('RFServer.Main Loop')
    suite.run(**robot_conf)
Ejemplo n.º 4
0
def random_walker(file_path, coverage, walk_path=None):
    # 初始化robot suite
    test_suite_name = os.path.basename(file_path).split('.')[0]
    suite = TestSuite(test_suite_name)
    suite.resource.imports.library('ApolloLibrary')

    g = graphml.read_graphml(file_path)
    e = [e for e in g.edges_iter()]
    n = [n for n in g.node]
    edges = g.edge
    nodes = g.node
    now_coverage = 0
    exec_paths = []

    while now_coverage < coverage:
        curr_path = []
        node = 'n0'
        while g.successors(node):
            if len(g.successors(node)) > 0 and node == 'n0':
                curr_path.append('n0')
                node = g.successors(node)[int(random.uniform(0, len(g.successors(node))))]
                curr_path.append(node)
            elif len(g.successors(node)) > 0 and node != 'n0':
                prev_node = curr_path[-2]
                node = g.successors(node)[int(random.uniform(0, len(g.successors(node))))]
                if node == prev_node:
                    break
                curr_path.append(node)
            elif len(g.successors(node)) == 0:
                break
        exec_paths.append(curr_path)
        if len(exec_paths) > 1:
            exec_paths = sorted(exec_paths)
            exec_paths = [exec_paths[i] for i in range(len(exec_paths)) if i == 0 or exec_paths[i] != exec_paths[i - 1]]
            curr_nodes = list(set([item for sub_list in exec_paths for item in sub_list]))
            now_coverage = float(len(curr_nodes)) / float(len(n)) * 100

    # 整合成robot suite
    if walk_path is None:
        for exec_path in exec_paths:
            generate_suite(suite, nodes, edges, exec_path)
    else:
        sorted_path = []
        for path in walk_path:
            temp = path.replace('[', '').replace(']', '').replace(',', '')
            sorted_path.append(temp)
        generate_suite(suite, nodes, edges, sorted_path)

    # 运行suite并回收报告
    suite.run(output='results/{}.xml'.format(test_suite_name))
    xml_files = [join('results/', f) for f in os.listdir('results/') if isfile(join('results/', f))]
    ResultWriter(*xml_files) \
        .write_results(log='reports/{}_log.html'.format(test_suite_name)
                       , report='reports/{}_report.html'.format(test_suite_name)
                       , output='reports/{}_output.xml'.format(test_suite_name))
Ejemplo n.º 5
0
def _build_rf_suite(datasources, settings, tests):
    parent_suite = TestSuite(datasources[0])
    rf_test_to_actual = {}
    current_suite = parent_suite
    for actual_test, module_name in tests:
        if current_suite.name != module_name:
            current_suite = parent_suite.suites.create()
            current_suite.name = module_name
        rf_test = current_suite.tests.create()
        rf_test.name = actual_test.__name__
        rf_test.tags = actual_test.tags
        rf_test_to_actual[rf_test] = actual_test
    parent_suite.configure(**settings.suite_config)
    return rf_test_to_actual, parent_suite
Ejemplo n.º 6
0
class BaiduSearchTest():
    def __init__(self, name, librarys=["SeleniumLibrary"]):
        # 创建测试套件
        self.suite = TestSuite(name)
        # 导入SeleniumLibrary
        for lib in librarys:
            self.suite.resource.imports.library(lib)

    # 定义变量
    def create_variables(self):
        variables = {
            "${baidu}": "https://www.baidu.com",
            "${browser}": "Chrome",
            "${search_input}": "id=kw",
            "${search_btn}": "id=su"
        }
        for k, v in variables.items():
            self.suite.resource.variables.create(k, v)

    # 测试用例:启动浏览器
    def open_browsers(self):
        test_01 = self.suite.tests.create("Open")
        test_01.keywords.create("Open Browser",
                                args=["${baidu}", "${browser}"])
        test_01.keywords.create("Title Should Be", args=[u"百度一下,你就知道"])

    # 测试用例:百度搜索测试
    def search_word(self):
        test_02 = self.suite.tests.create(u"百度搜索测试")
        test_02.keywords.create("Input Text",
                                args=["${search_input}", u"测试教程网"])
        test_02.keywords.create("Click Button", args=["${search_btn}"])
        test_02.keywords.create("Sleep", args=["5s"])

    # 测试用例:断言验证搜索结果标题
    def assert_title(self):
        test_03 = self.suite.tests.create(u"断言验证搜索结果标题")
        test_03.keywords.create("Title Should Be", args=[u"测试教程网_百度搜索"])

    # 测试用例:关闭测试用例
    def close_browsers(self):
        test_04 = self.suite.tests.create("Close")
        test_04.keywords.create("Close All Browsers")

    # 运行
    def run(self):
        self.create_variables()
        self.open_browsers()
        self.search_word()
        self.assert_title()
        self.close_browsers()

        # 运行套件
        result = self.suite.run(critical="find_baidu",
                                output=os.getcwd() + "/tempfile/output.xml")

        # 生成日志、报告文件
        ResultWriter(result).write_results(
            report=os.getcwd() + "/tempfile/report.html",
            log=os.getcwd() + "/tempfile/log.html")
Ejemplo n.º 7
0
    def end_suite(self, suite: TestSuite) -> None:
        """Removing test suites that are empty after excluding tests that are not part of the TestRail test run.

        *Args:*\n
            _suite_ - Robot Framework test suite object.
        """
        suite.suites = [s for s in suite.suites if s.test_count > 0]
        if not suite.suites:
            self._log_to_parent_suite(suite, "No tests to execute after using TestRail pre-run modifier.")
Ejemplo n.º 8
0
class BaiduSerachTest:
    def __init__(self, name, librarys=["SeleniumLibrary"]):
        # 创建测试套件
        self.suit = TestSuite(name)
        # 导入支持库
        for lib in librarys:
            self.suit.resource.imports.library(lib)

    # 创建变量
    def create_variables(self):
        variables = {
            "${baidu}": "http://www.baidu.com",
            "${browser}": "Chrome",
            "${searchWord}": "Python",
            "${search_input}": "id=kw",
            "${search_btn}": "id=su"
        }
        for k, v in variables.items():
            self.suit.resource.variables.create(k, v)

    # 创建测试用例:启动浏览器
    def open_browsers(self):
        test_01 = self.suit.tests.create("启动浏览器")
        test_01.keywords.create("Open Browser",
                                args=["${baidu}", "${browser}"])
        test_01.keywords.create("Title Should Be", args=["百度一下,你就知道"])

    # 创建测试用例:搜索测试
    def search_word(self):
        test_02 = self.suit.tests.create("关键字搜索测试")
        test_02.keywords.create("Input Text",
                                args=["${search_input}", "${searchWord}"])
        test_02.keywords.create("Click Button", args=["${search_btn}"])
        test_02.keywords.create("Sleep", args=["5s"])

    # 创建测试用例:断言
    def assert_title(self):
        test_03 = self.suit.tests.create("断言验证搜索结果页标题")
        test_03.keywords.create("Title should be", args=["Python_百度搜索"])

    # 创建测试用例:关闭
    def close_browsers(self):
        test_04 = self.suit.tests.create("关闭浏览器")
        test_04.keywords.create("Close All Browsers")

    # 运行
    def run(self):
        self.create_variables()
        self.open_browsers()
        self.search_word()
        self.assert_title()
        self.close_browsers()
        # 运行套件
        result = self.suit.run(critical="百度搜索", output="output3.xml")
        ResultWriter(result).write_results(report="report3.html",
                                           log="log3.html")
Ejemplo n.º 9
0
def try_to_run_it(suite):
    print "here we go!"

    # create a test suite object
    from robot.api import TestSuite
    suite = TestSuite('Autogenerated Suite')

    for testcase in suite.testcases:
        import pdb
        pdb.set_trace()
Ejemplo n.º 10
0
class BaiduTest(object):
    def __init__(self, name, librarys=['SeleniumLibrary']):
        #创建测试套件
        self.suite = TestSuite(name)

        #导入seleniumlibrary
        for lib in librarys:
            self.suite.resource.imports.library(lib)

    def create_variables(self):
        variables = {
            "${baidu}": "http://www.baidu.com",
            "${browser}": "Chrome",
            "${search_input}": "id = kw",
            "${search_btn}": "id = su"
        }
        for k, v in variables.items():
            self.suite.resource.variables.create(k, v)

    #测试用例
    def open_browser(self):
        test_01 = self.suite.tests.create('启动浏览器')
        test_01.keywords.create("Open Browser",
                                args=["${baidu}", "${browser}"])
        test_01.keywords.create('Title Should Be', args=['百度一下,你就知道'])

    def search_words(self):
        test_02 = self.suite.tests.create('百度搜索测试')
        test_02.keywords.create("Input Text",
                                args=["${search_input}", "测试教程网"])
        test_02.keywords.create("Click Button", args=["${search_btn}"])
        test_02.keywords.create("Sleep", args=['5s'])

    def assert_title(self):
        test_03 = self.suite.tests.create('断言结果')
        test_03.keywords.create("Title Should Be", args=["测试教程网_百度搜索"])

    def close_browsers(self):
        test_04 = self.suite.tests.create("关闭浏览器")
        test_04.keywords.create("Close All Browsers")
        test_04.keywords.create("Sleep", args=['5s'])

    def run(self):
        self.create_variables()
        self.open_browser()
        self.search_words()
        self.assert_title()
        self.close_browsers()

        # 运行套件
        result = self.suite.run(critical="百度搜索", output="output.xml")

        # 生成日志、报告文件
        ResultWriter(result).write_results(report="report.html",
                                           log="log.html")
Ejemplo n.º 11
0
def addTestSuite(name):
    """ Initialize Robot test suite object """
    global suite
    suite = TestSuite("name")
    suite.resource.imports.resource("browser.robot")

    robotfile.append("*** Generated from fMBT ***")
    robotfile.append("*** Settings ***")
    robotfile.append("Resource  browser.robot")
    robotfile.append("")
    robotfile.append("*** Test Cases ***")
Ejemplo n.º 12
0
def find_tests(reference, test_suite):

    model = get_model(reference)
    data = TestSuite.from_model(model)

    test_suite[data.name] = []
    for test_case in data.tests:
        test_suite[data.name].append({'test_name': test_case,
                                      'test_source': data.source})
    for child_data in data.suites:
        find_tests(child_data, test_suite)
    return test_suite
Ejemplo n.º 13
0
    def start_suite(self, suite: TestSuite) -> None:
        """Form list of tests for the Robot Framework test suite that are included in the TestRail test run.

        If analysis depth of the run results is greater than zero, when first suite is launched
        a list of 'testrailid' tags of stable test cases is obtained.
        After that the list of tags is written to the class attribute and for subsequent suites the obtaining is not happening.

        If analysis depth of the run results is zero, when the first suite is launched
        a list of 'testrailid' tags of all test cases in the given status is obtained.
        After that the list of tags is written to the class attribute and for subsequent suites the obtaining is not happening.

        *Args:*\n
            _suite_ - Robot Framework test suite object.
        """
        tests = suite.tests
        suite.tests = None
        try:
            if self.results_depth > 0:
                suite.tests = [t for t in tests if (set(t.tags) & set(self.tr_stable_tags_list))]
            else:
                suite.tests = [t for t in tests if (set(t.tags) & set(self.tr_tags_list))]
        except (RequestException, TimeoutError) as error:
            self._log_to_parent_suite(suite, str(error))
Ejemplo n.º 14
0
	def run(self):		
		if options.verbose: print " @@@ in SoapUIRunner (%s) @@@ " % self.file
		
		rc = 0
		if not options.batch:
			os.putenv('DB_PROPERTIES',db_prop)
			rc = loader.run_makesuds(self.file)
			
		else:
			from robot.api import TestSuite, TestSuiteBuilder
			suite = TestSuite(str(self))
			suite.imports.resource("common_resource.txt")
			suite.imports.library("generic_testloader")
			t = suite.tests.create(name=self.name)
			t.keywords.create("Set Environment Variable", args=["NO_SOAPUI_REPORT","1"])
			t.keywords.create("Set Environment Variable", args=["SOAPUI_LOGSDIR",os.getenv('ROBOT_REPORTDIR')+'/'+self.name+'/'+'SOAPUI_LOGS'])
			t.keywords.create("Set Environment Variable", args=["DB_PROPERTIES",db_prop])
			t.keywords.create("Run Makesuds", args=[self.file])
			t.keywords.create("Soapui Project Passed", args=[os.getenv('ROBOT_REPORTDIR')+'/'+self.name+'/'+'SOAPUI_LOGS/soapui-errors.log']) # dirty hack since create doesn't expand vars
			rc = suite.run(loglevel=os.getenv('ROBOT_SYSLOG_LEVEL'), outputdir=os.path.join(os.getenv('ROBOT_REPORTDIR'),self.name))
			#debugfile=os.getenv('ROBOT_DEBUGFILE')
			rc = rc.return_code		
		return rc		
Ejemplo n.º 15
0
	def run(self):
		if options.verbose: print " @@@ in PyBotRunner (%s) @@@ " % self.file	

		rc = 0
		if not options.batch:
			os.putenv('DB_PROPERTIES',db_prop)
			try:
				rc = loader.run_pybot(self.file)
			except AssertionError: 
				rc = 1
				
		else:
			from robot.api import TestSuite, TestSuiteBuilder
			suite = TestSuite(str(self))
			suite.imports.resource("common_resource.txt")
			suite.imports.library("generic_testloader")
			t = suite.tests.create(name=self.name)
			t.keywords.create("Set Environment Variable", args=["DB_PROPERTIES",db_prop])
			t.keywords.create("Run Pybot", args=[self.file])			
			rc = suite.run(loglevel=os.getenv('ROBOT_SYSLOG_LEVEL'), outputdir=os.path.join(os.getenv('ROBOT_REPORTDIR'),self.name))
			#debugfile=os.getenv('ROBOT_DEBUGFILE')
			rc = rc.return_code		
		return rc
Ejemplo n.º 16
0
	def run(self):
		if options.verbose: print " @@@ in ContainerRunner (%s) @@@ " % self.file	
		
		rc = 0
		if not options.batch:
			for r in self.runners:
				if r.run()==1: 
					rc=1
					break 

		else:
			from robot.running import TestSuite, TestSuiteBuilder
			suite = TestSuite(str(self))
			suite.imports.resource("common_resource.txt")
			suite.imports.library("generic_testloader")
			t = suite.tests.create(name=self.name)
			
			for r in self.runners:
				if isinstance(r,RobotRunner):
					t.keywords.create("Run Pybot", args=[r.file])	
					t.keywords.create("Set Environment Variable", args=["DB_PROPERTIES",db_prop])
				
				elif isinstance(r,PyTestRunner):
					t.keywords.create("Set Environment Variable", args=["SCREENSHOT_DIR",os.getenv('ROBOT_REPORTDIR')+'/'+'SEL-SCREENSHOTS'])
					t.keywords.create("Set Environment Variable", args=["DB_PROPERTIES",db_prop])
					t.keywords.create("Run Pytest", args=[r.file])
				
				elif isinstance(r,SoapUIRunner):
					t.keywords.create("Set Environment Variable", args=["NO_SOAPUI_REPORT","1"])
					t.keywords.create("Set Environment Variable", args=["SOAPUI_LOGSDIR",os.getenv('ROBOT_REPORTDIR')+'/'+r.name+'/'+'SOAPUI_LOGS'])
					t.keywords.create("Set Environment Variable", args=["DB_PROPERTIES",db_prop])
					t.keywords.create("Run Makesuds", args=[r.file])
					t.keywords.create("Soapui Project Passed", args=[os.getenv('ROBOT_REPORTDIR')+'/'+r.name+'/'+'SOAPUI_LOGS/soapui-errors.log']) # dirty hack since create doesn't expand vars
			
			rc = suite.run(loglevel=os.getenv('ROBOT_SYSLOG_LEVEL'), outputdir=os.path.join(os.getenv('ROBOT_REPORTDIR'),r.name)) #debugfile=os.getenv('ROBOT_DEBUGFILE') XXX not working ???
			rc = rc.return_code		
		return rc	
Ejemplo n.º 17
0
def find_tests(reference, test_suite):

    model = get_model(reference)
    data = TestSuite.from_model(model)

    test_suite[data.name] = []
    # data.tests is a list
    for test_case in data.tests:  # pylint: disable=E1133
        test_suite[data.name].append({
            'test_name': test_case,
            'test_source': data.source
        })

    # data.suites is a list
    for child_data in data.suites:  # pylint: disable=E1133
        find_tests(child_data, test_suite)
    return test_suite
Ejemplo n.º 18
0
class LowLevelTest(TestCase):

    @classmethod
    def setUpClass(cls):
        cls.settings = {'log_level': logging.DEBUG}

    def setUp(self):
        self.suite = TestSuite('Test low level keywords')
        self.suite.resource.imports.library('VnfValidator')

    def tearDown(self):
        pass

    def test__set_context__pass(self):
        tests = [
            Keyword(name=u'Set application context to node_1'),
            Keyword(name=u'Set network context to node_1'),
            Keyword(name=u'Set node context to node_1'),
            Keyword(name=u'Set service context to node_1'),
        ]

        with patch('DockerController.DockerController') as mock_controller:
            mock_controller = MagicMock(DockerController)
            run_keyword_tests(test_instance=self, tests=tests, expected_result=Result.PASS)

    def test__set_context__wrong_context_type__fail(self):
        test = self.suite.tests.create(name=u'Test context')

        test.keywords.append(Keyword(name=u'Set app context to bla'))
        result = self.suite.run()

        self.assertIn("Invalid context given", result.suite.tests[0].message)

    def test__port__pass(self):
        self.suite.keywords.append(Keyword(name='Set network context to node_1', type='setup'))

        tests = [
            Keyword(name=u'Port 80: state is open'),
            Keyword(name=u'Port 80/TCP: state is open'),
            Keyword(name=u'Port 80/UDP: state is open'),
            Keyword(name=u'Port 80/UDP: state is closed'),
        ]
        run_keyword_tests(test_instance=self, tests=tests, expected_result=Result.PASS)

    def test__port__invalid_property__fail(self):
        self.suite.keywords.append(Keyword(name='Set network context to node_1', type='setup'))

        tests = [
            Keyword(name=u'Port 80: stateful is open'),
        ]
        with patch('ValidationTargets.port.exc.SetupError.ROBOT_EXIT_ON_FAILURE', False):
            run_keyword_tests(test_instance=self, setup=None, tests=tests, expected_result=Result.FAIL,
                              expected_message=u'ValidationError: Property')

    def test__port__invalid_port__fail(self):
        self.suite.keywords.append(Keyword(name='Set network context to node_1', type='setup'))

        tests = [
            Keyword(name=u'Port abc: stateful is open'),
            Keyword(name=u'Port abc: stateful is open'),
        ]
        with patch('ValidationTargets.port.exc.SetupError.ROBOT_EXIT_ON_FAILURE', False):
            run_keyword_tests(test_instance=self, setup=None, tests=tests, expected_result=Result.FAIL,
                              expected_message=u'ValidationError: Port')

    def test__port__invalid_value__fail(self):
        self.suite.keywords.append(Keyword(name='Set network context to node_1', type='setup'))

        tests = [
            Keyword(name=u'Port 80: state is openedd'),
        ]
        with patch('ValidationTargets.port.exc.SetupError.ROBOT_EXIT_ON_FAILURE', False):
            run_keyword_tests(test_instance=self, setup=None, tests=tests, expected_result=Result.FAIL,
                              expected_message=u'ValidationError: Value')
Ejemplo n.º 19
0
from robot.api import TestSuite
from robot.api import ResultWriter
from robot.reporting.resultwriter import Results

suite = TestSuite('I am Test Suite')

#TODO: import python module
suite.imports.library('lib.py')


test_case = suite.tests.create('Should Activate Skynet', tags=['smoke'])


kw = test_case.keywords.create(assign=['${var}'], name='Set Variable', args=['value in variable'])
kw2 = test_case.keywords.create('log', args=['this is my first robot python case'])

result = suite.run(critical='smoke', dryrun = 'dryrun',output='skynet.xml')
'''
<class 'robot.result.executionresult.Result'>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', 
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 
'_stat_config', '_status_rc', 'configure', 'errors', 'generated_by_robot', 'handle_suite_teardown_failures', 'return_code', 'save', 'source', 'statistics', 'suite', 'visit']
'''

#result = suite.run()

assert result.return_code == 0

# Report and xUnit files can be generated based on the  result object.
ResultWriter(result).write_results(report='report.html', log='log.html')
Ejemplo n.º 20
0
class CRM_add_areaTest:
    def __init__(self, name, librarys=["SeleniumLibrary"]):
        # 创建测试套件
        self.suite = TestSuite(name)
        # 导入SeleniumLibrary
        for lib in librarys:
            self.suite.resource.imports.library(lib)

    # 定义变量
    def create_variables(self):
        variables = {
            "${CRM}": "https://crm.kemai.com.cn",
            "${browser}": "Chrome",
            "${login1_input}": "name=user_name",
            "${login2_input}": "name=password",
            "${login_btn}": "class=loginBut",
            "${ziliao_element}": "xpath=//*[.='资料']",
            "${area_element}": "xpath=//*[.='区域信息']",
            "${area_add_btn}": "id=area_add",
            "${area_name_input}":
            "xpath=//div[@class='form-body']/div[2]/div/input",
            "${area_save_btn}": "xpath=//*[.='保存']",
            "${area_add_result}": "class=km-modal-dialog-msg"
        }
        for k, v in variables.items():
            self.suite.resource.variables.create(k, v)

    # 测试用例:启动浏览器
    def open_browsers(self):
        test_01 = self.suite.tests.create("启动浏览器")
        test_01.keywords.create("Open Browser", args=["${CRM}", "${browser}"])
        test_01.keywords.create("Title Should Be", args=["科脉慧猿CRM"])

    # 测试用例:慧猿CRM登录
    def login(self):
        test_02 = self.suite.tests.create("慧猿CRM登录测试")
        test_02.keywords.create("Input Text",
                                args=["${login1_input}", "769316"])
        test_02.keywords.create("Input Text",
                                args=["${login2_input}", "crm666"])
        test_02.keywords.create("Click Button", args=["${login_btn}"])
        test_02.keywords.create("Sleep", args=["3s"])

    # 测试用例:断言验证搜索结果标题
    def assert_title(self):
        test_03 = self.suite.tests.create("断言验证登录结果标题")
        test_03.keywords.create("Title Should Be", args=["科脉慧猿CRM-首页"])

    # 测试用例:新增区域
    def add_area(self):
        test_04 = self.suite.tests.create("新增区域")
        test_04.keywords.create("Sleep", args=["5s"])
        test_04.keywords.create("Click element", args=["${ziliao_element}"])
        test_04.keywords.create("Sleep", args=["3s"])
        test_04.keywords.create("Click element", args=["${area_element}"])
        test_04.keywords.create("Sleep", args=["3s"])
        test_04.keywords.create("Click Button", args=["${area_add_btn}"])
        test_04.keywords.create("Sleep", args=["3s"])
        test_04.keywords.create("Input Text",
                                args=["${area_name_input}", "测试robot"])
        test_04.keywords.create("Click Button", args=["${area_save_btn}"])
        test_04.keywords.create("Sleep", args=["3s"])

    # 测试用例:断言验证新增区域结果
    def assert_result(self):
        test_05 = self.suite.tests.create("断言验证新增区域结果")
        test_05.keywords.create("Page Should Contain Button", args=["确定"])

    # 测试用例:关闭测试用例
    def close_browsers(self):
        test_06 = self.suite.tests.create("关闭浏览器")
        test_06.keywords.create("Close All Browsers")

    # 运行
    def run(self):
        self.create_variables()
        self.open_browsers()
        self.login()
        self.assert_title()
        self.add_area()
        self.assert_result()
        self.close_browsers()

        # 运行套件
        result = self.suite.run(critical="登录测试", output="output.xml")

        # 生成日志、报告文件
        ResultWriter(result).write_results(report="report.html",
                                           log="log.html")
Ejemplo n.º 21
0
 def __init__(self):
     self.suite = TestSuite()
     librarys = ["Selenium2Library"]
     for lib in librarys:
         self.suite.resource.imports.library(lib)
Ejemplo n.º 22
0
#-*- coding:utf-8 -*-#-*- coding:utf-8 -*-
from robot.api import TestSuite
from robot.api import ResultWriter

if __name__ == '__main__':
    print("robot framework实例")

    # 创建套件
    suite = TestSuite("搜索测试套件")
    # 导入seleniumLibrary库
    suite.resource.imports.library("SeleniumLibrary")

    # 以下是测试步骤
    # 创建测试用例:启动浏览器
    test_01 = suite.tests.create("启动浏览器")
    test_01.keywords.create("Open Browser",
                            args=["http://www.baidu.com", "Chrome"])
    test_01.keywords.create("Title Should Be",
                            args=["百度一下,你就知道"])

    # 创建测试用例:搜索测试
    test_02 = suite.tests.create("关键字搜索测试")
    test_02.keywords.create("Input Text",
                            args=["id=kw","Python"])
    test_02.keywords.create("Click Button",
                            args=["id=su"])
    test_02.keywords.create("Sleep", args=["5s"])

    # 创建测试用例:断言验证搜索结果页标题
    test_03 = suite.tests.create("断言验证搜索结果页标题")
    test_03.keywords.create("Title should be",
Ejemplo n.º 23
0
def read_feature(filename):
    print '=' * 78
    print 'Parsing feature: %s' % filename
    print '=' * 78
    keywords = []

    file_feature = os.path.splitext(os.path.basename(filename))[0]
    my_resource = filename.replace('.feature', '.txt')

    if not os.path.exists(my_resource):
        my_resource = filename.replace('.feature', '.html')
        if not os.path.exists(my_resource):
            print "\033[1;31;40mWARNING:\033[1;37;40m No resource file for this feature (%s.[txt|html])\033[0m" % file_feature
            my_resource = None

    suite = TestSuite(file_feature)
    suite.imports.library('OperatingSystem')

    if my_resource:
        #print 'Found keywords:'
        resource = ResourceFile(my_resource).populate()
        for k in resource.keywords:
            #print ' %s' % k.name
            keywords.append(k.name.lower())

        suite.imports.resource(my_resource)
        #print '-' * 78
    #else:
    #    resource = ResourceFile(filename.replace('.feature', '.html' ))

    #print keywords

    in_scenario = False
    lineno = 0
    cnt_steps = 0
    undefined_steps = []

    f = open(filename, 'r')
    for line in f:
        lineno += 1
        if line.strip():
            l = line.strip()
            if line[:8] == 'Feature:':
                print "\033[1;37;40m%s\033[0m" % line.rstrip()

            elif l[:9] == 'Scenario:':
                print "\033[1;37;40m%s\033[0m" % line.rstrip()
                current_scenario = l[9:].strip()
                test = suite.tests.create(current_scenario)
                in_scenario = True

            elif in_scenario:
                test_step = l.strip()
                cnt_steps += 1
                test_step2 = test_step

                if test_step.split(' ')[0] in ['Given', 'When', 'Then']:
                    test_step2 = ' '.join(test_step.split(' ')[1:])

                test.keywords.create(test_step)
                print ' ' * 6,
                if test_step.lower() in keywords or test_step2.lower(
                ) in keywords:
                    print "\033[1;30;40m",
                else:
                    print "\033[33;40m",
                    if not test_step2 in undefined_steps:
                        undefined_steps.append(test_step2)

                    #kw = UserKeyword( resource, test_step2 )

                filler = ' ' * (40 - len(test_step))
                print "%s%s%s:%d\033[0m" % (test_step, filler, filename,
                                            lineno)

            else:
                print line,

    if undefined_steps:
        #resource.save()
        print ""
        print "Undefined keywords:"
        for k in undefined_steps:
            print k
        print
        print "These keywords can already be defined, but have variables in the name"
        print "or be available in a deeper resource file"
        print

    return suite
Ejemplo n.º 24
0
from robot.api import TestSuite

suite = TestSuite('Activate Skynet')
suite.resource.imports.library('OperatingSystem')
test = suite.tests.create('Should Activate Skynet', tags=['smoke'])
test.keywords.create('Set Environment Variable', args=['SKYNET', 'activated'], type='setup')
test.keywords.create('Environment Variable Should Be Set', args=['SKYNET'])
Ejemplo n.º 25
0
def create_suite(name):

    return TestSuite(name)
Ejemplo n.º 26
0
 def setUp(self):
     self.suite = TestSuite('Test low level keywords')
     self.suite.resource.imports.library('VnfValidator')
Ejemplo n.º 27
0
class CxmCaiWuTest:
    def __init__(self, name, librarys=["SeleniumLibrary"]):
        # 创建测试套件
        self.suite = TestSuite(name)

        # 导入SeleniumLibrary
        for lib in librarys:
            self.suite.resource.imports.library(lib)

    # 定义变量
    def create_variables(self):
        variables = {
            "${url}":
            "http://test.mmp-new.caixm.cn/",
            "${browser}":
            "Chrome",
            "${username_type}":
            "id=userName",
            "${password_type}":
            "id=password",
            "${loginBtn}":
            'xpath=//*[@id="root"]/div/div[2]/div[2]/div/form/div[3]/div/div/span/button'
        }
        for k, v in variables.items():
            self.suite.resource.variables.create(k, v)

    # 测试用例:启动浏览器
    def open_browsers(self):
        test_01 = self.suite.tests.create("启动浏览器")
        test_01.keywords.create("Open Browser", args=["${url}", "${browser}"])
        test_01.keywords.create("Title Should Be", args=["菜小秘"])

    # 测试用例:输入账号和密码,登录财务端
    def et_word(self):
        test_02 = self.suite.tests.create("登录财务端")
        test_02.keywords.create("Sleep", args=["5s"])
        test_02.keywords.create("Input Text",
                                args=["${username_type}", "15868134428"])
        test_02.keywords.create("Input Text",
                                args=["${password_type}", "232323"])
        test_02.keywords.create("Click Button", args=["${loginBtn}"])
        test_02.keywords.create("Sleep", args=["5s"])

    # 测试用例:断言验证登录之后标题
    def assert_title(self):
        test_03 = self.suite.tests.create("断言验证登录之后标题")
        test_03.keywords.create("Title Should Be", args=["工作台 - 菜小秘"])

    # 测试用例:关闭测试用例
    def close_browsers(self):
        test_04 = self.suite.tests.create("关闭浏览器")
        test_04.keywords.create("Close All Browsers")

        # 运行
    def run(self):
        self.create_variables()
        self.open_browsers()
        self.et_word()
        self.assert_title()
        self.close_browsers()

        # 运行套件
        result = self.suite.run(critical="菜小秘财务端",
                                output="../reports/output.xml")

        # 生成日志、报告文件
        ResultWriter(result).write_results(report="../reports/report.html",
                                           log="../reports/log.html")
Ejemplo n.º 28
0
def full_walker(file_path):
    # 初始化robot suite
    test_suite_name = os.path.basename(file_path).split('.')[0]
    suite = TestSuite(test_suite_name)
    suite.resource.imports.library('ApolloLibrary')

    g = graphml.read_graphml(file_path)
    e = [e for e in g.edges_iter()]
    n = [n for n in g.node]
    edges = g.edge
    nodes = g.node

    revers_paths = []
    exec_paths = []

    # 获取所有反向路径
    for edge1 in e:
        for edge2 in e:
            if edge1[0] == edge2[1] and edge1[1] == edge2[0]:
                revers_paths.append(edge1)

    # 遍历反向路径
    if len(revers_paths) > 0:
        for revers_path in revers_paths:
            for path in nx.all_simple_paths(g, 'n0', revers_path[0]):
                if path[-2] == revers_path[1]:
                    exec_paths.append(path + [revers_path[1]])

    # 搜寻所有的末端路径
    for node in n:
        if len(g.successors(node)) == 0:
            for path in nx.all_simple_paths(g, 'n0', node):
                exec_paths.append(path)

    # 整合成robot suite
    for exec_path in exec_paths:
        test = suite.tests.create(str(exec_path).strip(' '))
        for i in range(len(exec_path)-1):
            prev_node = exec_path[i]
            next_node = exec_path[i+1]
            if str(nodes[prev_node]['label']).lower() == 'start':
                test.keywords.create('Log', args=['测试开始'.decode('utf-8')])
                e_label = edges['n0'][next_node]['label']
                if len(e_label.split('/')) > 1:
                    test.keywords.create(e_label.split('/')[0], args=[e_label.split('/')[1]])
                else:
                    test.keywords.create(edges['n0'][next_node]['label'])
                test.keywords.create('Log', args=['当前的节点为: {}'.format(next_node).decode('utf-8')])
                n_label = nodes[next_node]['label']
                if len(n_label.split('/')) > 1:
                    test.keywords.create(n_label.split('/')[0], args=[n_label.split('/')[1]])
                else:
                    test.keywords.create(n_label)
            else:
                test.keywords.create('Log', args=['当前的向量为: {}'.format(edges[prev_node][next_node]['id']).decode('utf-8')])
                e_label = edges[prev_node][next_node]['label']
                if len(e_label.split('/')) > 1:
                    test.keywords.create(e_label.split('/')[0], args=[e_label.split('/')[1]])
                else:
                    test.keywords.create(e_label)
                test.keywords.create('Log', args=['当前的节点为: {}'.format(next_node).decode('utf-8')])
                n_label = nodes[next_node]['label']
                if len(n_label.split('/')) > 1:
                    test.keywords.create(n_label.split('/')[0], args=[n_label.split('/')[1]])
                else:
                    test.keywords.create(n_label)

    # 运行suite并回收报告
    suite.run(output='../results/{}.xml'.format(test_suite_name))
    xml_files = [join('../results/', f) for f in listdir('../results/') if isfile(join('../results/', f))]
    ResultWriter(*xml_files) \
        .write_results(log='../reports/{}_log.html'.format(test_suite_name)
                       , report='../reports/{}_report.html'.format(test_suite_name)
                       , output='../reports/{}_output.xml'.format(test_suite_name))
Ejemplo n.º 29
0
    return cp_steps


yaml_file = '..\\cases.yaml'

yaml_obj = yaml_to_obj(yaml_file)
configs = get_yaml_configures(yaml_obj)
testcases = get_yaml_cases(yaml_obj)

suite_name = configs.get('suite_name')
librarys = configs.get('librarys')
librarys_path = configs.get('librarys_path')
suite_steps = configs.get('steps')

suite = TestSuite(suite_name)
for _lib in librarys:
    suite.resource.imports.library('{}'.format(_lib))

# un-comment follows line, see what happen
suite_steps = order_suite_setup_and_teardown(suite_steps)
create_case_step(suite, suite_steps)

for case in testcases:
    test_case_name = case.get('name')
    tags = case.get('tags')
    steps = case.get('steps')
    assertions = case.get('assertions')

    # test = suite.tests.create(test_case_name, tags=tags)
    test = suite.tests.create(test_case_name, tags=tags)
Ejemplo n.º 30
0
def build_keywords(parsed_keywords, suite):
    for name, settings, steps in parsed_keywords:
        kw = suite.keywords.create(name=name)
        for name, value in settings:
            pass
        for assign, name, args in steps:
            if assign is not None:
                assign = [assign]
            else:
                assign = []
            kw.keywords.create(name=name, assign=assign, args=args)
    return suite


if __name__ == '__main__':
    data = open(sys.argv[1]).read()
    sections = parse_sections(data)
    parsed_settings = setting_parser.parse(sections['SETTING'])
    parsed_variables = variable_parser.parse(sections['VARIABLE'])
    parsed_tests = testcase_parser.parse(sections['TESTCASE'])
    parsed_kws = keyword_parser.parse(sections['KEYWORD'])
    print(parsed_kws)

    suite = TestSuite('test suite name')
    suite = build_settings(parsed_settings, suite)
    suite = build_variables(parsed_variables, suite)
    suite = build_tests(parsed_tests, suite)
    suite = build_keywords(parsed_kws, suite)
    suite.run(outputdir=tempfile.gettempdir(), log='log.html')
Ejemplo n.º 31
0
        file_list = glob.glob('*.feature')

    print file_list

    init_suite = None
    #    if os.path.exists( '__init__.txt' ):
    #        print "__init__ found"
    #        init_suite = TestSuiteBuilder().build('__init__.txt')

    if len(file_list) == 0:
        import sys
        print "No feature files found."
        sys.exit()

    elif len(file_list) > 1:
        suite = TestSuite('Main')
        if init_suite:
            suite.suites.append(init_suite)

        for f in file_list:
            feature_suite = read_feature(f)
            suite.suites.append(feature_suite)

    else:
        if init_suite:
            suite = TestSuite('Main')
            suite.suites.append(init_suite)
            feature_suite = read_feature(file_list[0])
            suite.suites.append(feature_suite)

        else:
Ejemplo n.º 32
0
def build_settings(parsed_settings, suite):
    for name, data in parsed_settings:
        setting = suite.resource.imports.create(type=name, name=data[0])
    return suite


def build_tests(parsed_tests, suite):
    for name, steps in parsed_tests:
        test = suite.tests.create(name=name)
        for assign, name, args in steps:
            if assign is not None:
                assign = [assign]
            else:
                assign = []
            test.keywords.create(name=name, assign=assign, args=args)
    return suite


if __name__ == '__main__':
    data = open(sys.argv[1]).read()
    sections = parse_sections(data)
    parsed_settings = parse_section(sections['SETTING'], SettingLexer,
                                    SettingParser)
    parsed_tests = parse_section(sections['TESTCASE'], TestCaseLexer,
                                 TestCaseParser)

    suite = build_tests(
        parsed_tests,
        build_settings(parsed_settings, TestSuite('test suite name')))
    suite.run(outputdir=tempfile.gettempdir())
Ejemplo n.º 33
0
 def __init__(self, name):
     # 创建TestSuite
     self.testSuite = TestSuite(name)
Ejemplo n.º 34
0
from robot.api import TestSuite

suite = TestSuite('Login')
suite.resource.imports.library('ITASLibrary')

test = suite.tests.create('LoginTest', tags=['smoke'])
print type(test)
test.keywords.create('SetBaseUrl', args=[ 'http://192.168.168.151:8080'], type='setup')
loginResp=test.keywords.create('login', args=[ 'REGSUP201504','1234a*'])
print type(loginResp)




result = suite.run(critical='smoke', output='skynet.xml')