Table of contents
1.
Introduction
2.
CherryPy — A Minimalist Python Web Framework
3.
Organizing our code
4.
Dispatchers
5.
Tools
6.
Plugins
7.
Code coverage
8.
Using pytest and code coverage
9.
Pytest
10.
Adding Code Coverage
10.1.
Note:
11.
Frequently Asked Questions
11.1.
What Is Cherrypy?
11.2.
What Is Cherrypy Environment Setup?
11.3.
Is CherryPy open source?
11.4.
Is CherryPy good?
12.
Conclusion
Last Updated: Mar 27, 2024

Using pytest and code coverage in cherrypy

Author SHIVANGI MALL
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Python is a programming language that is used by the object-oriented web application framework known as CherryPy. Although it wraps the HTTP protocol allowing quick creation of web applications, it remains low level and does not provide much more than what is specified in RFC 7231. In this article, the reader will learn about CherryPy — A Minimalist Python Web Framework, Organizing our code, and we will also look in detail dispatchers, tools, plugins,  using pytest and code coverage.

 

Introduction

CherryPy — A Minimalist Python Web Framework

A Python-based, object-oriented web framework is called CherryPy.

With CherryPy, programmers may create web apps in a manner similar to how they would create any other object-oriented Python program. This leads to shorter development times and smaller source code. CherryPy has been around for almost ten years and has shown to be quick and dependable. Many sites, from the simplest to the most demanding, are using it in production.

Typically, a CherryPy application looks like this:

Import cherrypy
class HelloWorld(object):
    @cherrypy.expose

    def index(self):

        return "Hello World!"
cherrypy.quickstart(HelloWorld())

Organizing our code

With the support of CherryPy's robust architecture, you may organize your code in a way that should make it more flexible and simple to maintain.

You have access to other mechanisms, but this course will concentrate on the three primary ones:

  • dispatchers
  • tools
  • plugins

Imagine you are in a superstore to better understand them:

  • There are lines of people waiting at each of your multiple tills (those are your requests)
  • There are several areas containing food and other items (these are your data)
  • The superstore employees and their daily activities to ensure that the sections are always in order are the last groups (this is your backend)

Despite being extremely rudimentary, this closely resembles how your program functions. CherryPy assists you in organizing your application so that it reflects these fundamental concepts.

Dispatchers

Returning to the superstore example, it's likely that you'll wish to carry out the following actions using the till:

  • For baskets containing fewer than ten things, have a till.
  • Set up a disabled people's register.
  • A register just for expectant mothers
  • A till where only store cards are accepted

CherryPy provides a mechanism called a dispatcher to accommodate various use-cases. Early in the request processing process, a dispatcher is called in order to choose which section of your application's code will handle the incoming request. Alternatively, a dispatcher will choose which till to direct a customer to stick with the store analogy.

Tools

Let's say your business has decided to run a discount campaign, but exclusively for a certain type of clientele. Such a use case will be handled by CherryPy via a technique known as a tool.

A tool is a piece of code that executes once for each request in order to carry out extra work. Typically, a tool is just a straightforward Python function that CherryPy runs at a specific stage of the request processing.

Plugins

As we've seen, the store employs a team of individuals who are responsible for managing the inventory and satisfying any consumer expectations.

This translates into CherryPy functions running independently of any request life cycle. Background jobs, persistent connections (such as those to a database, for instance), etc., should be handled by these functions.

Because they collaborate with the CherryPy engine and expand it with your functions, plugins are so named.

Code coverage

Code coverage, put simply, is a gauge of how thorough a test suite is. A system is completely tested when it has 100% code coverage.

Why is Python code coverage important?

Theoretically, a system should have fewer flaws the larger its code coverage. Naturally, testing cannot detect every possible error, but we need all the assistance we can get in this unfair war.

The codebase is made up of individual lines, which is extremely mechanically speaking. This means that a straightforward formula for calculating code coverage would be (number of code lines run at least once under tests / total number of lines) * 100%. This formula only appears logical at first glance. It is far too inadequate. Consider the following line of code for the sake of this article:

//to import dataclass
from dataclasses import dataclass
@dataclass
class Patient:
    age: int
    is_pregnant: bool = False
    is_regular_blood_donor: bool = False

def determine_queue_position(patient, queue):
     # we assume initially that a patient will just join the queue
    position = len(queue)
   # without having to wait in a queue
    # certain groups of patients are served 
    if patient.is_pregnant or patient.is_regular_blood_donor:
        position = 0
    return position

Why concentrating only on covering lines is insufficient

Let's suppose we have a test for it now:

def test_pregnancy_means_accessing_doctor_without_having_to_wait():
    queue = [Patient(age=25), Patient(age=44)]
    patient = Patient(age=28, is_pregnant=True)
    queue_position = determine_queue_position(patient, queue)
    assert queue_position == 0

Every line in the function determines queue position is put to the test in this test. With just one test, we were able to achieve 100% code coverage as per our original definition. However, this limited test set hardly qualifies as exhaustive! For instance, we didn't test on patients like these:

  • A regular blood donor
  • both being pregnant and a regular blood donor
  • neither a regular blood donor nor a pregnant woman

etc. Not to include scenarios like a waiting line when one or more patients are expecting or regularly donate blood (the latter is not addressed by implementation, so we won't be concentrating on it).

Using pytest and code coverage

Pytest

import random
import string
import cherrypy
class StringGenerator(object):
    @cherrypy.expose
    def index(self):
        return "Hello world!"
    @cherrypy.expose
    def generate(self):
        return ''.join(random.sample(string.hexdigits, 8))

if __name__ == '__main__':
    cherrypy.quickstart(StringGenerator())

This should be saved as tut12.py.

Create the test file now:

 

import cherrypy
from cherrypy.test import helper
from tut12 import StringGenerator
class SimpleCPTest(helper.CPWebCase):
    @staticmethod
    def setup_server():
        cherrypy.tree.mount(StringGenerator(), '/', {})
    def test_index(self):
        self.getPage("/")
        self.assertStatus('200 OK')
    def test_generate(self):
        self.getPage("/generate")
        self.assertStatus('200 OK')

Run after saving this to a test tut12.py file.

$ pytest -v test_tut12.py

We now have a clever technique to practice writing tests for our applications.

Adding Code Coverage

Run to obtain code coverage.

$ pytest --cov=tut12 --cov-report term-missing test_tut12.py

Note:

Installing pip install pytest-cov will add coverage support to pytest.

This indicates that there is a line missing. Naturally, it is, as it is only carried out when the Python program is launched directly. We can easily alter the lines in tut12.py that follow:

if __name__ == '__main__': # pragma: no cover
    cherrypy.quickstart(StringGenerator())

Rerunning the code coverage should now result in a 100% result.

Now let's discuss some frequently asked questions associated with pytest and code coverage in cherrypy.

Frequently Asked Questions

What Is Cherrypy?

A user-friendly interface to the HTTP protocol is provided for Python developers by the Python web framework CherryPy. Another name for it is a web application library.

What Is Cherrypy Environment Setup?

Like most open-source projects, CherryPy is available in packages that can be downloaded and installed using the methods listed below. By means of a Tarball, Make use of easy_install and Subversion.

Is CherryPy open source?

CherryPy is an open-source project, and hence contributions are welcome.

Is CherryPy good?

With its high scalability and flexibility, CherryPy's integration with any common Python library is quick and easy. Although this architecture has a small community, it lacks any focused tools or solutions.

Conclusion

 We hope this article helps you to learn something new. And if you're interested in learning more, see our posts on Basics of PythonHow To Build Applications Development Using Python?Introduction to Bottle Framework, and cherrypy python.

Visit our practice platform Coding Ninjas Studio to practice top problems, attempt mock testsread interview experiences, and much more.! Feel free to upvote and share this article if it has been helpful for you.

 

Live masterclass