如何在python中获取测试方法的起始行号和结束行号?
我目前正在尝试获取python文件中所有测试方法的第一行和最后一行编号 例如: 文件test_lift.py测试文件lift.py 测试提升.py如何在python中获取测试方法的起始行号和结束行号?,python,pytest,Python,Pytest,我目前正在尝试获取python文件中所有测试方法的第一行和最后一行编号 例如: 文件test_lift.py测试文件lift.py 测试提升.py 1 import random 2 3 from src.lift import Lift 4 from flaky import flaky 5 6 7 def test_upwards(): 8 tester = Lift() 9 tester.upwards() 10 assert 1 == tes
1 import random
2
3 from src.lift import Lift
4 from flaky import flaky
5
6
7 def test_upwards():
8 tester = Lift()
9 tester.upwards()
10 assert 1 == tester.curr_floor
11
12 def test_downwards():
13 tester = Lift()
14 tester.curr_floor = 1
15 tester.downwards()
16 assert 0 == tester.curr_floor
17 tester.downwards()
18 assert 0 == tester.curr_floor
19
...
现在,我想在test_lift.py中获得每个测试方法的第一行和最后一行编号,例如:
向上测试,7,10
测试_向下,12,18
我已经尝试过使用conftest.py,但没有成功。也许我忽略了什么?
解决方案不一定必须使用python。如果有人知道如何通过解析文件来解决这个问题,我很乐意。您可以使用
检查模块来解决这个问题
import inspect
lines,line_start = inspect.getsourcelines(test_downwards)
print("Lines:",line_start,line_start+len(lines) - 1 )
或者,没有任何附加模块(但有一些Python内部构件):
这样就有了:函数从第1行(thing.\uuuuu code\uuu.co\ufirstlineno
)到第4行
dis
模块证明了这一点(第一列中的数字是行号):
注意最后一个数字是4,这是函数最后一行的数字
有关co_lnotab
结构的更多信息,请参见
测试程序
输出:
$ python3 test.py
(1, 5)
(7, 9)
This is line number: 8
This is line number: 10
Variable 'this' at line: 9
Inspect在这方面工作得很好:
import inspect
def line_number():
return inspect.currentframe().f_back.f_lineno
print "This is line number:", line_number()
this = line_number()
print "This is line number:", line_number()
print "Variable 'this' at line: ", this
line_number()
输出:
$ python3 test.py
(1, 5)
(7, 9)
This is line number: 8
This is line number: 10
Variable 'this' at line: 9
Java使用Scanner类,这使得解析文件非常容易;但是,Python也有自己的版本:。请看一下有关读取文件的示例。您可以轻松获取内容。也许可以尝试其他相关功能。
This is line number: 8
This is line number: 10
Variable 'this' at line: 9