Skip to content

Commit 531416c

Browse files
committed
code: simplify Code construction
1 parent 6506f01 commit 531416c

File tree

7 files changed

+40
-45
lines changed

7 files changed

+40
-45
lines changed

src/_pytest/_code/code.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,12 @@ class Code:
5656

5757
__slots__ = ("raw",)
5858

59-
def __init__(self, rawcode) -> None:
60-
if not hasattr(rawcode, "co_filename"):
61-
rawcode = getrawcode(rawcode)
62-
if not isinstance(rawcode, CodeType):
63-
raise TypeError(f"not a code object: {rawcode!r}")
64-
self.raw = rawcode
59+
def __init__(self, obj: CodeType) -> None:
60+
self.raw = obj
61+
62+
@classmethod
63+
def from_function(cls, obj: object) -> "Code":
64+
return cls(getrawcode(obj))
6565

6666
def __eq__(self, other):
6767
return self.raw == other.raw
@@ -1196,7 +1196,7 @@ def getfslineno(obj: object) -> Tuple[Union[str, py.path.local], int]:
11961196
obj = obj.place_as # type: ignore[attr-defined]
11971197

11981198
try:
1199-
code = Code(obj)
1199+
code = Code.from_function(obj)
12001200
except TypeError:
12011201
try:
12021202
fn = inspect.getsourcefile(obj) or inspect.getfile(obj) # type: ignore[arg-type]

src/_pytest/_code/source.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import inspect
33
import textwrap
44
import tokenize
5+
import types
56
import warnings
67
from bisect import bisect_right
78
from typing import Iterable
@@ -29,8 +30,11 @@ def __init__(self, obj: object = None) -> None:
2930
elif isinstance(obj, str):
3031
self.lines = deindent(obj.split("\n"))
3132
else:
32-
rawcode = getrawcode(obj)
33-
src = inspect.getsource(rawcode)
33+
try:
34+
rawcode = getrawcode(obj)
35+
src = inspect.getsource(rawcode)
36+
except TypeError:
37+
src = inspect.getsource(obj) # type: ignore[arg-type]
3438
self.lines = deindent(src.split("\n"))
3539

3640
def __eq__(self, other: object) -> bool:
@@ -122,19 +126,17 @@ def findsource(obj) -> Tuple[Optional[Source], int]:
122126
return source, lineno
123127

124128

125-
def getrawcode(obj, trycall: bool = True):
129+
def getrawcode(obj: object, trycall: bool = True) -> types.CodeType:
126130
"""Return code object for given function."""
127131
try:
128-
return obj.__code__
132+
return obj.__code__ # type: ignore[attr-defined,no-any-return]
129133
except AttributeError:
130-
obj = getattr(obj, "f_code", obj)
131-
obj = getattr(obj, "__code__", obj)
132-
if trycall and not hasattr(obj, "co_firstlineno"):
133-
if hasattr(obj, "__call__") and not inspect.isclass(obj):
134-
x = getrawcode(obj.__call__, trycall=False)
135-
if hasattr(x, "co_firstlineno"):
136-
return x
137-
return obj
134+
pass
135+
if trycall:
136+
call = getattr(obj, "__call__", None)
137+
if call and not isinstance(obj, type):
138+
return getrawcode(call, trycall=False)
139+
raise TypeError(f"could not get code object for {obj!r}")
138140

139141

140142
def deindent(lines: Iterable[str]) -> List[str]:

src/_pytest/python.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1647,7 +1647,7 @@ def setup(self) -> None:
16471647

16481648
def _prunetraceback(self, excinfo: ExceptionInfo[BaseException]) -> None:
16491649
if hasattr(self, "_obj") and not self.config.getoption("fulltrace", False):
1650-
code = _pytest._code.Code(get_real_func(self.obj))
1650+
code = _pytest._code.Code.from_function(get_real_func(self.obj))
16511651
path, firstlineno = code.path, code.firstlineno
16521652
traceback = excinfo.traceback
16531653
ntraceback = traceback.cut(path=path, firstlineno=firstlineno)

testing/code/test_code.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,25 +28,26 @@ def test_code_gives_back_name_for_not_existing_file() -> None:
2828
assert code.fullsource is None
2929

3030

31-
def test_code_with_class() -> None:
31+
def test_code_from_function_with_class() -> None:
3232
class A:
3333
pass
3434

35-
pytest.raises(TypeError, Code, A)
35+
with pytest.raises(TypeError):
36+
Code.from_function(A)
3637

3738

3839
def x() -> None:
3940
raise NotImplementedError()
4041

4142

4243
def test_code_fullsource() -> None:
43-
code = Code(x)
44+
code = Code.from_function(x)
4445
full = code.fullsource
4546
assert "test_code_fullsource()" in str(full)
4647

4748

4849
def test_code_source() -> None:
49-
code = Code(x)
50+
code = Code.from_function(x)
5051
src = code.source()
5152
expected = """def x() -> None:
5253
raise NotImplementedError()"""
@@ -73,7 +74,7 @@ def func() -> FrameType:
7374

7475

7576
def test_code_from_func() -> None:
76-
co = Code(test_frame_getsourcelineno_myself)
77+
co = Code.from_function(test_frame_getsourcelineno_myself)
7778
assert co.firstlineno
7879
assert co.path
7980

@@ -92,25 +93,25 @@ def test_code_getargs() -> None:
9293
def f1(x):
9394
raise NotImplementedError()
9495

95-
c1 = Code(f1)
96+
c1 = Code.from_function(f1)
9697
assert c1.getargs(var=True) == ("x",)
9798

9899
def f2(x, *y):
99100
raise NotImplementedError()
100101

101-
c2 = Code(f2)
102+
c2 = Code.from_function(f2)
102103
assert c2.getargs(var=True) == ("x", "y")
103104

104105
def f3(x, **z):
105106
raise NotImplementedError()
106107

107-
c3 = Code(f3)
108+
c3 = Code.from_function(f3)
108109
assert c3.getargs(var=True) == ("x", "z")
109110

110111
def f4(x, *y, **z):
111112
raise NotImplementedError()
112113

113-
c4 = Code(f4)
114+
c4 = Code.from_function(f4)
114115
assert c4.getargs(var=True) == ("x", "y", "z")
115116

116117

testing/code/test_excinfo.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def xyz():
147147
]
148148

149149
def test_traceback_cut(self):
150-
co = _pytest._code.Code(f)
150+
co = _pytest._code.Code.from_function(f)
151151
path, firstlineno = co.path, co.firstlineno
152152
traceback = self.excinfo.traceback
153153
newtraceback = traceback.cut(path=path, firstlineno=firstlineno)
@@ -290,7 +290,7 @@ def f():
290290
excinfo = pytest.raises(ValueError, f)
291291
tb = excinfo.traceback
292292
entry = tb.getcrashentry()
293-
co = _pytest._code.Code(h)
293+
co = _pytest._code.Code.from_function(h)
294294
assert entry.frame.code.path == co.path
295295
assert entry.lineno == co.firstlineno + 1
296296
assert entry.frame.code.name == "h"
@@ -307,7 +307,7 @@ def f():
307307
excinfo = pytest.raises(ValueError, f)
308308
tb = excinfo.traceback
309309
entry = tb.getcrashentry()
310-
co = _pytest._code.Code(g)
310+
co = _pytest._code.Code.from_function(g)
311311
assert entry.frame.code.path == co.path
312312
assert entry.lineno == co.firstlineno + 2
313313
assert entry.frame.code.name == "g"

testing/code/test_source.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616
import pytest
1717
from _pytest._code import Code
1818
from _pytest._code import Frame
19-
from _pytest._code import Source
2019
from _pytest._code import getfslineno
20+
from _pytest._code import Source
2121

2222

2323
def test_source_str_function() -> None:
@@ -291,7 +291,7 @@ def test_source_of_class_at_eof_without_newline(tmpdir, _sys_snapshot) -> None:
291291
# does not return the "x = 1" last line.
292292
source = Source(
293293
"""
294-
class A(object):
294+
class A:
295295
def method(self):
296296
x = 1
297297
"""
@@ -374,14 +374,6 @@ class B:
374374
B.__name__ = B.__qualname__ = "B2"
375375
assert getfslineno(B)[1] == -1
376376

377-
co = compile("...", "", "eval")
378-
assert co.co_filename == ""
379-
380-
if hasattr(sys, "pypy_version_info"):
381-
assert getfslineno(co) == ("", -1)
382-
else:
383-
assert getfslineno(co) == ("", 0)
384-
385377

386378
def test_code_of_object_instance_with_call() -> None:
387379
class A:
@@ -393,14 +385,14 @@ class WithCall:
393385
def __call__(self) -> None:
394386
pass
395387

396-
code = Code(WithCall())
388+
code = Code.from_function(WithCall())
397389
assert "pass" in str(code.source())
398390

399391
class Hello:
400392
def __call__(self) -> None:
401393
pass
402394

403-
pytest.raises(TypeError, lambda: Code(Hello))
395+
pytest.raises(TypeError, lambda: Code.from_function(Hello))
404396

405397

406398
def getstatement(lineno: int, source) -> Source:

testing/test_assertrewrite.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def getmsg(
4242
f, extra_ns: Optional[Mapping[str, object]] = None, *, must_pass: bool = False
4343
) -> Optional[str]:
4444
"""Rewrite the assertions in f, run it, and get the failure message."""
45-
src = "\n".join(_pytest._code.Code(f).source().lines)
45+
src = "\n".join(_pytest._code.Code.from_function(f).source().lines)
4646
mod = rewrite(src)
4747
code = compile(mod, "<test>", "exec")
4848
ns: Dict[str, object] = {}

0 commit comments

Comments
 (0)