Example #1
0
class CoverageParser(object):
    def __init__(self):
        self.reader = Reader()

    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
Example #2
0
class UnittestParser(object):
    def __init__(self):
        self.reader = Reader()

    def parse(self, path: str, file_type: str) -> dict:
        return_val = {
            'success': 0,
            'fail': 0,
            'skip': 0
        }
        if file_type == 'xml':
            xml = self.reader.read_xml_file(path)
            data = xml['testsuites']['testsuite']
            total = int(data['@tests'])
            fail = int(data['@failures']) + int(data['@errors'])
            skip = int(data['@skipped'])
            success = total - fail - skip
            return_val['success'] = success
            return_val['fail'] = fail
            return_val['skip'] = skip
        elif file_type == 'html':
            report_list = glob.glob(path + '/*.html')
            for file in report_list:
                html = self.reader.read_html_file(file)
                data = html['html']['body']['div']['div'][0]['div']['p'][2]['text']
                data = [x.rstrip(',').rstrip(':') for x in data.split()]
                r = {}
                for i in range(0, len(data), 2):
                    r[data[i]] = data[i + 1]
                return_val['success'] += int(r['Pass']) if 'Pass' in r else 0
                return_val['fail'] += int(r['Fail']) if 'Fail' in r else 0
                return_val['skip'] += int(r['Skip']) if 'Skip' in r else 0

        return return_val
Example #3
0
 def __init__(self):
     self.config = ConfigReader()
     self.mariadb = mariadb.MariaDB()
     self.mongodb = mongodb.MongoDB()
     self.mysql = mysql.MySQL()
     self.oracle = oracle.Oracle()
     self.reader = Reader()
Example #4
0
class Oracle(object):
    def __init__(self):
        self.reader = Reader()

    @timer
    def open_DB_session(self) -> NoReturn:
        def _read_DB_info() -> dict:
            return self.reader.read_json_file(os.getcwd() + '/data/db.json')

        try:
            colored_print('Connecting DB...', 'yellow')
            self.db_info = _read_DB_info()['oracle']
            db_host = self.db_info['host'] + '@' + self.db_info[
                'port'] + '/' + self.db_info['sid']
            self.conn = cx_Oracle.connect(self.db_info['user'],
                                          self.db_info['password'], db_host)
            self.cursor = self.conn.cursor()
        except Exception as e:
            colored_print(e, 'red')
        else:
            colored_print('Done', 'green')

    def close_DB_session(self) -> NoReturn:
        try:
            self.conn.commit()
            self.conn.close()
            self.cursor.close()
        except Exception as e:
            print(e, 'red')
Example #5
0
class PMDParser(object):
    def __init__(self):
        self.reader = Reader()

    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
Example #6
0
class Flake8Parser(object):
    def __init__(self):
        self.reader = Reader()

    def parse(self, path: str, file_type: str) -> dict:
        return_val = {'warning': 0}
        if file_type == 'txt':
            test_result = self.reader.read_raw_file(path)
            return_val['warning'] = len(test_result.split('\n')) - 1
        else:
            colored_print(
                'Sorry, there is no information you can get from this type of file.',
                'orange')

        return return_val
Example #7
0
class SeleniumParser(object):
    def __init__(self):
        self.reader = Reader()

    def parse(self, path: str, file_type: str) -> dict:
        return_val: dict = {'success': 0, 'fail': 0, 'skip': 0}
        if file_type == 'xml':
            xml_path = glob.glob(path + '/**/*.xml', recursive=True)
            for xml_file in xml_path:
                selenium_data = self.reader.read_xml_file(xml_file)
                total = int(selenium_data['testsuites']['@tests'])
                fail = int(selenium_data['testsuites']['@failures'])
                success = total - fail
                return_val['success'] += success
                return_val['fail'] += fail
        else:
            colored_print(
                'Sorry, there is no information you can get from this type of file.',
                'orange')

        return return_val
Example #8
0
class JacocoParser(object):
    def __init__(self):
        self.reader = Reader()

    def parse(self, path: str, file_type: str) -> {str, int}:
        return_val = {'test_val': 0}
        if file_type == 'html':
            html = self.reader.read_html_file(path)
            return_val['test_val'] = int(html['html']['body']['table']['tfoot']
                                         ['tr']['td'][2]['text'].rstrip('%'))
        elif file_type == 'csv':
            # csv = self.reader.read_raw_file(path)
            colored_print(
                'Sorry, there is no information you can get from this type of file.',
                'orange')
            return_val['test_val'] = -1
        elif file_type == 'xml':
            # xml = self.reader.read_xml_file(path)
            return_val['test_val'] = -1

        return return_val
Example #9
0
 def __init__(self):
     self.reader = Reader()
Example #10
0
 def __init__(self) -> NoReturn:
     self._file_reader: Reader = Reader()
     self._file_writer: Writer = Writer()
Example #11
0
 def __init__(self) -> NoReturn:
     self.reader: Reader = Reader()  # 결과 파일을 읽기위해 클래스 선언
Example #12
0
class ESLintParser(object):
    def __init__(self):
        self.reader = Reader()

    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')
Example #13
0
class DatabaseManager(object):
    """Everything that happens in the database is done through this class."""
    def __init__(self):
        self.config = ConfigReader()
        self.mariadb = mariadb.MariaDB()
        self.mongodb = mongodb.MongoDB()
        self.mysql = mysql.MySQL()
        self.oracle = oracle.Oracle()
        self.reader = Reader()

    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 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