This repository has been archived by the owner on Mar 3, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 428
/
browser.rb
90 lines (73 loc) · 1.62 KB
/
browser.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
require 'socket'
require 'capybara/util/timeout'
require 'json'
class Capybara::Driver::Webkit
class Browser
def initialize(options = {})
@socket_class = options[:socket_class] || TCPSocket
start_server
connect
end
def visit(url)
command "Visit", url
end
def find(query)
command("Find", query).split(",")
end
def reset!
command("Reset")
end
def source
command("Source")
end
def url
command("Url")
end
def command(name, *args)
@socket.puts name
@socket.puts args.size
args.each do |arg|
@socket.puts arg.to_s.bytesize
@socket.print arg
end
check
read_response
end
def evaluate_script(script)
json = command('Evaluate', script)
JSON.parse("[#{json}]").first
end
def execute_script(script)
command('Execute', script)
end
def show
command "Show"
end
private
def start_server
server_path = File.expand_path("../../../../../bin/webkit_server", __FILE__)
@pid = fork { exec(server_path) }
at_exit { Process.kill("INT", @pid) }
end
def connect
Capybara.timeout(5) do
attempt_connect
!@socket.nil?
end
end
def attempt_connect
@socket = @socket_class.open("localhost", 9200)
rescue Errno::ECONNREFUSED
end
def check
result = @socket.gets.strip
unless result == 'ok'
raise WebkitError, read_response
end
end
def read_response
response_length = @socket.gets.to_i
@socket.read(response_length)
end
end
end