diff --git a/src/_pytest/_code/source.py b/src/_pytest/_code/source.py index 379393b10cd..8dc247a067f 100644 --- a/src/_pytest/_code/source.py +++ b/src/_pytest/_code/source.py @@ -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 diff --git a/testing/code/test_source.py b/testing/code/test_source.py index 030e6067625..de4fde3a3f1 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -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