Python unit test integration with Jenkins

Problem: Jenkins is still somewhat of a black box to testers.

This post is for the hands on tester looking to integrate their Python unit tests with Jenkins.


Why this post?

Jenkins is an extremely popular continuous integration tool. Jenkins is often setup and maintained by the development team or I.T. team in many companies. Testers know about Jenkins but rarely get a chance to explore Jenkins. At Qxf2, we believe in learning and exploring the tools we work with everyday. In a previous post, we showed you how to get started with Jenkins. In this post, we will show you how to install and configure plugins and run some Python unit tests.


Overview

This post will walk you through the following steps:
1. Download and install Jenkins
2. Install and configure the required Jenkins plugins
3. Install Python mock and Python nose
4. Add Python unit test cases
5. Set up the project in Jenkins
6. Start the build
7. Verify the result

We are going to be using a fairly popular Python plugin call ShiningPanda.

NOTE: If you are new to Python unit tests, please refer to our previous blog on Python unit checks where we downloaded the Python Chess application and wrote a Python unit test for it.


A step by step guide

STEP 1: Download and install Jenkins
Jenkins provides installers for different operating systems. In companies, it is more common to see Jenkins hosted on a *nix system. Our best guess is that most testers use Windows. Our goal is to help you, the tester, learn about Jenkins. So we are choosing to use Windows in this example. You can download the Windows native package as a zip file. Extract the file and install Jenkins. Since we are installing Jenkins using the Windows installer, we don’t need to do anything else as the Windows installer automatically runs Jenkins as a Windows service.

You can verify Jenkins is running as a service by launching the Services app from the Windows Start Menu and looking for a running service called “Jenkins” among the list of all windows services running on the machine.

Windows Service

By default, Jenkins runs at http://localhost:8080/. You can change it by editing jenkins.xml, which is located in your installation directory.

Jenkins

STEP 2: Install and configure required Jenkins Plugins to run Python Unit Test
There are various Python Plugins available to build python files in Jenkins. We will use ShiningPanda Plugin which provides Python support to Jenkins with some useful builders.

To install the plugin click on the Manage Jenkins link on the left-hand side of the page. On the next page click on Manage Plugins link. Finally on Plugin Manager page click on the Available tab and search for ShiningPanda. Check the checkbox for the plugin and install it.Jenkins will install the selected plugins and then take a moment to restart

Jenkins Plugin

To configure Python installations, navigate to Manage Jenkins > Configure System. Search for the Python. Select Python Installations and configure it. The Name is the name of the Python installation and Home or executable is the path to the root folder of the Python installation

Configure Python installation

STEP 3: Install Python mock and Python nose
We will use the Python mock module in our test case to mock some classes. The mock module has one of my favorite features – patch decorators, that make it easy to mock classes. We are doing this on Python 2.7. For Python 3.x you could skip this step. To install mock, open a command prompt and run:

pip install -U mock

Python nose extends unittest to make testing easier. By default, nose will run tests in files or directories under the current working directory whose names include “test” or “Test”. To install nose, open a command prompt and run:

pip install nose

STEP 4: Add Python unit test cases
In real life, you run a suite of tests. To make this example realistic, we are going to be writing three test cases. If you are already comfortable with Python nose, you can choose to run exactly one test.

Test 1: Please refer to our previous blog on python unit check where we have written a python unit test for a python chess app. The test case to check whether the GetListOfValidMoves method is getting called with the arguments that we expect it to be called with.

Test 2: Check if the mocked method was called at least once with some arguments

"""
Example written for Qxf2 Services' blog post on Python Unit Checking
Check if IsCheckmate method in ChessRules class calls GetListOfValidMoves  
Assert that it called at least once with some expected argument
"""
import unittest, mock
import ChessRules 
from ChessBoard import ChessBoard
 
class CheckIsCheckmate(unittest.TestCase):
    "Class to unit check the IsCheckmate method of ChessRules.py module"
    # creating a mock for GetListOfValidMoves
    @mock.patch('ChessRules.ChessRules.GetListOfValidMoves')        
    def test_called_with_args(self, mockGetListOfValidMoves):
        "Unit test for ChessRules method: IsCheckmate"
 
        # Creating objects of Chessboard and ChessRules class and calling IsCheckmate function with each piece for initial position and "black" color
        cb = ChessBoard(0) #Create a chess board object with the initial position
        chess_rules_obj = ChessRules.ChessRules()
        chess_rules_obj.IsCheckmate(cb.GetState(),"black")
 
        # Create expected_arg_calls list which is supposed to be called with GetListOfValidMoves for initial position
        # IsCheckmate calls GetListOfValidMoves with arguments: board, color (who is to play?) and co-ordinates of a square with a piece on it
        expected_arg_calls = []
        for row in range(0,2):
            for col in range(0,8):
                expected_arg_calls.append(mock.call(cb.GetState(), 'black', (row, col)))
 
 
        # assert that method was called at least once with some argument        
        mockGetListOfValidMoves.assert_any_call(cb.GetState(),"black",(1,6))
 
 
if __name__=="__main__":
    unittest.main()

Test 3: Check if the mocked method was called exactly 16 times

"""
Example written for Qxf2 Services' blog post on Python Unit Checking
Check if IsCheckmate method in ChessRules class calls GetListOfValidMoves  
Assert that the mocked method is called 16 times
"""
import unittest, mock
import ChessRules 
from ChessBoard import ChessBoard
 
class CheckIsCheckmate(unittest.TestCase):
    "Class to unit check the IsCheckmate method of ChessRules.py module"
    # creating a mock for GetListOfValidMoves
    @mock.patch('ChessRules.ChessRules.GetListOfValidMoves')        
    def test_call_count(self, mockGetListOfValidMoves):
        "Unit test for ChessRules method: IsCheckmate"
 
        # Creating objects of Chessboard and ChessRules class and calling IsCheckmate function with each piece for initial position and "black" color
        cb = ChessBoard(0) #Create a chess board object with the initial position
        chess_rules_obj = ChessRules.ChessRules()
        chess_rules_obj.IsCheckmate(cb.GetState(),"black")
 
        # Create expected_arg_calls list which is supposed to be called with GetListOfValidMoves for initial position
        # IsCheckmate calls GetListOfValidMoves with arguments: board, color (who is to play?) and co-ordinates of a square with a piece on it
        expected_arg_calls = []
        for row in range(0,2):
            for col in range(0,8):
                expected_arg_calls.append(mock.call(cb.GetState(), 'black', (row, col)))
 
 
        # check the number of times your mocked method was called
        self.assertEqual(mockGetListOfValidMoves.call_count,16)
 
 
if __name__=="__main__":
    unittest.main()

STEP 5: Set up the project in Jenkins

  • Go to Jenkins, select “New Item”, enter a name for your build and then choose “Build a free-style software project and click “OK”.
  • We will run the project directly from our local machine. Configure the project as “None” under “Source Code Management”.
  • Click on “Add Build step” and select Python Builder.
  • Select the Nature as Shell and in command field enter “nosetests $Path of testcase ”

Configure Python Setting for Build

STEP 6: Start the build
Go back to your build page in Jenkins and click on “Build Now”. The Build will start and you can view the status.

Start the Jenkins Build

STEP 7: Verify the result
Click on Console Output to view the Result. All the 3 test cases ran and the status shows as “SUCCESS”

View result in Jenkins


And that brings us to the end of this tutorial on integrating your Python unit tests with Jenkins. As always, we are happy to answer any questions you may have.


Subscribe to our weekly Newsletter


View a sample



27 thoughts on “Python unit test integration with Jenkins

  1. Hi, so I followed every step, But Jenkins is unable to find my test file. I tried running the nostests command on my cmd, then it runs properly. But in Jenkins it is throwing an error saying the file does not exist. Kindly help me what to do.

  2. How do I install nose it shows syntax error when I try ‘pip install nose’
    + pip install nose
    Traceback (most recent call last):
    File “/bxp/jen/slave99/shiningpanda/jobs/0467e27d/virtualenvs/d41d8cd9/bin/pip”, line 7, in
    from pip._internal.cli.main import main
    File “/bxp/jen/slave99/shiningpanda/jobs/0467e27d/virtualenvs/d41d8cd9/lib/python2.6/site-packages/pip/_internal/cli/main.py”, line 10, in
    from pip._internal.cli.autocompletion import autocomplete
    File “/bxp/jen/slave99/shiningpanda/jobs/0467e27d/virtualenvs/d41d8cd9/lib/python2.6/site-packages/pip/_internal/cli/autocompletion.py”, line 9, in
    from pip._internal.cli.main_parser import create_main_parser
    File “/bxp/jen/slave99/shiningpanda/jobs/0467e27d/virtualenvs/d41d8cd9/lib/python2.6/site-packages/pip/_internal/cli/main_parser.py”, line 7, in
    from pip._internal.cli import cmdoptions
    File “/bxp/jen/slave99/shiningpanda/jobs/0467e27d/virtualenvs/d41d8cd9/lib/python2.6/site-packages/pip/_internal/cli/cmdoptions.py”, line 107
    binary_only = FormatControl(set(), {‘:all:’})
    ^
    SyntaxError: invalid syntax
    Build step ‘Virtualenv Builder’ marked build as failure

      1. It shows System-CPython-2.6(only this option drops in drop down) in virtual builder but my code is written in python3.6.6

      2. Hi,

        Although you have mentioned that, you are using Python 3.6.6 from the log message you have shared it still looks like your pip install is still referring Python 2.6 libraries.
        To narrow down the problem would you please create a new virtual environment and try installing nose there.

        Also before installing nose, I would request you to upgrade your pip as well.

        There is nose2 library available in case you want give it a try!
        https://pypi.org/project/nose2/

        Regards,
        Rahul

      3. Hi,
        You could add the Python 3.6 installation to the virtual builder by clicking on the ‘Add Python’ button.
        However, as a pre-requisite, ensure to configure Python installations (ie) navigate to Manage Jenkins > Configure System. Search for the Python. Select Python Installations and configure it. The Name is the name of the Python installation and Home or executable is the path to the root folder of the Python installation. Hope this helps.

    1. Hi,

      Whenever your tests are failed the build history will show that tests are failed(This will be marked as Red bubble in the console output). The detail failure you can check in the console output(step 7 from the article).

      I hope this helps.

      Regards,
      Rahul Bhave

Leave a Reply

Your email address will not be published.