예제 #1
0
파일: oracle.py 프로젝트: Minsoo-web/TIMO
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')
예제 #2
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
예제 #3
0
파일: eslint.py 프로젝트: Minsoo-web/TIMO
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')
예제 #4
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