top of page

Day 24 - Testing in Python - Unit Testing and Test Cases

Writer's picture: vPvP

Welcome back to another day in our Python for DevOps series! Today, we're going to discuss about testing. Testing is like the superhero of coding – it saves you from bugs and ensures your code works as expected. Today, we'll focus on Unit Testing and Test Cases in Python, helping you become a testing maestro.


Why Testing?

Before we jump into the how, let's understand the why. Imagine building a car without testing its brakes – it's a recipe for disaster. Similarly, in coding, testing ensures your functions and classes work as intended. It's not just about finding bugs; it's about preventing them.


Unit Testing 101

Unit testing is like checking individual ingredients before baking a cake. Each part of your code, whether it's a function or a class, should be tested independently. Python comes with a fantastic module for this – unittest.


Writing Your First Test Case

Let's say you have a simple function that adds two numbers. You want to make sure it works, right? Here's how you write a test case for it:

import unittest

def add_numbers(a, b):
    return a + b

class TestAddNumbers(unittest.TestCase):
    def test_add_positive_numbers(self):
        result = add_numbers(2, 3)
        self.assertEqual(result, 5)

    def test_add_negative_numbers(self):
        result = add_numbers(-2, -3)
        self.assertEqual(result, -5)

    def test_add_mixed_numbers(self):
        result = add_numbers(5, -3)
        self.assertEqual(result, 2)

if name == '__main__':
    unittest.main()

Here, we've created a test case class TestAddNumbers that inherits from unittest.TestCase. Inside, we have individual test methods, each checking a scenario. The assertEqual method checks if the result matches the expected value.


Running Your Tests

Save the above code in a file (let's call it test_math.py) and run it using:

python test_math.py

You'll see a dot for each successful test. If something fails, it will point you to the issue.


Organizing Test Cases

As your project grows, so will your tests. Organizing them is crucial. You can group related tests into test suites and use setUp and tearDown methods to prepare and clean up.

class TestMathOperations(unittest.TestCase):
  def setUp(self):
        # Code to run before each test
        pass

    def tearDown(self):
        # Code to run after each test
        pass

    def test_addition(self):
        # Test addition
        pass

    def test_subtraction(self):
        # Test subtraction
        pass

    # ... more test methods ...

Mocking for Isolation

Sometimes, your code relies on external services or APIs. You don't want to test those every time. Mocking comes to the rescue.


Let's say your function sends an email. Instead of actually sending an email every time you run your tests, you can use unittest.mock to create a mock object.


from unittest.mock import patch

def send_email(message):
    # Code to send an email
    pass

class TestSendEmail(unittest.TestCase):
    @patch('your_module.send_email')  # 'your_module' is where your send_email function is
    def test_send_email(self, mock_send_email):
        # Test send_email function
        pass

Assertions Galore

unittest provides various assertion methods like assertEqual, assertTrue, assertFalse, and more. Choose the one that best fits your test scenario.


Today, we've dipped our toes into the vast ocean of testing in Python. Unit testing is your shield against bugs and a powerful tool for crafting robust code. As you embark on your coding journey, remember – a well-tested code is a reliable code.


In our next blog, we'll explore more advanced testing techniques.


Until then, happy coding!


*** Explore | Share | Grow ***

7 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
vp1.2_23.png

vPundit

Explore | Share | Grow

Thanks for submitting!

vPundit

bottom of page