def _create_new_query(self, test_name: str, data: dict) -> str: """ Generates SQL query statement containing each test result. Parameters: test_name(str): Name of the test performed. data(dict): This is a dictionary containing test results. Returns: str: Generated SQL query statement. """ test_name = test_name.lower() project_name = self.config.get_project_name() test_tool = self.config.get_test_tool(test_name=test_name.upper()) if equals(test_name, 'csw'): return f"INSERT INTO CSW(PROJECT_NAME, BUILD_NUMBER, TEST_TOOL, TEST_VAL) VALUES('{project_name}', {data['build_number']}, '{test_tool['uses']}', {data['warning']})" elif equals(test_name, 'unittest'): return f"""INSERT INTO UNITTEST(PROJECT_NAME, BUILD_NUMBER, TEST_TOOL, SUCCESS, FAIL, SKIP) VALUES ('{project_name}', {data['build_number']}, '{test_tool['uses']}', {data['success']}, {data['fail']}, {data['skip']})""" elif equals(test_name, 'coverage'): return f"""INSERT INTO COVERAGE(PROJECT_NAME, BUILD_NUMBER, TEST_TOOL, TEST_VAL) VALUES ('{project_name}', {data['build_number']}, '{test_tool['uses']}', {data['test_val']}) """ elif equals(test_name, 'apitest'): pass elif equals(test_name, 'e2etest'): pass
def _save(data: Any, *, ext=''): with open(file=path, mode='w', encoding='utf-8') as f: if equals(ext, 'csv'): wr = csv.writer(f) wr.writerows(data) else: f.write(data)
def _coverage(self) -> dict: """ Parse Coverage test result. Returns: dict: Test result """ if equals(self.test_tool, 'jacoco'): result = self.jacoco.parse(path=self.path, file_type=self.file_type) elif equals(self.test_tool, 'coverage'): result = self.coverage.parse(path=self.path, file_type=self.file_type) else: raise UnknownTestTestToolError return result
def _unittest(self) -> dict: """ Parse Unittest result. Returns: dict: Test result """ if equals(self.test_tool, 'surefire'): result = self.surefire.parse(path=self.path, file_type=self.file_type) elif equals(self.test_tool, 'unittest'): result = self.unittest.parse(path=self.path, file_type=self.file_type) else: raise UnknownTestTestToolError return result
def insert_test_result(self, test_name: str, data: dict, db_name: str) -> NoReturn: """ The test results are analyzed and inserted into the database.\n Tables must be prepared for each test name.\n Example: CSW, UNITTEST, E2ETEST Parameters: test_name(str): Name of the test performed. data(dict): This is a dictionary containing test results. db_name(str): Database type name. Examples: MySQL, Oracle, MongoDB, MariaDB... """ if not os.path.isfile('data/db.json'): # db.json 파일이 없을경우 오류 발생 raise FileNotFoundError else: db_data = self.reader.read_json_file('data/db.json') if db_name in list(db_data): # 입력받은 데이터베이스가 목록에 없을 경우 오류 발생 if equals(db_name, 'mariadb'): colored_print('Currently MariaDB is handled as MySQL.', 'orange') self.insert_test_result(test_name=test_name, data=data, db_name='mysql') elif equals(db_name, 'mongodb'): colored_print('Database type not currently supported.', 'orange') elif equals(db_name, 'mysql'): self.mysql.open_DB_session() self.mysql.send_query(sql=self._create_new_query( test_name, data), type='insert') self.mysql.close_DB_session() elif equals(db_name, 'oracle'): colored_print('Database type not currently supported.', 'orange') else: colored_print('Database type not currently supported.', 'orange') raise UnknownDatabaseError # 목록에는 있지만 지원하지 않는 데이터베이스의 경우 오류 발생 else: raise UnknownDataError
def _csw(self) -> dict: """ Parse Code static analysis result. Returns: dict: Test result """ result = {} if equals(self.test_tool, 'flake8'): result = self.flake8.parse(path=self.path, file_type=self.file_type) elif equals(self.test_tool, 'eslint'): result = self.eslint.parse(path=self.path, file_type=self.file_type) elif equals(self.test_tool, 'pmd'): result = self.pmd.parse(path=self.path, file_type=self.file_type) else: raise UnknownTestTestToolError return result
def _e2etest(self) -> dict: """ Parse End to End result. Returns: dict: Test result """ if equals(self.test_tool, 'selenium'): result = self.selenium.parse(path=self.path, file_type=self.file_type) return result
def run_all(self, command_list: List): """ Executes all commands in the command list. Parameters: command_list(str): List of commands to be executed. """ if equals(len(command_list), 0): colored_print('No command found.', 'orange') else: for command in command_list: self.run(command)
def write_file(self, path: str, content: Any, ext: str) -> bool: def _save(data: Any, *, ext=''): with open(file=path, mode='w', encoding='utf-8') as f: if equals(ext, 'csv'): wr = csv.writer(f) wr.writerows(data) else: f.write(data) try: if equals(ext, 'json'): _save(json.dumps(content, indent=' ')) elif equals(ext, 'yaml') or equals(ext, 'yml'): _save(yaml.dump(content, indent=4)) else: _save(content, ext='csv') except Exception as e: print(e) return False else: return True
def parse(self, path: str, file_type: str) -> dict: return_val = {'test_val': 0} if equals(file_type, 'html'): coverage_data = self.reader.read_html_file(path) rate = int(coverage_data['html']['body']['div'][2]['table'] ['tfoot']['tr']['td'][4]['text'].rstrip('%')) return_val['test_val'] = rate elif equals(file_type, 'xml'): coverage_data = self.reader.read_xml_file(path) rate = coverage_data['coverage']['@line-rate'].split('.')[1][:2] return_val['test_val'] = int(rate) elif equals(file_type, 'json'): coverage_data = self.reader.read_json_file(path) return_val['test_val'] = int( coverage_data['totals']['percent_covered']) else: colored_print( 'Sorry, there is no information you can get from this type of file.', 'orange') return_val['test_val'] = -1 return return_val
def parse(self, path: str, file_type: str) -> dict: return_val = {'warning': 0} try: if not equals(file_type, 'xml'): raise FileExtensionError test_result = self.reader.read_xml_file(path) data = test_result['pmd']['file'] except FileExtensionError: colored_print( 'Sorry, there is no information you can get from this type of file.', 'orange') except ValueError: pass else: if equals(isinstance(data, dict), True): data = [data] for file in data: if 'violation' in file: if equals(isinstance(file['violation'], dict), True): file['violation'] = [file['violation']] return_val['warning'] += len(file['violation']) finally: return return_val
def parse(self, path: str, file_type: str) -> dict: def _checkstyle() -> dict: def find_warnings(file_tag: dict): if 'error' not in file_tag: return 0 if isinstance(file_tag['error'], list): return len(file_tag['error']) return 1 xml = self.reader.read_xml_file(path) data = xml['checkstyle']['file'] warnings = 0 if isinstance(data, list): for tag in data: warnings += find_warnings(tag) else: warnings = find_warnings(data) return { 'warning': warnings } def _codeframe() -> dict: txt = self.reader.read_raw_file(path) result_line = txt.splitlines()[-2] result = re.sub('[^0-9]', '', result_line) return { 'warning': int(result[0]) + int(result[1]) } def _compact() -> dict: txt = self.reader.read_raw_file(path) result_line = txt.splitlines()[-1] return { 'warning': int(result_line.split()[0]) } def _junit() -> dict: xml = self.reader.read_xml_file(path) return { 'warning': int(xml['testsuites']['testsuite']['@errors']) } def _jslint_xml() -> dict: xml = self.reader.read_xml_file(path) return { 'warning': len(xml['jslint']['file']['issue']) } def _json() -> dict: json = self.reader.read_json_file(path) warning = int(json[0]['errorCount']) + int(json[0]['warningCount']) return { 'warning': warning } def _json_with_metadata() -> dict: json = self.reader.read_json_file(path) warning = int(json['results'][0]['errorCount']) + int(json['results'][0]['warningCount']) return { 'warning': warning } if equals(file_type, 'checkstyle'): return _checkstyle() if equals(file_type, 'codeframe'): return _codeframe() if equals(file_type, 'compact'): return _compact() if equals(file_type, 'junit'): return _junit() if equals(file_type, 'jslint-xml'): return _jslint_xml() if equals(file_type, 'json'): return _json() if equals(file_type, 'json-with-metadata'): return _json_with_metadata() colored_print('Sorry, there is no information you can get from this type of file.', 'orange')