Wednesday, July 17, 2013

PyTest - Quick Reference

What is PyTest?
PyTest is just like any other unit test framework for Python. It generates JUnit XML report as well which makes easy to integrate it's report with Jenkins

How to Install PyTest: 
pip install -U pytest or
easy_install pytest

How it Identifies: 
Every unit testing framework has some pattern though which identifies which is Test Class, which is Test Method, Which is Setup and TearDown method and so do PyTest.
Test Class - Any Class name which starts with Test is indentified as Test Class (i.e. TestMathFunc) Test- Any function which starts with test_ is identified as test method (i.e. test_devision)
Apart from this there are few setup and teardown methods as well, as mention below
setup_module:- Called before the first test of the module
teardown_module:- Called after the last test of the module
setup_class:- Called before the first test of the class
teardown_class:- Called after the last test of the class 
setup_method:- Called before each and every test inside class
teardown_method:- Called after each and every test inside class
setup_function:- Called before each and every test outside class 
teardown_function:- Called after each and every test outside class 

Sample Code:
PyTestDemo.py
class TestPyTestDemo():
    """
    This class demonstrates who to write simple test using pytest framework
    @author: Gaurang Shah
    @contact: gaurangnshah@gmail.com
    
    """
    def add(self,arg1,arg2):
        return arg1+arg2

    def test_pass(self):
        print "test_pass"
        assert self.add(2, 3) == 5
        
    def test_fail(self):
        print "test_fail"
        assert self.add(0, 2) == 1

    def setup_method(self,method):
        "This method will be called before each and every method inside class"
        print "setup_method"
        
    def teardown_method(self,method):
        "This method will be called after each and every method inside class"
        print "teardown_method" 
                
    @classmethod
    def setup_class(cls):
        "This method will be called before first method of classe"
        print "setup_class"
         
    @classmethod
    def teardown_class(cls):
        "This method will be called after last method of class"
        print "teardown_class"

def setup_module(module):
    "This method will be called before first method of module"
    print "setup_module"

def teardown_module(module):
    "This method will be called after last method of module"
    print "teardown_module"  
   
def setup_function(function):
    "This method will be called before each and every function outside class"
    print "setup function"
    
def teardown_function(function):
    "This method will be called before each and every function outside class"
    print "teardown function"
    
def test_function():
    print "test_function"
How to Execute :
py.test PyTestDemo.py

0 comments:

Post a Comment