DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Debugging Tips and Tricks for Python Structural Pattern Matching
  • Mastering Test Code Quality Assurance
  • Comparison of Various AI Code Generation Tools
  • Building a Windows App for a Resilient SSH SOCKS Proxy and Selective Browser Routing

Trending

  • Architecture Review Boards for Generative AI: A Framework for Governance, Risk Management, and Responsible Adoption
  • Build a Voice Assistant With Gemini Live API
  • Designing Memory Architecture for Stateful AI Agents: Short-Term Context and Long-Term Persistence
  • Designing a Polling Pipeline for Rate-Limited APIs Without Losing Data

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Python Unit Testing: One Time Initialization

Python Unit Testing: One Time Initialization

By creating unit tests within class methods, developers can save time while testing Python code — learn how to do all of that and more in this quick read.

By 
Bipin Patwardhan
·
Mar. 17, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
21.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Introduction

Recently, after writing a microservice to manage Create-Read-Update-Delete (CRUD) operations for a MongoDB database, it logically was time to write unit test cases. As I had developed the microservice using Python and Flask, the unit test also had to be in Python. For unit testing, I used the unittest package.

Writing Unit Tests

By writing unit tests, not only was I ensuring that I could run the same tests over and over again but, assuming that the underlying functionality of the micro-service had not broken, I could expect the same results for each execution. Moreover, as the number of REST functions increased, the unit tests would help me ensure that none of the existing functionality was broken. Additionally, the unit tests would help me reduce the total amount of time I needed to spend on testing the same functionality over and over again.

Initial Approach

As is the typical development method, I started writing test cases by defining one method per test case. Before the actual test functionality, I had to ensure that I had a valid database connection. Thus, the first few lines of each method were common across the test cases — that of creating a connection to MongoDB.

Python
 




x


 
1
class TestDatabase(unittest.TestCase):
2
    def testGetAllDocuments(self):
3
        self.connection = connect to database
4
        doc = TestDatabase.connection.find({})
5
        self.assertTrue(len(doc) > 0)
6

          
7
if __name__ == "__main__":
8
    unittest.main()


setUp and tearDown

As you may have noticed, the initial few lines of code in each method are common — that of making a connection to the database. As this code is repeated in each test method, we might make mistakes while copying and pasting the code.

To help solve the copy-and-paste situation, the unittest package provides two special methods – setUp and tearDown. These methods allow us to place code that is common to each test case method. The only difference is that the setUp method is executed before the test method is executed, while the tearDown method is executed after the execution of the test method. I placed the connection creation code in the setUp method and the connection closure method is in the tearDown method.

Python
 




xxxxxxxxxx
1
13


 
1
class TestDatabase(unittest.TestCase):
2
    def setUp(self):
3
        self.connection = connect to database
4

          
5
    def tearDown(self):
6
        self.connection.close()
7

          
8
    def testGetAllDocuments(self):
9
        doc = self.connection.find({})
10
        self.assertTrue(len(doc) > 0)
11

          
12
if __name__ == "__main__":
13
    unittest.main()


setUp and tearDown Limitation

The fact that we can keep code that is common to all test methods in setUp and tearDown is the most logical design. The only part about this design is the fact that setUp and tearDown are called before each test method execution. In our case, I was connecting to a MonogoDB database. This means that a new connection is created before each test method and is closed after each test method. While it takes only a few milliseconds to create a connection, it adds to the total time needed for the execution of all the test cases, particularly if the number of test cases is large (as was the case).

Class Wide setUp and tearDown

As it happens, the designers of this package are one step ahead of us. The unit test package allows us to define a setUp method for the class — a class method, namely setUpClass. Similarly, we can define a tearDown method for the class — tearDownClass. These methods are executed only once — once when the class instance is created and once when the class instance is destroyed.

By putting the connection creation code in this method, we end up calling it only once — when the class object is created. This method is not invoked before each test case, saving us the time needed for connection establishment. I used the setUpClass method to create the connection and the tearDownClass method to close the connection. The only thing we need to keep in mind is that a connection object is an object with a class scope. To use the connection object in the test method, we have to refer to it using the class name and not using self.

Python
 




xxxxxxxxxx
1
15


 
1
class TestDatabase(unittest.TestCase):
2
    @classmethod
3
    def setUpClass(cls):
4
        cls.connection = connect to database
5

          
6
    @classmethod
7
    def tearDownClass(cls):
8
        cls.connection.close()
9

          
10
    def testGetAllDocuments(self):
11
        doc = TestDatabase.connection.find({})
12
        self.assertTrue(len(doc) > 0)
13

          
14
if __name__ == "__main__":
15
    unittest.main()



Note

It is important to remember that the test class has been derived from unittest. Hence, we need to include main and invoke unittest.main() in it. To execute the test case, we use

$ python mongo_test.p or $ python -m unittest mongo_test.py

pytest

The unit test class can also be executed by pytest, as

$ pytest mongo_test.py or $ pytest

Conclusion

A unit test is one of the mandatory hygiene factors that we have to adopt for our projects. By writing unit tests, we are not only reducing the amount of time needed for testing but more importantly, we are creating a mechanism that brings in transparency in testing. People no longer have to overthink the "Y" present in the Excel against a test case. By using unit testing, the "Y" means a successful test condition check. As the unit testing code can be examined by all stakeholders, it also brings in transparency and helps us address questions regarding test methodology and coverage.

unit test Python (language) Connection (dance) Test method

Opinions expressed by DZone contributors are their own.

Related

  • Debugging Tips and Tricks for Python Structural Pattern Matching
  • Mastering Test Code Quality Assurance
  • Comparison of Various AI Code Generation Tools
  • Building a Windows App for a Resilient SSH SOCKS Proxy and Selective Browser Routing

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook