Testing any application we make is one of the most important parts of development. There are many reasons why we should test our application:
Testing helps us to find out the defects as well as errors that we can't recognize during the development.
We can also say that testing is necessary to check whether the application produces the correct/expected output.
It is also necessary to check about the quality of the application. Testing also helps us to check the quality of the product.
As we now understand the importance of testing we will now test our CherryPy application. First, we will write an application where '<application-name>/' opens the main page '<application-name>/second_page' opens another page. To do this in CherryPy we will define two methods in our class, one index(self) to handle the first page and another second_page(self) to handle the second page.
Save the below code in a file named 'app.py'.
import cherrypy
class application:
def index(self):
return "This is the main page of the application."
def second_page(self):
return "This is the second page of the application."
if __name__ == '__main__':
cherrypy.quickstart(application())
Now, we will make the test file. Save the below code in a file named 'test.py'.
import cherrypy
from cherrypy.test import helper
from app import application
class SimpleCPTest(helper.CPWebCase):
def setup_server():
cherrypy.tree.mount(application(), '/', {})
def test_index(self):
self.getPage("/")
self.assertStatus('200 OK')
def test_second_page(self):
self.getPage("/second_page")
self.assertStatus('200 OK')
To run the test we will need Pytest. Install it by writing the following command on a Terminal/Command Line.
pip3 install pytest
To check if the installation is correct or to check for any additional info. Run the following on a Terminal/Command Line.
pip3 show pytest
Now run the test with the following command.
pytest -v test.py
The output of the test will be something like this
=============================== test session starts ================================
platform linux -- Python 3.8.2, pytest-6.0.2, py-1.9.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: <test-directory-path>
collected 3 items
test.py::SimpleCPTest::test_index PASSED [ 33%]
test.py::SimpleCPTest::test_second_page PASSED [ 66%]
test.py::SimpleCPTest::test_gc PASSED [100%]
================================ 3 passed in 0.50s =================================
The output says that all the tests have passed which means that our application is running correctly.
Comments