Python: Getting started with pyTest

https://docs.pytest.org/en/latest/
pytest is a mature full-featured Python testing tool that helps you write better programs.py.test, aka we-don't-need-no-stinking-API unit test suite, is an alternative, more Pythonic way of writing your tests. The best part is, the overhead for creating unit tests is close to zero! So without further ado, let's start.
Step 1: INSTALL 'pytest'. Simply 'pip install pytest' or create a requirements.text as below and run
'pip install -r requirements.text'
Step: CREATE a python file:















Note: the name of the file and the method name should start with 'test'
Step 3: cmd > py.test -v -s
Output







-v -s , these arguments enables printing of the print statements
pytest Fixtures
The purpose of test fixtures is to provide a fixed baseline upon which tests can reliably and repeatedly execute.Although unittest does allow us to have setup and teardown, pytest extends this quite a bit.
We can add specific code to run:
  •     at the beginning and end of a module of test code (setup_module/teardown_module)
  •     at the beginning and end of a class of test methods (setup_class/teardown_class)
  •     alternate style of the class level fixtures (setup/teardown)
  •     before and after a test function call (setup_function/teardown_function)
  •     before and after a test method call (setup_method/teardown_method)














if I want to execute the method "mySetUp" before each of these methods, then the above snapshot depicts how we could achieve it. @pytest.fixture is a python decorator, the method that enatails this decorator has to be passed as argument in the methods as done for ''text_py_1" and "test_py_2".
When I run it, the Output is:









Now if I want to run a statement after each method, we use 'yield'. In the same directory create another python file with the below code. Note the 'mySetUp' method .













cmd > py.test -v -s
Output:











py.test -v -s will fetch all the test methods and run them
To run a specific method in a particular module(a python file)
py.test test_two.py::test_py_1 -v -s
This directs pytest to run test_py_1 method in test_two.py file(module)

Comments

Post a Comment

Popular Posts