Verify file upload functionality on the upload page
Preconditions (2)
✅ Expected Result: The upload confirmation message 'File uploaded successfully' is displayed on the page
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:
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.
Now add data-driven testing with 3 different files: 'testfile.txt', 'image.png', and 'document.pdf'
send_keys().send_keys() method inputs the file path string to the file input element, triggering the upload.send_keys() on the file input element -> Option Asend_keys() on the file input element.send_keys() correctly with the file path string.file_input = driver.find_element(By.NAME, 'upload')
file_input.send_keys('/home/user/document.txt')
print(file_input.get_attribute('value'))send_keys() sets its value attribute to a browser-generated fake path 'C:\\fakepath\\document.txt' for security reasons.get_attribute('value') returns the fake path 'C:\\fakepath\\document.txt'.driver.find_element(By.CSS_SELECTOR, 'input[type="file"]').click()
driver.find_element(By.CSS_SELECTOR, 'input[type="file"]').send_keys('/path/to/file')click() opens the OS file dialog, which Selenium cannot control, blocking automation.send_keys() with the file path is needed; clicking before it can interfere.Pass the test and this pattern moves unknown