To create a Python project with a structure that includes a main.py file containing some functions, and an integration test located in tests/integration/test_integration.py that imports those functions and tests them using pytest, follow these steps:
1. Setup Your Project Structure
First, create a suitable directory structure for your project. Here's an example structure in your terminal or command line:
mkdir my_python_project
cd my_python_project
mkdir -p tests/integration
touch main.py
touch tests/__init__.py
touch tests/integration/__init__.py
touch tests/integration/test_integration.py
The structure will look like this:
my_python_project/
├── main.py
└── tests/
├── __init__.py
├── integration/
├── __init__.py
└── test_integration.py
2. Writing Your Main Code
Edit main.py to define a simple function. Here's an example function:
# main.py
def multiply(x, y):
return x * y
3. Setting up a Virtual Environment and Installing pytest
It's good practice to use a virtual environment. Inside your project directory:
python3 -m venv venv # Create a virtual environment named venv
source venv/bin/activate # Activate the virtual environment on Unix-like OSes
.\venv\Scripts\Activate # On Windows use this command instead
Next, install pytest:
pip install pytest
4. Writing Your Integration Test
Now, go to tests/integration/test_integration.py to write your test. Since this is about integration testing, we'll keep it simple but structured to reflect an integration test approach. Here's an example:
# tests/integration/test_integration.py
from main import multiply
def test_multiply():
# Given
x = 5
y = 10
# When
result = multiply(x, y)
# Then
assert result == 50
This imports the multiply function from main.py and tests it.
5. Running the Tests with pytest
From your project's root directory (my_python_project/), run:
pytest
pytest will automatically discover your test(s) and run them. If everything is set up correctly, you should see output indicating that your test has passed.
Additional Notes
- Make sure your virtual environment is activated whenever you are working on this project.
- Try to follow good coding practices by adding docstrings to your functions and tests.
- You can use command-line flags with pytest for various purposes, like
-v for verbose output, -k to run tests matching a specific name expression, and many more, which are documented in pytest's official documentation.
This sets up a basic structure and workflow for a Python project using pytest for an integration test. From here, you can expand your project by adding more functionality, writing more tests (including unit tests and more complex integration tests), and perhaps integrating with other tools or services.