How to deal with file uploading in test automation using selenium or webdriver

lisak picture lisak · May 25, 2011 · Viewed 48.2k times · Source

I think that everybody who uses Webdriver for test automation must be aware of its great advantages for web development.

But there is a huge issue if file uploading is part of your web flow. It stops being test automation. The security restriction of browsers (invoking file selection) practically makes it impossible to automate tests.

Afaik the only option is to have Webdriver click the file upload button, sleep the thread, have developer/tester manually select the file, and then do the rest of the web flow.

How to deal with this, is there a workaround for it? Because it really can't be done like this. It wouldn't make sense.

This is the only case I know of when browser security restrictions do not apply:

<script language=javascript>   
  function window.onload(){   
          document.all.attachment.focus();   
          var WshShell=new ActiveXObject("WScript.Shell")   
          WshShell.sendKeys("D:\MyFile.doc")
  }   
</script>

Answer

AutomatedTester picture AutomatedTester · May 25, 2011

Webdriver can handle this quite easily in IE and Firefox. Its a simple case of finding the element and typing into it.

driver = webdriver.Firefox()
element = driver.find_element_by_id("fileUpload")
element.send_keys("myfile.txt")

The above example is in Python but you get the idea