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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Debugging Tips and Tricks for Python Structural Pattern Matching
  • Mastering Test Code Quality Assurance
  • Comparison of Various AI Code Generation Tools
  • Start Coding With Google Cloud Workstations

Trending

  • How to Practice TDD With Kotlin
  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  • A Guide to Container Runtimes
  • Solid Testing Strategies for Salesforce Releases
  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 user avatar
Bipin Patwardhan
·
Mar. 17, 21 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
19.6K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • Start Coding With Google Cloud Workstations

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!