python – py.test – 如何继承其他测试

所以假设我有两个文件(test_file1.py,test_file2.py)用于使用py.test进行集成测试.

test_file1.py是这样的:

import datetime
import pytest

Datetime = datetime.datetime.now()

def test_connect():

  #1st Query to a mysql database

  #2nd Query to a mysql database

  ..

  #N Query to a mysql database

现在我正在编写test_file2.py,这是test_file1.py的扩展,但我不想编写我在上面的测试中编写的相同的mysql查询.

如何让py.test继承上面的测试并在执行py.test test_file2.py之后运行它们?

像这样的东西(test_file2.py内容):

import datetime
import pytest

from testDirectory import test_file1

Datetime = datetime.datetime.now()

def test_connect():

  #Here should run all the tests from 'test_file1' somehow...

  #1st new  additional Query to a mysql database

  #2nd new additional Query to a mysql database

  ..

  #N new additional Query to a mysql database

谢谢!!

最佳答案 导入模块时,它将执行其中的所有代码.所以只需编写您想要在原始文件中执行的代码.例如,在文件中添加对函数的调用,如下所示:

test_file1.py:

import datetime
import pytest

Datetime = datetime.datetime.now()

def test_connect():

    #1st Query to a mysql database

    #2nd Query to a mysql database

    ..

    #N Query to a mysql database

test_connect() # This will run your function when you import

因此,当您调用import test_file1时,在py.test中,它将执行test_connect()和您想要的任何其他代码而不执行任何其他操作.

换句话说,这是一个包含3个文件的简单示例:

文件1:hello_world.py:

def hello_world():
    print('hello world!')

hello_world()

文件2:print_text.py:

def print_text():
    print('foo bar baz')

print_text()

文件3:run_everything.py:

import hello_world
import print_text

运行run_everything.py时的结果:

>>>hello world!
>>>foo bar baz

如果希望在直接执行文件时执行该函数,而不是作为模块导入,则可以执行以下操作:

test_file1.py:

    import datetime
    import pytest

    Datetime = datetime.datetime.now()

    def test_connect():

       #1st Query to a mysql database

       #2nd Query to a mysql database

       ..

       #N Query to a mysql database

   def main():
       # This will _not_ run your function when you import. You would 
       # have to use test_file1.test_connect() in your py.test.
       test_connect()


   if __name__ == '__main__':
       main()

所以在这个例子中,你的py.test将是:

    import test_file1

    test_file1.test_connect()
点赞