Skip to content

Commit

Permalink
Add multiline tests
Browse files Browse the repository at this point in the history
Update type annotations
  • Loading branch information
plinss committed Aug 19, 2022
1 parent 915b4e7 commit bb2054e
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 22 deletions.
8 changes: 5 additions & 3 deletions flake8_noqa/noqa_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import enum
import re
import tokenize
from typing import ClassVar, Iterator, Sequence, Tuple
from typing import ClassVar, TYPE_CHECKING

import flake8_noqa

Expand All @@ -14,6 +14,8 @@
from . import noqa_filter
from .noqa_comment import FileComment, InlineComment

if (TYPE_CHECKING):
from collections.abc import Iterator, Sequence

try:
try:
Expand Down Expand Up @@ -75,10 +77,10 @@ def __init__(self, logical_line: str, tokens: Sequence[tokenize.TokenInfo], file
self.tokens = tokens
self.filename = filename

def _message(self, token: tokenize.TokenInfo, message: Message, **kwargs) -> Tuple[Tuple[int, int], str]:
def _message(self, token: tokenize.TokenInfo, message: Message, **kwargs) -> tuple[tuple[int, int], str]:
return (token.start, f'{message.code}{self.plugin_name} {message.text(**kwargs)}')

def __iter__(self) -> Iterator[Tuple[Tuple[int, int], str]]:
def __iter__(self) -> Iterator[tuple[tuple[int, int], str]]:
"""Primary call from flake8, yield error messages."""
prev_token = None
for token in self.tokens:
Expand Down
13 changes: 7 additions & 6 deletions flake8_noqa/noqa_comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

import re
from typing import ClassVar, Dict, List, Match, Optional, Sequence, TYPE_CHECKING
from typing import ClassVar, TYPE_CHECKING

import flake8.checker
import flake8.defaults
Expand All @@ -12,6 +12,7 @@
import flake8.utils

if (TYPE_CHECKING):
from collections.abc import Sequence
from tokenize import TokenInfo


Expand All @@ -29,14 +30,14 @@ class FileComment:
token: TokenInfo

@classmethod
def match(cls, token: TokenInfo) -> Optional[FileComment]:
def match(cls, token: TokenInfo) -> (FileComment | None):
"""Create a FileComment if it matches the token."""
match = NOQA_FILE.match(token.string)
if (not match):
return None
return FileComment(match, token)

def __init__(self, match: Match, token: TokenInfo) -> None:
def __init__(self, match: re.Match, token: TokenInfo) -> None:
self.flake8 = match.group('flake8')
self.sep = match.group('sep') or ''
self.noqa = match.group('noqa')
Expand All @@ -47,7 +48,7 @@ def __init__(self, match: Match, token: TokenInfo) -> None:
class InlineComment:
"""noqa comment info."""

comments: ClassVar[Dict[str, List[InlineComment]]] = {}
comments: ClassVar[dict[str, list[InlineComment]]] = {}

noqa: str
sep: str
Expand All @@ -58,7 +59,7 @@ class InlineComment:
start_line: int

@classmethod
def match(cls, token: TokenInfo, prev_token: TokenInfo = None) -> Optional[InlineComment]:
def match(cls, token: TokenInfo, prev_token: TokenInfo = None) -> (InlineComment | None):
"""Create an InlineComment if it matches the token."""
match = NOQA_INLINE.search(token.string)
if (not match):
Expand All @@ -79,7 +80,7 @@ def start_line(comment: InlineComment) -> int:
return comment.start_line
return sorted(cls.comments.get(filename, []), key=start_line)

def __init__(self, match: Match, token: TokenInfo, prev_token: TokenInfo = None) -> None:
def __init__(self, match: re.Match, token: TokenInfo, prev_token: TokenInfo = None) -> None:
self.noqa = match.group('noqa')
self.sep = match.group('sep') or ''
self.codes = match.group('codes') or ''
Expand Down
21 changes: 11 additions & 10 deletions flake8_noqa/noqa_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

import enum
from typing import Any, ClassVar, Dict, Iterator, List, Optional, Sequence, Set, TYPE_CHECKING, Tuple
from typing import Any, ClassVar, TYPE_CHECKING

import flake8.checker
import flake8.defaults
Expand All @@ -20,6 +20,7 @@
if (TYPE_CHECKING):
import ast
import tokenize
from collections.abc import Iterator, Sequence


try:
Expand All @@ -35,10 +36,10 @@
class Report:
"""Violation report info."""

reports: ClassVar[Dict[str, Dict[int, List[str]]]] = {}
reports: ClassVar[dict[str, dict[int, list[str]]]] = {}

@classmethod
def add_report(cls, filename: str, error_code: Optional[str], line_number: int, column: int, text: str) -> None:
def add_report(cls, filename: str, error_code: (str | None), line_number: int, column: int, text: str) -> None:
"""Add violation report to master list."""
code = error_code if (error_code is not None) else text.split(' ', 1)[0]
if (code.startswith(flake8_noqa.plugin_prefix)):
Expand All @@ -52,7 +53,7 @@ def add_report(cls, filename: str, error_code: Optional[str], line_number: int,
@classmethod
def reports_from(cls, filename: str, start_line: int, end_line: int) -> Sequence[str]:
"""Get all volation reports for a range of lines."""
reports: List[str] = []
reports: list[str] = []
for line_number in range(start_line, end_line + 1):
reports += cls.reports.get(filename, {}).get(line_number, [])
return reports
Expand Down Expand Up @@ -90,7 +91,7 @@ class NoqaFilter:
version: ClassVar[str] = package_version
plugin_name: ClassVar[str]
require_code: ClassVar[bool]
_filters: ClassVar[List[NoqaFilter]] = []
_filters: ClassVar[list[NoqaFilter]] = []

tree: ast.AST
filename: str
Expand Down Expand Up @@ -132,20 +133,20 @@ def __init__(self, tree: ast.AST, filename: str) -> None:
self.filename = filename
self._filters.append(self)

def __iter__(self) -> Iterator[Tuple[int, int, str, Any]]:
def __iter__(self) -> Iterator[tuple[int, int, str, Any]]:
"""Primary call from flake8, yield violations."""
return iter([])

def _message(self, token: tokenize.TokenInfo, message: Message, **kwargs) -> Tuple[int, int, str, Any]:
def _message(self, token: tokenize.TokenInfo, message: Message, **kwargs) -> tuple[int, int, str, Any]:
return (token.start[0], token.start[1], f'{message.code}{self.plugin_name} {message.text(**kwargs)}', type(self))

def violations(self) -> Iterator[Tuple[int, int, str, Any]]:
def violations(self) -> Iterator[tuple[int, int, str, Any]]:
"""Private iterator to return violations."""
for comment in InlineComment.file_comments(self.filename):
reports = Report.reports_from(self.filename, comment.start_line, comment.end_line)
comment_codes = set(comment.code_list)
if (comment_codes):
matched_codes: Set[str] = set()
matched_codes: set[str] = set()
for code in reports:
if (code in comment_codes):
matched_codes.add(code)
Expand Down Expand Up @@ -192,7 +193,7 @@ def run_checks(self, *args, **kwargs) -> Any:
NoqaFilter.clear_filters()
return result

def report(self, error_code: Optional[str], line_number: int, column: int, text: str, *args, **kwargs) -> str:
def report(self, error_code: (str | None), line_number: int, column: int, text: str, *args, **kwargs) -> str:
"""Capture report information."""
Report.add_report(self.filename, error_code, line_number, column, text)
return super().report(error_code, line_number, column, text, *args, **kwargs)
Expand Down
3 changes: 1 addition & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
'flake8-literal',
'flake8-noqa',
'flake8-polyfill',
'flake8-postponed-annotations',
'flake8-modern-annotations',
'flake8-requirements',
# 'flake8-smart-tabs',
'flake8-tabs',
Expand All @@ -50,7 +50,6 @@
'pep8-naming',
],
'test': [
'flake8-docstrings',
],
},
classifiers=[
Expand Down
5 changes: 4 additions & 1 deletion test.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,14 +133,17 @@ def test_codes(self) -> None:
'1:5: NQA005 "# noqa: E225, E225" has duplicate codes, remove E225',
])

def test_multiline(self) -> None:
self.assertEqual(flake8("x='''\n''' # noqa: E225"), [])

def test_double(self) -> None:
self.assertEqual(flake8('x=1 # type: ignore[type] # noqa: X101'), [
'1:5: NQA102 "# noqa: X101" has no matching violations',
])

def test_require_code(self) -> None:
self.assertEqual(flake8('x=1 # noqa', ['--noqa-require-code']), [
'1:5: NQA104 "# noqa" must have codes, e.g. "# noqa: D100, E225, E261, W292"',
'1:5: NQA104 "# noqa" must have codes, e.g. "# noqa: E225, E261, W292"',
])

def test_inlude_name(self) -> None:
Expand Down

0 comments on commit bb2054e

Please sign in to comment.