python
#!/usr/bin/env python3
"""
Sherlock's Automated Software Testing Workflow Script
===================================================
This Python script automates end-to-end web testing workflows using Selenium WebDriver.
It performs automated tests on DuckDuckGo's search functionality as a demo (easily adaptable
to your own web app). Key features:
- Auto-installs ChromeDriver using webdriver-manager (no manual setup needed).
- Runs tests in headless mode for CI/CD compatibility.
- Takes screenshots on test failure for debugging.
- Uses unittest framework for structured, extensible tests.
- Command-line arguments for customization (e.g., non-headless mode, custom URL).
- Generates a simple test report in console.
Workflow:
1. Setup: Installs browser driver automatically.
2. Test: Navigates, interacts, asserts.
3. Teardown: Screenshots on failure, quits driver.
4. Report: Console output + optional screenshots.
Dependencies:
Run `pip install selenium webdriver-manager` before first use.
Usage:
python testing_workflow.py --help
python testing_workflow.py # Headless default
python testing_workflow.py --headless=false --browser=firefox # Visible Firefox test
"""
import argparse
import os
import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
class WebTestingWorkflow(unittest.TestCase):
def setUp(self):
"""Setup WebDriver per test."""
options = self.options.copy() if hasattr(self, 'options') else {}
if self.browser == 'chrome':
service = ChromeService(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service, options=webdriver.ChromeOptions().update(**options))
elif self.browser == 'firefox':
service = FirefoxService(GeckoDriverManager().install())
self.driver = webdriver.Firefox(service=service, options=webdriver.FirefoxOptions().update(**options))
else:
raise ValueError(f"Unsupported browser: {self.browser}")
self.wait = WebDriverWait(self.driver, 10)
self.driver.maximize_window()
self.screenshot_dir = "screenshots"
os.makedirs(self.screenshot_dir, exist_ok=True)
def tearDown(self):
"""Teardown: Screenshot on failure, quit driver."""
if hasattr(self._outcome, 'errors')[-1] or hasattr(self._outcome, 'failures')[-1]:
test_name = self._testMethodName
screenshot_path = os.path.join(self.screenshot_dir, f"{test_name}_failure.png")
self.driver.save_screenshot(screenshot_path)
print(f"Failure screenshot saved: {screenshot_path}")
self.driver.quit()
def test_search_functionality(self):
"""Test 1: Search for 'Python programming' and verify results."""
self.driver.get("https://duckduckgo.com/")
search_box = self.wait.until(EC.element_to_be_clickable((By.ID, "search_form_input")))
search_box.clear()
search_box.send_keys("Python programming")
search_box.submit()
# Wait for and verify first result
first_result = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "[data-testid='result-0']")))
self.assertIn("Python", first_result.text, "Search result should contain 'Python'")
print("✓ Search test passed!")
def test_page_load_and_title(self):
"""Test 2: Verify page loads correctly and title is expected."""
self.driver.get("https://duckduckgo.com/")
self.assertEqual("DuckDuckGo — Privacy, simplified.", self.driver.title)
print("✓ Page load and title test passed!")
def main():
parser = argparse.ArgumentParser(description="Sherlock's Automated Web Testing Workflow")
parser.add_argument('--browser', default='chrome', choices=['chrome', 'firefox'],
help='Browser to use (default: chrome)')
parser.add_argument('--headless', action='store_true', default=True,
help='Run in headless mode (default: true)')
parser.add_argument('--url', default='https://duckduckgo.com/',
help='Base URL to test (default: DuckDuckGo)')
args = parser.parse_args()
# Configure options based on args
options = {}
if args.headless:
if args.browser == 'chrome':
options['add_argument'] = ['--headless=new', '--no-sandbox', '--disable-dev-shm-usage']
else:
options['add_argument'] = ['--headless']
# Monkey-patch args into test class for access
WebTestingWorkflow.browser = args.browser
WebTestingWorkflow.options = options # Dict for update()
# Run tests
print("🚀 Starting automated testing workflow...")
loader = unittest.TestLoader()
suite = loader.loadTestsFromTestCase(WebTestingWorkflow)
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
if result.wasSuccessful():
print("\n🎉 All tests passed! Workflow complete.")
else:
print("\n❌ Tests failed. Check screenshots in 'screenshots/' folder.")
return 0 if result.wasSuccessful() else 1
if __name__ == "__main__":
exit(main())
This script handles setup/teardown, error capture, and reporting – a full testing pipeline in one file. Questions? Elementary! 🔍