Beispiel #1
0
 def run_tests(filename):
     """Run all the tests from a file."""
     lines = readlines(filename) + ['#:\n']
     line_offset = 0
     codes = ['Okay']
     testcase = []
     count_files = report.counters['files']
     for index, line in enumerate(lines):
         if not line.startswith('#:'):
             if codes:
                 # Collect the lines of the test case
                 testcase.append(line)
             continue
         if codes and index:
             if 'noeol' in codes:
                 testcase[-1] = testcase[-1].rstrip('\n')
             codes = [c for c in codes if c not in ('Okay', 'noeol')]
             # Run the checker
             runner(filename,
                    testcase,
                    expected=codes,
                    line_offset=line_offset)
         # output the real line numbers
         line_offset = index + 1
         # configure the expected errors
         codes = line.split()[1:]
         # empty the test case buffer
         del testcase[:]
     report.counters['files'] = count_files + 1
     return report.counters['failed tests']
Beispiel #2
0
 def run_tests(filename):
     """Run all the tests from a file."""
     lines = readlines(filename) + ['#:\n']
     line_offset = 0
     codes = ['Okay']
     testcase = []
     count_files = report.counters['files']
     for index, line in enumerate(lines):
         if not line.startswith('#:'):
             if codes:
                 # Collect the lines of the test case
                 testcase.append(line)
             continue
         if codes and index:
             if 'noeol' in codes:
                 testcase[-1] = testcase[-1].rstrip('\n')
             codes = [c for c in codes
                      if c not in ('Okay', 'noeol')]
             # Run the checker
             runner(filename, testcase, expected=codes,
                    line_offset=line_offset)
         # output the real line numbers
         line_offset = index + 1
         # configure the expected errors
         codes = line.split()[1:]
         # empty the test case buffer
         del testcase[:]
     report.counters['files'] = count_files + 1
     return report.counters['failed tests']
Beispiel #3
0
    def load_file(self):
        if self.filename in ('stdin', '-', None):
            self.filename = 'stdin'
            self.lines = pycodestyle.stdin_get_value().splitlines(True)
        else:
            self.lines = pycodestyle.readlines(self.filename)

        if not self.tree:
            self.tree = ast.parse(''.join(self.lines))
Beispiel #4
0
    def load_file(self):
        if self.filename in ("stdin", "-", None):
            self.filename = "stdin"
            self.lines = pycodestyle.stdin_get_value().splitlines(True)
        else:
            self.lines = pycodestyle.readlines(self.filename)

        if not self.tree:
            self.tree = ast.parse("".join(self.lines))
Beispiel #5
0
    def load_file(self):
        if self.filename in ("stdin", "-", None):
            self.filename = "stdin"
            self.lines = stdin_utils.stdin_get_value().splitlines(True)
        else:
            self.lines = pycodestyle.readlines(self.filename)

        if not self.tree:
            self.tree = ast.parse("".join(self.lines))
    def run(self):
        lines = pycodestyle.readlines(self.filename)
        for node in UnitupleVisitor(self.tree):
            line = lines[node.lineno - 1].rstrip()
            if pycodestyle.noqa(line):
                continue

            has, col = has_terse_tuple(line)
            if has:
                yield node.lineno, col, T001, type(self)
Beispiel #7
0
    def read_headers(self):
        try:
            # flake8 >= v3.0
            import pycodestyle as pep8
        except ImportError:
            import pep8

        if self.filename in ('stdin', '-', None):
            return pep8.stdin_get_value().splitlines(True)[:2]
        else:
            return pep8.readlines(self.filename)[:2]
    def read_headers(self):
        try:
            # flake8 >= v3.0
            import pycodestyle as pep8
        except ImportError:
            import pep8

        if self.filename in ('stdin', '-', None):
            return pep8.stdin_get_value().splitlines(True)[:2]
        else:
            return pep8.readlines(self.filename)[:2]
Beispiel #9
0
def get_tokens(filename):
    if filename == 'stdin':
        file_contents = stdin_utils.stdin_get_value().splitlines(True)
    else:
        file_contents = pycodestyle.readlines(filename)
    file_contents_iter = iter(file_contents)

    def file_contents_next():
        return next(file_contents_iter)

    for t in tokenize.generate_tokens(file_contents_next):
        yield Token(t)
Beispiel #10
0
def get_tokens(filename):
    if filename == 'stdin':
        file_contents = stdin_utils.stdin_get_value().splitlines(True)
    else:
        file_contents = pycodestyle.readlines(filename)
    file_contents_iter = iter(file_contents)

    def file_contents_next():
        return next(file_contents_iter)

    for t in tokenize.generate_tokens(file_contents_next):
        yield Token(t)
Beispiel #11
0
 def read_headers(self):
     if self.filename in ('stdin', '-', None):
         try:
             # flake8 >= v3.0
             from flake8.engine import pep8 as stdin_utils
         except ImportError:
             from flake8 import utils as stdin_utils
         return stdin_utils.stdin_get_value().splitlines(True)[:2]
     else:
         try:
             import pycodestyle
         except ImportError:
             import pep8 as pycodestyle
         return pycodestyle.readlines(self.filename)[:2]
Beispiel #12
0
    def _load_source(self):
        """Loads the file in a way that auto-detects source encoding and deals
        with broken terminal encodings for stdin.

        Stolen from flake8_import_order because it's good.
        """

        if self.filename in ("stdin", "-", None):
            self.filename = "stdin"
            self.lines = stdin_utils.stdin_get_value().splitlines(True)
        else:
            self.lines = pycodestyle.readlines(self.filename)
        if not self.tree:
            self.tree = ast.parse("".join(self.lines))
Beispiel #13
0
    def load_file(self):
        """
        Loads the file in a way that auto-detects source encoding and deals
        with broken terminal encodings for stdin.
        Stolen from flake8_import_order because it's good.
        """

        if self.filename in ("stdin", "-", None):
            self.filename = "stdin"
            self.lines = pycodestyle.stdin_get_value().splitlines(True)
        else:
            self.lines = pycodestyle.readlines(self.filename)

        if not self.tree:
            self.tree = ast.parse("".join(self.lines))
Beispiel #14
0
    def run(self):
        filename = self.filename

        if filename == 'stdin':
            lines = stdin_utils.stdin_get_value().splitlines(True)
        else:
            lines = pycodestyle.readlines(filename)

        for idx, line in enumerate(lines):
            line = line.strip()
            if line and line in ['},', '),', '],']:
                yield (
                    idx,
                    len(line),
                    "My Word!",
                    "C811",
                )
Beispiel #15
0
    def handle(self, error):  # type: (Violation) -> None
        """Handle an error reported by Flake8.

        This defaults to calling :meth:`format`, :meth:`show_source`, and
        then :meth:`write`. This version implements the pattern-based ignore
        behavior from `spack flake8` as a native flake8 plugin.

        :param error:
            This will be an instance of
            :class:`~flake8.style_guide.Violation`.
        :type error:
            flake8.style_guide.Violation
        """

        # print(error.code)
        # print(error.physical_line)
        # get list of patterns for this error code
        pats = self.spack_errors.get(error.code, None)
        # if any pattern matches, skip line
        if pats is not None and any(
            (pat.search(error.physical_line) for pat in pats)):
            return

        # Special F811 handling
        # Prior to Python 3.8, `noqa: F811` needed to be placed on the `@when`
        # line
        # Starting with Python 3.8, it must be placed on the `def` line
        # https://gitlab.com/pycqa/flake8/issues/583
        # we can only determine if F811 should be ignored given the previous
        # line, so get the previous line and check it
        if (self.spack_errors.get("F811", False) and error.code == "F811"
                and error.line_number > 1):
            if self.file_lines is None:
                if self.filename in {"stdin", "-", "(none)", None}:
                    self.file_lines = pycodestyle.stdin_get_value().splitlines(
                        True)
                else:
                    self.file_lines = pycodestyle.readlines(self.filename)
            for pat in self.spack_errors["F811"]:
                if pat.search(self.file_lines[error.line_number - 2]):
                    return

        self.error_seen = True
        line = self.format(error)
        source = self.show_source(error)
        self.write(line, source)
Beispiel #16
0
    def run(self):
        if self.filename in ('stdin', '-', None):
            self.filename = 'stdin'
            self.lines = pycodestyle.stdin_get_value().splitlines(True)
        else:
            self.lines = pycodestyle.readlines(self.filename)

        if not self.tree:
            self.tree = ast.parse(''.join(self.lines))

        for node in ast.walk(self.tree):
            for child_node in ast.iter_child_nodes(node):
                child_node._flake8_datetimez_parent = node

        visitor = DateTimeZVisitor()
        visitor.visit(self.tree)

        for err in visitor.errors:
            yield err
Beispiel #17
0
 def run_tests(filename):
     """Run all the tests from a file."""
     # Skip tests meant for higher versions of python
     ver_match = re.search(r'python(\d)(\d+)?\.py$', filename)
     if ver_match:
         test_against_version = tuple(
             int(val or 0) for val in ver_match.groups())
         if sys.version_info < test_against_version:
             return
     lines = readlines(filename) + ['#:\n']
     line_offset = 0
     codes = ['Okay']
     testcase = []
     count_files = report.counters['files']
     for index, line in enumerate(lines):
         if not line.startswith('#:'):
             if codes:
                 # Collect the lines of the test case
                 testcase.append(line)
             continue
         if codes and index:
             if 'noeol' in codes:
                 testcase[-1] = testcase[-1].rstrip('\n')
             codes = [c for c in codes if c not in ('Okay', 'noeol')]
             # Run the checker
             runner(filename,
                    testcase,
                    expected=codes,
                    line_offset=line_offset)
         # output the real line numbers
         line_offset = index + 1
         # configure the expected errors
         codes = line.split()[1:]
         # empty the test case buffer
         del testcase[:]
     report.counters['files'] = count_files + 1
     return report.counters['failed tests']
Beispiel #18
0
    def run(self):
        """Auto Call Validation"""

        formatted_filename = self.filename.replace('\\', '_').replace('/', '_')
        if re.match(r'.*tests_cases.+', formatted_filename):
            sanitized_filename = os.path.splitext(
                os.path.basename(self.filename))[0]
            if (not re.match(
                    r'^test_(post|get|put|delete|patch|smoke_test)_\w+$',
                    sanitized_filename) and
                    not re.match(r'.*database_tests.+', formatted_filename)):
                if not re.match(r'^__init__$', sanitized_filename):
                    yield 0, 0, ERROR['MC100'], type(self)
            else:
                errors = []

                read_line = list(pycodestyle.readlines(self.filename))
                for line_number, line in enumerate(read_line):
                    if line.strip().startswith(constants.CLASS):  # Check class
                        # Checking the occurrence of the file name in the class name
                        if sanitized_filename.replace(
                                '_', '') not in line[len(constants.CLASS) +
                                                     1:-1].lower():
                            yield line_number + 1, len(
                                constants.CLASS) + 1, ERROR['MC101'], type(
                                    self)

                    if line.strip().startswith(constants.DEF):
                        errors += function_validator(line, line_number,
                                                     read_line)

                if self.tokens:
                    errors += token_parser(self.tokens)

                for error in errors:
                    yield error[0] + 1, error[1], error[2], type(self)
Beispiel #19
0
 def run_tests(filename):
     """Run all the tests from a file."""
     # Skip tests meant for higher versions of python
     ver_match = re.search(r'python(\d)(\d)?\.py$', filename)
     if ver_match:
         test_against_version = tuple(int(val or 0)
                                      for val in ver_match.groups())
         if sys.version_info < test_against_version:
             return
     lines = readlines(filename) + ['#:\n']
     line_offset = 0
     codes = ['Okay']
     testcase = []
     count_files = report.counters['files']
     for index, line in enumerate(lines):
         if not line.startswith('#:'):
             if codes:
                 # Collect the lines of the test case
                 testcase.append(line)
             continue
         if codes and index:
             if 'noeol' in codes:
                 testcase[-1] = testcase[-1].rstrip('\n')
             codes = [c for c in codes
                      if c not in ('Okay', 'noeol')]
             # Run the checker
             runner(filename, testcase, expected=codes,
                    line_offset=line_offset)
         # output the real line numbers
         line_offset = index + 1
         # configure the expected errors
         codes = line.split()[1:]
         # empty the test case buffer
         del testcase[:]
     report.counters['files'] = count_files + 1
     return report.counters['failed tests']
Beispiel #20
0
def get_lines(filename):
    if filename in ("stdin", "-", None):
        return pep8.stdin_get_value().splitlines(True)
    else:
        return pep8.readlines(filename)
Beispiel #21
0
def get_lines(filename):
    if filename in ('stdin', '-', None):
        return stdin_utils.stdin_get_value().splitlines(True)
    else:
        return pep8.readlines(filename)
Beispiel #22
0
 def load_file(self):
     if self.filename in ('stdin', '-', None):
         self.filename = 'stdin'
         self.lines = pycodestyle.stdin_get_value().splitlines(True)
     else:
         self.lines = pycodestyle.readlines(self.filename)
def get_lines(filename):
    if filename in ("stdin", "-", None):
        return pycodestyle.stdin_get_value().splitlines(True)
    else:
        return pycodestyle.readlines(filename)
Beispiel #24
0
 def get_file_contents(self):
     if self.filename in ('stdin', '-', None):
         return pycodestyle.stdin_get_value().splitlines(True)
     else:
         return pycodestyle.readlines(self.filename)
Beispiel #25
0
def read_file_lines(name):
    """Read and return all the lines of a file."""
    return pycodestyle.readlines(name)
Beispiel #26
0
 def get_file_contents(self):
     if self.filename in ('stdin', '-', None):
         return pycodestyle.stdin_get_value().splitlines(True)
     else:
         return pycodestyle.readlines(self.filename)
Beispiel #27
0
 def _get_file_content(self) -> List[str]:
     """Return file content as a list of lines."""
     if self.filename in ('stdin', '-', None):
         return stdin_get_value().splitlines(True)
     else:
         return readlines(self.filename)