py.test - 如何继承其他测试

Lig*_*low 5 python inheritance integration-testing unit-testing pytest

假设我有两个文件 ( 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
Run Code Online (Sandbox Code Playgroud)

现在我正在编写test_file2.pywhich 是 的扩展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
Run Code Online (Sandbox Code Playgroud)

谢谢!!

Igo*_*gor 2

当您导入模块时,它将执行其中的所有代码。因此,只需在原始文件中写入要执行的代码即可。例如,在文件中添加对函数的调用,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

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

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

文件 1: hello_world.py:

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

hello_world()
Run Code Online (Sandbox Code Playgroud)

文件 2: print_text.py:

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

print_text()
Run Code Online (Sandbox Code Playgroud)

文件 3: run_everything.py:

import hello_world
import print_text
Run Code Online (Sandbox Code Playgroud)

运行时的结果run_everything.py

>>>hello world!
>>>foo bar baz
Run Code Online (Sandbox Code Playgroud)

如果你希望函数在文件执行时直接执行,而不是作为模块导入,可以这样做:

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()
Run Code Online (Sandbox Code Playgroud)

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

    import test_file1

    test_file1.test_connect()
Run Code Online (Sandbox Code Playgroud)