2021年2月22日 星期一

[ Python 常見問題 ] Pytest - How to get the current test's name from the setup method?

 Source From Here

Question
I am using py.test and wonder if/how it is possible to retrieve the name of the currently executed test within the setup method that is invoked before running each test. Consider this code:
  1. class TestSomething(object):  
  2.   
  3.     def setup(self):  
  4.         test_name = ...  
  5.   
  6.     def teardown(self):  
  7.         pass  
  8.   
  9.     def test_the_power(self):  
  10.         assert "foo" != "bar"  
  11.   
  12.     def test_something_else(self):  
  13.         assert True  
Right before TestSomething.test_the_power becomes executed, I would like to have access to this name in setup as outlined in the code via test_name = ... so that test_name == "TestSomething.test_the_power".

HowTo
You can also use the PYTEST_CURRENT_TEST environment variable set by pytest for each test case. (PYTEST_CURRENT_TEST environment variable) To get just the test name:
  1. os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...