import unittest
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class TestFileUpload(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.wait = WebDriverWait(self.driver, 10)
def test_file_upload(self):
driver = self.driver
wait = self.wait
# Step 1: Open the upload page
driver.get('http://example.com/upload')
# Step 2: Locate file input field
file_input = wait.until(EC.presence_of_element_located((By.ID, 'file-upload')))
# Step 3: Upload the file
file_path = os.path.abspath('testfile.txt')
file_input.send_keys(file_path)
# Step 4: Click upload button
upload_button = wait.until(EC.element_to_be_clickable((By.ID, 'upload-button')))
upload_button.click()
# Step 5: Wait for confirmation message
success_msg = wait.until(EC.visibility_of_element_located((By.ID, 'upload-success')))
# Assertions
self.assertTrue(success_msg.is_displayed(), 'Upload success message is not visible')
self.assertEqual(success_msg.text, 'File uploaded successfully', 'Upload success message text mismatch')
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()This test script uses Python's unittest framework with Selenium WebDriver.
In setUp, we start the Chrome browser and set an explicit wait of 10 seconds.
The test test_file_upload follows the manual steps exactly:
- Open the upload page URL.
- Wait for the file input field by its ID and send the absolute path of the test file.
- Wait for the upload button to be clickable and click it.
- Wait for the success message to appear and verify it is visible and has the correct text.
Using explicit waits ensures the test waits only as long as needed for elements to appear or be clickable, avoiding flaky tests.
In tearDown, the browser closes to clean up after the test.
This structure keeps the test clear, reliable, and easy to maintain.