I am currently experimenting with the Python version of Selenium Web Driver. Using the driver has been straight forward so far but I have been struggling recently with the issue of mocking HTTP
responses. Is there a Python package that allows you to mock HTTP
responses in web applications programmatically ? i.e. it allows Selenium to send real HTTP
requests (by clicking on a link in the application for example) but then intercepts them and sends back fake HTTP
responses that were created by me via code. Those fake responses will, of course, be displayed by the application.
It has to be one that can integrate perfectly with Python Web Driver and does not interfere with its communication with the web application. A bonus would be to be able to tally all the requests made to a specific URL (or URL regular expression)
Edit: Based on neo's suggestion below, I implemented the following steps:
1) I downloaded the original browsermob-proxy (JAVA version) and saved it in C:\Users\johnsmith\Computer_Code\browsermob-proxy-2.1.0-beta-1\
2) I installed the Python client of browsermob-proxy. The egg file was installed in C:\Python27\Lib\site-packages
3) I created a fake HTML page and saved it in C:\Users\johnsmith\Computer_Code\Python\Automation_Testing
.
The HTML page code is shown below:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to my fun page</title>
<meta charset = "UTF-8">
</head>
<body>
<h2>Search Python.org</h2>
<h2>Mocking is not going well so far !!</h2>
<img src = "http://i.imgur.com/EjcKmEj.gif">
</body>
</html>
4) I navigated to the folder in step 3 above using the command line and then executed the following command: python -m SimpleHTTPServer This started a server on port 8000 for the purpose of serving the fake HTML file.
5) I wrote the following simple code that uses Selenium WebDriver to try and navigate to the Python home page. Using Browsermob's rewrite function, I tried to replace the real response to the request for http://www.python.org with the fake HTML page in step 3
# contents of Selenium_WebDriver_Mocking_test.py
import browsermobproxy
import selenium.webdriver as driver
import time
website_homepage_url = "http://www.python.org"
server = browsermobproxy.Server("C:\Users\johnsmith\Computer_Code\\browsermob-proxy-2.1.0-beta-1\\bin\\browsermob-proxy")
server.start()
proxy = server.create_proxy()
profile = driver.FirefoxProfile()
profile.set_proxy(proxy.selenium_proxy())
browser = driver.Firefox(firefox_profile=profile)
proxy.new_har("Python.org")
proxy.rewrite_url(website_homepage_url, 'http://localhost:8000/Fake_Search_Results_Page.html')
browser.get(website_homepage_url)
time.sleep(10)
proxy.har # returns a HAR JSON blob
server.stop()
browser.quit()
The result of running the above code was a page with the following message:
Error response. Error code 404. Message: File not found. Error code explanation: 404 = Nothing matches the given URI.
Where did I go wrong ?