Step 1: Project Setup and Directory Structure
To begin building our Python project, we need to set up a clean project structure. This helps organize our code, tests, and documentation. We’ll create a project folder with separate directories for the source code and tests.
Here’s an example of how you can organize your project:
mentor_project/
├── src/
│ └── math_operations.py
├── tests/
│ └── test_math_operations.py
├── README.md
└── requirements.txt
Explanation: • The folder “src” will contain our Python modules (e.g., math operations). • The folder “tests” will include our unit tests. • The README.md file provides an overview of the project. • The requirements.txt file (if needed) lists project dependencies.
Step 2: Setting Up a Virtual Environment
Using a virtual environment isolates your project’s dependencies. This is a best practice for Python projects.
To create and activate a virtual environment (assuming you have Python 3 installed), run the following commands:
# Create the virtual environment
python3 -m venv venv
# Activate the virtual environment (Linux/Mac)
source venv/bin/activate
# Activate the virtual environment (Windows)
venv\Scripts\activate
Explanation: • The first command generates a directory named “venv” containing the virtual environment. • Activation ensures that any package installations occur only in your isolated environment.
Step 3: Implementing a Simple Python Module
Now, let’s create a simple function inside our module. We’ll place this code in the file src/math_operations.py. The function will add two numbers.
# File: src/math_operations.py
def add(a, b):
"""
Adds two numbers and returns the result.
Parameters:
a (int or float): The first number.
b (int or float): The second number.
Returns:
int or float: The sum of a and b.
"""
return a + b
# Additional functions can be added here, such as subtract, multiply, etc.
Explanation: • The function add takes two parameters and returns their sum. • The docstring explains what the function does, its parameters, and its return type. This is useful for both users and automated documentation.
Step 4: Creating a Main Script to Use the Module
Next, we’ll create a script that utilizes our function. This file, for example, can serve as the entry point for our application.
# File: src/main.py
from math_operations import add
def main():
# Example usage of the add function.
number1 = 10
number2 = 5
result = add(number1, number2)
print(f"The sum of {number1} and {number2} is: {result}")
if __name__ == "__main__":
main()
Explanation: • We import the add function from math_operations. • The main() function demonstrates how to use add. • The conditional block ensures that main() runs only when executed as the main program, not when imported.
Step 5: Writing Unit Tests
Testing our code is essential to ensure it works correctly. We’ll now write tests using Python’s built-in unittest framework. Create a file called tests/test_math_operations.py:
# File: tests/test_math_operations.py
import unittest
from src.math_operations import add
class TestMathOperations(unittest.TestCase):
def test_add_positive_numbers(self):
"""
Test addition of two positive numbers.
"""
self.assertEqual(add(3, 7), 10, "Adding 3 and 7 should be 10")
def test_add_negative_numbers(self):
"""
Test addition of two negative numbers.
"""
self.assertEqual(add(-5, -3), -8, "Adding -5 and -3 should be -8")
def test_add_with_zero(self):
"""
Test addition where one of the numbers is zero.
"""
self.assertEqual(add(0, 10), 10, "Adding 0 and 10 should be 10")
if __name__ == '__main__':
unittest.main()
Explanation: • Each test function checks different cases for the add function. • The unittest framework provides assertion methods to validate the expected outcomes. • Running this file executes all test cases.
Step 6: Running the Tests and the Application
Once your code and tests are ready, you can run your tests using the command line.
To run the tests, execute:
python -m unittest discover -s tests
Explanation: • The unittest discovery command looks for test files in the “tests” directory and runs them. • Ensure your virtual environment is activated prior to running the command.
To run the main application:
python src/main.py
Explanation: • This runs the main script, which demonstrates the functionality of your module by printing the result of the addition operation.
By following these steps, you now have a basic, well-structured Python project with clear separation between your application logic and tests. This approach ensures maintainability and easy scalability for future enhancements. Enjoy coding and testing your project!