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.
- 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 needpip
to install Python packages. To install the required libraries, run the following commands:
pip install pytest
pip install selenium
Code language: Python (python)
- Setup the project structure: Create a directory for your automation project and inside it, create a subdirectory named
tests
. - 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:
pytest
Code 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;
- What is slicing and indexing in Python explain with an example?
- What are the 7 operators in Python?
- How can I run a Python script online for free?
- What is Generator in Python With Example?
- What is class and object in Python with example?
- What is an example of a user-defined function in Python?
- Can R and Python be used together? [With Example]
- How does format () work in Python?
- What is .2f Python format?
- What is the e function in Python?
- What is module and example in Python?
- What is overriding in Python with example?