Opening multiple threads with watir-webdriver results in a "Connection reject" error

I have this simple example:

require 'watir-webdriver' arr = [] sites = [ "www.google.com", "www.bbc.com", "www.cnn.com", "www.gmail.com" ] sites.each do |site| arr << Thread.new { b = Watir::Browser.new :chrome b.goto site puts b.url b.close } end arr.each {|t| t.join} 

Every time I run this script, I get

 ruby/2.1.0/net/http.rb:879:in `initialize': Connection refused - connect(2) for "127.0.0.1" port 9517 (Errno::ECONNREFUSED) 

Or one of the browsers unexpectedly closes with at least one of the threads.

on the other hand, if I set sleep 2 at the end of each cycle of the cycle, everything runs smoothly! Any idea why?

There must be something to do with understanding how threads work ...

+5
source share
1 answer

Basically, you create a race condition between instances of your browser to connect to the open port of watir-webdriver. In this case, your first browser instance sees that port 9517 is open and connects to it. Since you are rotating these instances in parallel, your second instance also thinks that port 9517 is open and trying to connect. But, unfortunately, this port is already used by the first browser instance. That is why you get this particular error.

This also explains why sleep 2 fixes the problem. The first browser instance connects to port 9517, and a dream causes the second browser instance to see 9517. Then it connects to port 9518.

EDIT

You can see how this is implemented using Selenium::WebDriver::Chrome::Service#initialize ( here ), which calls Selenium::WebDriver::PortProber ( here ). PortProber is how webdriver determines which port is open.

+5
source

Source: https://habr.com/ru/post/1206611/


All Articles