Skip to content

[WIP] typing: fix _pytest._code.source.getfslineno: returns str; assignment #6590

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

Closed
wants to merge 5 commits into from
Closed
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
31 changes: 12 additions & 19 deletions src/_pytest/_code/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,33 +282,26 @@ def compile_( # noqa: F811
return s.compile(filename, mode, flags, _genframe=_genframe)


def getfslineno(obj) -> Tuple[Optional[Union["Literal['']", py.path.local]], int]:
def getfslineno(obj: object) -> Tuple[Optional[Union[str, py.path.local]], int]:
""" Return source location (path, lineno) for the given object.
If the source cannot be determined return ("", -1).

The line number is 0-based.
"""
from .code import Code

try:
code = Code(obj)
fn = inspect.getsourcefile(obj) or inspect.getfile(obj) # type: ignore[arg-type] # noqa: F821
except TypeError:
return "", -1

assert fn, repr(fn)

fspath = fn and py.path.local(fn) or None
lineno = -1
if fspath:
try:
fn = inspect.getsourcefile(obj) or inspect.getfile(obj)
except TypeError:
return "", -1

fspath = fn and py.path.local(fn) or None
lineno = -1
if fspath:
try:
_, lineno = findsource(obj)
except IOError:
pass
else:
fspath = code.path
lineno = code.firstlineno
assert isinstance(lineno, int)
_, lineno = findsource(obj)
except IOError:
pass
return fspath, lineno


Expand Down
1 change: 1 addition & 0 deletions testing/code/test_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,7 @@ class A:
fspath, lineno = getfslineno(A)

_, A_lineno = inspect.findsource(A)
assert isinstance(fspath, py.path.local)
assert fspath.basename == "test_source.py"
assert lineno == A_lineno

Expand Down