16

I have an application A that should handle a form submit made with POST method. The actual form, that initiates the request, is in totally separate application B. I am testing application A using Selenium, and I like to write a test case for form submit handling.

How to do this? Can this be done in Selenium at all? Application A does not have a form that can initiate this request.

Note, that the request must use POST, otherwise I could just use WebDriver.get(url) method.

Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
  • 1
    Why don't you fill out the form with selenium and submit the form and ensure you are presented with the proper data upon execution completing. However, if application B is down this test will always fail -- in other words I think you need to mock this interaction. – Scott May 08 '12 at 14:09
  • @Scott: I won't have any access to application B where the form will be. – Juha Syrjälä May 09 '12 at 12:23
  • 1
    it seems the only way to do that is to mock the form inside the application you do have access to, otherwise selenium doesn't make the most sense in this context. – Scott May 09 '12 at 12:42
  • I think form mocking is the best way to go. You may even create this form dynamically with JavaScript – neoascetic Dec 11 '14 at 11:08
  • Duplicate of http://stackoverflow.com/questions/5660956/is-there-any-way-to-start-with-a-post-request-using-selenium ? – rwitzel Mar 10 '15 at 14:25

3 Answers3

15

With selenium you can execute arbitrary Javascript including programmatically submit a form.

Simplest JS execution with Selenium Java:

if (driver instanceof JavascriptExecutor) {
    System.out.println(((JavascriptExecutor) driver).executeScript("prompt('enter text...');"));
}

and with Javascript you can create a POST request, set the required parameters and HTTP headers, and submit it.

// Javascript example of a POST request
var xhr = new XMLHttpRequest();
// false as 3rd argument will forces synchronous processing
xhr.open('POST', 'http://httpbin.org/post', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('login=test&password=test');
alert(xhr.response);

In modern bleeding edge browsers you can also use fetch().

If you need to pass over to selenium the response text then instead of alert(this.responseText) use return this.responseText or return this.response and assign to a variable the result of execute_script (or execute_async_script) (if using python). For java that will be executeScript() or executeAsyncScript() correspondingly.

Here is a full example for python:

from selenium import webdriver

driver = webdriver.Chrome()

js = '''var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://httpbin.org/post', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

xhr.send('login=test&password=test');
return xhr.response;'''

result = driver.execute_script(js);

result will contain the return value of your JavaScript provided that the js code is synchronous. Setting false as the third argument to xhr.open(..) forces the request to be synchronous. Setting the 3rd arg to true or omitting it will make the request asynchronous.

❗️ If you are calling asynchronous js code then make sure that instead of execute_script you use execute_async_script or otherwise the call won't return anything!

NOTE: If you need to pass string arguments to the javascript make sure you always escape them using json.dumps(myString) or otherwise your js will break when the string contains single or double quotes or other tricky characters.

ccpizza
  • 28,968
  • 18
  • 162
  • 169
3

I don't think that's possible using Selenium. There isn't a way to create a POST request out of nothing using a web browser, and Selenium works by manipulating web browsers. I'd suggest you use a HTTP library to send the POST request instead, and run that alongside your Selenium tests. (What language/testing framework are you using?)

Zarkonnen
  • 22,200
  • 14
  • 65
  • 81
  • 6
    Java+JUnit. I can make the POST request using other tools but how can I make Selenium process the response? – Juha Syrjälä May 08 '12 at 10:44
  • except from directly accessing the local filesystem, with a browser you can do pretty much everything network-related, including create and submit a POST payload programatically – ccpizza Sep 10 '21 at 07:37
1

The easiest way I found is making an intermediary page solely for the purposes of submitting a POST request. Have selenium open the page, submit the form, and then get the source of the final page.

from selenium import webdriver
html='<html><head><title>test</title></head><body><form action="yoursite.com/postlocation" method="post" id="formid"><input type="hidden" name="firstName" id="firstName" value="Bob"><input type="hidden" name="lastName" id="lastName" value="Boberson"><input type="submit" id="inputbox"></form></body></html>'
htmlfile='/tmp/temp.html'
    try:
        with open(htmlfile, "w") as text_file:
            text_file.write(html)
    except:
        print('Unable to create temporary HTML file')
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Firefox()
driver.get('file://'+htmlfile)
driver.find_element_by_id('inputbox').click();
#wait for form to submit and finish loading page
wait = WebDriverWait(driver, 30)
response=driver.page_source
Mr. T
  • 294
  • 2
  • 13