简体   繁体   English

从 python 文件而不是从命令行运行 pytest 测试

[英]Running a pytest test from a python file and NOT from a command line

I have three python files in one directory (c:\\Tests), I am trying to run the test using pytest from the file TestCases1.py but I have not succeed.我在一个目录 (c:\\Tests) 中有三个 python 文件,我试图使用文件 TestCases1.py 中的 pytest 运行测试,但我没有成功。 I am new to python and I do not know if I am asking the right question.我是 python 新手,我不知道我问的问题是否正确。 I have seen several examples but almost all use the command line to run the test and I want to run them from a python file.我看过几个例子,但几乎都使用命令行来运行测试,我想从 python 文件中运行它们。 Since I am newbie to testing, I would appreciate a very simple answer (I have seen some similar questions but I did not get the answers).由于我是测试新手,我希望得到一个非常简单的答案(我看过一些类似的问题,但我没有得到答案)。 I am using Python 36-32 and Eclipse Oxygen 3a.我正在使用 Python 36-32 和 Eclipse Oxygen 3a。

min_max.py => Some basic functions to be tested min_max.py => 一些需要测试的基本功能

def min(values):
    _min = values[0]
    for val in values:
        if val < _min:
            _min = val
    return _min

    

def max(values):
    _max = values[0]
    for val in values:
        if val > _max:
            _max = valal
    return _max

min_max_test.py => Some tests for the functions min_max_test.py => 函数的一些测试

import min_max

def test_min():
    print("starting")
    values = (2, 3, 1, 4, 6)
    val = min(values)
    assert val == 1
    print("done test_min")


def test_max():
    print("starting")
    values = (2, 3, 1, 4, 6)
    val = max(values)
    assert val == 6
    print("done test_max") 

TestCases1.py => File from where I want to run the test TestCases1.py => 我想运行测试的文件

import pytest
pytest_args = [
    'c:\Tests\min_max_test.py'
]

pytest.main(pytest_args)

In min_max_test.py , the min and max variable names in the test functions would be taken from the built-ins and not from your min_max.py file.min_max_test.py ,测试函数中的minmax变量名称将取自内置函数,而不是取自 min_max.py 文件。

You either need to use something like min_max.min or import those functions using a from import rather than a full module import.您要么需要使用min_max.min东西,要么使用from import 而不是完整模块导入来导入这些函数。

PS please include the error messages along with the questions and be specific as to what problem you are having. PS 请包括错误消息和问题,并具体说明您遇到的问题。 makes it that much easier :)让它变得更容易:)

Optionally, you could use subprocess to run pytest commands on your python script.或者,你可以使用subprocess在您的Python脚本运行pytest命令。 For example,例如,

# ~/tests
import subprocess
subprocess.run(["pytest . -q"], shell=True)
>>>
.                                                                                             [100%]
1 passed in 0.00s
CompletedProcess(args=['pytest . -q'], returncode=0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM