How do you write an automation test script in Python?

Writing an automation test script in Python involves using various testing frameworks and libraries to create and execute the tests. Here, I’ll walk you through the process of setting up a basic automation test script using the popular testing framework called pytest along with the selenium library for web automation.

  1. Install necessary dependencies: Ensure you have Python installed on your system. You can check the Python version by running python --version in the command line. Additionally, you’ll need pip to install Python packages. To install the required libraries, run the following commands:
pip install pytest
pip install seleniumCode language: Python (python)
  1. Setup the project structure: Create a directory for your automation project and inside it, create a subdirectory named tests.
  2. Write the automation test script: Create a new Python file inside the tests directory, for example, test_example.py.
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

@pytest.fixture
def browser():
    # This fixture sets up the browser instance and closes it after the test runs.
    driver = webdriver.Chrome()  # You can choose a different browser if you prefer.
    yield driver
    driver.quit()

def test_example(browser):
    # This is the actual test function.
    url = "https://example.com"  # Replace this with the URL of your application.
    browser.get(url)

    # Perform some actions and verifications on the page using Selenium
    # For example:
    assert "Example Domain" in browser.title
    assert browser.find_element(By.TAG_NAME, "h1").text == "Example Domain"Code language: Python (python)

Run the test: Open your command line, navigate to the project directory (the one containing the tests directory), and run the following command:

pytestCode language: Python (python)

pytest will automatically discover and run the test cases inside the tests directory. It will use the test_ prefix to identify test functions.

That’s it! This is a basic example of how you can write an automation test script in Python using pytest and selenium. Of course, in real-world scenarios, you’ll likely have more complex test scenarios and multiple test files to organize your tests effectively.

Read More;

  • I am an enthusiastic learner and aspiring Python developer with expertise in Django and Flask. I pursued my education at Ivan Franko Lviv University, specializing in the Faculty of Physics. My skills encompass Python programming, backend development, and working with databases. I am well-versed in various computer software, including Ubuntu, Linux, MaximDL, LabView, C/C++, and Python, among others.

    View all posts

Leave a Comment