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.

An example of configuring a Sauce Labs virtual machine with a pre-run executable is editing the host file in the virtual machine, so when the driver tries to access a particular domain, like google.com, it will be redirected to a new IP address, for example (saucelabs.com). As with other prerun configurations, the basic steps are:

  1. Write a script with the URL redirect to the new IP address.
  2. Upload the script to a publicly accessible location, like GitHub or Sauce Storage
  3. Set the prerun capability in your test script to load the script as host file in the Sauce Labs virtual machine.

The Host File Script

Here are examples of the host file script, EditDNS,in both OS X/Linux and Windows versions.

echo " www.google.com" >> /etc/hosts
@echo off
echo www.google.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 script, as shown in this Python example.

# -*- coding: UTF-8 -*-

from selenium import webdriver

desired_capabilities = webdriver.DesiredCapabilities.CHROME
desired_capabilities['version'] = 'latest'
desired_capabilities['platform'] = 'macOS 10.14'
desired_capabilities['name'] = 'Editing the DNS'
desired_capabilities['prerun'] = {'executable':'https://raw.githubusercontent.com/albedithdiaz/sauceSupport/master/preRunScripts/EditHostFile.sh', 'background': False }

remote_url = 'http://SAUCE_USERNAME:SAUCE_ACCESS_KEY@ondemand.saucelabs.com/wd/hub'

driver = webdriver.Remote(command_executor = remote_url, desired_capabilities = desired_capabilities)

title = driver.title
assert "Swag Labs" in title