PyTest Installation and pytest identifies the test files and test methods in PyTest
How
to install PyTest
To install the latest version of pytest,
execute the following command.
Pip
install pytest
Confirm the installation using the following
command to display the help section of pytest.
Pytest
-h
How
pytest identifies the test files and test methods
pytest only identifies the file names starting with test_ or
ending with _test as the test files in the current
directory and subdirectories. Pytest automatically identifies those files as
test files. We can make pytest run other filenames by explicitly mentioning them.
Pytest requires the test function names to
start with test. Function names which are not of format test* are not
considered as test functions by pytest. We cannot explicitly make pytest
consider any function not starting with test as a test function.
some
examples of valid and invalid pytest file names
test_add.py
– valid
subtract_test.py
– valid
testadd.py
– invalid
subtracttest.py
– invalid
login.py
--- invalid
some examples of valid and invalid
pytest test methods
def
test_addition() – valid
def
testaddition() – valid
def
addition() – invalid
Note:
Even if we explicitly mention addition() pytest will not run this method.
Basic PyTest Example
Create
a new directory named pytestautomation
and navigate into the directory in your command line.
Create
a file named test_addition.py and add the below code to that file.
import pytest
def
test_add():
assert (10+5 ==15)
def testaddeven_num():
assert(4+4==9)
assert (10+5 ==15)
def testaddeven_num():
assert(4+4==9)
Run
the test using below command in command line
Note:
you should navigate into the directory
in your command line.
c:\pytest
output
will be
F
says failure
Dot(.)
says success.
In the failures section, you can see the failed
method and the line of failure. Here 4+4 == 9 which is false.
In the end, we can see test execution summary, 1
failed and 1 passed.
Now, I want to result more explanatory about the test
, you can use below command in command line
C:\Pytest -v
Output will be
Note : pytest command will execute all the files of
format test_* or *_test in the current directory and subdirectories.
Run tests by node ids
Each collected test is assigned a unique nodeid which consist of the module filename followed by:: characters
To run a specific test within a module:
Pytest test_addition.py::test_add
Output Will be
Run tests by node ids
Each collected test is assigned a unique nodeid which consist of the module filename followed by:: characters
To run a specific test within a module:
Pytest test_addition.py::test_add
Output Will be
Comments
Post a Comment