Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 1469 lines (1340 sloc) 46.378 kB
6a381cd @thodg Added tests for custom multipart
thodg authored
1 # -*- encoding: utf-8 -*-
beaf135 * forgot to add new files in the previous commit.
nahi authored
2 require 'test/unit'
3 require 'httpclient'
4 require 'webrick'
5 require 'webrick/httpproxy.rb'
6 require 'logger'
7 require 'stringio'
8 require 'cgi'
9 require 'webrick/httputils'
10
11
12 class TestHTTPClient < Test::Unit::TestCase
13 Port = 17171
14 ProxyPort = 17172
15
16 def setup
17 @logger = Logger.new(STDERR)
18 @logger.level = Logger::Severity::FATAL
19 @proxyio = StringIO.new
20 @proxylogger = Logger.new(@proxyio)
21 @proxylogger.level = Logger::Severity::DEBUG
22 @url = "http://localhost:#{Port}/"
23 @proxyurl = "http://localhost:#{ProxyPort}/"
24 @server = @proxyserver = @client = nil
25 @server_thread = @proxyserver_thread = nil
26 setup_server
27 setup_client
28 end
29
30 def teardown
31 teardown_client
32 teardown_proxyserver if @proxyserver
33 teardown_server
34 end
35
36 def test_initialize
37 setup_proxyserver
38 escape_noproxy do
39 @proxyio.string = ""
40 @client = HTTPClient.new(@proxyurl)
41 assert_equal(URI.parse(@proxyurl), @client.proxy)
42 assert_equal(200, @client.head(@url).status)
7008822 * test cleanups for 1.9
nahi authored
43 assert(/accept/ =~ @proxyio.string)
beaf135 * forgot to add new files in the previous commit.
nahi authored
44 end
45 end
46
47 def test_agent_name
48 @client = HTTPClient.new(nil, "agent_name_foo")
49 str = ""
50 @client.debug_dev = str
51 @client.get(@url)
52 lines = str.split(/(?:\r?\n)+/)
53 assert_equal("= Request", lines[0])
54 assert_match(/^User-Agent: agent_name_foo/, lines[4])
55 end
56
57 def test_from
58 @client = HTTPClient.new(nil, nil, "from_bar")
59 str = ""
60 @client.debug_dev = str
61 @client.get(@url)
62 lines = str.split(/(?:\r?\n)+/)
63 assert_equal("= Request", lines[0])
64 assert_match(/^From: from_bar/, lines[4])
65 end
66
67 def test_debug_dev
68 str = ""
69 @client.debug_dev = str
4fc7a2b * added tests for coverage. closes #189.
nahi authored
70 assert_equal(str.object_id, @client.debug_dev.object_id)
beaf135 * forgot to add new files in the previous commit.
nahi authored
71 assert(str.empty?)
72 @client.get(@url)
73 assert(!str.empty?)
74 end
75
4fc7a2b * added tests for coverage. closes #189.
nahi authored
76 def test_debug_dev_stream
beaf135 * forgot to add new files in the previous commit.
nahi authored
77 str = ""
78 @client.debug_dev = str
4fc7a2b * added tests for coverage. closes #189.
nahi authored
79 conn = @client.get_async(@url)
80 Thread.pass while !conn.finished?
81 assert(!str.empty?)
82 end
83
84 def test_protocol_version_http09
85 @client.protocol_version = 'HTTP/0.9'
86 @client.debug_dev = str = ''
a176e7b * check test coverage on lib/httpclient/session.rb. see #189.
nahi authored
87 @client.test_loopback_http_response << "hello\nworld\n"
9fb9280 * create new self-signing dist-cert which has serial number 0x01 and…
nahi authored
88 res = @client.get(@url + 'hello')
1949938 @nahi Do not depend on Float#to_s behavior. closes #36.
authored
89 assert_equal('0.9', res.http_version)
a176e7b * check test coverage on lib/httpclient/session.rb. see #189.
nahi authored
90 assert_equal(nil, res.status)
91 assert_equal(nil, res.reason)
92 assert_equal("hello\nworld\n", res.content)
beaf135 * forgot to add new files in the previous commit.
nahi authored
93 lines = str.split(/(?:\r?\n)+/)
94 assert_equal("= Request", lines[0])
95 assert_equal("! CONNECTION ESTABLISHED", lines[2])
96 assert_equal("GET /hello HTTP/0.9", lines[3])
97 assert_equal("Connection: close", lines[5])
98 assert_equal("= Response", lines[6])
a176e7b * check test coverage on lib/httpclient/session.rb. see #189.
nahi authored
99 assert_match(/^hello$/, lines[7])
100 assert_match(/^world$/, lines[8])
beaf135 * forgot to add new files in the previous commit.
nahi authored
101 end
102
103 def test_protocol_version_http10
4fc7a2b * added tests for coverage. closes #189.
nahi authored
104 assert_equal(nil, @client.protocol_version)
beaf135 * forgot to add new files in the previous commit.
nahi authored
105 @client.protocol_version = 'HTTP/1.0'
4fc7a2b * added tests for coverage. closes #189.
nahi authored
106 assert_equal('HTTP/1.0', @client.protocol_version)
beaf135 * forgot to add new files in the previous commit.
nahi authored
107 str = ""
108 @client.debug_dev = str
109 @client.get(@url + 'hello')
110 lines = str.split(/(?:\r?\n)+/)
111 assert_equal("= Request", lines[0])
112 assert_equal("! CONNECTION ESTABLISHED", lines[2])
113 assert_equal("GET /hello HTTP/1.0", lines[3])
114 assert_equal("Connection: close", lines[5])
115 assert_equal("= Response", lines[6])
116 end
117
58bde3a @nahi Do not override given Host header. closes #19.
authored
118 def test_host_given
119 str = ""
120 @client.debug_dev = str
121 @client.get(@url)
122 lines = str.split(/(?:\r?\n)+/)
123 assert_equal("= Request", lines[0])
124 assert_equal("! CONNECTION ESTABLISHED", lines[2])
125 assert_equal("GET / HTTP/1.1", lines[3])
126 assert_equal("Host: localhost:#{Port}", lines[5])
127 #
128 @client.reset_all
129 str = ""
130 @client.debug_dev = str
131 @client.get(@url, nil, {'Host' => 'foo'})
132 lines = str.split(/(?:\r?\n)+/)
133 assert_equal("= Request", lines[0])
134 assert_equal("! CONNECTION ESTABLISHED", lines[2])
135 assert_equal("GET / HTTP/1.1", lines[3])
136 assert_equal("Host: foo", lines[4]) # use given param
137 end
138
beaf135 * forgot to add new files in the previous commit.
nahi authored
139 def test_protocol_version_http11
4fc7a2b * added tests for coverage. closes #189.
nahi authored
140 assert_equal(nil, @client.protocol_version)
beaf135 * forgot to add new files in the previous commit.
nahi authored
141 str = ""
142 @client.debug_dev = str
143 @client.get(@url)
144 lines = str.split(/(?:\r?\n)+/)
145 assert_equal("= Request", lines[0])
146 assert_equal("! CONNECTION ESTABLISHED", lines[2])
147 assert_equal("GET / HTTP/1.1", lines[3])
4ada884 * do not send 'Content-Length: 0' when a request doesn't have messag…
nahi authored
148 assert_equal("Host: localhost:#{Port}", lines[5])
beaf135 * forgot to add new files in the previous commit.
nahi authored
149 @client.protocol_version = 'HTTP/1.1'
4fc7a2b * added tests for coverage. closes #189.
nahi authored
150 assert_equal('HTTP/1.1', @client.protocol_version)
beaf135 * forgot to add new files in the previous commit.
nahi authored
151 str = ""
152 @client.debug_dev = str
153 @client.get(@url)
154 lines = str.split(/(?:\r?\n)+/)
155 assert_equal("= Request", lines[0])
156 assert_equal("! CONNECTION ESTABLISHED", lines[2])
157 assert_equal("GET / HTTP/1.1", lines[3])
158 @client.protocol_version = 'HTTP/1.0'
159 str = ""
160 @client.debug_dev = str
161 @client.get(@url)
162 lines = str.split(/(?:\r?\n)+/)
163 assert_equal("= Request", lines[0])
164 assert_equal("! CONNECTION ESTABLISHED", lines[2])
165 assert_equal("GET / HTTP/1.0", lines[3])
166 end
167
168 def test_proxy
169 setup_proxyserver
170 escape_noproxy do
171 assert_raises(URI::InvalidURIError) do
172 @client.proxy = "http://"
173 end
174 assert_raises(ArgumentError) do
175 @client.proxy = ""
176 end
4fc7a2b * added tests for coverage. closes #189.
nahi authored
177 @client.proxy = "http://admin:admin@foo:1234"
178 assert_equal(URI.parse("http://admin:admin@foo:1234"), @client.proxy)
beaf135 * forgot to add new files in the previous commit.
nahi authored
179 uri = URI.parse("http://bar:2345")
180 @client.proxy = uri
181 assert_equal(uri, @client.proxy)
182 #
183 @proxyio.string = ""
184 @client.proxy = nil
185 assert_equal(200, @client.head(@url).status)
7008822 * test cleanups for 1.9
nahi authored
186 assert(/accept/ !~ @proxyio.string)
beaf135 * forgot to add new files in the previous commit.
nahi authored
187 #
188 @proxyio.string = ""
189 @client.proxy = @proxyurl
d202412 * added test for #195.
nahi authored
190 @client.debug_dev = str = ""
beaf135 * forgot to add new files in the previous commit.
nahi authored
191 assert_equal(200, @client.head(@url).status)
7008822 * test cleanups for 1.9
nahi authored
192 assert(/accept/ =~ @proxyio.string)
d202412 * added test for #195.
nahi authored
193 assert(/Host: localhost:17171/ =~ str)
beaf135 * forgot to add new files in the previous commit.
nahi authored
194 end
195 end
196
d202412 * added test for #195.
nahi authored
197 def test_host_header
198 @client.proxy = @proxyurl
199 @client.debug_dev = str = ""
200 @client.test_loopback_http_response << "HTTP/1.0 200 OK\r\n\r\n"
201 assert_equal(200, @client.head('http://www.example.com/foo').status)
202 # ensure no ':80' is added. some servers dislike that.
203 assert(/\r\nHost: www\.example\.com\r\n/ =~ str)
204 #
205 @client.debug_dev = str = ""
206 @client.test_loopback_http_response << "HTTP/1.0 200 OK\r\n\r\n"
207 assert_equal(200, @client.head('http://www.example.com:12345/foo').status)
208 # ensure ':12345' exists.
209 assert(/\r\nHost: www\.example\.com:12345\r\n/ =~ str)
210 end
211
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
212 def test_proxy_env
213 setup_proxyserver
214 escape_env do
215 ENV['http_proxy'] = "http://admin:admin@foo:1234"
216 ENV['NO_PROXY'] = "foobar"
217 client = HTTPClient.new
218 assert_equal(URI.parse("http://admin:admin@foo:1234"), client.proxy)
219 assert_equal('foobar', client.no_proxy)
220 end
221 end
222
223 def test_proxy_env_cgi
224 setup_proxyserver
225 escape_env do
226 ENV['REQUEST_METHOD'] = 'GET' # CGI environment emulation
227 ENV['http_proxy'] = "http://admin:admin@foo:1234"
228 ENV['no_proxy'] = "foobar"
229 client = HTTPClient.new
230 assert_equal(nil, client.proxy)
231 ENV['CGI_HTTP_PROXY'] = "http://admin:admin@foo:1234"
232 client = HTTPClient.new
233 assert_equal(URI.parse("http://admin:admin@foo:1234"), client.proxy)
234 end
235 end
236
beaf135 * forgot to add new files in the previous commit.
nahi authored
237 def test_noproxy_for_localhost
238 @proxyio.string = ""
239 @client.proxy = @proxyurl
240 assert_equal(200, @client.head(@url).status)
7008822 * test cleanups for 1.9
nahi authored
241 assert(/accept/ !~ @proxyio.string)
beaf135 * forgot to add new files in the previous commit.
nahi authored
242 end
243
244 def test_no_proxy
245 setup_proxyserver
246 escape_noproxy do
247 # proxy is not set.
4fc7a2b * added tests for coverage. closes #189.
nahi authored
248 assert_equal(nil, @client.no_proxy)
beaf135 * forgot to add new files in the previous commit.
nahi authored
249 @client.no_proxy = 'localhost'
4fc7a2b * added tests for coverage. closes #189.
nahi authored
250 assert_equal('localhost', @client.no_proxy)
beaf135 * forgot to add new files in the previous commit.
nahi authored
251 @proxyio.string = ""
252 @client.proxy = nil
253 assert_equal(200, @client.head(@url).status)
7008822 * test cleanups for 1.9
nahi authored
254 assert(/accept/ !~ @proxyio.string)
beaf135 * forgot to add new files in the previous commit.
nahi authored
255 #
256 @proxyio.string = ""
257 @client.proxy = @proxyurl
258 assert_equal(200, @client.head(@url).status)
7008822 * test cleanups for 1.9
nahi authored
259 assert(/accept/ !~ @proxyio.string)
beaf135 * forgot to add new files in the previous commit.
nahi authored
260 #
261 @client.no_proxy = 'foobar'
262 @proxyio.string = ""
263 @client.proxy = @proxyurl
264 assert_equal(200, @client.head(@url).status)
7008822 * test cleanups for 1.9
nahi authored
265 assert(/accept/ =~ @proxyio.string)
beaf135 * forgot to add new files in the previous commit.
nahi authored
266 #
267 @client.no_proxy = 'foobar,localhost:baz'
268 @proxyio.string = ""
269 @client.proxy = @proxyurl
270 assert_equal(200, @client.head(@url).status)
7008822 * test cleanups for 1.9
nahi authored
271 assert(/accept/ !~ @proxyio.string)
beaf135 * forgot to add new files in the previous commit.
nahi authored
272 #
273 @client.no_proxy = 'foobar,localhost:443'
274 @proxyio.string = ""
275 @client.proxy = @proxyurl
276 assert_equal(200, @client.head(@url).status)
7008822 * test cleanups for 1.9
nahi authored
277 assert(/accept/ =~ @proxyio.string)
beaf135 * forgot to add new files in the previous commit.
nahi authored
278 #
279 @client.no_proxy = 'foobar,localhost:443:localhost:17171,baz'
280 @proxyio.string = ""
281 @client.proxy = @proxyurl
282 assert_equal(200, @client.head(@url).status)
7008822 * test cleanups for 1.9
nahi authored
283 assert(/accept/ !~ @proxyio.string)
beaf135 * forgot to add new files in the previous commit.
nahi authored
284 end
285 end
286
cf55b01 * Cookie header is not set in authentication negotiation. do not reu…
nahi authored
287 def test_cookie_update_while_authentication
288 escape_noproxy do
289 @client.test_loopback_http_response << <<EOS
290 HTTP/1.0 401\r
291 Date: Fri, 19 Dec 2008 11:57:29 GMT\r
292 Content-Type: text/plain\r
293 Content-Length: 0\r
294 WWW-Authenticate: Basic realm="hello"\r
295 Set-Cookie: foo=bar; path=/; domain=.example.org; expires=#{Time.mktime(2030, 12, 31).httpdate}\r
296 \r
297 EOS
298 @client.test_loopback_http_response << <<EOS
299 HTTP/1.1 200 OK\r
300 Content-Length: 5\r
301 Connection: close\r
302 \r
303 hello
304 EOS
305 @client.debug_dev = str = ''
306 @client.set_auth("http://www.example.org/baz/", 'admin', 'admin')
307 assert_equal('hello', @client.get('http://www.example.org/baz/foo').content)
308 assert_match(/^Cookie: foo=bar/, str)
309 assert_match(/^Authorization: Basic YWRtaW46YWRtaW4=/, str)
310 end
311 end
312
313
ac0fa20 * added a test for CONNECT proxy auth.
nahi authored
314 def test_proxy_ssl
315 escape_noproxy do
316 @client.proxy = 'http://admin:admin@localhost:8080/'
317 # disconnected at initial 'CONNECT' so there're 2 loopback responses
318 @client.test_loopback_http_response << <<EOS
319 HTTP/1.0 407 Proxy Authentication Required\r
320 Date: Fri, 19 Dec 2008 11:57:29 GMT\r
321 Content-Type: text/plain\r
322 Content-Length: 0\r
323 Proxy-Authenticate: Basic realm="hello"\r
324 Proxy-Connection: close\r
325 \r
326 EOS
327 @client.test_loopback_http_response << <<EOS
328 HTTP/1.0 200 Connection established\r
329 \r
330 HTTP/1.1 200 OK\r
331 Content-Length: 5\r
332 Connection: close\r
333 \r
334 hello
335 EOS
336 assert_equal('hello', @client.get('https://localhost:17171/baz').content)
337 end
338 end
339
4fc7a2b * added tests for coverage. closes #189.
nahi authored
340 def test_loopback_response
341 @client.test_loopback_response << 'message body 1'
342 @client.test_loopback_response << 'message body 2'
343 assert_equal('message body 1', @client.get_content('http://somewhere'))
344 assert_equal('message body 2', @client.get_content('http://somewhere'))
345 #
346 @client.debug_dev = str = ''
347 @client.test_loopback_response << 'message body 3'
348 assert_equal('message body 3', @client.get_content('http://somewhere'))
349 assert_match(/message body 3/, str)
350 end
351
352 def test_loopback_response_stream
353 @client.test_loopback_response << 'message body 1'
354 @client.test_loopback_response << 'message body 2'
355 conn = @client.get_async('http://somewhere')
356 Thread.pass while !conn.finished?
357 assert_equal('message body 1', conn.pop.content.read)
358 conn = @client.get_async('http://somewhere')
359 Thread.pass while !conn.finished?
360 assert_equal('message body 2', conn.pop.content.read)
361 end
362
363 def test_loopback_http_response
364 @client.test_loopback_http_response << "HTTP/1.0 200 OK\ncontent-length: 100\n\nmessage body 1"
365 @client.test_loopback_http_response << "HTTP/1.0 200 OK\ncontent-length: 100\n\nmessage body 2"
366 assert_equal('message body 1', @client.get_content('http://somewhere'))
367 assert_equal('message body 2', @client.get_content('http://somewhere'))
368 end
369
7968719 @nahi multiline response message header support.
authored
370 def test_multiline_header
371 @client.test_loopback_http_response << "HTTP/1.0 200 OK\nX-Foo: XXX\n YYY\nX-Bar: \n XXX\n\tYYY\ncontent-length: 100\n\nmessage body 1"
372 res = @client.get('http://somewhere')
373 assert_equal('message body 1', res.content)
374 assert_equal(['XXX YYY'], res.header['x-foo'])
375 assert_equal(['XXX YYY'], res.header['x-bar'])
376 end
377
4fc7a2b * added tests for coverage. closes #189.
nahi authored
378 def test_broken_header
379 @client.test_loopback_http_response << "HTTP/1.0 200 OK\nXXXXX\ncontent-length: 100\n\nmessage body 1"
7968719 @nahi multiline response message header support.
authored
380 res = @client.get('http://somewhere')
381 assert_equal('message body 1', res.content)
4fc7a2b * added tests for coverage. closes #189.
nahi authored
382 end
383
5fb4436 * Security fix introduced at 2.1.3.
nahi authored
384 def test_redirect_non_https
385 url = @url + 'redirect1'
386 https_url = URI.parse(url)
387 https_url.scheme = 'https'
388 #
389 redirect_to_http = "HTTP/1.0 302 OK\nLocation: #{url}\n\n"
390 redirect_to_https = "HTTP/1.0 302 OK\nLocation: #{https_url}\n\n"
391 #
392 # https -> http is denied
393 @client.test_loopback_http_response << redirect_to_http
394 assert_raises(HTTPClient::BadResponseError) do
395 @client.get_content(https_url)
396 end
397 #
398 # http -> http is OK
399 @client.reset_all
400 @client.test_loopback_http_response << redirect_to_http
401 assert_equal('hello', @client.get_content(url))
402 #
403 # http -> https is OK
404 @client.reset_all
405 @client.test_loopback_http_response << redirect_to_https
406 assert_raises(OpenSSL::SSL::SSLError) do
407 # trying to normal endpoint with SSL -> SSL negotiation failure
408 @client.get_content(url)
409 end
410 #
411 # https -> https is OK
412 @client.reset_all
413 @client.test_loopback_http_response << redirect_to_https
414 assert_raises(OpenSSL::SSL::SSLError) do
415 # trying to normal endpoint with SSL -> SSL negotiation failure
416 @client.get_content(https_url)
417 end
a620b5f @nahi Invalidate pooled sessions for the same destination when we got a Kee…
authored
418 #
419 # https -> http with strict_redirect_uri_callback
420 @client.redirect_uri_callback = @client.method(:strict_redirect_uri_callback)
421 @client.test_loopback_http_response << redirect_to_http
422 assert_raises(HTTPClient::BadResponseError) do
423 @client.get_content(https_url)
424 end
5fb4436 * Security fix introduced at 2.1.3.
nahi authored
425 end
426
4fc7a2b * added tests for coverage. closes #189.
nahi authored
427 def test_redirect_relative
428 @client.test_loopback_http_response << "HTTP/1.0 302 OK\nLocation: hello\n\n"
429 assert_equal('hello', @client.get_content(@url + 'redirect1'))
430 #
431 @client.reset_all
432 @client.redirect_uri_callback = @client.method(:strict_redirect_uri_callback)
433 assert_equal('hello', @client.get_content(@url + 'redirect1'))
434 @client.reset_all
435 @client.test_loopback_http_response << "HTTP/1.0 302 OK\nLocation: hello\n\n"
5ddb7c5 * added 'res' attribute to HTTPClient::BadResponse. you can get res…
nahi authored
436 begin
437 @client.get_content(@url + 'redirect1')
438 assert(false)
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
439 rescue HTTPClient::BadResponseError => e
5ddb7c5 * added 'res' attribute to HTTPClient::BadResponse. you can get res…
nahi authored
440 assert_equal(302, e.res.status)
4fc7a2b * added tests for coverage. closes #189.
nahi authored
441 end
442 end
443
8a94b21 @nahi Fixed NME for non absolute-URI redirect on https. closes #20.
authored
444 def test_redirect_https_relative
445 url = @url + 'redirect1'
446 https_url = URI.parse(url)
447 https_url.scheme = 'https'
448 @client.test_loopback_http_response << "HTTP/1.0 302 OK\nLocation: /foo\n\n"
449 @client.test_loopback_http_response << "HTTP/1.0 200 OK\n\nhello"
450 assert_equal('hello', @client.get_content(https_url))
451 end
452
d24ab1d @nahi do not try to read when a response code is 1XX, 204 or 304. closes #10.
authored
453 def test_no_content
454 assert_nothing_raised do
455 timeout(2) do
456 @client.get(@url + 'status', :status => 101)
457 @client.get(@url + 'status', :status => 204)
458 @client.get(@url + 'status', :status => 304)
459 end
460 end
461 end
462
beaf135 * forgot to add new files in the previous commit.
nahi authored
463 def test_get_content
464 assert_equal('hello', @client.get_content(@url + 'hello'))
465 assert_equal('hello', @client.get_content(@url + 'redirect1'))
466 assert_equal('hello', @client.get_content(@url + 'redirect2'))
4fc7a2b * added tests for coverage. closes #189.
nahi authored
467 url = @url.sub(/localhost/, '127.0.0.1')
468 assert_equal('hello', @client.get_content(url + 'hello'))
469 assert_equal('hello', @client.get_content(url + 'redirect1'))
470 assert_equal('hello', @client.get_content(url + 'redirect2'))
471 @client.reset(@url)
472 @client.reset(url)
473 @client.reset(@url)
474 @client.reset(url)
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
475 assert_raises(HTTPClient::BadResponseError) do
beaf135 * forgot to add new files in the previous commit.
nahi authored
476 @client.get_content(@url + 'notfound')
477 end
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
478 assert_raises(HTTPClient::BadResponseError) do
beaf135 * forgot to add new files in the previous commit.
nahi authored
479 @client.get_content(@url + 'redirect_self')
480 end
481 called = false
482 @client.redirect_uri_callback = lambda { |uri, res|
483 newuri = res.header['location'][0]
484 called = true
485 newuri
486 }
487 assert_equal('hello', @client.get_content(@url + 'relative_redirect'))
488 assert(called)
489 end
490
95964f1 @nahi Added transparent_gzip_decompression property. closes #42.
authored
491 GZIP_CONTENT = "\x1f\x8b\x08\x00\x1a\x96\xe0\x4c\x00\x03\xcb\x48\xcd\xc9\xc9\x07\x00\x86\xa6\x10\x36\x05\x00\x00\x00"
492 DEFLATE_CONTENT = "\x78\x9c\xcb\x48\xcd\xc9\xc9\x07\x00\x06\x2c\x02\x15"
493 GZIP_CONTENT.force_encoding('BINARY') if GZIP_CONTENT.respond_to?(:force_encoding)
494 DEFLATE_CONTENT.force_encoding('BINARY') if DEFLATE_CONTENT.respond_to?(:force_encoding)
495 def test_get_gzipped_content
496 @client.transparent_gzip_decompression = false
497 content = @client.get_content(@url + 'compressed?enc=gzip')
498 content.force_encoding('BINARY') if content.respond_to?(:force_encoding)
499 assert_not_equal('hello', content)
500 assert_equal(GZIP_CONTENT, content)
501 @client.transparent_gzip_decompression = true
502 assert_equal('hello', @client.get_content(@url + 'compressed?enc=gzip'))
503 assert_equal('hello', @client.get_content(@url + 'compressed?enc=deflate'))
504 @client.transparent_gzip_decompression = false
505 end
506
c9d999f * get_content with block yielded unexpected message body. closes #173.
nahi authored
507 def test_get_content_with_block
508 @client.get_content(@url + 'hello') do |str|
509 assert_equal('hello', str)
510 end
511 @client.get_content(@url + 'redirect1') do |str|
512 assert_equal('hello', str)
513 end
514 @client.get_content(@url + 'redirect2') do |str|
515 assert_equal('hello', str)
516 end
517 end
518
beaf135 * forgot to add new files in the previous commit.
nahi authored
519 def test_post_content
520 assert_equal('hello', @client.post_content(@url + 'hello'))
521 assert_equal('hello', @client.post_content(@url + 'redirect1'))
522 assert_equal('hello', @client.post_content(@url + 'redirect2'))
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
523 assert_raises(HTTPClient::BadResponseError) do
beaf135 * forgot to add new files in the previous commit.
nahi authored
524 @client.post_content(@url + 'notfound')
525 end
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
526 assert_raises(HTTPClient::BadResponseError) do
beaf135 * forgot to add new files in the previous commit.
nahi authored
527 @client.post_content(@url + 'redirect_self')
528 end
529 called = false
530 @client.redirect_uri_callback = lambda { |uri, res|
531 newuri = res.header['location'][0]
532 called = true
533 newuri
534 }
535 assert_equal('hello', @client.post_content(@url + 'relative_redirect'))
536 assert(called)
537 end
538
fad6e92 * post an IO body on the second request as well as the first request…
nahi authored
539 def test_post_content_io
540 post_body = StringIO.new("1234567890")
541 assert_equal('post,1234567890', @client.post_content(@url + 'servlet', post_body))
542 post_body = StringIO.new("1234567890")
543 assert_equal('post,1234567890', @client.post_content(@url + 'servlet_redirect', post_body))
544 #
545 post_body = StringIO.new("1234567890")
546 post_body.read(5)
547 assert_equal('post,67890', @client.post_content(@url + 'servlet_redirect', post_body))
548 end
549
beaf135 * forgot to add new files in the previous commit.
nahi authored
550 def test_head
551 assert_equal("head", @client.head(@url + 'servlet').header["x-head"][0])
552 res = @client.head(@url + 'servlet', {1=>2, 3=>4})
553 assert_equal('1=2&3=4', res.header["x-query"][0])
554 end
555
4fc7a2b * added tests for coverage. closes #189.
nahi authored
556 def test_head_async
557 conn = @client.head_async(@url + 'servlet', {1=>2, 3=>4})
558 Thread.pass while !conn.finished?
559 res = conn.pop
560 assert_equal('1=2&3=4', res.header["x-query"][0])
561 end
562
beaf135 * forgot to add new files in the previous commit.
nahi authored
563 def test_get
564 assert_equal("get", @client.get(@url + 'servlet').content)
565 res = @client.get(@url + 'servlet', {1=>2, 3=>4})
566 assert_equal('1=2&3=4', res.header["x-query"][0])
2253f95 * test coverage checked. see #189.
nahi authored
567 assert_nil(res.contenttype)
568 #
569 url = @url.to_s + 'servlet?5=6&7=8'
570 res = @client.get(url, {1=>2, 3=>4})
571 assert_equal('1=2&3=4&5=6&7=8', res.header["x-query"][0])
572 assert_nil(res.contenttype)
beaf135 * forgot to add new files in the previous commit.
nahi authored
573 end
574
4fc7a2b * added tests for coverage. closes #189.
nahi authored
575 def test_get_async
576 conn = @client.get_async(@url + 'servlet', {1=>2, 3=>4})
577 Thread.pass while !conn.finished?
578 res = conn.pop
579 assert_equal('1=2&3=4', res.header["x-query"][0])
580 end
581
0b7e801 @nahi avoid data corruption bug in async method.
authored
582 def test_get_async_for_largebody
583 conn = @client.get_async(@url + 'largebody')
584 res = conn.pop
585 assert_equal(1000*1000, res.content.read.length)
586 end
587
47ba7a6 * [212] broke get/post with block. fixed. closes #173.
nahi authored
588 def test_get_with_block
589 called = false
590 res = @client.get(@url + 'servlet') { |str|
591 assert_equal('get', str)
592 called = true
593 }
594 assert(called)
595 # res does not have a content
596 assert_nil(res.content)
597 end
598
beaf135 * forgot to add new files in the previous commit.
nahi authored
599 def test_post
47ba7a6 * [212] broke get/post with block. fixed. closes #173.
nahi authored
600 assert_equal("post", @client.post(@url + 'servlet').content[0, 4])
601 res = @client.post(@url + 'servlet', {1=>2, 3=>4})
beaf135 * forgot to add new files in the previous commit.
nahi authored
602 assert_equal('1=2&3=4', res.header["x-query"][0])
603 end
604
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
605 def test_post_with_content_type
606 ext = {'content-type' => 'application/x-www-form-urlencoded', 'hello' => 'world'}
607 assert_equal("post", @client.post(@url + 'servlet').content[0, 4], ext)
608 res = @client.post(@url + 'servlet', {1=>2, 3=>4}, ext)
609 assert_equal('1=2&3=4', res.header["x-query"][0])
610 #
611 ext = [['content-type', 'multipart/form-data'], ['hello', 'world']]
612 assert_equal("post", @client.post(@url + 'servlet').content[0, 4], ext)
613 res = @client.post(@url + 'servlet', {1=>2, 3=>4}, ext)
2253f95 * test coverage checked. see #189.
nahi authored
614 assert_match(/Content-Disposition: form-data; name="1"/, res.content)
615 assert_match(/Content-Disposition: form-data; name="3"/, res.content)
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
616 #
617 ext = {'content-type' => 'multipart/form-data; boundary=hello'}
618 assert_equal("post", @client.post(@url + 'servlet').content[0, 4], ext)
619 res = @client.post(@url + 'servlet', {1=>2, 3=>4}, ext)
2253f95 * test coverage checked. see #189.
nahi authored
620 assert_match(/Content-Disposition: form-data; name="1"/, res.content)
621 assert_match(/Content-Disposition: form-data; name="3"/, res.content)
622 assert_equal("post,--hello\r\nContent-Disposition: form-data; name=\"1\"\r\n\r\n2\r\n--hello\r\nContent-Disposition: form-data; name=\"3\"\r\n\r\n4\r\n--hello--\r\n\r\n", res.content)
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
623 end
624
625 def test_post_with_file
626 STDOUT.sync = true
627 File.open(__FILE__) do |file|
628 res = @client.post(@url + 'servlet', {1=>2, 3=>file})
7c8ebd1 @nahi Avoid unused variable warnings from 1.9. closes #24.
authored
629 res.content.force_encoding('BINARY') if res.content.respond_to?(:force_encoding)
f4f6d9a @nahi test update for 1.9 support. (not yet completed)
authored
630 assert_match(/^Content-Disposition: form-data; name="1"\r\n/nm, res.content)
a176e7b * check test coverage on lib/httpclient/session.rb. see #189.
nahi authored
631 assert_match(/^Content-Disposition: form-data; name="3";/, res.content)
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
632 assert_match(/FIND_TAG_IN_THIS_FILE/, res.content)
633 end
634 end
635
2253f95 * test coverage checked. see #189.
nahi authored
636 def test_post_with_io # chunked post
637 myio = StringIO.new("4")
638 def myio.size
639 nil
640 end
641 res = @client.post(@url + 'servlet', {1=>2, 3=>myio})
642 assert_match(/\r\nContent-Disposition: form-data; name="1"\r\n/m, res.content)
643 assert_match(/\r\n2\r\n/m, res.content)
644 assert_match(/\r\nContent-Disposition: form-data; name="3"; filename=""\r\n/m, res.content)
645 assert_match(/\r\n4\r\n/m, res.content)
646 end
647
4fc7a2b * added tests for coverage. closes #189.
nahi authored
648 def test_post_async
649 conn = @client.post_async(@url + 'servlet', {1=>2, 3=>4})
650 Thread.pass while !conn.finished?
651 res = conn.pop
652 assert_equal('1=2&3=4', res.header["x-query"][0])
653 end
654
47ba7a6 * [212] broke get/post with block. fixed. closes #173.
nahi authored
655 def test_post_with_block
656 called = false
657 res = @client.post(@url + 'servlet') { |str|
658 assert_equal('post,', str)
659 called = true
660 }
661 assert(called)
662 assert_nil(res.content)
663 #
664 called = false
665 res = @client.post(@url + 'servlet', {1=>2, 3=>4}) { |str|
666 assert_equal('post,1=2&3=4', str)
667 called = true
668 }
669 assert(called)
670 assert_equal('1=2&3=4', res.header["x-query"][0])
671 assert_nil(res.content)
672 end
673
6a381cd @thodg Added tests for custom multipart
thodg authored
674 def test_post_with_custom_multipart
675 ext = {'content-type' => 'multipart/form-data'}
676 assert_equal("post", @client.post(@url + 'servlet').content[0, 4], ext)
677 body = [{ 'Content-Disposition' => 'form-data; name="1"', :content => "2"},
678 { 'Content-Disposition' => 'form-data; name="3"', :content => "4"}]
679 res = @client.post(@url + 'servlet', body, ext)
680 assert_match(/Content-Disposition: form-data; name="1"/, res.content)
681 assert_match(/Content-Disposition: form-data; name="3"/, res.content)
682 #
683 ext = {'content-type' => 'multipart/form-data; boundary=hello'}
684 assert_equal("post", @client.post(@url + 'servlet').content[0, 4], ext)
685 res = @client.post(@url + 'servlet', body, ext)
686 assert_match(/Content-Disposition: form-data; name="1"/, res.content)
687 assert_match(/Content-Disposition: form-data; name="3"/, res.content)
688 assert_equal("post,--hello\r\nContent-Disposition: form-data; name=\"1\"\r\n\r\n2\r\n--hello\r\nContent-Disposition: form-data; name=\"3\"\r\n\r\n4\r\n--hello--\r\n\r\n", res.content)
689 end
690
691 def test_post_with_custom_multipart_and_file
692 STDOUT.sync = true
693 File.open(__FILE__) do |file|
694 ext = { 'Content-Type' => 'multipart/alternative' }
695 body = [{ 'Content-Type' => 'text/plain', :content => "this is only a test" },
696 { 'Content-Type' => 'application/x-ruby', :content => file }]
697 res = @client.post(@url + 'servlet', body, ext)
9ada537 @nahi Make Keep-Alive test use threads properly.
authored
698 res.content.force_encoding('BINARY') if res.content.respond_to?(:force_encoding)
6a381cd @thodg Added tests for custom multipart
thodg authored
699 assert_match(/^Content-Type: text\/plain\r\n/m, res.content)
700 assert_match(/^this is only a test\r\n/m, res.content)
701 assert_match(/^Content-Type: application\/x-ruby\r\n/m, res.content)
702 assert_match(/FIND_TAG_IN_THIS_FILE/, res.content)
703 end
704 end
705
beaf135 * forgot to add new files in the previous commit.
nahi authored
706 def test_put
707 assert_equal("put", @client.put(@url + 'servlet').content)
4fc7a2b * added tests for coverage. closes #189.
nahi authored
708 res = @client.put(@url + 'servlet', {1=>2, 3=>4})
709 assert_equal('1=2&3=4', res.header["x-query"][0])
710 end
711
58bde3a @nahi Do not override given Host header. closes #19.
authored
712 def test_put_bytesize
713 res = @client.put(@url + 'servlet', 'txt' => 'あいうえお')
714 assert_equal('txt=%E3%81%82%E3%81%84%E3%81%86%E3%81%88%E3%81%8A', res.header["x-query"][0])
715 assert_equal('15', res.header["x-size"][0])
716 end
717
4fc7a2b * added tests for coverage. closes #189.
nahi authored
718 def test_put_async
719 conn = @client.put_async(@url + 'servlet', {1=>2, 3=>4})
720 Thread.pass while !conn.finished?
721 res = conn.pop
beaf135 * forgot to add new files in the previous commit.
nahi authored
722 assert_equal('1=2&3=4', res.header["x-query"][0])
723 end
724
725 def test_delete
726 assert_equal("delete", @client.delete(@url + 'servlet').content)
4fc7a2b * added tests for coverage. closes #189.
nahi authored
727 end
728
729 def test_delete_async
730 conn = @client.delete_async(@url + 'servlet')
731 Thread.pass while !conn.finished?
732 res = conn.pop
733 assert_equal('delete', res.content.read)
beaf135 * forgot to add new files in the previous commit.
nahi authored
734 end
735
736 def test_options
737 assert_equal("options", @client.options(@url + 'servlet').content)
4fc7a2b * added tests for coverage. closes #189.
nahi authored
738 end
739
740 def test_options_async
741 conn = @client.options_async(@url + 'servlet')
742 Thread.pass while !conn.finished?
743 res = conn.pop
744 assert_equal('options', res.content.read)
745 end
746
747 def test_propfind
748 assert_equal("propfind", @client.propfind(@url + 'servlet').content)
749 end
750
751 def test_propfind_async
752 conn = @client.propfind_async(@url + 'servlet')
753 Thread.pass while !conn.finished?
754 res = conn.pop
755 assert_equal('propfind', res.content.read)
756 end
757
758 def test_proppatch
759 assert_equal("proppatch", @client.proppatch(@url + 'servlet').content)
760 res = @client.proppatch(@url + 'servlet', {1=>2, 3=>4})
761 assert_equal('proppatch', res.content)
762 assert_equal('1=2&3=4', res.header["x-query"][0])
763 end
764
765 def test_proppatch_async
766 conn = @client.proppatch_async(@url + 'servlet', {1=>2, 3=>4})
767 Thread.pass while !conn.finished?
768 res = conn.pop
769 assert_equal('proppatch', res.content.read)
beaf135 * forgot to add new files in the previous commit.
nahi authored
770 assert_equal('1=2&3=4', res.header["x-query"][0])
771 end
772
773 def test_trace
774 assert_equal("trace", @client.trace(@url + 'servlet').content)
4fc7a2b * added tests for coverage. closes #189.
nahi authored
775 res = @client.trace(@url + 'servlet', {1=>2, 3=>4})
beaf135 * forgot to add new files in the previous commit.
nahi authored
776 assert_equal('1=2&3=4', res.header["x-query"][0])
777 end
778
4fc7a2b * added tests for coverage. closes #189.
nahi authored
779 def test_trace_async
780 conn = @client.trace_async(@url + 'servlet', {1=>2, 3=>4})
781 Thread.pass while !conn.finished?
782 res = conn.pop
783 assert_equal('1=2&3=4', res.header["x-query"][0])
784 end
785
786 def test_chunked
787 assert_equal('chunked', @client.get_content(@url + 'chunked', { 'msg' => 'chunked' }))
788 end
789
790 def test_chunked_empty
791 assert_equal('', @client.get_content(@url + 'chunked', { 'msg' => '' }))
792 end
793
beaf135 * forgot to add new files in the previous commit.
nahi authored
794 def test_get_query
795 assert_equal({'1'=>'2'}, check_query_get({1=>2}))
796 assert_equal({'a'=>'A', 'B'=>'b'}, check_query_get({"a"=>"A", "B"=>"b"}))
797 assert_equal({'&'=>'&'}, check_query_get({"&"=>"&"}))
798 assert_equal({'= '=>' =+'}, check_query_get({"= "=>" =+"}))
799 assert_equal(
800 ['=', '&'].sort,
801 check_query_get([["=", "="], ["=", "&"]])['='].to_ary.sort
802 )
803 assert_equal({'123'=>'45'}, check_query_get('123=45'))
804 assert_equal({'12 3'=>'45', ' '=>' '}, check_query_get('12+3=45&+=+'))
805 assert_equal({}, check_query_get(''))
2253f95 * test coverage checked. see #189.
nahi authored
806 assert_equal({'1'=>'2'}, check_query_get({1=>StringIO.new('2')}))
807 assert_equal({'1'=>'2', '3'=>'4'}, check_query_get(StringIO.new('3=4&1=2')))
beaf135 * forgot to add new files in the previous commit.
nahi authored
808 end
809
810 def test_post_body
811 assert_equal({'1'=>'2'}, check_query_post({1=>2}))
812 assert_equal({'a'=>'A', 'B'=>'b'}, check_query_post({"a"=>"A", "B"=>"b"}))
813 assert_equal({'&'=>'&'}, check_query_post({"&"=>"&"}))
814 assert_equal({'= '=>' =+'}, check_query_post({"= "=>" =+"}))
815 assert_equal(
816 ['=', '&'].sort,
817 check_query_post([["=", "="], ["=", "&"]])['='].to_ary.sort
818 )
819 assert_equal({'123'=>'45'}, check_query_post('123=45'))
820 assert_equal({'12 3'=>'45', ' '=>' '}, check_query_post('12+3=45&+=+'))
821 assert_equal({}, check_query_post(''))
822 #
823 post_body = StringIO.new("foo=bar&foo=baz")
824 assert_equal(
825 ["bar", "baz"],
826 check_query_post(post_body)["foo"].to_ary.sort
827 )
828 end
829
830 def test_extra_headers
831 str = ""
832 @client.debug_dev = str
833 @client.head(@url, nil, {"ABC" => "DEF"})
834 lines = str.split(/(?:\r?\n)+/)
835 assert_equal("= Request", lines[0])
836 assert_match("ABC: DEF", lines[4])
837 #
838 str = ""
839 @client.debug_dev = str
840 @client.get(@url, nil, [["ABC", "DEF"], ["ABC", "DEF"]])
841 lines = str.split(/(?:\r?\n)+/)
842 assert_equal("= Request", lines[0])
843 assert_match("ABC: DEF", lines[4])
844 assert_match("ABC: DEF", lines[5])
845 end
846
847 def test_timeout
848 assert_equal(60, @client.connect_timeout)
849 assert_equal(120, @client.send_timeout)
850 assert_equal(60, @client.receive_timeout)
4fc7a2b * added tests for coverage. closes #189.
nahi authored
851 #
852 @client.connect_timeout = 1
853 @client.send_timeout = 2
854 @client.receive_timeout = 3
855 assert_equal(1, @client.connect_timeout)
856 assert_equal(2, @client.send_timeout)
857 assert_equal(3, @client.receive_timeout)
beaf135 * forgot to add new files in the previous commit.
nahi authored
858 end
859
860 def test_connect_timeout
861 # ToDo
862 end
863
864 def test_send_timeout
865 # ToDo
866 end
867
868 def test_receive_timeout
869 # this test takes 2 sec
870 assert_equal('hello', @client.get_content(@url + 'sleep?sec=2'))
871 @client.receive_timeout = 1
872 assert_equal('hello', @client.get_content(@url + 'sleep?sec=0'))
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
873 assert_raise(HTTPClient::ReceiveTimeoutError) do
beaf135 * forgot to add new files in the previous commit.
nahi authored
874 @client.get_content(@url + 'sleep?sec=2')
875 end
876 @client.receive_timeout = 3
877 assert_equal('hello', @client.get_content(@url + 'sleep?sec=2'))
878 end
879
59dbc78 @nahi just added POST receive_timeout test for #2.
authored
880 def test_receive_timeout_post
881 # this test takes 2 sec
882 assert_equal('hello', @client.post(@url + 'sleep', :sec => 2).content)
883 @client.receive_timeout = 1
884 assert_equal('hello', @client.post(@url + 'sleep', :sec => 0).content)
885 assert_raise(HTTPClient::ReceiveTimeoutError) do
886 @client.post(@url + 'sleep', :sec => 2)
887 end
888 @client.receive_timeout = 3
889 assert_equal('hello', @client.post(@url + 'sleep', :sec => 2).content)
890 end
891
1986c59 @nahi Applied the patch in #44: let Connection#pop raise the Exception when…
authored
892 def test_async_error
893 assert_raise( SocketError ) do
894 conn = @client.get_async("http://non-existing-host/")
895 conn.pop
896 end
897 end
898
4fc7a2b * added tests for coverage. closes #189.
nahi authored
899 def test_reset
900 url = @url + 'servlet'
901 assert_nothing_raised do
902 5.times do
903 @client.get(url)
904 @client.reset(url)
905 end
906 end
907 end
908
909 def test_reset_all
910 assert_nothing_raised do
911 5.times do
912 @client.get(@url + 'servlet')
913 @client.reset_all
914 end
915 end
916 end
917
beaf135 * forgot to add new files in the previous commit.
nahi authored
918 def test_cookies
4fc7a2b * added tests for coverage. closes #189.
nahi authored
919 cookiefile = File.join(File.dirname(File.expand_path(__FILE__)), 'test_cookies_file')
beaf135 * forgot to add new files in the previous commit.
nahi authored
920 File.open(cookiefile, "wb") do |f|
4fc7a2b * added tests for coverage. closes #189.
nahi authored
921 f << "http://rubyforge.org/account/login.php session_ser LjEwMy45Ni40Ni0q%2A-fa0537de8cc31 2000000000 .rubyforge.org / 13\n"
beaf135 * forgot to add new files in the previous commit.
nahi authored
922 end
4fc7a2b * added tests for coverage. closes #189.
nahi authored
923 @client.set_cookie_store(cookiefile)
924 cookie = @client.cookie_manager.cookies.first
beaf135 * forgot to add new files in the previous commit.
nahi authored
925 url = cookie.url
926 assert(cookie.domain_match(url.host, cookie.domain))
4fc7a2b * added tests for coverage. closes #189.
nahi authored
927 #
928 @client.reset_all
929 @client.test_loopback_http_response << "HTTP/1.0 200 OK\nSet-Cookie: foo=bar; expires=#{Time.mktime(2030, 12, 31).httpdate}\n\nOK"
930 @client.get_content('http://rubyforge.org/account/login.php')
931 @client.save_cookie_store
932 str = File.read(cookiefile)
0d46b59 @nahi illegal Cookie PATH handling. closes #13.
authored
933 assert_match(%r(http://rubyforge.org/account/login.php foo bar 1924873200 rubyforge.org /account 1), str)
4fc7a2b * added tests for coverage. closes #189.
nahi authored
934 end
935
350acc3 * applied a patch from user. IO#readpartial does not clear the secon…
nahi authored
936 def test_eof_error_length
937 io = StringIO.new('')
938 def io.gets(*arg)
939 @buf ||= ["HTTP/1.0 200 OK\n", "content-length: 123\n", "\n"]
940 @buf.shift
941 end
942 def io.readpartial(size, buf)
943 @second ||= false
944 if !@second
945 @second = '1st'
946 buf << "abc"
947 buf
948 elsif @second == '1st'
949 @second = '2nd'
950 raise EOFError.new
951 else
952 raise Exception.new
953 end
954 end
955 def io.eof?
956 true
957 end
958 @client.test_loopback_http_response << io
959 assert_nothing_raised do
960 @client.get('http://foo/bar')
961 end
962 end
963
964 def test_eof_error_rest
965 io = StringIO.new('')
966 def io.gets(*arg)
967 @buf ||= ["HTTP/1.0 200 OK\n", "\n"]
968 @buf.shift
969 end
970 def io.readpartial(size, buf)
971 @second ||= false
972 if !@second
973 @second = '1st'
974 buf << "abc"
975 buf
976 elsif @second == '1st'
977 @second = '2nd'
978 raise EOFError.new
979 else
980 raise Exception.new
981 end
982 end
983 def io.eof?
984 true
985 end
986 @client.test_loopback_http_response << io
987 assert_nothing_raised do
988 @client.get('http://foo/bar')
989 end
990 end
991
4fc7a2b * added tests for coverage. closes #189.
nahi authored
992 def test_urify
993 extend HTTPClient::Util
994 assert_nil(urify(nil))
995 uri = 'http://foo'
996 assert_equal(URI.parse(uri), urify(uri))
997 assert_equal(URI.parse(uri), urify(URI.parse(uri)))
998 end
999
1000 def test_connection
1001 c = HTTPClient::Connection.new
1002 assert(c.finished?)
1003 assert_nil(c.join)
1004 end
1005
1006 def test_site
1007 site = HTTPClient::Site.new
1008 assert_equal('tcp', site.scheme)
1009 assert_equal('0.0.0.0', site.host)
1010 assert_equal(0, site.port)
1011 assert_equal('tcp://0.0.0.0:0', site.addr)
1012 assert_equal('tcp://0.0.0.0:0', site.to_s)
1013 assert_nothing_raised do
1014 site.inspect
1015 end
1016 #
1017 site = HTTPClient::Site.new(URI.parse('http://localhost:12345/foo'))
1018 assert_equal('http', site.scheme)
1019 assert_equal('localhost', site.host)
1020 assert_equal(12345, site.port)
1021 assert_equal('http://localhost:12345', site.addr)
1022 assert_equal('http://localhost:12345', site.to_s)
1023 assert_nothing_raised do
1024 site.inspect
1025 end
1026 #
1027 site1 = HTTPClient::Site.new(URI.parse('http://localhost:12341/'))
1028 site2 = HTTPClient::Site.new(URI.parse('http://localhost:12342/'))
1029 site3 = HTTPClient::Site.new(URI.parse('http://localhost:12342/'))
1030 assert(!(site1 == site2))
1031 h = { site1 => 'site1', site2 => 'site2' }
1032 h[site3] = 'site3'
1033 assert_equal('site1', h[site1])
1034 assert_equal('site3', h[site2])
beaf135 * forgot to add new files in the previous commit.
nahi authored
1035 end
1036
2253f95 * test coverage checked. see #189.
nahi authored
1037 def test_http_header
1038 res = @client.get(@url + 'hello')
1039 assert_equal('text/html', res.contenttype)
1040 assert_equal(5, res.header.get(nil).size)
1041 #
1042 res.header.delete('connection')
1043 assert_equal(4, res.header.get(nil).size)
1044 #
1045 res.header['foo'] = 'bar'
1046 assert_equal(['bar'], res.header['foo'])
1047 #
1048 assert_equal([['foo', 'bar']], res.header.get('foo'))
83dc6ec * avoid duplicated request header line while HTTP access negotiation…
nahi authored
1049 res.header['foo'] = ['bar', 'bar2']
2253f95 * test coverage checked. see #189.
nahi authored
1050 assert_equal([['foo', 'bar'], ['foo', 'bar2']], res.header.get('foo'))
1051 end
1052
1053 def test_mime_type
1054 assert_equal('text/plain', HTTP::Message.mime_type('foo.txt'))
1055 assert_equal('text/html', HTTP::Message.mime_type('foo.html'))
1056 assert_equal('text/html', HTTP::Message.mime_type('foo.htm'))
1057 assert_equal('application/msword', HTTP::Message.mime_type('foo.doc'))
1058 assert_equal('image/png', HTTP::Message.mime_type('foo.png'))
1059 assert_equal('image/gif', HTTP::Message.mime_type('foo.gif'))
1060 assert_equal('image/jpeg', HTTP::Message.mime_type('foo.jpg'))
1061 assert_equal('image/jpeg', HTTP::Message.mime_type('foo.jpeg'))
1062 assert_equal('application/octet-stream', HTTP::Message.mime_type('foo.unknown'))
1063 #
7008822 * test cleanups for 1.9
nahi authored
1064 handler = lambda { |path| 'hello/world' }
1065 assert_nil(HTTP::Message.mime_type_handler)
2253f95 * test coverage checked. see #189.
nahi authored
1066 assert_nil(HTTP::Message.get_mime_type_func)
7008822 * test cleanups for 1.9
nahi authored
1067 HTTP::Message.mime_type_handler = handler
1068 assert_not_nil(HTTP::Message.mime_type_handler)
2253f95 * test coverage checked. see #189.
nahi authored
1069 assert_not_nil(HTTP::Message.get_mime_type_func)
1070 assert_equal('hello/world', HTTP::Message.mime_type('foo.txt'))
7008822 * test cleanups for 1.9
nahi authored
1071 HTTP::Message.mime_type_handler = nil
1072 assert_equal('text/plain', HTTP::Message.mime_type('foo.txt'))
2253f95 * test coverage checked. see #189.
nahi authored
1073 HTTP::Message.set_mime_type_func(nil)
1074 assert_equal('text/plain', HTTP::Message.mime_type('foo.txt'))
7008822 * test cleanups for 1.9
nahi authored
1075 #
1076 handler = lambda { |path| nil }
1077 HTTP::Message.mime_type_handler = handler
1078 assert_equal('application/octet-stream', HTTP::Message.mime_type('foo.txt'))
2253f95 * test coverage checked. see #189.
nahi authored
1079 end
1080
1081 def test_connect_request
7008822 * test cleanups for 1.9
nahi authored
1082 req = HTTP::Message.new_connect_request(URI.parse('https://foo/bar'))
2253f95 * test coverage checked. see #189.
nahi authored
1083 assert_equal("CONNECT foo:443 HTTP/1.0\r\n\r\n", req.dump)
7008822 * test cleanups for 1.9
nahi authored
1084 req = HTTP::Message.new_connect_request(URI.parse('https://example.com/'))
1085 assert_equal("CONNECT example.com:443 HTTP/1.0\r\n\r\n", req.dump)
2253f95 * test coverage checked. see #189.
nahi authored
1086 end
1087
1088 def test_response
1089 res = HTTP::Message.new_response('response')
1090 res.contenttype = 'text/plain'
1091 res.header.body_date = Time.mktime(2000, 1, 1)
1092 assert_equal(
1093 [
1094 "",
1095 "Content-Length: 8",
1096 "Content-Type: text/plain",
1097 "Last-Modified: Fri, 31 Dec 1999 15:00:00 GMT",
1098 "Status: 200 OK",
1099 "response"
1100 ],
1101 res.dump.split(/\r\n/).sort
1102 )
1103 res.header.set('foo', 'bar')
1104 assert_equal(
1105 [
1106 "",
1107 "Content-Length: 8",
1108 "Content-Type: text/plain",
1109 "Last-Modified: Fri, 31 Dec 1999 15:00:00 GMT",
1110 "Status: 200 OK",
1111 "foo: bar",
1112 "response"
1113 ],
1114 res.dump.split(/\r\n/).sort
1115 )
1116 # nil body
1117 res = HTTP::Message.new_response(nil)
1118 assert_equal(
1119 [
1120 "Content-Length: 0",
1121 "Content-Type: text/html; charset=us-ascii",
1122 "Status: 200 OK"
1123 ],
1124 res.dump.split(/\r\n/).sort
1125 )
1126 # for mod_ruby env
1127 Object.const_set('Apache', nil)
1128 begin
1129 res = HTTP::Message.new_response('response')
1130 assert(res.dump.split(/\r\n/).any? { |line| /^Date/ =~ line })
1131 #
1132 res = HTTP::Message.new_response('response')
1133 res.contenttype = 'text/plain'
1134 res.header.body_date = Time.mktime(2000, 1, 1)
c6d461b * added RDoc for httpclient/connection.rb. see #162.
nahi authored
1135 res.header['Date'] = Time.mktime(2000, 1, 1).httpdate
2253f95 * test coverage checked. see #189.
nahi authored
1136 assert_equal(
1137 [
1138 "",
1139 "Content-Length: 8",
1140 "Content-Type: text/plain",
c6d461b * added RDoc for httpclient/connection.rb. see #162.
nahi authored
1141 "Date: Fri, 31 Dec 1999 15:00:00 GMT",
2253f95 * test coverage checked. see #189.
nahi authored
1142 "HTTP/1.1 200 OK",
1143 "Last-Modified: Fri, 31 Dec 1999 15:00:00 GMT",
1144 "response"
1145 ],
1146 res.dump.split(/\r\n/).sort
1147 )
1148 ensure
1149 Object.instance_eval { remove_const('Apache') }
1150 end
1151 end
1152
b6d2b8b * test added for #197. closes #197.
nahi authored
1153 def test_timeout_scheduler
1154 assert_equal('hello', @client.get_content(@url + 'hello'))
261b280 @nahi define String#bytesize and use it for 1.9 compatibility. closes #23.
authored
1155 status = HTTPClient.timeout_scheduler.instance_eval { @thread.kill; @thread.join; @thread.status }
b6d2b8b * test added for #197. closes #197.
nahi authored
1156 assert(!status) # dead
1157 assert_equal('hello', @client.get_content(@url + 'hello'))
1158 end
1159
33b4eab * let SessionManager inherit proxy and debug_dev setting from client…
nahi authored
1160 def test_session_manager
1161 mgr = HTTPClient::SessionManager.new(@client)
1162 assert_nil(mgr.instance_eval { @proxy })
1163 assert_nil(mgr.debug_dev)
1164 @client.debug_dev = Object.new
1165 @client.proxy = 'http://myproxy:12345'
1166 mgr = HTTPClient::SessionManager.new(@client)
1167 assert_equal('http://myproxy:12345', mgr.instance_eval { @proxy }.to_s)
1168 assert_equal(@client.debug_dev, mgr.debug_dev)
1169 end
1170
9ada537 @nahi Make Keep-Alive test use threads properly.
authored
1171 def create_keepalive_thread(idx, sock)
1172 Thread.new {
1173 # return "12345" for the first connection
1174 sock.gets
1175 sock.gets
1176 sock.write("HTTP/1.1 200 OK\r\n")
1177 sock.write("Content-Length: 5\r\n")
1178 sock.write("\r\n")
1179 sock.write("12345")
1180 # for the next connection, close while reading the request for emulating
1181 # KeepAliveDisconnected
1182 sock.gets
1183 sock.close
1184 }
1185 end
1186
a620b5f @nahi Invalidate pooled sessions for the same destination when we got a Kee…
authored
1187 def test_keepalive_disconnected
1188 client = HTTPClient.new
1189 server = TCPServer.open('127.0.0.1', 0)
1190 server.listen(30) # set enough backlogs
9ada537 @nahi Make Keep-Alive test use threads properly.
authored
1191 endpoint = "http://127.0.0.1:#{server.addr[1]}/"
a620b5f @nahi Invalidate pooled sessions for the same destination when we got a Kee…
authored
1192 server_thread = Thread.new {
9ada537 @nahi Make Keep-Alive test use threads properly.
authored
1193 Thread.abort_on_exception = true
1194 # emulate 10 keep-alive connections
1195 10.times do |idx|
1196 sock = server.accept
1197 create_keepalive_thread(idx, sock)
1198 end
1199 # return "23456" for the request which gets KeepAliveDisconnected
a620b5f @nahi Invalidate pooled sessions for the same destination when we got a Kee…
authored
1200 5.times do
1201 sock = server.accept
1202 sock.gets
1203 sock.gets
1204 sock.write("HTTP/1.1 200 OK\r\n")
1205 sock.write("\r\n")
9ada537 @nahi Make Keep-Alive test use threads properly.
authored
1206 sock.write("23456")
1207 sock.close
a620b5f @nahi Invalidate pooled sessions for the same destination when we got a Kee…
authored
1208 end
9ada537 @nahi Make Keep-Alive test use threads properly.
authored
1209 # return "34567" for the rest requests
a620b5f @nahi Invalidate pooled sessions for the same destination when we got a Kee…
authored
1210 while true
1211 sock = server.accept
9ada537 @nahi Make Keep-Alive test use threads properly.
authored
1212 sock.gets
1213 sock.gets
1214 sock.write("HTTP/1.1 200 OK\r\n")
1215 sock.write("Connection: close\r\n")
1216 sock.write("Content-Length: 5\r\n")
1217 sock.write("\r\n")
1218 sock.write("34567")
a620b5f @nahi Invalidate pooled sessions for the same destination when we got a Kee…
authored
1219 sock.close
1220 end
1221 }
9ada537 @nahi Make Keep-Alive test use threads properly.
authored
1222 # allocate 10 keep-alive connections
1223 10.times.to_enum.map {
1224 Thread.new {
1225 assert_equal("12345", client.get(endpoint).content)
1226 }
1227 }.each(&:join)
1228 # send 5 requests, which should get KeepAliveDesconnected.
1229 # doing these requests, rest keep-alive connections are invalidated.
1230 5.times.to_enum.map {
1231 Thread.new {
1232 assert_equal("23456", client.get(endpoint).content)
1233 }
1234 }.each(&:join)
1235 # rest requests won't get KeepAliveDisconnected; how can I check this?
a620b5f @nahi Invalidate pooled sessions for the same destination when we got a Kee…
authored
1236 10.times.to_enum.map {
1237 Thread.new {
9ada537 @nahi Make Keep-Alive test use threads properly.
authored
1238 assert_equal("34567", client.get(endpoint).content)
a620b5f @nahi Invalidate pooled sessions for the same destination when we got a Kee…
authored
1239 }
9ada537 @nahi Make Keep-Alive test use threads properly.
authored
1240 }.each(&:join)
a620b5f @nahi Invalidate pooled sessions for the same destination when we got a Kee…
authored
1241 end
1242
beaf135 * forgot to add new files in the previous commit.
nahi authored
1243 private
1244
1245 def check_query_get(query)
1246 WEBrick::HTTPUtils.parse_query(
1247 @client.get(@url + 'servlet', query).header["x-query"][0]
1248 )
1249 end
1250
1251 def check_query_post(query)
1252 WEBrick::HTTPUtils.parse_query(
1253 @client.post(@url + 'servlet', query).header["x-query"][0]
1254 )
1255 end
1256
1257 def setup_server
1258 @server = WEBrick::HTTPServer.new(
a560489 * use 'localhost' instead of '0.0.0.0'
nahi authored
1259 :BindAddress => "localhost",
beaf135 * forgot to add new files in the previous commit.
nahi authored
1260 :Logger => @logger,
1261 :Port => Port,
1262 :AccessLog => [],
1263 :DocumentRoot => File.dirname(File.expand_path(__FILE__))
1264 )
95964f1 @nahi Added transparent_gzip_decompression property. closes #42.
authored
1265 [:hello, :sleep, :servlet_redirect, :redirect1, :redirect2, :redirect3, :redirect_self, :relative_redirect, :chunked, :largebody, :status, :compressed].each do |sym|
beaf135 * forgot to add new files in the previous commit.
nahi authored
1266 @server.mount(
1267 "/#{sym}",
1268 WEBrick::HTTPServlet::ProcHandler.new(method("do_#{sym}").to_proc)
1269 )
1270 end
1271 @server.mount('/servlet', TestServlet.new(@server))
1272 @server_thread = start_server_thread(@server)
1273 end
1274
1275 def setup_proxyserver
1276 @proxyserver = WEBrick::HTTPProxyServer.new(
a560489 * use 'localhost' instead of '0.0.0.0'
nahi authored
1277 :BindAddress => "localhost",
beaf135 * forgot to add new files in the previous commit.
nahi authored
1278 :Logger => @proxylogger,
1279 :Port => ProxyPort,
1280 :AccessLog => []
1281 )
1282 @proxyserver_thread = start_server_thread(@proxyserver)
1283 end
1284
1285 def setup_client
1286 @client = HTTPClient.new
1287 end
1288
1289 def teardown_server
1290 @server.shutdown
1291 end
1292
1293 def teardown_proxyserver
1294 @proxyserver.shutdown
1295 end
1296
1297 def teardown_client
1298 @client.reset_all
1299 end
1300
1301 def start_server_thread(server)
1302 t = Thread.new {
1303 Thread.current.abort_on_exception = true
1304 server.start
1305 }
1306 while server.status != :Running
1307 sleep 0.1
1308 unless t.alive?
1309 t.join
1310 raise
1311 end
1312 end
1313 t
1314 end
1315
b041b24 * added tests for proxy environment settings. see #109.
nahi authored
1316 def escape_env
1317 env = {}
1318 env.update(ENV)
1319 yield
1320 ensure
1321 ENV.clear
1322 ENV.update(env)
1323 end
1324
beaf135 * forgot to add new files in the previous commit.
nahi authored
1325 def escape_noproxy
1326 backup = HTTPClient::NO_PROXY_HOSTS.dup
1327 HTTPClient::NO_PROXY_HOSTS.clear
1328 yield
1329 ensure
1330 HTTPClient::NO_PROXY_HOSTS.replace(backup)
1331 end
1332
1333 def do_hello(req, res)
1334 res['content-type'] = 'text/html'
1335 res.body = "hello"
1336 end
1337
1338 def do_sleep(req, res)
1339 sec = req.query['sec'].to_i
1340 sleep sec
1341 res['content-type'] = 'text/html'
1342 res.body = "hello"
1343 end
1344
47ba7a6 * [212] broke get/post with block. fixed. closes #173.
nahi authored
1345 def do_servlet_redirect(req, res)
1346 res.set_redirect(WEBrick::HTTPStatus::Found, @url + "servlet")
1347 end
1348
beaf135 * forgot to add new files in the previous commit.
nahi authored
1349 def do_redirect1(req, res)
1350 res.set_redirect(WEBrick::HTTPStatus::MovedPermanently, @url + "hello")
1351 end
1352
1353 def do_redirect2(req, res)
1354 res.set_redirect(WEBrick::HTTPStatus::TemporaryRedirect, @url + "redirect3")
1355 end
1356
1357 def do_redirect3(req, res)
1358 res.set_redirect(WEBrick::HTTPStatus::Found, @url + "hello")
1359 end
1360
1361 def do_redirect_self(req, res)
1362 res.set_redirect(WEBrick::HTTPStatus::Found, @url + "redirect_self")
1363 end
1364
1365 def do_relative_redirect(req, res)
1366 res.set_redirect(WEBrick::HTTPStatus::Found, "hello")
1367 end
1368
4fc7a2b * added tests for coverage. closes #189.
nahi authored
1369 def do_chunked(req, res)
1370 res.chunked = true
1371 piper, pipew = IO.pipe
1372 res.body = piper
1373 pipew << req.query['msg']
1374 pipew.close
1375 end
1376
0b7e801 @nahi avoid data corruption bug in async method.
authored
1377 def do_largebody(req, res)
1378 res['content-type'] = 'text/html'
1379 res.body = "a" * 1000 * 1000
1380 end
1381
95964f1 @nahi Added transparent_gzip_decompression property. closes #42.
authored
1382 def do_compressed(req, res)
1383 if req.query['enc'] == 'gzip'
1384 res['content-encoding'] = 'gzip'
1385 res.body = GZIP_CONTENT
1386 elsif req.query['enc'] == 'deflate'
1387 res['content-encoding'] = 'deflate'
1388 res.body = DEFLATE_CONTENT
1389 end
1390 end
1391
d24ab1d @nahi do not try to read when a response code is 1XX, 204 or 304. closes #10.
authored
1392 def do_status(req, res)
1393 res.status = req.query['status'].to_i
1394 end
1395
beaf135 * forgot to add new files in the previous commit.
nahi authored
1396 class TestServlet < WEBrick::HTTPServlet::AbstractServlet
1397 def get_instance(*arg)
1398 self
1399 end
1400
1401 def do_HEAD(req, res)
1402 res["x-head"] = 'head' # use this for test purpose only.
1403 res["x-query"] = query_response(req)
1404 end
1405
1406 def do_GET(req, res)
1407 res.body = 'get'
1408 res["x-query"] = query_response(req)
1409 end
1410
1411 def do_POST(req, res)
47ba7a6 * [212] broke get/post with block. fixed. closes #173.
nahi authored
1412 res.body = 'post,' + req.body.to_s
beaf135 * forgot to add new files in the previous commit.
nahi authored
1413 res["x-query"] = body_response(req)
1414 end
1415
1416 def do_PUT(req, res)
4fc7a2b * added tests for coverage. closes #189.
nahi authored
1417 res["x-query"] = body_response(req)
58bde3a @nahi Do not override given Host header. closes #19.
authored
1418 param = WEBrick::HTTPUtils.parse_query(req.body) || {}
1419 res["x-size"] = (param['txt'] || '').size
261b280 @nahi define String#bytesize and use it for 1.9 compatibility. closes #23.
authored
1420 res.body = param['txt'] || 'put'
beaf135 * forgot to add new files in the previous commit.
nahi authored
1421 end
1422
1423 def do_DELETE(req, res)
1424 res.body = 'delete'
1425 end
1426
1427 def do_OPTIONS(req, res)
1428 # check RFC for legal response.
1429 res.body = 'options'
1430 end
1431
4fc7a2b * added tests for coverage. closes #189.
nahi authored
1432 def do_PROPFIND(req, res)
1433 res.body = 'propfind'
1434 end
1435
1436 def do_PROPPATCH(req, res)
1437 res.body = 'proppatch'
1438 res["x-query"] = body_response(req)
1439 end
1440
beaf135 * forgot to add new files in the previous commit.
nahi authored
1441 def do_TRACE(req, res)
1442 # client SHOULD reflect the message received back to the client as the
1443 # entity-body of a 200 (OK) response. [RFC2616]
1444 res.body = 'trace'
1445 res["x-query"] = query_response(req)
1446 end
1447
1448 private
1449
1450 def query_response(req)
1451 query_escape(WEBrick::HTTPUtils.parse_query(req.query_string))
1452 end
1453
1454 def body_response(req)
1455 query_escape(WEBrick::HTTPUtils.parse_query(req.body))
1456 end
1457
1458 def query_escape(query)
1459 escaped = []
2253f95 * test coverage checked. see #189.
nahi authored
1460 query.sort_by { |k, v| k }.collect do |k, v|
beaf135 * forgot to add new files in the previous commit.
nahi authored
1461 v.to_ary.each do |ve|
1462 escaped << CGI.escape(k) + '=' + CGI.escape(ve)
1463 end
1464 end
1465 escaped.join('&')
1466 end
1467 end
1468 end
Something went wrong with that request. Please try again.