Automate your tasks Using Pytest: A practical guide with examples

Ahmad Idrees - Oct 8 - - Dev Community

Automation is a critical part of modern software development and testing. It saves time, reduces manual errors, and ensures consistency across processes. The Pytest framework is one of the most popular and powerful tools for automating tasks in Python, particularly in testing. It’s lightweight, easy to use, and offers numerous plugins and built-in features to simplify the automation process.

In this article, we will explore the best ways to automate tasks using the Pytest framework. We’ll walk through three practical examples, demonstrating how Pytest can automate different types of tasks effectively.

Why Pytest?
Before diving into the examples, let's discuss why Pytest is a great choice for task automation:

Simplicity: Pytest has a simple and concise syntax, making it easy to write and read test cases.
Extensibility: With a wide range of plugins and hooks, Pytest can be extended to support different testing needs.
Fixtures: Pytest provides fixtures, which are a powerful feature for setting up preconditions or states for tests, enhancing reusability.
Integration: Pytest integrates well with other tools, including CI/CD platforms, enabling end-to-end automation.

Example 1: Automating API Testing with Pytest
APIs are the backbone of many applications, and ensuring their reliability is critical. Pytest, along with the requests library, makes it easy to automate API testing.

Step 1: Install Required Libraries
First, ensure you have Pytest and the requests library installed:

pip install pytest requests
Step 2: Write the Test Script
Let’s automate a simple GET request to a public API like JSONPlaceholder, a fake online REST API for testing.

`import requests
import pytest

Define the base URL

BASE_URL = "https://jsonplaceholder.typicode.com"

@pytest.fixture
def api_client():
# This fixture provides a session object for making API requests
session = requests.Session()
yield session
session.close()

def test_get_posts(api_client):
# Send a GET request to fetch posts
response = api_client.get(f"{BASE_URL}/posts")
# Assertions
assert response.status_code == 200
assert len(response.json()) > 0, "No posts found"`

Explanation:
Fixture (api_client): This fixture sets up a reusable session for making HTTP requests, ensuring we don’t need to create a new session each time.
Test Function (test_get_posts): This function sends a GET request to the /posts endpoint and verifies that:
The status code is 200, indicating success.
The response contains at least one post.
Step 3: Run the Test
To execute the test, run the following command:

bash
Copy code
pytest -v test_api.py
Why This Works
The test is concise and reusable, leveraging Pytest’s fixtures to handle setup and teardown.
Pytest’s output shows which tests passed or failed, making it easy to track API reliability over time.

Example 2: Automating Web UI Testing with Pytest and Selenium
Web UI testing ensures that the frontend of an application behaves as expected. Pytest can be combined with Selenium to automate these tasks efficiently.

Step 1: Install Required Libraries
Install Pytest, Selenium, and WebDriver Manager:

pip install pytest selenium webdriver-manager
Step 2: Write the Test Script
Here’s how you can automate a simple web UI test that verifies a search function on Google:

`import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager

@pytest.fixture
def browser():
# Set up the Chrome WebDriver
driver = webdriver.Chrome(ChromeDriverManager().install())
yield driver
driver.quit()

def test_google_search(browser):
# Navigate to Google
browser.get("https://www.google.com")`{% endraw %}

# Find the search box and enter a query
search_box = browser.find_element(By.NAME, "q")
search_box.send_keys("Pytest Automation")
search_box.send_keys(Keys.RETURN)

# Assert that results are shown
results = browser.find_elements(By.CSS_SELECTOR, "div.g")
assert len(results) > 0, "No search results found"
Enter fullscreen mode Exit fullscreen mode

Explanation:
Fixture (browser): This fixture sets up a Chrome WebDriver instance using webdriver-manager and ensures it’s properly closed after each test.
Test Function (test_google_search): This function:
Opens Google’s homepage.
Searches for “Pytest Automation”.
Asserts that the search returns at least one result.
Step 3: Run the Test
Execute the test with:

{% raw %}pytest -v test_ui.py
Why This Works
Pytest’s fixture manages the browser instance, making the test setup and teardown clean and efficient.
Using Selenium, the script interacts with the web page like a real user, ensuring the UI functions as expected.
Example 3: Automating Data Validation with Pytest and Pandas
Data validation is crucial in data engineering, analytics, and ETL processes. Pytest can automate data validation tasks using the pandas library.

Step 1: Install Required Libraries
Ensure that Pytest and Pandas are installed:

pip install pytest pandas
Step 2: Write the Test Script
Let’s automate a task where we validate that a dataset meets certain conditions (e.g., no null values, correct data types, etc.).

`import pytest
import pandas as pd

@pytest.fixture
def sample_data():
# Create a sample DataFrame
data = {
"name": ["Alice", "Bob", "Charlie", "David"],
"age": [25, 30, 35, 40],
"email": ["alice@example.com", "bob@example.com", None, "david@example.com"]
}
df = pd.DataFrame(data)
return df

def test_data_not_null(sample_data):
# Check if there are any null values in the DataFrame
assert sample_data.isnull().sum().sum() == 0, "Data contains null values"

def test_age_column_type(sample_data):
# Verify that the 'age' column is of integer type
assert sample_data['age'].dtype == 'int64', "Age column is not of integer type"`
Explanation:
Fixture (sample_data): This fixture sets up a sample DataFrame, simulating a dataset that can be reused in multiple tests.
Test Function (test_data_not_null): This test checks if there are any null values in the DataFrame and fails if any are found.
Test Function (test_age_column_type): This test verifies that the age column is of integer type, ensuring data consistency.
Step 3: Run the Test
Execute the test with:

pytest -v test_data.py
Why This Works
Pytest’s flexibility allows data-centric tests, ensuring that datasets meet expected criteria.
The fixture makes it easy to set up and modify test data without duplicating code.
Best Practices for Automating Tasks with Pytest
Use Fixtures for Setup and Teardown: Fixtures help manage setup and teardown efficiently, making your tests modular and reusable.
Leverage Plugins: Pytest has a variety of plugins (e.g., pytest-html for HTML reports, pytest-xdist for parallel execution) to enhance your automation efforts.
Parameterize Tests: Use @pytest.mark.parametrize to test multiple sets of data or inputs, reducing code duplication.
Integrate with CI/CD Pipelines: Integrate Pytest tests with CI/CD tools like Jenkins or GitHub Actions for continuous testing.

Conclusion
Pytest is a powerful tool for automating a variety of tasks, from API and web UI testing to data validation. Its simplicity, combined with flexibility and extensive plugin support, makes it an excellent choice for developers and QA engineers alike. By leveraging Pytest's features such as fixtures, parameterization, and integrations with CI/CD pipelines, you can build robust, maintainable, and scalable automation frameworks.

If you're looking to automate your workflow or enhance your testing process, Pytest is a great starting point. Happy testing!

.
Terabox Video Player