Editing the Host file of the virtual machine will not work if Sauce Connect Proxy is in use. If you are using Sauce Connect Proxy, the Host file of the machine running Sauce Connect Proxy will be referenced and you can make the desired changes there. |
Tests often include http requests to various domains/endpoints. DNS will, of course, resolve those domain names to an IP address.
Sometimes tests need to redirect their normal requests to a development server. These domains will not be found by DNS. A solution to this problem is to add an entry to the local hosts
file of the computer running the test, thus making the domain resolve to the IP address of the development server. For example, one might want www.fonts.com
to resolve to the IP address 196.118.45.9
, because that is the IP address of a server that holds a development version of the fonts.
This can be done on a Sauce Labs VM with the help of a pre-run executable.
To make this happen, follow these steps:
- Write a host file script with the URL redirect to the new IP address.
- Upload the script to a publicly accessible location, like GitHub or Sauce Storage
- Set prerun capability in your test script to load the script as the host file in the Sauce Labs virtual machine.
Below are examples of steps (1) and (3).
The Host File Script
Here are examples of the host file script, EditDNS,
in both OS X/Linux and Windows versions.
#!/bin/bash echo "196.118.45.9 www.fonts.com" >> /etc/hosts |
@echo off echo 196.118.45.9 www.fonts.com > %temp%\temphosts.txt type C:\WINDOWS\system32\drivers\etc\hosts >> %temp%\temphosts.txt copy /Y %temp%\temphosts.txt C:\WINDOWS\system32\drivers\etc\hosts |
Setting the prerun Capability in Your Test Script
Having created and uploaded your host file script, you now need to refer to it using the prerun capability in your test script, as shown in this Python example.
#!/usr/bin/python # -*- coding: UTF-8 -*- import unittest import time from selenium import webdriver class Selenium2OnSauce(unittest.TestCase): def setUp(self): self.desired_capabilities = webdriver.DesiredCapabilities.CHROME self.desired_capabilities['version'] = '56' self.desired_capabilities['platform'] = 'OS X 10.11' self.desired_capabilities['name'] = 'Editing the DNS' self.desired_capabilities['prerun'] = {'executable':'[LINK_TO_SCRIPT]', 'background': False } self.driver = webdriver.Remote(command_executor = 'http://SAUCE_USERNAME:SAUCE_ACCESS_KEY@ondemand.us-west-1.saucelabs.com:443/wd/hub', desired_capabilities = self.desired_capabilities) self.driver.implicitly_wait(30) def test_sauce(self): self.driver.get('http://www.fonts.com') title = self.driver.title self.assertEquals("Cross Browser Testing, Selenium Testing, and Mobile Testing | Sauce Labs", title) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main() |