Showing posts with label Python Testing. Show all posts
Showing posts with label Python Testing. Show all posts

Unit Testing in Python: Get Started with unittest & pytest

← Back to Home


Unit Testing in Python: Getting Started with unittest and pytest


Introduction

Writing code is only half the battle—testing it ensures your program works as expected and helps catch bugs early. Unit testing is a fundamental software development practice that involves testing small parts (units) of your code independently.

Python offers powerful testing frameworks like the built-in unittest module and the popular third-party tool pytest. In this guide, you’ll learn how to write and run unit tests with both, helping you improve code quality and reliability.


What is Unit Testing?

Unit testing focuses on verifying that individual pieces of code (functions, classes, methods) behave correctly in isolation. By writing tests for these units, you create a safety net that alerts you when changes break functionality.


Using Python’s Built-in unittest Module

Python comes with the unittest framework pre-installed.

Writing Your First Test Case

Suppose you have a simple function:

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

Here’s how to test it with unittest:

import unittest
from your_module import add  # Replace with actual module name

class TestAddFunction(unittest.TestCase):
    
    def test_add_positive_numbers(self):
        self.assertEqual(add(2, 3), 5)

    def test_add_negative_numbers(self):
        self.assertEqual(add(-1, -1), -2)

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

Run this test file, and unittest will report if the tests pass or fail.


Introduction to pytest

pytest is a popular third-party testing tool that simplifies writing tests and offers advanced features.

Installing pytest

pip install pytest

Writing Tests with pytest

You don’t need to use classes or inherit from test frameworks. Just write test functions:

from your_module import add

def test_add_positive():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-1, -1) == -2

Run tests using the command:

pytest

Key Differences Between unittest and pytest

Feature unittest pytest
Test style                 Class-based             Function-based
Setup/teardown                 Methods like setUp, tearDown             Fixtures with decorators
Assertions                 Specific assert methods             Python’s native assert
Plugins                 Limited             Extensive plugin ecosystem
Ease of use                 More boilerplate             Minimal code, more expressive

Example: Testing a Simple Function

Suppose your function calculates the factorial of a number:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

unittest version

import unittest
from your_module import factorial

class TestFactorial(unittest.TestCase):

    def test_factorial_zero(self):
        self.assertEqual(factorial(0), 1)

    def test_factorial_positive(self):
        self.assertEqual(factorial(5), 120)

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

pytest version

from your_module import factorial

def test_factorial_zero():
    assert factorial(0) == 1

def test_factorial_positive():
    assert factorial(5) == 120

Running Tests and Interpreting Results

  • With unittest, run your test file directly.

  • With pytest, run the pytest command in your terminal.

Both tools will tell you which tests passed or failed and provide helpful output to diagnose issues.


Tips for Effective Testing

  • Write tests for edge cases and normal cases.

  • Use meaningful test names.

  • Test one thing per test function.

  • Use assertions effectively to validate expected results.

  • Consider test coverage tools like coverage.py to measure how much code your tests cover.


Conclusion

Unit testing helps ensure your Python code is reliable, maintainable, and bug-free. Whether you choose Python’s built-in unittest or the powerful pytest, adding tests to your workflow is a valuable skill.

Start small—test your utility functions—and gradually expand coverage to larger components. 

For more Python insights and practical guides, check out our other posts on Python Projects for Beginners and Publishing Python Packages.


What’s Next?

๐Ÿ‘‰ In Next article, we’ll learn Python List Comprehensions


Python Interactive Mode

← Back to Home

What is Python Interactive Mode?


Python interactive mode is a feature of python through which you can test your code immediately. It interprets only one line at a time and gives immediate output for any statement written.

It is a very good tool when we are working on large programs and need to test piece of code in which each statement can be easily tested, later used and embedded within the program.

see video=>   https://youtu.be/EBZDlgrIh-g

How to get in to interactive Mode?

To get the python interactive mode you only need to get python installed in your system.

Interactive mode can be used through either from console (command prompt) or using python IDLE(Integrated Development Environment) .

steps to get python IDLE (windows system)

       press window key from keyboard ----->>  from start menu open ,click  the python IDLE

Python Interactive Mode









see video=>   https://youtu.be/EBZDlgrIh-g


steps to get python interactive mode from console (Windows system command prompt)  .

       press Ctrl+R ----->>  type "cmd" ----->> press ENTER

    from command prompt open Type PYTHON ---->>  press Enter

you are in the python interactive mode.

Python Interactive Mode











For LINUX system: 

for LINUX system :  from terminal open ---->> type PYTHON and press Enter
                                                                           
                                  (same as windows command prompt)



Verifying interactive mode :


when you see  >>>  (triple greater than symbols) followed by the version information of python, you are in python interactive mode.

see video=>   https://youtu.be/EBZDlgrIh-g


if you want to learn python script mode click link=>  Python Script Mode:



๐Ÿง  Why Use Python Interactive Mode?

Python's interactive mode is a quick and easy way to test small code snippets. Whether you're learning Python or debugging a function, this mode gives you immediate feedback.

Key use cases:

  • Test a single line of code instantly.

  • Quickly experiment with built-in functions.

  • Understand how a new Python feature works.

  • Debug variables step-by-step.

๐Ÿ’ก Tip: You can even use Python interactive mode as a calculator!


⚠️ Limitations of Interactive Mode

While interactive mode is great for trying out code, it's not ideal for everything. Here are a few limitations to keep in mind:

  • Not for big projects: Writing long scripts or building apps is better suited to .py files.

  • No save by default: Code in interactive mode isn’t saved unless you copy it out manually.

  • Limited formatting: Unlike in full IDEs, formatting and documentation tools are minimal.

✅ Use it for learning and quick tests—not for long-term development.


๐Ÿงฐ Best Practices When Using Interactive Mode

Following a few best practices can help you use interactive mode more effectively:

  1. Use clear variable names – Avoid a, b, x1; use names like total_sum or user_input.

  2. Keep it short – Write small, testable lines of code.

  3. Use help() and dir() – These built-in tools are your best friends in interactive mode.

  4. Follow PEP 8 – This is Python’s style guide. It keeps your code clean and consistent.

>>> help(len)
>>> dir(str)

๐Ÿ›  Troubleshooting: Common Interactive Mode Issues

Even in interactive mode, you might run into small errors. Here’s how to fix common ones:

Problem Solution
'python' is not recognized Add Python to your system's PATH variable.
SyntaxError or IndentationError Double-check spacing and colons.
Can't exit the mode Use exit() or press Ctrl + Z (Windows), Ctrl + D (Linux/Mac).

๐Ÿ” Still stuck? Try running Python from a different terminal like Git Bash or PowerShell.


๐Ÿ”— Optional Add-on Section for SEO:

๐Ÿงช Interactive Mode vs. Script Mode in Python

Script mode lets you save and run entire Python programs from .py files, while interactive mode is more immediate and temporary.

Feature Interactive Mode Script Mode
Code is saved? ❌ No ✅ Yes
Suited for learning? ✅ Yes ✅ Yes
Runs full programs? ❌ Not ideal ✅ Best choice

๐Ÿ’ฌ "When learning Python, it's best to start with interactive mode—then shift to script mode as your projects grow."


Click Next for: Python Script Mode


Featured Post

Extra Challenge: Using References Between Documents

  ๐ŸŽฏ ๐Ÿ’ก Extra Challenge: Using References Between Documents Here's an  Extra Challenge  designed to build on the original MongoDB mode...

Popular Posts