Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a pytest test from a python file and NOT from a command line

Tags:

python

pytest

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. I am new to python and I do not know if I am asking the right question. 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. 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.

min_max.py => Some basic functions to be tested

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

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

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

pytest.main(pytest_args)
like image 222
nanunga Avatar asked May 31 '26 12:05

nanunga


1 Answers

Optionally, you could use subprocess to run pytest commands on your python script. For example,

# ~/tests
import subprocess
subprocess.run(["pytest . -q"], shell=True)
>>>
.                                                                                             [100%]
1 passed in 0.00s
CompletedProcess(args=['pytest . -q'], returncode=0)
like image 82
Miguel Trejo Avatar answered Jun 02 '26 02:06

Miguel Trejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!