<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ahmad Idrees</title>
    <description>The latest articles on DEV Community by Ahmad Idrees (@mahmad321).</description>
    <link>https://dev.to/mahmad321</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2172271%2Fdbacd683-4068-4b2d-bbb6-0acbd5a3f58e.png</url>
      <title>DEV Community: Ahmad Idrees</title>
      <link>https://dev.to/mahmad321</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mahmad321"/>
    <language>en</language>
    <item>
      <title>Automate your tasks Using Pytest: A practical guide with examples</title>
      <dc:creator>Ahmad Idrees</dc:creator>
      <pubDate>Tue, 08 Oct 2024 03:24:08 +0000</pubDate>
      <link>https://dev.to/mahmad321/automate-your-tasks-using-pytest-a-practical-guide-with-examples-5g1l</link>
      <guid>https://dev.to/mahmad321/automate-your-tasks-using-pytest-a-practical-guide-with-examples-5g1l</guid>
      <description>&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Pytest?&lt;/strong&gt;&lt;br&gt;
Before diving into the examples, let's discuss why Pytest is a great choice for task automation:&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;Example 1: Automating API Testing with Pytest&lt;/strong&gt;&lt;br&gt;
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.&lt;/p&gt;

&lt;p&gt;Step 1: Install Required Libraries&lt;br&gt;
First, ensure you have Pytest and the requests library installed:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;pip install pytest requests&lt;/code&gt;&lt;br&gt;
Step 2: Write the Test Script&lt;br&gt;
Let’s automate a simple GET request to a public API like JSONPlaceholder, a fake online REST API for testing.&lt;/p&gt;

&lt;p&gt;`import requests&lt;br&gt;
import pytest&lt;/p&gt;

&lt;h1&gt;
  
  
  Define the base URL
&lt;/h1&gt;

&lt;p&gt;BASE_URL = "&lt;a href="https://jsonplaceholder.typicode.com" rel="noopener noreferrer"&gt;https://jsonplaceholder.typicode.com&lt;/a&gt;"&lt;/p&gt;

&lt;p&gt;@pytest.fixture&lt;br&gt;
def api_client():&lt;br&gt;
    # This fixture provides a session object for making API requests&lt;br&gt;
    session = requests.Session()&lt;br&gt;
    yield session&lt;br&gt;
    session.close()&lt;/p&gt;

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

&lt;p&gt;Explanation:&lt;br&gt;
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.&lt;br&gt;
Test Function (test_get_posts): This function sends a GET request to the /posts endpoint and verifies that:&lt;br&gt;
The status code is 200, indicating success.&lt;br&gt;
The response contains at least one post.&lt;br&gt;
Step 3: Run the Test&lt;br&gt;
To execute the test, run the following command:&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;Example 2: Automating Web UI Testing with Pytest and Selenium&lt;/strong&gt;&lt;br&gt;
Web UI testing ensures that the frontend of an application behaves as expected. Pytest can be combined with Selenium to automate these tasks efficiently.&lt;/p&gt;

&lt;p&gt;Step 1: Install Required Libraries&lt;br&gt;
Install Pytest, Selenium, and WebDriver Manager:&lt;/p&gt;

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

&lt;p&gt;`import pytest&lt;br&gt;
from selenium import webdriver&lt;br&gt;
from selenium.webdriver.common.by import By&lt;br&gt;
from selenium.webdriver.common.keys import Keys&lt;br&gt;
from webdriver_manager.chrome import ChromeDriverManager&lt;/p&gt;

&lt;p&gt;@pytest.fixture&lt;br&gt;
def browser():&lt;br&gt;
    # Set up the Chrome WebDriver&lt;br&gt;
    driver = webdriver.Chrome(ChromeDriverManager().install())&lt;br&gt;
    yield driver&lt;br&gt;
    driver.quit()&lt;/p&gt;

&lt;p&gt;def test_google_search(browser):&lt;br&gt;
    # Navigate to Google&lt;br&gt;
    browser.get("&lt;a href="https://www.google.com%22)%60%7B%" rel="noopener noreferrer"&gt;https://www.google.com")`{%&lt;/a&gt; endraw %}&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# 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) &amp;gt; 0, "No search results found"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

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

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

&lt;p&gt;Step 1: Install Required Libraries&lt;br&gt;
Ensure that Pytest and Pandas are installed:&lt;/p&gt;

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

&lt;p&gt;`import pytest&lt;br&gt;
import pandas as pd&lt;/p&gt;

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

&lt;p&gt;def test_data_not_null(sample_data):&lt;br&gt;
    # Check if there are any null values in the DataFrame&lt;br&gt;
    assert sample_data.isnull().sum().sum() == 0, "Data contains null values"&lt;/p&gt;

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

&lt;p&gt;&lt;code&gt;pytest -v test_data.py&lt;/code&gt;&lt;br&gt;
&lt;strong&gt;Why This Works&lt;/strong&gt;&lt;br&gt;
Pytest’s flexibility allows data-centric tests, ensuring that datasets meet expected criteria.&lt;br&gt;
The fixture makes it easy to set up and modify test data without duplicating code.&lt;br&gt;
&lt;strong&gt;Best Practices for Automating Tasks with Pytest&lt;/strong&gt;&lt;br&gt;
Use Fixtures for Setup and Teardown: Fixtures help manage setup and teardown efficiently, making your tests modular and reusable.&lt;br&gt;
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.&lt;br&gt;
Parameterize Tests: Use @pytest.mark.parametrize to test multiple sets of data or inputs, reducing code duplication.&lt;br&gt;
Integrate with CI/CD Pipelines: Integrate Pytest tests with CI/CD tools like Jenkins or GitHub Actions for continuous testing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
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.&lt;/p&gt;

&lt;p&gt;If you're looking to automate your workflow or enhance your testing process, Pytest is a great starting point. Happy testing!&lt;/p&gt;

</description>
      <category>pytest</category>
      <category>python</category>
      <category>testing</category>
      <category>automation</category>
    </item>
  </channel>
</rss>
