bterlson-httpclient 2.1.4

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,352 @@
1
+ require 'test/unit'
2
+ require 'uri'
3
+
4
+ require 'httpclient/cookie'
5
+
6
+ class TestCookie < Test::Unit::TestCase
7
+
8
+ def setup()
9
+ @c = WebAgent::Cookie.new()
10
+ end
11
+
12
+ def test_s_new()
13
+ assert_instance_of(WebAgent::Cookie, @c)
14
+ end
15
+
16
+ def test_discard?
17
+ assert_equal(false, !!(@c.discard?))
18
+ @c.discard = true
19
+ assert_equal(true, !!(@c.discard?))
20
+ end
21
+
22
+ def test_match()
23
+ url = URI.parse('http://www.rubycolor.org/hoge/funi/#919191')
24
+
25
+ @c.domain = 'www.rubycolor.org'
26
+ assert_equal(true, @c.match?(url))
27
+
28
+ @c.domain = '.rubycolor.org'
29
+ assert_equal(true, @c.match?(url))
30
+
31
+ @c.domain = 'aaa.www.rubycolor.org'
32
+ assert_equal(false, @c.match?(url))
33
+
34
+ @c.domain = 'aaa.www.rubycolor.org'
35
+ assert_equal(false, @c.match?(url))
36
+
37
+ @c.domain = 'www.rubycolor.org'
38
+ @c.path = '/'
39
+ assert_equal(true, @c.match?(url))
40
+
41
+ @c.domain = 'www.rubycolor.org'
42
+ @c.path = '/hoge'
43
+ assert_equal(true, @c.match?(url))
44
+
45
+ @c.domain = 'www.rubycolor.org'
46
+ @c.path = '/hoge/hoge'
47
+ assert_equal(false, @c.match?(url))
48
+
49
+ @c.domain = 'www.rubycolor.org'
50
+ @c.path = '/hoge'
51
+ @c.secure = true
52
+ assert_equal(false, @c.match?(url))
53
+
54
+ url2 = URI.parse('https://www.rubycolor.org/hoge/funi/#919191')
55
+ @c.domain = 'www.rubycolor.org'
56
+ @c.path = '/hoge'
57
+ @c.secure = true
58
+ assert_equal(true, @c.match?(url2))
59
+
60
+ @c.domain = 'www.rubycolor.org'
61
+ @c.path = '/hoge'
62
+ @c.secure = nil
63
+ assert_equal(true, @c.match?(url2)) ## not false!
64
+
65
+ url.port = 80
66
+ @c.domain = 'www.rubycolor.org'
67
+ @c.path = '/hoge'
68
+ # @c.port = [80,8080]
69
+ assert_equal(true, @c.match?(url))
70
+
71
+ end
72
+
73
+ def test_head_match?()
74
+ assert_equal(true, @c.head_match?("",""))
75
+ assert_equal(false, @c.head_match?("a",""))
76
+ assert_equal(true, @c.head_match?("","a"))
77
+ assert_equal(true, @c.head_match?("abcde","abcde"))
78
+ assert_equal(true, @c.head_match?("abcde","abcdef"))
79
+ assert_equal(false, @c.head_match?("abcdef","abcde"))
80
+ assert_equal(false, @c.head_match?("abcde","bcde"))
81
+ assert_equal(false, @c.head_match?("bcde","abcde"))
82
+ end
83
+
84
+ def test_tail_match?()
85
+ assert_equal(true, @c.tail_match?("",""))
86
+ assert_equal(false, @c.tail_match?("a",""))
87
+ assert_equal(true, @c.tail_match?("","a"))
88
+ assert_equal(true, @c.tail_match?("abcde","abcde"))
89
+ assert_equal(false, @c.tail_match?("abcde","abcdef"))
90
+ assert_equal(false, @c.tail_match?("abcdef","abcde"))
91
+ assert_equal(false, @c.tail_match?("abcde","bcde"))
92
+ assert_equal(true, @c.tail_match?("bcde","abcde"))
93
+ end
94
+
95
+
96
+ def test_domain_match()
97
+ extend WebAgent::CookieUtils
98
+ assert_equal(true, !!domain_match("hoge.co.jp","."))
99
+ # assert_equal(true, !!domain_match("locahost",".local"))
100
+ assert_equal(true, !!domain_match("192.168.10.1","192.168.10.1"))
101
+ assert_equal(false, !!domain_match("192.168.10.1","192.168.10.2"))
102
+ # assert_equal(false, !!domain_match("hoge.co.jp",".hoge.co.jp"))
103
+ # allows; host == rubyforge.org, domain == .rubyforge.org
104
+ assert_equal(true, !!domain_match("hoge.co.jp",".hoge.co.jp"))
105
+ assert_equal(true, !!domain_match("www.hoge.co.jp", "www.hoge.co.jp"))
106
+ assert_equal(false, !!domain_match("www.hoge.co.jp", "www2.hoge.co.jp"))
107
+ assert_equal(true, !!domain_match("www.hoge.co.jp", ".hoge.co.jp"))
108
+ assert_equal(true, !!domain_match("www.aa.hoge.co.jp", ".hoge.co.jp"))
109
+ assert_equal(false, !!domain_match("www.hoge.co.jp", "hoge.co.jp"))
110
+ end
111
+
112
+ def test_join_quotedstr()
113
+ arr1 = ['hoge=funi', 'hoge2=funi2']
114
+ assert_equal(arr1, @c.instance_eval{join_quotedstr(arr1,';')})
115
+ arr2 = ['hoge="fu', 'ni"', 'funi=funi']
116
+ assert_equal(['hoge="fu;ni"','funi=funi'],
117
+ @c.instance_eval{join_quotedstr(arr2,';')})
118
+ arr3 = ['hoge="funi";hoge2="fu','ni2";hoge3="hoge"', 'funi="funi"']
119
+ assert_equal(['hoge="funi";hoge2="fu,ni2";hoge3="hoge"', 'funi="funi"'],
120
+ @c.instance_eval{join_quotedstr(arr3,',')})
121
+ end
122
+
123
+ end
124
+
125
+ class TestCookieManager < Test::Unit::TestCase
126
+
127
+ def setup()
128
+ @cm = WebAgent::CookieManager.new()
129
+ end
130
+
131
+ def teardown()
132
+ end
133
+
134
+ def test_total_dot_num()
135
+ assert_equal(0, @cm.total_dot_num(""))
136
+ assert_equal(0, @cm.total_dot_num("abcde"))
137
+ assert_equal(1, @cm.total_dot_num("ab.cde"))
138
+ assert_equal(1, @cm.total_dot_num(".abcde"))
139
+ assert_equal(1, @cm.total_dot_num("abcde."))
140
+ assert_equal(2, @cm.total_dot_num("abc.de."))
141
+ assert_equal(2, @cm.total_dot_num("a.bc.de"))
142
+ assert_equal(2, @cm.total_dot_num(".abcde."))
143
+ assert_equal(3, @cm.total_dot_num(".a.bcde."))
144
+ assert_equal(3, @cm.total_dot_num("a.b.cde."))
145
+ assert_equal(3, @cm.total_dot_num("a.b.c.de"))
146
+ end
147
+
148
+ def test_parse()
149
+ str = "inkid=n92b0ADOgACIgUb9lsjHqAAAHu2a; expires=Wed, 01-Dec-2010 00:00:00 GMT; path=/"
150
+ @cm.parse(str,URI.parse('http://www.test.jp'))
151
+ cookie = @cm.cookies[0]
152
+ assert_instance_of(WebAgent::Cookie, cookie)
153
+ assert_equal("inkid", cookie.name)
154
+ assert_equal("n92b0ADOgACIgUb9lsjHqAAAHu2a", cookie.value)
155
+ assert_equal(Time.gm(2010, 12, 1, 0,0,0), cookie.expires)
156
+ assert_equal("/", cookie.path)
157
+ end
158
+
159
+ def test_parse2()
160
+ str = "xmen=off,0,0,1; path=/; domain=.excite.co.jp; expires=Wednesday, 31-Dec-2009 12:00:00 GMT"
161
+ @cm.parse(str,URI.parse('http://www.excite.co.jp'))
162
+ cookie = @cm.cookies[0]
163
+ assert_instance_of(WebAgent::Cookie, cookie)
164
+ assert_equal("xmen", cookie.name)
165
+ assert_equal("off,0,0,1", cookie.value)
166
+ assert_equal("/", cookie.path)
167
+ assert_equal(".excite.co.jp", cookie.domain)
168
+ assert_equal(Time.gm(2009,12,31,12,0,0), cookie.expires)
169
+ end
170
+
171
+ # def test_make_portlist()
172
+ # assert_equal([80,8080], @cm.instance_eval{make_portlist("80,8080")})
173
+ # assert_equal([80], @cm.instance_eval{make_portlist("80")})
174
+ # assert_equal([80,8080,10080], @cm.instance_eval{make_portlist(" 80, 8080, 10080 \n")})
175
+ # end
176
+
177
+ def test_check_expired_cookies()
178
+ c1 = WebAgent::Cookie.new()
179
+ c2 = c1.dup
180
+ c3 = c1.dup
181
+ c4 = c1.dup
182
+ c1.expires = Time.now - 100
183
+ c2.expires = Time.now + 100
184
+ c3.expires = Time.now - 10
185
+ c4.expires = nil
186
+ cookies = [c1,c2,c3,c4]
187
+ @cm.cookies = cookies
188
+ @cm.check_expired_cookies()
189
+ # expires == nil cookies (session cookie) exists.
190
+ assert_equal([c2,c4], @cm.cookies)
191
+ end
192
+
193
+ def test_parse_expires
194
+ str = "inkid=n92b0ADOgACIgUb9lsjHqAAAHu2a; expires=; path=/"
195
+ @cm.parse(str,URI.parse('http://www.test.jp'))
196
+ cookie = @cm.cookies[0]
197
+ assert_equal("inkid", cookie.name)
198
+ assert_equal("n92b0ADOgACIgUb9lsjHqAAAHu2a", cookie.value)
199
+ assert_equal(nil, cookie.expires)
200
+ assert_equal("/", cookie.path)
201
+ #
202
+ str = "inkid=n92b0ADOgACIgUb9lsjHqAAAHu2a; path=/; expires="
203
+ @cm.parse(str,URI.parse('http://www.test.jp'))
204
+ cookie = @cm.cookies[0]
205
+ assert_equal("inkid", cookie.name)
206
+ assert_equal("n92b0ADOgACIgUb9lsjHqAAAHu2a", cookie.value)
207
+ assert_equal(nil, cookie.expires)
208
+ assert_equal("/", cookie.path)
209
+ #
210
+ str = "inkid=n92b0ADOgACIgUb9lsjHqAAAHu2a; path=/; expires=\"\""
211
+ @cm.parse(str,URI.parse('http://www.test.jp'))
212
+ cookie = @cm.cookies[0]
213
+ assert_equal("inkid", cookie.name)
214
+ assert_equal("n92b0ADOgACIgUb9lsjHqAAAHu2a", cookie.value)
215
+ assert_equal(nil, cookie.expires)
216
+ assert_equal("/", cookie.path)
217
+ end
218
+
219
+ def test_find_cookie()
220
+ str = "xmen=off,0,0,1; path=/; domain=.excite2.co.jp; expires=Wednesday, 31-Dec-2009 12:00:00 GMT"
221
+ @cm.parse(str, URI.parse("http://www.excite2.co.jp/"))
222
+
223
+ str = "xmen=off,0,0,2; path=/; domain=.excite.co.jp; expires=Wednesday, 31-Dec-2009 12:00:00 GMT"
224
+ @cm.parse(str, URI.parse("http://www.excite.co.jp/"))
225
+
226
+ @cm.cookies[0].use = true
227
+ @cm.cookies[1].use = true
228
+
229
+ url = URI.parse('http://www.excite.co.jp/hoge/funi/')
230
+ cookie_str = @cm.find(url)
231
+ assert_equal("xmen=off,0,0,2", cookie_str)
232
+ end
233
+
234
+ def test_load_cookies()
235
+ begin
236
+ File.open("tmp_test.tmp","w") {|f|
237
+ f.write <<EOF
238
+ http://www.zdnet.co.jp/news/0106/08/e_gibson.html NGUserID d29b8f49-10875-992421294-1 2145801600 www.zdnet.co.jp / 9 0
239
+ http://www.zdnet.co.jp/news/0106/08/e_gibson.html PACK zd3-992421294-7436 1293839999 .zdnet.co.jp / 13 0
240
+ http://example.org/ key value 0 .example.org / 13 0
241
+ http://example.org/ key value .example.org / 13 0
242
+ EOF
243
+ }
244
+
245
+ @cm.cookies_file = 'tmp_test.tmp'
246
+ @cm.load_cookies()
247
+ c0, c1, c2, c3 = @cm.cookies
248
+ assert_equal('http://www.zdnet.co.jp/news/0106/08/e_gibson.html', c0.url.to_s)
249
+ assert_equal('NGUserID', c0.name)
250
+ assert_equal('d29b8f49-10875-992421294-1', c0.value)
251
+ assert_equal(Time.at(2145801600), c0.expires)
252
+ assert_equal('www.zdnet.co.jp', c0.domain)
253
+ assert_equal('/', c0.path)
254
+ assert_equal(9, c0.flag)
255
+ #
256
+ assert_equal('http://www.zdnet.co.jp/news/0106/08/e_gibson.html', c1.url.to_s)
257
+ assert_equal('PACK', c1.name)
258
+ assert_equal('zd3-992421294-7436', c1.value)
259
+ assert_equal(Time.at(1293839999), c1.expires)
260
+ assert_equal('.zdnet.co.jp', c1.domain)
261
+ assert_equal('/', c1.path)
262
+ assert_equal(13, c1.flag)
263
+ #
264
+ assert_equal(nil, c2.expires)
265
+ assert_equal(nil, c3.expires) # allow empty 'expires' (should not happen)
266
+ ensure
267
+ File.unlink("tmp_test.tmp")
268
+ end
269
+ end
270
+
271
+ def test_save_cookie()
272
+ str = <<EOF
273
+ http://www.zdnet.co.jp/news/0106/08/e_gibson.html NGUserID d29b8f49-10875-992421294-1 2145801600 www.zdnet.co.jp / 9
274
+ http://www.zdnet.co.jp/news/0106/08/e_gibson.html PACK zd3-992421294-7436 1293839999 .zdnet.co.jp / 13
275
+ EOF
276
+ begin
277
+ File.open("tmp_test.tmp","w") {|f|
278
+ f.write str
279
+ }
280
+ @cm.cookies_file = 'tmp_test.tmp'
281
+ @cm.load_cookies()
282
+ @cm.instance_eval{@is_saved = false}
283
+ @cm.cookies_file = 'tmp_test2.tmp'
284
+ @cm.save_cookies()
285
+ str2 = ''
286
+ File.open("tmp_test2.tmp","r") {|f|
287
+ str2 = f.read()
288
+ }
289
+ assert_equal(str, str2)
290
+ #
291
+ assert(File.exist?('tmp_test2.tmp'))
292
+ File.unlink("tmp_test2.tmp")
293
+ @cm.save_cookies()
294
+ assert(!File.exist?('tmp_test2.tmp'))
295
+ @cm.save_cookies(true)
296
+ assert(File.exist?('tmp_test2.tmp'))
297
+ ensure
298
+ File.unlink("tmp_test.tmp")
299
+ if FileTest.exist?("tmp_test2.tmp")
300
+ File.unlink("tmp_test2.tmp")
301
+ end
302
+ end
303
+ end
304
+
305
+ def test_not_saved_expired_cookies
306
+ begin
307
+ @cm.cookies_file = 'tmp_test.tmp'
308
+ uri = URI.parse('http://www.example.org')
309
+ @cm.parse("foo=1; path=/", uri)
310
+ @cm.parse("bar=2; path=/; expires=", uri)
311
+ @cm.parse("baz=3; path=/; expires=\"\"", uri)
312
+ @cm.parse("qux=4; path=/; expires=#{(Time.now + 10).asctime}", uri)
313
+ @cm.parse("quxx=5; path=/; expires=#{(Time.now - 10).asctime}", uri)
314
+ @cm.save_cookies()
315
+ @cm.load_cookies
316
+ assert_equal(1, @cm.cookies.size) # +10 cookies only
317
+ ensure
318
+ File.unlink("tmp_test.tmp") if File.exist?("tmp_test.tmp")
319
+ end
320
+ end
321
+
322
+ def test_add()
323
+ c = WebAgent::Cookie.new()
324
+ c.name = "hoge"
325
+ c.value = "funi"
326
+ c.url = URI.parse("http://www.inac.co.jp/hoge")
327
+ @cm.add(c)
328
+ c = @cm.cookies[0]
329
+ assert_equal('hoge', c.name)
330
+ assert_equal('funi', c.value)
331
+ assert_equal(nil, c.expires)
332
+ end
333
+
334
+ def test_check_cookie_accept_domain()
335
+ @cm.accept_domains = [".example1.co.jp", "www1.example.jp"]
336
+ @cm.reject_domains = [".example2.co.jp", "www2.example.jp"]
337
+ check1 = @cm.check_cookie_accept_domain("www.example1.co.jp")
338
+ assert_equal(true, check1)
339
+ check2 = @cm.check_cookie_accept_domain("www.example2.co.jp")
340
+ assert_equal(false, check2)
341
+ check3 = @cm.check_cookie_accept_domain("www1.example.jp")
342
+ assert_equal(true, check3)
343
+ check4 = @cm.check_cookie_accept_domain("www2.example.jp")
344
+ assert_equal(false, check4)
345
+ check5 = @cm.check_cookie_accept_domain("aa.www2.example.jp")
346
+ assert_equal(true, check5)
347
+ check6 = @cm.check_cookie_accept_domain("aa.www2.example.jp")
348
+ assert_equal(true, check6)
349
+ assert_equal(false, @cm.check_cookie_accept_domain(nil))
350
+ end
351
+
352
+ end
@@ -0,0 +1,560 @@
1
+ require 'test/unit'
2
+ require 'http-access2'
3
+ require 'webrick'
4
+ require 'webrick/httpproxy.rb'
5
+ require 'logger'
6
+ require 'stringio'
7
+ require 'cgi'
8
+ require 'webrick/httputils'
9
+
10
+
11
+ module HTTPAccess2
12
+
13
+
14
+ class TestClient < Test::Unit::TestCase
15
+ Port = 17171
16
+ ProxyPort = 17172
17
+
18
+ def setup
19
+ @logger = Logger.new(STDERR)
20
+ @logger.level = Logger::Severity::FATAL
21
+ @proxyio = StringIO.new
22
+ @proxylogger = Logger.new(@proxyio)
23
+ @proxylogger.level = Logger::Severity::DEBUG
24
+ @url = "http://localhost:#{Port}/"
25
+ @proxyurl = "http://localhost:#{ProxyPort}/"
26
+ @server = @proxyserver = @client = nil
27
+ @server_thread = @proxyserver_thread = nil
28
+ setup_server
29
+ setup_client
30
+ end
31
+
32
+ def teardown
33
+ teardown_client
34
+ teardown_proxyserver if @proxyserver
35
+ teardown_server
36
+ end
37
+
38
+ def test_initialize
39
+ setup_proxyserver
40
+ escape_noproxy do
41
+ @proxyio.string = ""
42
+ @client = HTTPAccess2::Client.new(@proxyurl)
43
+ assert_equal(URI.parse(@proxyurl), @client.proxy)
44
+ assert_equal(200, @client.head(@url).status)
45
+ assert(!@proxyio.string.empty?)
46
+ end
47
+ end
48
+
49
+ def test_agent_name
50
+ @client = HTTPAccess2::Client.new(nil, "agent_name_foo")
51
+ str = ""
52
+ @client.debug_dev = str
53
+ @client.get(@url)
54
+ lines = str.split(/(?:\r?\n)+/)
55
+ assert_equal("= Request", lines[0])
56
+ assert_match(/^User-Agent: agent_name_foo/, lines[4])
57
+ end
58
+
59
+ def test_from
60
+ @client = HTTPAccess2::Client.new(nil, nil, "from_bar")
61
+ str = ""
62
+ @client.debug_dev = str
63
+ @client.get(@url)
64
+ lines = str.split(/(?:\r?\n)+/)
65
+ assert_equal("= Request", lines[0])
66
+ assert_match(/^From: from_bar/, lines[4])
67
+ end
68
+
69
+ def test_debug_dev
70
+ str = ""
71
+ @client.debug_dev = str
72
+ assert(str.empty?)
73
+ @client.get(@url)
74
+ assert(!str.empty?)
75
+ end
76
+
77
+ def _test_protocol_version_http09
78
+ @client.protocol_version = 'HTTP/0.9'
79
+ str = ""
80
+ @client.debug_dev = str
81
+ @client.get(@url + 'hello')
82
+ lines = str.split(/(?:\r?\n)+/)
83
+ assert_equal("= Request", lines[0])
84
+ assert_equal("! CONNECTION ESTABLISHED", lines[2])
85
+ assert_equal("GET /hello HTTP/0.9", lines[3])
86
+ assert_equal("Connection: close", lines[5])
87
+ assert_equal("= Response", lines[6])
88
+ assert_match(/^hello/, lines[7])
89
+ end
90
+
91
+ def test_protocol_version_http10
92
+ @client.protocol_version = 'HTTP/1.0'
93
+ str = ""
94
+ @client.debug_dev = str
95
+ @client.get(@url + 'hello')
96
+ lines = str.split(/(?:\r?\n)+/)
97
+ assert_equal("= Request", lines[0])
98
+ assert_equal("! CONNECTION ESTABLISHED", lines[2])
99
+ assert_equal("GET /hello HTTP/1.0", lines[3])
100
+ assert_equal("Connection: close", lines[5])
101
+ assert_equal("= Response", lines[6])
102
+ end
103
+
104
+ def test_protocol_version_http11
105
+ str = ""
106
+ @client.debug_dev = str
107
+ @client.get(@url)
108
+ lines = str.split(/(?:\r?\n)+/)
109
+ assert_equal("= Request", lines[0])
110
+ assert_equal("! CONNECTION ESTABLISHED", lines[2])
111
+ assert_equal("GET / HTTP/1.1", lines[3])
112
+ assert_equal("Host: localhost:#{Port}", lines[6])
113
+ @client.protocol_version = 'HTTP/1.1'
114
+ str = ""
115
+ @client.debug_dev = str
116
+ @client.get(@url)
117
+ lines = str.split(/(?:\r?\n)+/)
118
+ assert_equal("= Request", lines[0])
119
+ assert_equal("! CONNECTION ESTABLISHED", lines[2])
120
+ assert_equal("GET / HTTP/1.1", lines[3])
121
+ @client.protocol_version = 'HTTP/1.0'
122
+ str = ""
123
+ @client.debug_dev = str
124
+ @client.get(@url)
125
+ lines = str.split(/(?:\r?\n)+/)
126
+ assert_equal("= Request", lines[0])
127
+ assert_equal("! CONNECTION ESTABLISHED", lines[2])
128
+ assert_equal("GET / HTTP/1.0", lines[3])
129
+ end
130
+
131
+ def test_proxy
132
+ setup_proxyserver
133
+ escape_noproxy do
134
+ assert_raises(URI::InvalidURIError) do
135
+ @client.proxy = "http://"
136
+ end
137
+ assert_raises(ArgumentError) do
138
+ @client.proxy = ""
139
+ end
140
+ @client.proxy = "http://foo:1234"
141
+ assert_equal(URI.parse("http://foo:1234"), @client.proxy)
142
+ uri = URI.parse("http://bar:2345")
143
+ @client.proxy = uri
144
+ assert_equal(uri, @client.proxy)
145
+ #
146
+ @proxyio.string = ""
147
+ @client.proxy = nil
148
+ assert_equal(200, @client.head(@url).status)
149
+ assert(@proxyio.string.empty?)
150
+ #
151
+ @proxyio.string = ""
152
+ @client.proxy = @proxyurl
153
+ assert_equal(200, @client.head(@url).status)
154
+ assert(!@proxyio.string.empty?)
155
+ end
156
+ end
157
+
158
+ def test_noproxy_for_localhost
159
+ @proxyio.string = ""
160
+ @client.proxy = @proxyurl
161
+ assert_equal(200, @client.head(@url).status)
162
+ assert(@proxyio.string.empty?)
163
+ end
164
+
165
+ def test_no_proxy
166
+ setup_proxyserver
167
+ escape_noproxy do
168
+ # proxy is not set.
169
+ @client.no_proxy = 'localhost'
170
+ @proxyio.string = ""
171
+ @client.proxy = nil
172
+ assert_equal(200, @client.head(@url).status)
173
+ assert(@proxyio.string.empty?)
174
+ #
175
+ @proxyio.string = ""
176
+ @client.proxy = @proxyurl
177
+ assert_equal(200, @client.head(@url).status)
178
+ assert(@proxyio.string.empty?)
179
+ #
180
+ @client.no_proxy = 'foobar'
181
+ @proxyio.string = ""
182
+ @client.proxy = @proxyurl
183
+ assert_equal(200, @client.head(@url).status)
184
+ assert(!@proxyio.string.empty?)
185
+ #
186
+ @client.no_proxy = 'foobar,localhost:baz'
187
+ @proxyio.string = ""
188
+ @client.proxy = @proxyurl
189
+ assert_equal(200, @client.head(@url).status)
190
+ assert(@proxyio.string.empty?)
191
+ #
192
+ @client.no_proxy = 'foobar,localhost:443'
193
+ @proxyio.string = ""
194
+ @client.proxy = @proxyurl
195
+ assert_equal(200, @client.head(@url).status)
196
+ assert(!@proxyio.string.empty?)
197
+ #
198
+ @client.no_proxy = 'foobar,localhost:443:localhost:17171,baz'
199
+ @proxyio.string = ""
200
+ @client.proxy = @proxyurl
201
+ assert_equal(200, @client.head(@url).status)
202
+ assert(@proxyio.string.empty?)
203
+ end
204
+ end
205
+
206
+ def test_get_content
207
+ assert_equal('hello', @client.get_content(@url + 'hello'))
208
+ assert_equal('hello', @client.get_content(@url + 'redirect1'))
209
+ assert_equal('hello', @client.get_content(@url + 'redirect2'))
210
+ assert_raises(HTTPClient::Session::BadResponse) do
211
+ @client.get_content(@url + 'notfound')
212
+ end
213
+ assert_raises(HTTPClient::Session::BadResponse) do
214
+ @client.get_content(@url + 'redirect_self')
215
+ end
216
+ called = false
217
+ @client.redirect_uri_callback = lambda { |uri, res|
218
+ newuri = res.header['location'][0]
219
+ called = true
220
+ newuri
221
+ }
222
+ assert_equal('hello', @client.get_content(@url + 'relative_redirect'))
223
+ assert(called)
224
+ end
225
+
226
+ def test_post_content
227
+ assert_equal('hello', @client.post_content(@url + 'hello'))
228
+ assert_equal('hello', @client.post_content(@url + 'redirect1'))
229
+ assert_equal('hello', @client.post_content(@url + 'redirect2'))
230
+ assert_raises(HTTPClient::Session::BadResponse) do
231
+ @client.post_content(@url + 'notfound')
232
+ end
233
+ assert_raises(HTTPClient::Session::BadResponse) do
234
+ @client.post_content(@url + 'redirect_self')
235
+ end
236
+ called = false
237
+ @client.redirect_uri_callback = lambda { |uri, res|
238
+ newuri = res.header['location'][0]
239
+ called = true
240
+ newuri
241
+ }
242
+ assert_equal('hello', @client.post_content(@url + 'relative_redirect'))
243
+ assert(called)
244
+ end
245
+
246
+ def test_head
247
+ assert_equal("head", @client.head(@url + 'servlet').header["x-head"][0])
248
+ res = @client.head(@url + 'servlet', {1=>2, 3=>4})
249
+ assert_equal('1=2&3=4', res.header["x-query"][0])
250
+ end
251
+
252
+ def test_get
253
+ assert_equal("get", @client.get(@url + 'servlet').content)
254
+ res = @client.get(@url + 'servlet', {1=>2, 3=>4})
255
+ assert_equal('1=2&3=4', res.header["x-query"][0])
256
+ end
257
+
258
+ def test_post
259
+ assert_equal("post", @client.post(@url + 'servlet').content)
260
+ res = @client.get(@url + 'servlet', {1=>2, 3=>4})
261
+ assert_equal('1=2&3=4', res.header["x-query"][0])
262
+ end
263
+
264
+ def test_put
265
+ assert_equal("put", @client.put(@url + 'servlet').content)
266
+ res = @client.get(@url + 'servlet', {1=>2, 3=>4})
267
+ assert_equal('1=2&3=4', res.header["x-query"][0])
268
+ end
269
+
270
+ def test_delete
271
+ assert_equal("delete", @client.delete(@url + 'servlet').content)
272
+ res = @client.get(@url + 'servlet', {1=>2, 3=>4})
273
+ assert_equal('1=2&3=4', res.header["x-query"][0])
274
+ end
275
+
276
+ def test_options
277
+ assert_equal("options", @client.options(@url + 'servlet').content)
278
+ res = @client.get(@url + 'servlet', {1=>2, 3=>4})
279
+ assert_equal('1=2&3=4', res.header["x-query"][0])
280
+ end
281
+
282
+ def test_trace
283
+ assert_equal("trace", @client.trace(@url + 'servlet').content)
284
+ res = @client.get(@url + 'servlet', {1=>2, 3=>4})
285
+ assert_equal('1=2&3=4', res.header["x-query"][0])
286
+ end
287
+
288
+ def test_get_query
289
+ assert_equal({'1'=>'2'}, check_query_get({1=>2}))
290
+ assert_equal({'a'=>'A', 'B'=>'b'}, check_query_get({"a"=>"A", "B"=>"b"}))
291
+ assert_equal({'&'=>'&'}, check_query_get({"&"=>"&"}))
292
+ assert_equal({'= '=>' =+'}, check_query_get({"= "=>" =+"}))
293
+ assert_equal(
294
+ ['=', '&'].sort,
295
+ check_query_get([["=", "="], ["=", "&"]])['='].to_ary.sort
296
+ )
297
+ assert_equal({'123'=>'45'}, check_query_get('123=45'))
298
+ assert_equal({'12 3'=>'45', ' '=>' '}, check_query_get('12+3=45&+=+'))
299
+ assert_equal({}, check_query_get(''))
300
+ end
301
+
302
+ def test_post_body
303
+ assert_equal({'1'=>'2'}, check_query_post({1=>2}))
304
+ assert_equal({'a'=>'A', 'B'=>'b'}, check_query_post({"a"=>"A", "B"=>"b"}))
305
+ assert_equal({'&'=>'&'}, check_query_post({"&"=>"&"}))
306
+ assert_equal({'= '=>' =+'}, check_query_post({"= "=>" =+"}))
307
+ assert_equal(
308
+ ['=', '&'].sort,
309
+ check_query_post([["=", "="], ["=", "&"]])['='].to_ary.sort
310
+ )
311
+ assert_equal({'123'=>'45'}, check_query_post('123=45'))
312
+ assert_equal({'12 3'=>'45', ' '=>' '}, check_query_post('12+3=45&+=+'))
313
+ assert_equal({}, check_query_post(''))
314
+ #
315
+ post_body = StringIO.new("foo=bar&foo=baz")
316
+ assert_equal(
317
+ ["bar", "baz"],
318
+ check_query_post(post_body)["foo"].to_ary.sort
319
+ )
320
+ end
321
+
322
+ def test_extra_headers
323
+ str = ""
324
+ @client.debug_dev = str
325
+ @client.head(@url, nil, {"ABC" => "DEF"})
326
+ lines = str.split(/(?:\r?\n)+/)
327
+ assert_equal("= Request", lines[0])
328
+ assert_match("ABC: DEF", lines[4])
329
+ #
330
+ str = ""
331
+ @client.debug_dev = str
332
+ @client.get(@url, nil, [["ABC", "DEF"], ["ABC", "DEF"]])
333
+ lines = str.split(/(?:\r?\n)+/)
334
+ assert_equal("= Request", lines[0])
335
+ assert_match("ABC: DEF", lines[4])
336
+ assert_match("ABC: DEF", lines[5])
337
+ end
338
+
339
+ def test_timeout
340
+ assert_equal(60, @client.connect_timeout)
341
+ assert_equal(120, @client.send_timeout)
342
+ assert_equal(60, @client.receive_timeout)
343
+ end
344
+
345
+ def test_connect_timeout
346
+ # ToDo
347
+ end
348
+
349
+ def test_send_timeout
350
+ # ToDo
351
+ end
352
+
353
+ def test_receive_timeout
354
+ # this test takes 2 sec
355
+ assert_equal('hello', @client.get_content(@url + 'sleep?sec=2'))
356
+ @client.receive_timeout = 1
357
+ assert_equal('hello', @client.get_content(@url + 'sleep?sec=0'))
358
+ assert_raise(HTTPClient::ReceiveTimeoutError) do
359
+ @client.get_content(@url + 'sleep?sec=2')
360
+ end
361
+ @client.receive_timeout = 3
362
+ assert_equal('hello', @client.get_content(@url + 'sleep?sec=2'))
363
+ end
364
+
365
+ def test_cookies
366
+ cookiefile = File.join(File.dirname(File.expand_path(__FILE__)),
367
+ 'test_cookies_file')
368
+ # from [ruby-talk:164079]
369
+ File.open(cookiefile, "wb") do |f|
370
+ f << "http://rubyforge.org//account/login.php session_ser LjEwMy45Ni40Ni0q%2A-fa0537de8cc31 1131676286 .rubyforge.org / 13\n"
371
+ end
372
+ cm = WebAgent::CookieManager::new(cookiefile)
373
+ cm.load_cookies
374
+ cookie = cm.cookies.first
375
+ url = cookie.url
376
+ assert(cookie.domain_match(url.host, cookie.domain))
377
+ end
378
+
379
+ private
380
+
381
+ def check_query_get(query)
382
+ WEBrick::HTTPUtils.parse_query(
383
+ @client.get(@url + 'servlet', query).header["x-query"][0]
384
+ )
385
+ end
386
+
387
+ def check_query_post(query)
388
+ WEBrick::HTTPUtils.parse_query(
389
+ @client.post(@url + 'servlet', query).header["x-query"][0]
390
+ )
391
+ end
392
+
393
+ def setup_server
394
+ @server = WEBrick::HTTPServer.new(
395
+ :BindAddress => "localhost",
396
+ :Logger => @logger,
397
+ :Port => Port,
398
+ :AccessLog => [],
399
+ :DocumentRoot => File.dirname(File.expand_path(__FILE__))
400
+ )
401
+ [:hello, :sleep, :redirect1, :redirect2, :redirect3, :redirect_self, :relative_redirect].each do |sym|
402
+ @server.mount(
403
+ "/#{sym}",
404
+ WEBrick::HTTPServlet::ProcHandler.new(method("do_#{sym}").to_proc)
405
+ )
406
+ end
407
+ @server.mount('/servlet', TestServlet.new(@server))
408
+ @server_thread = start_server_thread(@server)
409
+ end
410
+
411
+ def setup_proxyserver
412
+ @proxyserver = WEBrick::HTTPProxyServer.new(
413
+ :BindAddress => "localhost",
414
+ :Logger => @proxylogger,
415
+ :Port => ProxyPort,
416
+ :AccessLog => []
417
+ )
418
+ @proxyserver_thread = start_server_thread(@proxyserver)
419
+ end
420
+
421
+ def setup_client
422
+ @client = HTTPAccess2::Client.new
423
+ @client.debug_dev = STDOUT if $DEBUG
424
+ end
425
+
426
+ def teardown_server
427
+ @server.shutdown
428
+ @server_thread.kill
429
+ @server_thread.join
430
+ end
431
+
432
+ def teardown_proxyserver
433
+ @proxyserver.shutdown
434
+ @proxyserver_thread.kill
435
+ @proxyserver_thread.join
436
+ end
437
+
438
+ def teardown_client
439
+ @client.reset_all
440
+ end
441
+
442
+ def start_server_thread(server)
443
+ t = Thread.new {
444
+ Thread.current.abort_on_exception = true
445
+ server.start
446
+ }
447
+ while server.status != :Running
448
+ sleep 0.1
449
+ unless t.alive?
450
+ t.join
451
+ raise
452
+ end
453
+ end
454
+ t
455
+ end
456
+
457
+ def escape_noproxy
458
+ backup = HTTPAccess2::Client::NO_PROXY_HOSTS.dup
459
+ HTTPAccess2::Client::NO_PROXY_HOSTS.clear
460
+ yield
461
+ ensure
462
+ HTTPAccess2::Client::NO_PROXY_HOSTS.replace(backup)
463
+ end
464
+
465
+ def do_hello(req, res)
466
+ res['content-type'] = 'text/html'
467
+ res.body = "hello"
468
+ end
469
+
470
+ def do_sleep(req, res)
471
+ sec = req.query['sec'].to_i
472
+ sleep sec
473
+ res['content-type'] = 'text/html'
474
+ res.body = "hello"
475
+ end
476
+
477
+ def do_redirect1(req, res)
478
+ res.set_redirect(WEBrick::HTTPStatus::MovedPermanently, @url + "hello")
479
+ end
480
+
481
+ def do_redirect2(req, res)
482
+ res.set_redirect(WEBrick::HTTPStatus::TemporaryRedirect, @url + "redirect3")
483
+ end
484
+
485
+ def do_redirect3(req, res)
486
+ res.set_redirect(WEBrick::HTTPStatus::Found, @url + "hello")
487
+ end
488
+
489
+ def do_redirect_self(req, res)
490
+ res.set_redirect(WEBrick::HTTPStatus::Found, @url + "redirect_self")
491
+ end
492
+
493
+ def do_relative_redirect(req, res)
494
+ res.set_redirect(WEBrick::HTTPStatus::Found, "hello")
495
+ end
496
+
497
+ class TestServlet < WEBrick::HTTPServlet::AbstractServlet
498
+ def get_instance(*arg)
499
+ self
500
+ end
501
+
502
+ def do_HEAD(req, res)
503
+ res["x-head"] = 'head' # use this for test purpose only.
504
+ res["x-query"] = query_response(req)
505
+ end
506
+
507
+ def do_GET(req, res)
508
+ res.body = 'get'
509
+ res["x-query"] = query_response(req)
510
+ end
511
+
512
+ def do_POST(req, res)
513
+ res.body = 'post'
514
+ res["x-query"] = body_response(req)
515
+ end
516
+
517
+ def do_PUT(req, res)
518
+ res.body = 'put'
519
+ end
520
+
521
+ def do_DELETE(req, res)
522
+ res.body = 'delete'
523
+ end
524
+
525
+ def do_OPTIONS(req, res)
526
+ # check RFC for legal response.
527
+ res.body = 'options'
528
+ end
529
+
530
+ def do_TRACE(req, res)
531
+ # client SHOULD reflect the message received back to the client as the
532
+ # entity-body of a 200 (OK) response. [RFC2616]
533
+ res.body = 'trace'
534
+ res["x-query"] = query_response(req)
535
+ end
536
+
537
+ private
538
+
539
+ def query_response(req)
540
+ query_escape(WEBrick::HTTPUtils.parse_query(req.query_string))
541
+ end
542
+
543
+ def body_response(req)
544
+ query_escape(WEBrick::HTTPUtils.parse_query(req.body))
545
+ end
546
+
547
+ def query_escape(query)
548
+ escaped = []
549
+ query.collect do |k, v|
550
+ v.to_ary.each do |ve|
551
+ escaped << CGI.escape(k) + '=' + CGI.escape(ve)
552
+ end
553
+ end
554
+ escaped.join('&')
555
+ end
556
+ end
557
+ end
558
+
559
+
560
+ end