Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored main branch #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions doc/en/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@
html_title = "pytest documentation"

# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = "pytest-%s" % release
html_short_title = f"pytest-{release}"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 196-196 refactored with the following changes:


# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
Expand Down Expand Up @@ -402,17 +402,20 @@ def configure_logging(app: "sphinx.application.Sphinx") -> None:
import sphinx.util.logging
import logging



class WarnLogFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
"""Ignore warnings about missing include with "only" directive.

Ref: https://github.com/sphinx-doc/sphinx/issues/2150."""
if (
record.msg.startswith('Problems with "include" directive path:')
and "_changelog_towncrier_draft.rst" in record.msg
):
return False
return True
return (
not record.msg.startswith(
'Problems with "include" directive path:'
)
or "_changelog_towncrier_draft.rst" not in record.msg
)

Comment on lines 404 to +418
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function configure_logging refactored with the following changes:


logger = logging.getLogger(sphinx.util.logging.NAMESPACE)
warn_handler = [x for x in logger.handlers if x.level == logging.WARNING]
Expand Down
5 changes: 2 additions & 3 deletions doc/en/example/assertion/failure_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def test_eq_longer_list(self):
assert [1, 2] == [1, 2, 3]

def test_in_list(self):
assert 1 in [0, 2, 3, 4, 5]
assert 1 in {0, 2, 3, 4, 5}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TestSpecialisedExplanations.test_in_list refactored with the following changes:


def test_not_in_text_multiline(self):
text = "some multiline\ntext\nwhich\nincludes foo\nand a\ntail"
Expand Down Expand Up @@ -180,8 +180,7 @@ def test_reinterpret_fails_with_print_for_the_fun_of_it(self):
a, b = items.pop()

def test_some_error(self):
if namenotexi: # NOQA
pass
pass
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TestRaises.test_some_error refactored with the following changes:

This removes the following comments ( why? ):

# NOQA


def func1(self):
assert 41 == 42
Expand Down
8 changes: 4 additions & 4 deletions doc/en/example/assertion/test_setup_flow_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ def setup_module(module):


class TestStateFullThing:
def setup_class(cls):
cls.classcount += 1
def setup_class(self):
self.classcount += 1
Comment on lines -6 to +7
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TestStateFullThing.setup_class refactored with the following changes:


def teardown_class(cls):
cls.classcount -= 1
def teardown_class(self):
self.classcount -= 1
Comment on lines -9 to +10
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TestStateFullThing.teardown_class refactored with the following changes:


def setup_method(self, method):
self.id = eval(method.__name__[5:])
Expand Down
20 changes: 10 additions & 10 deletions extra/get_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ def main(args):

def _get_kind(issue):
labels = [label["name"] for label in issue["labels"]]
for key in ("bug", "enhancement", "proposal"):
if key in labels:
return key
return "issue"
return next(
(key for key in ("bug", "enhancement", "proposal") if key in labels),
"issue",
)
Comment on lines -49 to +52
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _get_kind refactored with the following changes:

  • Use the built-in function next instead of a for-loop (use-next)



def report(issues):
Expand All @@ -59,15 +59,15 @@ def report(issues):
kind = _get_kind(issue)
status = issue["state"]
number = issue["number"]
link = "https://github.com/pytest-dev/pytest/issues/%s/" % number
link = f"https://github.com/pytest-dev/pytest/issues/{number}/"
print("----")
print(status, kind, link)
print(title)
# print()
# lines = body.split("\n")
# print("\n".join(lines[:3]))
# if len(lines) > 3 or len(body) > 240:
# print("...")
# print()
# lines = body.split("\n")
# print("\n".join(lines[:3]))
# if len(lines) > 3 or len(body) > 240:
# print("...")
Comment on lines -62 to +70
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function report refactored with the following changes:

print("\n\nFound %s open issues" % len(issues))


Expand Down
3 changes: 1 addition & 2 deletions scripts/prepare-release-pr.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ def find_next_version(
output = check_output(["git", "tag"], encoding="UTF-8")
valid_versions = []
for v in output.splitlines():
m = re.match(r"\d.\d.\d+$", v.strip())
if m:
if m := re.match(r"\d.\d.\d+$", v.strip()):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_next_version refactored with the following changes:

valid_versions.append(tuple(int(x) for x in v.split(".")))

valid_versions.sort()
Expand Down
6 changes: 2 additions & 4 deletions scripts/publish-gh-release-notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,10 @@ def parse_changelog(tag_name):
consuming_version = False
version_lines = []
for line in changelog_lines:
m = title_regex.match(line)
if m:
if m := title_regex.match(line):
# found the version we want: start to consume lines until we find the next version title
if m.group(1) == tag_name:
if m[1] == tag_name:
consuming_version = True
# found a new version title while parsing the version we want: break out
Comment on lines -46 to -51
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_changelog refactored with the following changes:

This removes the following comments ( why? ):

# found a new version title while parsing the version we want: break out

elif consuming_version:
break
if consuming_version:
Expand Down
20 changes: 12 additions & 8 deletions scripts/update-plugin-list.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,12 @@ def iter_plugins():
regex = r">([\d\w-]*)</a>"
response = requests.get("https://pypi.org/simple")

matches = list(
matches = [
match
for match in re.finditer(regex, response.text)
if match.groups()[0].startswith("pytest-")
)
]

Comment on lines -55 to +60
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function iter_plugins refactored with the following changes:


for match in tqdm(matches, smoothing=0):
name = match.groups()[0]
Expand All @@ -69,12 +70,15 @@ def iter_plugins():
info = response.json()["info"]
if "Development Status :: 7 - Inactive" in info["classifiers"]:
continue
for classifier in DEVELOPMENT_STATUS_CLASSIFIERS:
if classifier in info["classifiers"]:
status = classifier[22:]
break
else:
status = "N/A"
status = next(
(
classifier[22:]
for classifier in DEVELOPMENT_STATUS_CLASSIFIERS
if classifier in info["classifiers"]
),
"N/A",
)

requires = "N/A"
if info["requires_dist"]:
for requirement in info["requires_dist"]:
Expand Down
2 changes: 1 addition & 1 deletion src/_pytest/_argcomplete.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def __call__(self, prefix: str, **kwargs: Any) -> List[str]:
if "*" not in prefix and "?" not in prefix:
# We are on unix, otherwise no bash.
if not prefix or prefix[-1] == os.path.sep:
globbed.extend(glob(prefix + ".*"))
globbed.extend(glob(f"{prefix}.*"))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function FastFilesCompleter.__call__ refactored with the following changes:

prefix += "*"
globbed.extend(glob(prefix))
for x in sorted(globbed):
Expand Down
112 changes: 49 additions & 63 deletions src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,9 +573,7 @@ def traceback(self, value: Traceback) -> None:
def __repr__(self) -> str:
if self._excinfo is None:
return "<ExceptionInfo for raises contextmanager>"
return "<{} {} tblen={}>".format(
self.__class__.__name__, saferepr(self._excinfo[1]), len(self.traceback)
)
return f"<{self.__class__.__name__} {saferepr(self._excinfo[1])} tblen={len(self.traceback)}>"

def exconly(self, tryshort: bool = False) -> str:
"""Return the exception as a string.
Expand All @@ -588,9 +586,8 @@ def exconly(self, tryshort: bool = False) -> str:
lines = format_exception_only(self.type, self.value)
text = "".join(lines)
text = text.rstrip()
if tryshort:
if text.startswith(self._striptext):
text = text[len(self._striptext) :]
if tryshort and text.startswith(self._striptext):
text = text[len(self._striptext) :]
return text

def errisinstance(
Expand Down Expand Up @@ -726,9 +723,11 @@ def _getentrysource(self, entry: TracebackEntry) -> Optional["Source"]:

def repr_args(self, entry: TracebackEntry) -> Optional["ReprFuncArgs"]:
if self.funcargs:
args = []
for argname, argvalue in entry.frame.getargs(var=True):
args.append((argname, saferepr(argvalue)))
args = [
(argname, saferepr(argvalue))
for argname, argvalue in entry.frame.getargs(var=True)
]

return ReprFuncArgs(args)
return None

Expand All @@ -750,11 +749,9 @@ def get_source(
if short:
lines.append(space_prefix + source.lines[line_index].strip())
else:
for line in source.lines[:line_index]:
lines.append(space_prefix + line)
lines.append(self.flow_marker + " " + source.lines[line_index])
for line in source.lines[line_index + 1 :]:
lines.append(space_prefix + line)
lines.extend(space_prefix + line for line in source.lines[:line_index])
lines.append(f"{self.flow_marker} {source.lines[line_index]}")
lines.extend(space_prefix + line for line in source.lines[line_index + 1 :])
if excinfo is not None:
indent = 4 if short else self._getindent(source)
lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))
Expand All @@ -778,30 +775,27 @@ def get_exconly(
return lines

def repr_locals(self, locals: Mapping[str, object]) -> Optional["ReprLocals"]:
if self.showlocals:
lines = []
keys = [loc for loc in locals if loc[0] != "@"]
keys.sort()
for name in keys:
value = locals[name]
if name == "__builtins__":
lines.append("__builtins__ = <builtins>")
else:
if not self.showlocals:
return None
lines = []
keys = [loc for loc in locals if loc[0] != "@"]
keys.sort()
for name in keys:
value = locals[name]
if name == "__builtins__":
lines.append("__builtins__ = <builtins>")
else:
# This formatting could all be handled by the
# _repr() function, which is only reprlib.Repr in
# disguise, so is very configurable.
if self.truncate_locals:
str_repr = saferepr(value)
else:
str_repr = safeformat(value)
# if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)):
lines.append(f"{name:<10} = {str_repr}")
# else:
# self._line("%-10s =\\" % (name,))
# # XXX
# pprint.pprint(value, stream=self.excinfowriter)
return ReprLocals(lines)
return None
str_repr = saferepr(value) if self.truncate_locals else safeformat(value)
# if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)):
lines.append(f"{name:<10} = {str_repr}")
# else:
# self._line("%-10s =\\" % (name,))
# # XXX
# pprint.pprint(value, stream=self.excinfowriter)
return ReprLocals(lines)

def repr_traceback_entry(
self,
Expand All @@ -818,13 +812,10 @@ def repr_traceback_entry(
else:
line_index = entry.lineno - entry.getfirstlinesource()
short = style == "short"
reprargs = self.repr_args(entry) if not short else None
reprargs = None if short else self.repr_args(entry)
s = self.get_source(source, line_index, excinfo, short=short)
lines.extend(s)
if short:
message = "in %s" % (entry.name)
else:
message = excinfo and excinfo.typename or ""
message = f"in {entry.name}" if short else excinfo and excinfo.typename or ""
entry_path = entry.path
path = self._makepath(entry_path)
reprfileloc = ReprFileLocation(path, entry.lineno + 1, message)
Expand Down Expand Up @@ -866,7 +857,7 @@ def repr_traceback(self, excinfo: ExceptionInfo[BaseException]) -> "ReprTracebac
entries.append(reprentry)
return ReprTraceback(entries, None, style=self.style)

for index, entry in enumerate(traceback):
for entry in traceback:
einfo = (last == entry) and excinfo or None
reprentry = self.repr_traceback_entry(entry, einfo)
entries.append(reprentry)
Expand Down Expand Up @@ -1199,22 +1190,22 @@ class ReprFuncArgs(TerminalRepr):
args: Sequence[Tuple[str, object]]

def toterminal(self, tw: TerminalWriter) -> None:
if self.args:
linesofar = ""
for name, value in self.args:
ns = f"{name} = {value}"
if len(ns) + len(linesofar) + 2 > tw.fullwidth:
if linesofar:
tw.line(linesofar)
linesofar = ns
else:
if linesofar:
linesofar += ", " + ns
else:
linesofar = ns
if linesofar:
tw.line(linesofar)
tw.line("")
if not self.args:
return
linesofar = ""
for name, value in self.args:
ns = f"{name} = {value}"
if len(ns) + len(linesofar) + 2 > tw.fullwidth:
if linesofar:
tw.line(linesofar)
linesofar = ns
elif linesofar:
linesofar += f", {ns}"
else:
linesofar = ns
if linesofar:
tw.line(linesofar)
tw.line("")


def getfslineno(obj: object) -> Tuple[Union[str, Path], int]:
Expand Down Expand Up @@ -1284,9 +1275,4 @@ def filter_traceback(entry: TracebackEntry) -> bool:
p = Path(entry.path)

parents = p.parents
if _PLUGGY_DIR in parents:
return False
if _PYTEST_DIR in parents:
return False

return True
return False if _PLUGGY_DIR in parents else _PYTEST_DIR not in parents
Loading