Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest - run multiple tests from a single file

I'm using Pytest (Selenium) to execute my functional tests. I have the tests split across 2 files in the following structure:

My_Positive_Tests.py

class Positive_tests:


  def test_pos_1():
    populate_page()
    check_values()

  def test_pos_2():
    process_entry()
    validate_result()

My_Negative_Tests.py

class Negative_tests:
  def test_neg_1
    populate_page()
    validate_error()

The assertions are done within the functions (check_values, validate_result, validate_error). I'm trying to find a way to run all the tests from a single file, so that the main test file would look something like:

My_Test_Suite.py

test_pos_1() 
test_pos_2()
test_neg_1()

Then from the command line I would execute:

py.test --tb=short "C:\PycharmProjects\My_Project\MyTest_Suite.py" --html=report.html

Is it possible to do something like this? I've been searching and haven't been able to find out how to put the calls to those tests in a single file.

like image 573
ChrisG29 Avatar asked Jul 12 '16 11:07

ChrisG29


2 Answers

You don't have to run your tests manually. Pytest finds and executes them automatically:

# tests/test_positive.py
def test_pos_1():
    populate_page()
    check_values()

def test_pos_2():
    process_entry()
    validate_result()

and

# tests/test_negative.py
def test_neg_1():
    populate_page()
    validate_error()

If you then run

py.test

They should automatically be picked up.

You can then also select a single file

py.test -k tests/test_negative.py

or a single test

py.test -k test_neg_1
like image 151
Nils Werner Avatar answered Oct 15 '22 09:10

Nils Werner


Start file names and tests with either test_ or end with _test.py. Classes should begin with Test

Directory example:
|-- files
|--|-- stuff_in stuff
|--|--|-- blah.py
|--|-- example.py
|
|-- tests
|--|-- stuff_in stuff
|--|--|-- test_blah.py
|--|-- test_example.py

In terminal: $ py.test --cov=files/ tests/ or just $ py.test tests/ if you don't need code coverage. The test directory file path must be in your current directory path. Or an exact file path ofcourse

With the above terminal command ($ py.test tests/), pytest will search the tests/ directory for all files beginning with test_. The same goes for the file.

test_example.py

# imports here

def test_try_this():   
    assert 1 == 1
# or
class TestThis:
    assert 1 == 0
# or even:
def what_test():
    assert True
like image 35
Comradsky Avatar answered Oct 15 '22 11:10

Comradsky