def GetTextCases(self): if os.path.isfile(self.task.testcase_file_name): print( f'Найден файл с тест кейсами: {self.task.testcase_file_name}') with open(self.task.testcase_file_name) as file: json_data = file.read() result = [TestCase(**json.loads(x)) for x in json.loads(json_data)] else: html = ProblemsHtml(self.task).GetHtml() soup = BeautifulSoup(html, 'html.parser') div_input = soup.find_all(class_="input") div_output = soup.find_all(class_="output") result = [] for i in range(len(div_input)): text_input = self.__GetPreText(div_input[i]) text_output = self.__GetPreText(div_output[i]).replace( '\n', '\r\n') result.append(TestCase(text_input, text_output)) jsontext = [json.dumps(x.__dict__) for x in result] print( f'Сохраняем файл с тест кейсами: {self.task.testcase_file_name}' ) with open(self.task.testcase_file_name, 'w') as filejson: json.dump(jsontext, filejson) ''' for x in result: print('=== Тест кейс ===') print('Input:') print(x.input) print('Output:') print(x.output) ''' print(f'Кол-во тест кейсов: {len(result)}') return result
def crossover(self, parent_1: TestCase, parent_2: TestCase) -> Tuple[TestCase]: crossover_point = random.choice(range(len(parent_1.input))) offspring_1 = TestCase(input=parent_1.input[:crossover_point] + parent_2.input[crossover_point:]) offspring_2 = TestCase(input=parent_2.input[:crossover_point] + parent_1.input[crossover_point:]) offspring_1.execute_test_on(self.source_code) offspring_2.execute_test_on(self.source_code) return offspring_1, offspring_2
def main(config): # FLASK REQUIREMENTS # ------------------ app = Flask(__name__) api = Api(app) # ------------------ # INSTANTIATE TEST CASE # --------------------- from testcase import TestCase with open(config) as json_file: model_config = json.load(json_file) case = TestCase(model_config) # --------------------- # DEFINE ARGUMENT PARSERS # ----------------------- # ``step`` interface parser_step = reqparse.RequestParser() parser_step.add_argument('step') # ``fault_info`` interface parser_fault_info = reqparse.RequestParser() parser_fault_info.add_argument('fault') # ``reset`` interface reset_step = reqparse.RequestParser() reset_step.add_argument('start_time') reset_step.add_argument('end_time') # ``advance`` interface parser_advance = reqparse.RequestParser() for key in case.u.keys(): parser_advance.add_argument(key)
def __init__(self,config=Config,result_handler=None,**kwargs): self.config = config if result_handler and getattr(result_handler,'handle',None): self.result_handler = result_handler else: from resultHandler import xmlHandler self.result_handler = xmlHandler() testdir = self.config.testdir # scan test file self.testcases = {} # 管理测试用例 #self.testCasesFile = {}#文件与testcase对应 for testfile in self.get_test_files(): # 构造测试并添加,视情况看是否需要启用新定时器 testcase = TestCase() file_name = os.path.sep.join((os.getcwd(),testfile)) try: xml = self.parsexml(testfile) testcase.fromxml(xml) if testcase.is_valid(): self.testcases[testcase.name] = testcase self.file2testcase[file_name] = testcase.name #后来添加 #self.testCasesFile[testfile] = testcase.name else: raise Exception,'no testcase found of empty testcase' except: log_exce('invalid testcase definition in file : %s, will be discard.'%testfile) log.info('load test file done! there are %d valided testcases.'%len(self.testcases.keys()))
def on_import_case(self): query_result = QMessageBox.warning(self, '警告', f'执行导入操作时,测试标识相同的用例将被覆盖,确认执行导入操作!?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if query_result == QMessageBox.No: return case_files = QFileDialog.getOpenFileNames(self, '选择用例文件', '.', 'Test Case Files(*.case);') total_import_count = len(case_files[0]) if not total_import_count: return self.process_progressbar.setMaximum(total_import_count) self.process_progressbar.setMinimum(0) fail = 0 import_count = 0 try: for file in case_files[0]: test_case = TestCase() test_case.load_from_file(file) ret = self.testcase_tree.findItems(test_case.case_mark,Qt.MatchCaseSensitive | Qt.MatchExactly, 0) if ret: ret[0].setText(1, test_case.case_name) else: item = QTreeWidgetItem() item.setText(0, test_case.case_mark) item.setText(1, test_case.case_name) item.setText(2, test_case.case_id) item.setCheckState(0, Qt.Checked) self.testcase_tree.addTopLevelItem(item) self.test_cases[test_case.case_mark] = test_case import_count += 1 self.process_progressbar.setValue(import_count) except Exception as e: fail += 1 QMessageBox.information(self, '提示', f'导入用例文件异常{str(e)}', QMessageBox.Yes, QMessageBox.Yes) QMessageBox.information(self, '提示', f'导入成功{import_count}个, 失败{fail}个', QMessageBox.Yes, QMessageBox.Yes)
def get_testcases(files_list: List[str], test_names: str = "") -> List[TestCase]: """ Load all the testcases from the given files_list and filter them by test_names and return the filtered items as list of TestCase objects If files_list is ['all'], then recursively get all the python files in the current directory :param files_list: List of file path strings :param test_names: (optional) comma separated regex to filter testcases :return: list of TestCase objects """ if len(files_list) and files_list[0] == 'all': files_list = get_all_testcase_files() all_testcase_objects: List[TestCase] = [] files_list = sorted(files_list) for fname in files_list: module = import_file(fname) func_list = dir(module) func_list = sorted(func_list) for func_name in func_list: if not func_name.startswith('test_'): continue if not does_testcase_name_match_pattern(func_name, test_names): continue func_obj = getattr(module, func_name) testcase_obj = TestCase(func_obj) all_testcase_objects.append(testcase_obj) return all_testcase_objects
def parse(self, num, filepath): branch_count = 0 stmt_count = 0 statements = set() branches = set() line_num = 1 with open(filepath, 'r') as reader: for line in reader.readlines(): #if the line matches the statement regex increment the stmt count if self.tot_stmts.match(line): stmt_count += 1 if self.exe_stmts.match( line ): #if the statement is executed add the statement line number stmt_num = int(self.stmt_line_num.match(line).group(1)) statements.add(stmt_num) #if the line matches the branch regex increment the branch count elif self.tot_branches.match(line): branch_count += 1 if self.exe_branches.match( line ): #if the statement is executed add the branch line number branches.add(line_num) line_num += 1 self.test_cases.append( TestCase(num, stmt_count, branch_count, statements, branches)) return self.test_cases
def run_testsuite(self, http): logger.info('正在获取套件[id=%s,name=%s]的测试用例...' % (self.testsuite_id, self.testsuite_name)) testcases_id_list_for_testsuit = self.get_testcases_id_for_testsuite() for testcase_id in testcases_id_list_for_testsuit[:]: testcase_info = mytestlink.getTestCase(testcase_id) # 获取测试用例基本信息 # 构造测试用例对象 testcase_name = testcase_info[0]['name'] testcase_steps = testcase_info[0]['steps'] testcase_isactive = int(testcase_info[0]['active']) testcase_obj = TestCase(testcase_id, testcase_name, testcase_steps, testcase_isactive, self.project_name) sql_insert = 'INSERT INTO '+testcase_report_tb +'(executed_history_id, testcase_id, testcase_name, testsuit, testplan, project, runresult, runtime)' \ ' VALUES' testplan = '无计划' data = "('{}','{}','{}','{}','{}','{}', 'Block','{}')".format(executed_history_id,testcase_id,testcase_name,self.testsuite_name,testplan,self.project_name,time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) logger.info('记录测试用例到到测试用例报表') sql = str(sql_insert) + str(data) testdb.execute_insert(sql) logger.info('开始执行测试用例[id=%s,name=%s]' % (testcase_id, testcase_name)) run_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # 记录运行时间 testcase_run_result = testcase_obj.run_testcase(http, testplan) logger.info('正在更新用例执行结果') sql_update = 'UPDATE '+testcase_report_tb +' SET runresult=\"%s\", runtime=\"%s\"' \ ' WHERE executed_history_id = %s and testcase_id = %s' \ ' AND project=\'%s\' AND testplan=\'%s\'' % \ (testcase_run_result, run_time, executed_history_id, testcase_id, self.project_name, testplan) testdb.execute_update(sql_update) logger.info('测试套件[id=%s ,name=%s]已执行完' % (self.testsuite_id, self.testsuite_name))
def gather_all_testcases_in_folder(foldername): filenames = sorted(os.listdir(foldername)) result = [] for filename in filenames: path = os.path.join(foldername, filename) if os.path.isdir(path): result += gather_all_testcases_in_folder(path) else: match = re.match('(.+)\.in$', filename) if match: input_filename = match.group(1) if (input_filename + '.out') in filenames: new_test_case = TestCase( os.path.abspath(path), os.path.abspath( os.path.join(foldername, input_filename + '.out'))) result.append(new_test_case) else: raise Exception( "found *.in file with no corresponding *.out file: " + path) return result
def __init__(self, case_path): self._testcase = TestCase(case_path) self._maint_session = None self._sessions = {} self._waitings = [] self._backend_pids = [] self._errorsteps = {} # {step: errormsg}
def loadFunctionDict(target_dict, importedDict, isClassTest=False): ''' Takes in a dictionary of the imported test values, mostly strings. Returns a dictionary of test class objects ''' #testDict = {} classInit = "" if "init" in importedDict.keys(): # If the test type is special, capture it then remove it so what's left is just test cases classInit = importedDict["init"] del importedDict["init"] for functionName, function in importedDict.items(): functionName = functionName.split("-")[ 0] # hack to allow different test types testType = "" if functionName not in target_dict: target_dict[functionName] = [] if "type" in function.keys(): # If the test type is special, capture it then remove it so what's left is just test cases testType = function["type"] del function["type"] for testInput, testOutput in function.items(): t = TestCase(functionName, str(testInput), str(testOutput), isClassTest, classInit, testType) target_dict[functionName].append(t)
def setUp(self): '''Setup for each test. ''' self.case = TestCase() # Instantiate a KPI calculator linked to an empty case self.cal = KPI_Calculator(self.case) # Read the reference data ref_filepath = os.path.join(utilities.get_root_path(), 'testing', 'references', 'kpis', 'tc2_results_python.csv') df = pd.read_csv(ref_filepath) # Fill the test case with the refernce data for var in df.keys(): # Assign time if var == 'time': self.case.y_store[var] = df.loc[:, var] # Assign inputs elif var.endswith('_u'): self.case.u_store[var] = df.loc[:, var] # Assign outputs elif var.endswith('_y'): self.case.y_store[var] = df.loc[:, var]
def create_many_test_cases(directory, n): digits = math.ceil(math.log10(n + 1)) name_template = 'RandomArithmeticTestCase_{0:0' + str(digits) + 'd}' for i in range(n): input_count = max(1, np.random.poisson(3)) tc = TestCase(name_template.format(i+1), np.random.exponential(20, input_count)) with open(os.path.join(directory, tc.name + '.cpp'), 'w') as outfile: outfile.write(str(tc))
def run_testsuite(self, http): logger.info('正在获取套件[id=%s,name=%s]的测试用例...' % (self.testsuite_id, self.testsuite_name)) testcases_id_list_for_testsuit = self.get_testcases_id_for_testsuite() logger.info('获取到用例id列表:%s', testcases_id_list_for_testsuit) for testcase_id in testcases_id_list_for_testsuit[:]: testcase_info = mytestlink.getTestCase(testcase_id) # 获取测试用例基本信息 logger.info('获取测试用例信息 %s' % testcase_info) # 构造测试用例对象 testcase_name = testcase_info[0]['name'] preconditions = testcase_info[0]['preconditions'] if preconditions.find('isglobal') != -1: logger.info('用例[id=%s, name=%s]为全局初始化用例,已跳过执行' % (testcase_id, testcase_name)) continue testcase_steps = testcase_info[0]['steps'] testcase_isactive = int(testcase_info[0]['active']) testcase_obj = TestCase(testcase_id, testcase_name, testcase_steps, testcase_isactive, self.project_name) # 获取测试套件名称 logger.info(testcase_id) full_path = mytestlink.getFullPath(int(testcase_id)) full_path = full_path[testcase_id] testsuite_name = '' for suit in full_path[1:]: testsuite_name = testsuite_name + '-' + suit testsuite_name = testsuite_name.lstrip('-') sql_insert = 'INSERT INTO '+testcase_report_tb +'(executed_history_id, testcase_id, testcase_name, testsuit, testplan, project, runresult, runtime)' \ ' VALUES(%s, %s, %s, %s, %s, %s, %s, %s)' testplan = '无计划' data = (executed_history_id, testcase_id, testcase_name, testsuite_name, testplan, self.project_name, 'Block', '0000-00-00 00:00:00') logger.info('记录测试用例到测试用例报表') testdb.execute_insert(sql_insert, data) logger.info('开始执行测试用例[id=%s,name=%s]' % (testcase_id, testcase_name)) run_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # 记录运行时间 testcase_run_result = testcase_obj.run_testcase(http, testplan) logger.info('正在更新用例执行结果') sql_update = 'UPDATE '+testcase_report_tb +' SET runresult=\"%s\", runtime=\"%s\"' \ ' WHERE executed_history_id = %s and testcase_id = %s' \ ' AND project=\'%s\' AND testplan=\'%s\'' data = (testcase_run_result[0], run_time, executed_history_id, testcase_id, self.project_name, testplan) testdb.execute_update(sql_update, data) logger.info('测试套件[id=%s ,name=%s]已执行完' % (self.testsuite_id, self.testsuite_name))
def run_testplan(self, http): logger.info('正在获取测试计划[project=%s,name=%s]的测试用例' % (self.testproject, self.testplan_name)) testcases_for_testplan = mytestlink.getTestCasesForTestPlan(self.testplan_id) if [] == testcases_for_testplan: logger.warning('未获取到测试用例') return testcases_id_for_testplan = testcases_for_testplan.keys() logger.info('成功获取测试计划[project=%s,name=%s]的测试用例id:%s' % (self.testproject, self.testplan_name, testcases_id_for_testplan)) if 0 == self.active_status: logger.warning('测试计划[project=%s,name=%s]处于不活动状态[active=0],不执行' % (self.testproject, self.testplan_name)) return for testcase_id_str in testcases_id_for_testplan: testcase_id = int(testcase_id_str) testcase_info = mytestlink.getTestCase(testcase_id) # 获取测试用例基本信息 # 构造测试用例对象 testcase_name = testcase_info[0]['name'] testcase_steps = testcase_info[0]['steps'] testcase_isactive = int(testcase_info[0]['active']) testsuite_id = int(testcase_info[0]['testsuite_id']) testsuite_info = mytestlink.getTestSuiteByID(testsuite_id) testsuite_name = testsuite_info['name'] testcase_obj = TestCase(testcase_id, testcase_name, testcase_steps, testcase_isactive, self.testproject) sql_insert = 'INSERT INTO '+testcase_report_tb +'(executed_history_id, testcase_id, testcase_name, testsuit, testplan, project, runresult, runtime)' \ ' VALUES(%s, %s, %s, %s, %s, %s, %s, %s)' data = (executed_history_id, testcase_id, str(testcase_name), testsuite_name, self.testplan_name, self.testproject, 'Block', '') logger.info('记录测试用例到测试用例报表') testdb.execute_insert(sql_insert, data) logger.info('开始执行测试用例[id=%s,name=%s]' % (testcase_id, testcase_name)) run_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # 记录运行时间 testcase_run_result = testcase_obj.run_testcase(http, self.testplan_name) logger.info('正在更新用例执行结果') sql_update = 'UPDATE '+testcase_report_tb +' SET runresult=\"%s\", runtime=\"%s\"' \ ' WHERE executed_history_id = %s AND testcase_id = %s' \ ' AND project=\'%s\' AND testplan=\'%s\'' % \ (testcase_run_result, run_time, executed_history_id, testcase_id, self.testproject, self.testplan_name) testdb.execute_update(sql_update) bulid_info = mytestlink.getLatestBuildForTestPlan(self.testplan_id) # 固定取最新的版本 bulid_version = bulid_info['name'] logger.info('正在更新testlink上测试计划[testplan_id=%s, bulid_version=%s],对应用例[testcase_id=%s]的执行结果' % (self.testplan_id, bulid_version, testcase_id)) notes = '用例[id:%s]在测试计划[testplan_id:%s,testplan_name:%s,bulidversion:%s]中的执行结果' \ % (testcase_id, self.testplan_id,self.testplan_name, bulid_version) if 'Fail' == testcase_run_result or 'Error' == testcase_run_result: self.__execute_case_in_testlink(testcase_id, bulid_version, 'f', notes) # f - 失败 elif 'Pass' == testcase_run_result: self.__execute_case_in_testlink(testcase_id, bulid_version, 'p', notes) # f - 成功 else: pass # 如果未执行,啥都不做,str(self.testplan_id) logger.info('测试计划[project=%s ,testplan=%s]已执行完' % (self.testproject, self.testplan_name))
def run_testcase_by_id(testcase_id, httpobj=None, testplan='无计划'): try: testcase_info = mytestlink.getTestCase(testcase_id) # 获取测试用例基本信息 logger.info('获取测试用例信息 %s' % testcase_info) except Exception as e: logger.error('获取用例信息失败 %s,,暂停执行该用例' % e) return ('Fail',[('global_funtion_module','获取用例信息失败 %s' % e)]) # 获取用例所在套件和项目名称 response = mytestlink.getFullPath([int(testcase_id)]) response = response[str(testcase_id)] testsuite_name = '' for suit in response[1:]: testsuite_name = testsuite_name + '-' + suit testsuite_name = testsuite_name.lstrip('-') project_name = response[0] # 构造测试用例对象 testcase_name = testcase_info[0]['name'] testcase_steps = testcase_info[0]['steps'] testcase_isactive = int(testcase_info[0]['active']) testsuite_id = int(testcase_info[0]['testsuite_id']) preconditions = testcase_info[0]['preconditions'] tc_external_id = testcase_info[0]['full_tc_external_id'] testcase_obj = TestCase(testcase_id, testcase_name, testcase_steps, testcase_isactive, project_name, testsuite_id, tc_external_id, preconditions) if httpobj: myhttp = httpobj else: myhttp = get_http_conf_of_project(project_name) if not myhttp: logger.critical('用例所在项目配置存在问题,停止执行该用例') return ('Block',[('golbal_function_module', '用例所在项目配置存在问题,停止执行该用例')]) try: sql_insert = 'INSERT INTO '+testcase_report_tb +'(executed_history_id, testcase_id, testcase_name, testsuit, testplan, project, runresult, runtime, tc_external_id)' \ ' VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)' data = (executed_history_id, testcase_id, testcase_name, testsuite_name, testplan, project_name, 'Block','0000-00-00 00:00:00', tc_external_id) logger.info('记录测试用例到测试用例报表') testdb.execute_insert(sql_insert, data) logger.info('开始执行测试用例[id=%s,name=%s]' % (testcase_id, testcase_name)) run_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # 记录运行时间 case_executed_history_id = time.strftime('%Y%m%d%H%M%S', time.localtime()) # 流水记录编号 testcase_run_result = testcase_obj.run_testcase(myhttp, testplan, case_executed_history_id) logger.info('正在更新用例执行结果') sql_update = 'UPDATE '+testcase_report_tb +' SET runresult=\"%s\", runtime=\"%s\",' \ ' case_exec_history_id=\"%s\"' \ ' WHERE executed_history_id = %s and testcase_id = %s' \ ' AND project=\'%s\' AND testplan=\'%s\'' data = (testcase_run_result[0], run_time, str(case_executed_history_id), executed_history_id, testcase_id, project_name, testplan) testdb.execute_update(sql_update, data) logger.info('指定用例[%s]已执行完' % testcase_name) return testcase_run_result except Exception as e: logger.error('运行用例出错 %s' % e) return ('Fail',[('golbal_function_module', '%s' % e)])
def setUp(self): """Create an instance of ProductSpec""" self._test_case = TestCase(filename) self._test_case.initialize() self._product_spec = ProductSpec(spec_filename) self._product_spec.parse() self._file_builder = FileBuilder(self._product_spec, test_suite_library, 1) return
def setUp(self): '''Setup for each test. ''' case = TestCase() # Instantiate a forecaster self.forecaster = Forecaster(case)
def read(test_path: str) -> List[TestCase]: ignored = read_ignored(test_path) def add_file(f) -> bool: st = splitext(f) return st[1] == '.py' and basename(st[0]) not in ignored files = filter(add_file, [abspath(join(test_path, f)) for f in listdir(test_path)]) return [TestCase(path) for path in files]
def setUp(self): '''Setup for each test. ''' from testcase import TestCase self.case = TestCase() # Instantiate a data manager self.man = Data_Manager(self.case)
def process_case(): report_title = '用例执行报告' desc = '测试执行情况展示' report_file = './Report/ExampleReport.html' suite = unittest.TestSuite() suite.addTests(TestCase().testcases) with open(report_file, 'wb') as report: runner = HTMLTestRunner(stream=report, title=report_title, description=desc) runner.run(suite)
def _load_test_cases(self) -> List[TestCase]: func_list = sorted(dir(self.module)) test_case_list: List[TestCase] = [] for func_name in func_list: # get all the functions that start with test_ if not func_name.startswith('test_'): continue func_obj = getattr(self.module, func_name) testcase_obj = TestCase(func_obj) test_case_list.append(testcase_obj) return test_case_list
def run_testsuite(self, http): logger.info('正在获取套件[id=%s,name=%s]的测试用例...' % (self.testsuite_id, self.testsuite_name)) testcases_id_list_for_testsuit = self.get_testcases_id_for_testsuite() for testcase_id in testcases_id_list_for_testsuit[:]: testcase_info = mytestlink.getTestCase(testcase_id) # 获取测试用例基本信息 #debug by david logger.info("测试用例信息%s" % testcase_info) # 构造测试用例对象 testcase_name = testcase_info[0]['name'] testcase_steps = testcase_info[0]['steps'] #testcase_steps = testcase_steps[0]["actions"] testcase_isactive = int(testcase_info[0]['active']) #调试用by david #logger.info('输出用例信息 =====step===david========%s'%testcase_info) #处理测试用例的步骤 #other_tools = OtherTools() #testcase_steps = other_tools.conver_date_from_testlink(testcase_steps) #示例testsuite_details = other_tools.conver_date_from_testlink(testsuite_info['details']) #logger.info('输出用例信息 ===处理后=====david========%s' % testcase_steps) testcase_obj = TestCase(testcase_id, testcase_name, testcase_steps, testcase_isactive, self.project_name) sql_insert = 'INSERT INTO '+testcase_report_tb +'(executed_history_id, testcase_id, testcase_name, testsuit, testplan, project, runresult, runtime)' \ ' VALUES(%s, %s, %s, %s, %s, %s, %s, %s)' testplan = '无计划' #MODIFY BY DAVID BLOCK TO PASS data = (executed_history_id, testcase_id, testcase_name, self.testsuite_name, testplan, self.project_name, 'PASS', '') logger.info('记录测试用例到到测试用例报表') testdb.execute_insert(sql_insert, data) logger.info('开始执行测试用例[id=%s,name=%s]' % (testcase_id, testcase_name)) run_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # 记录运行时间 testcase_run_result = testcase_obj.run_testcase(http, testplan) logger.info('正在更新用例执行结果') sql_update = 'UPDATE '+testcase_report_tb +' SET runresult=\"%s\", runtime=\"%s\"' \ ' WHERE executed_history_id = %s and testcase_id = %s' \ ' AND project=\'%s\' AND testplan=\'%s\'' % \ (testcase_run_result, run_time, executed_history_id, testcase_id, self.project_name, testplan) testdb.execute_update(sql_update) logger.info('测试套件[id=%s ,name=%s]已执行完' % (self.testsuite_id, self.testsuite_name))
def __generate_test_case(self, case_identification=''): """ 生成或更新测试用例 :param case_identification: 测试标识 :return: """ test_case = None try: test_case = self.test_cases[case_identification] except KeyError: self._case_id += 1 test_case = TestCase(case_id=str(self._case_id), case_mark=case_identification) self.test_cases[case_identification] = test_case # 更新除用例id和用例标识之外的其它内容 test_case.case_name = self.test_item_edit.text() test_case.case_cat = self.test_cat_combox.currentIndex() test_case.case_req_track = self.require_trace_edit.text() test_case.case_content = self.test_content_edit.text() test_case.case_sys_prepare = self.sys_prepare_edit.text() test_case.case_constraint = self.precondation_edit.text() test_case.case_input = self.test_input_edit.text() test_case.case_exec_procedure.clear() for i in range(0, self.test_procedure_tabel.rowCount()): test_case.case_exec_procedure.append([ self.test_procedure_tabel.item(i, 0).text() if self.test_procedure_tabel.item(i, 0) else str(i + 1), self.test_procedure_tabel.item(i, 1).text() if self.test_procedure_tabel.item(i, 1) else '无', self.test_procedure_tabel.item(i, 2).text() if self.test_procedure_tabel.item(i, 2) else '无', self.test_procedure_tabel.item(i, 3).text() if self.test_procedure_tabel.item(i, 3) else '无', self.test_procedure_tabel.item(i, 4).text() if self.test_procedure_tabel.item(i, 4) else '无', self.test_procedure_tabel.item(i, 5).text() if self.test_procedure_tabel.item(i, 5) else '无', self.test_procedure_tabel.item(i, 6).text() if self.test_procedure_tabel.item(i, 6) else '无', ]) test_case.case_qualified_rule = self.estimate_rule_eidt.text() test_case.case_env = self.test_env_combox.currentIndex() test_case.case_qualified_method = self.qualified_method_combox.currentIndex( ) test_case.case_safe_secret = self.safe_secret_edit.text() test_case.test_person = self.test_person_combox.currentIndex() test_case.test_join_person = self.test_person_join_edit.text() test_case.test_date = self.test_date_timepickedit.text() test_case.case_data = self.test_data_edit.text() test_case.case_problem_sheet = self.problem_sheet_edit.text() test_case.case_correct_sheet = self.correct_sheet_edit.text() test_case.case_diff = self.test_diff_edit.text() return test_case
def test_testcase_1(): from sourcecode import SourceCode from testcase import TestCase sc = SourceCode(path="./evaluation/gcd.py") sc.create_file() test = TestCase(input=[12, 10]) test.execute_test_on(sc) assert test.get_output() == [2]
def test_update(): sc = SourceCode( "# tri import sys i = int(sys.argv[1]) j = int(sys.argv[2]) k = int(sys.argv[3]) if i <= 0 or j <= 0 or k <= 0: " "print(4) exit() tri = 0 if i == j: tri += 1 if i == k: tri += 2 if j == k: tri += 3 if tri == 0: if i + j < k or " "j + k < i or k + i < j: tri = 4 else: tri = 1 print(tri) exit() if tri > 3: tri = 3 elif tri == 1 and i + j > k: " "tri = 2 elif tri == 2 and i + k > j: tri = 2 elif tri == 3 and j + k > i: tri = 2 else: tri = 4 print(tri) exit(" ")") cov_table = CoverageTable(sc) print(cov_table.calculate_coverage()) print(cov_table.tests) t1 = TestCase([9, 8, -1], [0]) t2 = TestCase([1, 2, 3], [0]) pop = Population(sc, [t1, t2]) cov_table.update(pop) print(cov_table.calculate_coverage()) print(cov_table.tests) t3 = TestCase([1, 1, 1], [0]) pop = Population(sc, [t3]) cov_table.update(pop) print(cov_table.calculate_coverage()) print(cov_table.tests)
def produce_test_case(self): """ Generate a test case file in the test suite directory. """ self._test_case = TestCase(self.test_case_filename) self.initialize() self.test_case.initialize() self.process_policy() self.process_product() self.process_quote() self.process_bind() self.test_case.output() return
def parse(self, xmlPath): doc = minidom.parse(xmlPath) root = doc.documentElement nameNodes = self.getXmlNodes(root, 'name') caseName = self.getNodeValue(nameNodes[0]) apList = [] apsNodes = self.getXmlNodes(root, 'aps') apNodes = self.getXmlNodes(apsNodes[0], 'ap') for apNode in apNodes: model = self.getAttrValue(apNode, 'model') mac = self.getAttrValue(apNode, 'mac') apList.append({"model": model, "mac": mac}) dutList = [] dutsNodes = self.getXmlNodes(root, 'duts') dutNodes = self.getXmlNodes(dutsNodes[0], 'dut') for dutNode in dutNodes: model = self.getAttrValue(dutNode, 'model') mac = self.getAttrValue(dutNode, 'mac') dutList.append({"model": model, "mac": mac}) scenarioList = [] scenariosNodes = self.getXmlNodes(root, 'scenarios') scenarioNodes = self.getXmlNodes(scenariosNodes[0], 'scenario') for scenarioNode in scenarioNodes: scenarioName = self.getAttrValue(scenarioNode, 'name') categoryNodes = self.getXmlNodes(scenarioNode, 'category') categoryValue = self.getNodeValue(categoryNodes[0]) scriptNodes = self.getXmlNodes(scenarioNode, 'script') scriptValue = self.getNodeValue(scriptNodes[0]) parameterNodes = self.getXmlNodes(scenarioNode, 'parameter') parameterValue = self.getNodeValue(parameterNodes[0]) scenario = Scenario(scenarioName, categoryValue, scriptValue, parameterValue) scenarioList.append(scenario) testCase = TestCase() testCase.name = caseName testCase.apList = apList testCase.dutList = dutList testCase.scenarioList = scenarioList return testCase
def main(): if len(argv) != 3: usage() exit(1) with open(argv[1]) as in_file: tc = TestCase(input=in_file) with open(argv[2]) as out_file: output = [] for i, row in enumerate(out_file): try: output.append(list(map(int, row.split()))) except Exception: error("Day-%d invalid output : %s" % (i, row)) score = judge(tc, output) print("%d" % score)
def simulate_skip_API(start_time=0, length=3.1536e+7, points='fcu.powHeaThe.y,fcu.powCooThe.y'): '''Invokes a simulation in the Docker container directly, without making use of the Rest API. Useful to retrieve data other than the available measurements from the read blocks. It is used when finding the peak and typical heating or cooling days. The simulation results are returned in `.csv` format. Parameters ---------- start_time: integer Start time of the simulation in seconds from beginning of the year. Default is 0. lenght: integer Length of the simulation to be performed in seconds. Default is one year. points: string Model variables to be returned from the simulation, separated by `,`. Results are stored in a `simulation.csv` file. ''' start_time = int(float(start_time)) length = int(float(length)) points = points.split(',') case = TestCase() case.initialize(start_time=start_time, warmup_period=0) # Initialize y = {'time': np.array([])} for point in points: y[point] = np.array([]) # Simulate res = case._TestCase__simulation(start_time=start_time, end_time=start_time + length) # Gather and store results y['time'] = np.append(y['time'], res['time'][1:]) for point in points: y[point] = np.append(y[point], res['mod.' + point][1:]) df = pd.DataFrame(y) df.set_index('time', inplace=True) df.index.name = 'Time' df.to_csv('simulation.csv')