Handling Basic Authentication Dialogs in Watir Tests
rherrick — Thu, 10/15/2009 - 11:57
I just ran into an issue where I'm creating Watir tests for some of the Web applications at my work. These applications require basic authentication to access them. Watir is not really set up to handle basic authentication on its own, since the whole process is sort of an odd bird (and, worth noting, isn't really used on actual secure sites for a number of reasons; our applications are secured with basic authentication in testing environments).
The Watir wiki has a couple of posted solutions so I tried those out. I can get both of the solutions to work on their own. The issue I ran into was detecting the presence of the basic auth pop-up dialog. Everything works fine with these solutions (and the variations suggested in the comments) as long as the pop-up dialog appears!
But sometimes the pop-up doesn't appear (usually this is due to an instance of IE that has already authenticated being open on the desktop). In that case, the solution using the handle_logon.rb script just hangs, waiting, I guess, for something to happen. The solution using the browser.send_keys calls just pushes ahead, sending keys willy nilly regardless of their appropriateness.
The solution I came up with was using the Watir.autoit.WinWait call to get the window, as shown in Solution #2, but adding a timeout to the call. Once that returns, you can check the return value. The WinWait function returns 0 if it can't locate the indicated window within the specified timeout period.
If the window was found, I call Watir.autoit.WinActivate to bring the window to the front and Watir.autoit.Send as shown.
I added one extra line to make sure the username text box is selected before sending the keystrokes. The ! character represents the Alt key to the Send function, meaning that !u is Alt-U. A corollary issue here is that if your username or password contains the ! character, you need to escape the ! with { and }. So, for example, hithere! becomes hithere!. This is easily accomplished with a bit of Ruby code:
@password.gsub(/!/, '{!}')
Of course, if the window wasn't found, we just continue on our way.
The basic code for this procedure is shown below.
# Opens the given URL in the browser and clears basic authentication.
def open_url
a = Thread.new { @browser.goto(@url) }
sleep 2
win_exists = Watir.autoit.WinWait(@login_title, "", 5)
if (win_exists > 0)
Watir.autoit.WinActivate(@login_title)
Watir.autoit.Send('!u')
Watir.autoit.Send(@username)
Watir.autoit.Send('{TAB}')
Watir.autoit.Send(@password.gsub(/!/, '{!}'))
Watir.autoit.Send('{ENTER}')
end
a.join
end
- rherrick's blog
- Login or register to post comments
- Delicious
- Digg
- Yahoo
- Technorati