A current project I am testing involves a HTML5 file upload. I had thought that the "Browser" a file prompt would prevent me from using a Selenium test framework to automate this process. However it turns out, as with many things that this is a "Solved problem".
The short answer is, you can identify the "Browser" button input element and use "Send Keys" function to provide the path to the file you want to upload. You then trigger the submit butting using the "Click" command as normal.
I entered the following commands in a PowerShell prompt, I already have Python 3, pip and virtualenv installed.
cd e:\dev virtualenv uploadtestenv .\uploadtestenv\Scripts\activate.ps1 pip install seleniumbase seleniumbase install chromedriver seleniumbase mkdir file_upload_test cd file_upload_test
SeleniumBase Help docs are available: https://github.com/seleniumbase/SeleniumBase/tree/master/help_docs
To run this example - copy the following into a file called
from seleniumbase import BaseCase from time import time from os import remove class MyTestClass(BaseCase): def test_basic(self): # setup testdata to be uploaded # time based filename generated for this run only filename = str(int(round(time() * 1000))) + ".txt" # path with filename path = "E:\\dev\\file_upload_test\\" + filename f= open(filename,"w+") for i in range(10): f.write("This is line %d\r\n" % (i+1)) f.close() # SelinumBase test self.open("https://the-internet.herokuapp.com/upload") self.send_keys('#file-upload', path) self.click('#file-submit') self.assert_exact_text(filename, '#uploaded-files') # Clean up testdata remove(path)
To run the test (again, PowerShell, same folder):
pytest .\file_upload_test.py --demo_mode
This prototype example makes use of the HTML5 Uploader on the wonderful "The Internet" resource, by Dave Haeffner. A very helpful resource for helping to test out Selenium tests. Check it out: https://the-internet.herokuapp.com
The test data creation example is based on a Guru99 article: Python File Handling: Create, Open, Append, Read, Write
Cover Photo "Python Book" by Christina Morillo