1. Understand the User's Request: The user wants a Python script to "automate software testing workflows." This is a broad request. "Software testing workflows" can mean anything from unit tests to integration tests, end-to-end UI tests (Selenium/Playwright), API testing, or CI/CD pipeline integration.
-
Identify the Goal: Provide a comprehensive, practical, and well-structured example that covers the most common use cases. Since I can't write every possible type of testing script, I should aim for a modular framework that demonstrates:
- Test Discovery/Execution: Using a standard library like
unittest or pytest (I'll choose pytest as it's the industry standard for Python testing).
- Reporting: Generating output (console and file).
- Setup/Teardown: Managing the environment.
- External Tool Integration (Optional but good): Maybe a simple API test or a mock UI test to show versatility.
- Command Line Interface (CLI): Making it runnable with arguments.
-
Determine the Scope and Structure:
- Core: A main script that sets up the environment and runs the tests.
- Tests: Dummy tests to show how it works.
- Configuration: Using
pytest.ini or command-line arguments.
- Dependencies:
pytest, requests (for API), selenium or playwright (for UI - keep it simple or mock it to avoid complex setup for the user). Let's stick to pytest and requests for a pure Python script that works out-of-the-box, but mention Selenium.
-
Drafting the Solution (Iterative Process):
-
Approach 1: Simple subprocess wrapper.
- Just running
pytest via subprocess.
- Pros: Simple.
- Cons: Not much "automation" logic beyond running a command.
-
Approach 2: Programmatic pytest execution.
- Using
pytest.main(). This allows pre-processing and post-processing within Python.
- Pros: More control. Can generate custom reports, send emails, or clean up directories before running.
-
Approach 3: A full "Workflow" class.
- A class that handles setup, execution, and reporting.
-
Refining the Chosen Approach (Approach 2 & 3 combined):
Let's build a script that simulates a real-world workflow:
- Pre-flight checks: Verify dependencies or environment variables.
- Run Unit Tests: Fast feedback.
- Run Integration/API Tests: (Using
requests).
- Generate Report: HTML report is a nice touch (requires
pytest-html).
- Notification: (Mocked) Send an email or Slack message.
-
Writing the Code (Mental Draft & refinement):
- Imports:
subprocess, sys, os, logging, datetime. Maybe shutil for cleanup.
- Structure:
TestRunner class.
setup_environment()
run_tests() -> Uses subprocess.run(["pytest", ...]) or pytest.main(). subprocess is often safer for isolating environments, but pytest.main is easier to script. Let's use subprocess for the main runner to simulate a CI step, as it's more robust against crashes.
generate_report()
cleanup()
-
Adding a Concrete Example:
The user needs to see what is being tested. I will provide a directory structure:
run_tests.py (The automation script)
tests/ (Directory containing tests)
-
Addressing Specific Requirements:
- Dependencies: Need to list them (
pip install pytest requests pytest-html).
- Comments: Explain why we are doing specific steps.
-
Final Polish of the Script:
- Add colored output for better readability (optional, maybe just stick to logging).
- Add error handling (try/except blocks).
- Include a "Success/Failure" exit code.
-
Reviewing the Output:
- Does it run? Yes.
- Is it extensible? Yes.
- Is it modern? Yes (Python 3,
pytest).
-
Constructing the Explanation:
- Explain the architecture.
- Explain how to install requirements.
- Explain the code sections (Pre-processing, Execution, Reporting).
- Suggest next steps (Docker, Jenkins/GitHub Actions).
-
Self-Correction during drafting:
- Initial thought: Include Selenium.
- Correction: Selenium requires drivers (ChromeDriver) which might fail for a beginner copying/pasting. Better to stick to API tests with
requests or just logic tests, and mention Selenium in the comments as a place to plug it in.
- Refinement: Use
argparse to make the script flexible (e.g., select specific test suites).
-
Final Code Structure Plan:
- File 1:
automation_suite.py (The main script).
- File 2:
tests/test_sample.py (Dummy tests).
- Instructions: How to run it.
(Self-Correction): Let's make automation_suite.py create the dummy tests itself if they don't exist, so the user can copy just one file and see it work? No, that's messy. Better to provide two code blocks.
Let's go with a robust TestOrchestrator class.
- Step 1: Prerequisites.
- Step 2: The Python Automation Script (The "Runner").
- Step 3: Sample Test Files (The "Payload").
- Step 4: Execution command.
This covers the "Workflow" aspect (setup -> run -> report).
-
Writing the content: (This aligns with the generated output, focusing on pytest, logging, subprocess, and HTML reporting).
Here is a complete, modular Python framework designed to automate software testing workflows.
This solution uses pytest as the core engine because it is the industry standard, but it wraps it in a Python script that handles environment setup, dependency checking, execution, and report generation.
Prerequisites
You will need to install the following packages:
pip install pytest pytest-html requests
1. The Test Automation Script (run_automation.py)
This script acts as the "Orchestrator." It checks your environment, cleans up old reports, runs the tests, and generates an HTML report.
import subprocess
import sys
import os
import shutil
import logging
from datetime import datetime
# Configure Logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.StreamHandler(sys.stdout)]
)
class TestAutomationWorkflow:
def __init__(self):
self.project_root = os.path.dirname(os.path.abspath(__file__))
self.reports_dir = os.path.join(self.project_root, "reports")
self.test_dir = os.path.join(self.project_root, "tests")
self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
def setup_environment(self):
"""Ensure directories exist and environment is ready."""
logging.info("Setting up environment...")
# Create reports directory if it doesn't exist
if not os.path.exists(self.reports_dir):
os.makedirs(self.reports_dir)
logging.info(f"Created directory: {self.reports_dir}")
# Check if tests directory exists
if not os.path.exists(self.test_dir):
logging.error(f"Test directory not found: {self.test_dir}")
sys.exit(1)
def run_linting_check(self):
"""Optional: Run a quick syntax check or linting before heavy tests."""
logging.info("Running pre-flight checks (simulated)...")
# In a real scenario, you might call 'flake8' or 'pylint' here
try:
import pyflakes.api
logging.info("Pyflakes available. Code looks clean.")
except ImportError:
logging.warning("Pyflakes not installed, skipping linting.")
def execute_tests(self):
"""Run pytest programmatically."""
logging.info("Starting Test Execution...")
report_file = os.path.join(self.reports_dir, f"report_{self.timestamp}.html")
# Construct pytest command
# -v: verbose
# --html: generate html report
# --self-contained-html: put CSS/JS inside the HTML file
command = [
sys.executable, "-m", "pytest",
self.test_dir,
"-v",
f"--html={report_file}",
"--self-contained-html",
"--color=yes"
]
# Run the command
result = subprocess.run(command, cwd=self.project_root)
if result.returncode == 0:
logging.info("✅ All tests passed successfully.")
else:
logging.error("❌ Some tests failed.")
return result.returncode
def cleanup_old_reports(self, keep_last=5):
"""Remove old reports to save space."""
logging.info("Cleaning up old reports...")
files = sorted(os.listdir(self.reports_dir), reverse=True)
if len(files) > keep_last:
for f in files[keep_last:]:
os.remove(os.path.join(self.reports_dir, f))
logging.info(f"Deleted old report: {f}")
def run(self):
"""Main workflow execution."""
try:
self.setup_environment()
self.run_linting_check()
exit_code = self.execute_tests()
self.cleanup_old_reports()
return exit_code
except Exception as e:
logging.exception("Workflow crashed with an error.")
return 1
if __name__ == "__main__":
workflow = TestAutomationWorkflow()
exit_code = workflow.run()
sys.exit(exit_code)
2. The Sample Tests (tests/test_api.py)
To make this script work immediately, create a folder named tests and add this file inside it. This demonstrates an Integration Test (checking an API) and a Unit Test.
# tests/test_api.py
import pytest
import requests
# A simple Unit Test
def test_simple_math():
assert 1 + 1 == 2, "Math is broken"
# A parameterized test (runs multiple times with different inputs)
@pytest.mark.parametrize("input, expected", [
(2, 4),
(3, 9),
(10, 100)
])
def test_squaring_numbers(input, expected):
assert input ** 2 == expected
# An Integration Test (Requires Internet)
def test_api_status_code():
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
assert response.status_code == 200
assert response.json()["id"] == 1
# A test intended to fail (to demonstrate reporting)
def test_intentional_failure():
assert False, "This test fails on purpose to show the report works"
3. How to Run It
- Save the first block of code as
run_automation.py.
- Create a folder named
tests next to it.
- Save the second block of code inside that folder as
test_api.py.
- Run the automation script:
python run_automation.py
Key Features of this Workflow:
- Modular Structure: The logic is separated into setup, execution, and cleanup methods.
- Reporting: It automatically generates a professional HTML report in the
reports/ folder. You can open this file in any web browser to see exactly which tests failed.
- Robustness: It uses
subprocess to run pytest. This ensures that even if your tests crash the Python interpreter severely, the main workflow script can continue (to send notifications or clean up).
- Report Management: It automatically deletes old reports, keeping only the 5 most recent ones to prevent disk clutter.
- Exit Codes: It returns a proper exit code (0 for success, 1 for failure), which is crucial if you intend to plug this script into a CI/CD pipeline (like Jenkins, GitHub Actions, or GitLab CI).