/
test_httpclient.rb
1530 lines (1399 loc) · 46.8 KB
/
test_httpclient.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
require 'test/unit'
require 'httpclient'
require 'webrick'
require 'webrick/httpproxy.rb'
require 'logger'
require 'stringio'
require 'cgi'
require 'webrick/httputils'
class TestHTTPClient < Test::Unit::TestCase
Port = 17171
ProxyPort = 17172
def setup
@logger = Logger.new(STDERR)
@logger.level = Logger::Severity::FATAL
@proxyio = StringIO.new
@proxylogger = Logger.new(@proxyio)
@proxylogger.level = Logger::Severity::DEBUG
@url = "http://localhost:#{Port}/"
@proxyurl = "http://localhost:#{ProxyPort}/"
@server = @proxyserver = @client = nil
@server_thread = @proxyserver_thread = nil
setup_server
setup_client
end
def teardown
teardown_client
teardown_proxyserver if @proxyserver
teardown_server
end
def test_initialize
setup_proxyserver
escape_noproxy do
@proxyio.string = ""
@client = HTTPClient.new(@proxyurl)
assert_equal(URI.parse(@proxyurl), @client.proxy)
assert_equal(200, @client.head(@url).status)
assert(/accept/ =~ @proxyio.string)
end
end
def test_agent_name
@client = HTTPClient.new(nil, "agent_name_foo")
str = ""
@client.debug_dev = str
@client.get(@url)
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_match(/^User-Agent: agent_name_foo/, lines[4])
end
def test_from
@client = HTTPClient.new(nil, nil, "from_bar")
str = ""
@client.debug_dev = str
@client.get(@url)
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_match(/^From: from_bar/, lines[4])
end
def test_debug_dev
str = ""
@client.debug_dev = str
assert_equal(str.object_id, @client.debug_dev.object_id)
assert(str.empty?)
@client.get(@url)
assert(!str.empty?)
end
def test_debug_dev_stream
str = ""
@client.debug_dev = str
conn = @client.get_async(@url)
Thread.pass while !conn.finished?
assert(!str.empty?)
end
def test_protocol_version_http09
@client.protocol_version = 'HTTP/0.9'
@client.debug_dev = str = ''
@client.test_loopback_http_response << "hello\nworld\n"
res = @client.get(@url + 'hello')
assert_equal('0.9', res.http_version)
assert_equal(nil, res.status)
assert_equal(nil, res.reason)
assert_equal("hello\nworld\n", res.content)
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_equal("! CONNECTION ESTABLISHED", lines[2])
assert_equal("GET /hello HTTP/0.9", lines[3])
assert_equal("Connection: close", lines[5])
assert_equal("= Response", lines[6])
assert_match(/^hello$/, lines[7])
assert_match(/^world$/, lines[8])
end
def test_protocol_version_http10
assert_equal(nil, @client.protocol_version)
@client.protocol_version = 'HTTP/1.0'
assert_equal('HTTP/1.0', @client.protocol_version)
str = ""
@client.debug_dev = str
@client.get(@url + 'hello')
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_equal("! CONNECTION ESTABLISHED", lines[2])
assert_equal("GET /hello HTTP/1.0", lines[3])
assert_equal("Connection: close", lines[5])
assert_equal("= Response", lines[6])
end
def test_host_given
str = ""
@client.debug_dev = str
@client.get(@url)
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_equal("! CONNECTION ESTABLISHED", lines[2])
assert_equal("GET / HTTP/1.1", lines[3])
assert_equal("Host: localhost:#{Port}", lines[5])
#
@client.reset_all
str = ""
@client.debug_dev = str
@client.get(@url, nil, {'Host' => 'foo'})
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_equal("! CONNECTION ESTABLISHED", lines[2])
assert_equal("GET / HTTP/1.1", lines[3])
assert_equal("Host: foo", lines[4]) # use given param
end
def test_protocol_version_http11
assert_equal(nil, @client.protocol_version)
str = ""
@client.debug_dev = str
@client.get(@url)
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_equal("! CONNECTION ESTABLISHED", lines[2])
assert_equal("GET / HTTP/1.1", lines[3])
assert_equal("Host: localhost:#{Port}", lines[5])
@client.protocol_version = 'HTTP/1.1'
assert_equal('HTTP/1.1', @client.protocol_version)
str = ""
@client.debug_dev = str
@client.get(@url)
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_equal("! CONNECTION ESTABLISHED", lines[2])
assert_equal("GET / HTTP/1.1", lines[3])
@client.protocol_version = 'HTTP/1.0'
str = ""
@client.debug_dev = str
@client.get(@url)
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_equal("! CONNECTION ESTABLISHED", lines[2])
assert_equal("GET / HTTP/1.0", lines[3])
end
def test_proxy
setup_proxyserver
escape_noproxy do
assert_raises(URI::InvalidURIError) do
@client.proxy = "http://"
end
assert_raises(ArgumentError) do
@client.proxy = ""
end
@client.proxy = "http://admin:admin@foo:1234"
assert_equal(URI.parse("http://admin:admin@foo:1234"), @client.proxy)
uri = URI.parse("http://bar:2345")
@client.proxy = uri
assert_equal(uri, @client.proxy)
#
@proxyio.string = ""
@client.proxy = nil
assert_equal(200, @client.head(@url).status)
assert(/accept/ !~ @proxyio.string)
#
@proxyio.string = ""
@client.proxy = @proxyurl
@client.debug_dev = str = ""
assert_equal(200, @client.head(@url).status)
assert(/accept/ =~ @proxyio.string)
assert(/Host: localhost:17171/ =~ str)
end
end
def test_host_header
@client.proxy = @proxyurl
@client.debug_dev = str = ""
@client.test_loopback_http_response << "HTTP/1.0 200 OK\r\n\r\n"
assert_equal(200, @client.head('http://www.example.com/foo').status)
# ensure no ':80' is added. some servers dislike that.
assert(/\r\nHost: www\.example\.com\r\n/ =~ str)
#
@client.debug_dev = str = ""
@client.test_loopback_http_response << "HTTP/1.0 200 OK\r\n\r\n"
assert_equal(200, @client.head('http://www.example.com:12345/foo').status)
# ensure ':12345' exists.
assert(/\r\nHost: www\.example\.com:12345\r\n/ =~ str)
end
def test_proxy_env
setup_proxyserver
escape_env do
ENV['http_proxy'] = "http://admin:admin@foo:1234"
ENV['NO_PROXY'] = "foobar"
client = HTTPClient.new
assert_equal(URI.parse("http://admin:admin@foo:1234"), client.proxy)
assert_equal('foobar', client.no_proxy)
end
end
def test_proxy_env_cgi
setup_proxyserver
escape_env do
ENV['REQUEST_METHOD'] = 'GET' # CGI environment emulation
ENV['http_proxy'] = "http://admin:admin@foo:1234"
ENV['no_proxy'] = "foobar"
client = HTTPClient.new
assert_equal(nil, client.proxy)
ENV['CGI_HTTP_PROXY'] = "http://admin:admin@foo:1234"
client = HTTPClient.new
assert_equal(URI.parse("http://admin:admin@foo:1234"), client.proxy)
end
end
def test_noproxy_for_localhost
@proxyio.string = ""
@client.proxy = @proxyurl
assert_equal(200, @client.head(@url).status)
assert(/accept/ !~ @proxyio.string)
end
def test_no_proxy
setup_proxyserver
escape_noproxy do
# proxy is not set.
assert_equal(nil, @client.no_proxy)
@client.no_proxy = 'localhost'
assert_equal('localhost', @client.no_proxy)
@proxyio.string = ""
@client.proxy = nil
assert_equal(200, @client.head(@url).status)
assert(/accept/ !~ @proxyio.string)
#
@proxyio.string = ""
@client.proxy = @proxyurl
assert_equal(200, @client.head(@url).status)
assert(/accept/ !~ @proxyio.string)
#
@client.no_proxy = 'foobar'
@proxyio.string = ""
@client.proxy = @proxyurl
assert_equal(200, @client.head(@url).status)
assert(/accept/ =~ @proxyio.string)
#
@client.no_proxy = 'foobar,localhost:baz'
@proxyio.string = ""
@client.proxy = @proxyurl
assert_equal(200, @client.head(@url).status)
assert(/accept/ !~ @proxyio.string)
#
@client.no_proxy = 'foobar,localhost:443'
@proxyio.string = ""
@client.proxy = @proxyurl
assert_equal(200, @client.head(@url).status)
assert(/accept/ =~ @proxyio.string)
#
@client.no_proxy = 'foobar,localhost:443:localhost:17171,baz'
@proxyio.string = ""
@client.proxy = @proxyurl
assert_equal(200, @client.head(@url).status)
assert(/accept/ !~ @proxyio.string)
end
end
def test_cookie_update_while_authentication
escape_noproxy do
@client.test_loopback_http_response << <<EOS
HTTP/1.0 401\r
Date: Fri, 19 Dec 2008 11:57:29 GMT\r
Content-Type: text/plain\r
Content-Length: 0\r
WWW-Authenticate: Basic realm="hello"\r
Set-Cookie: foo=bar; path=/; domain=.example.org; expires=#{Time.mktime(2030, 12, 31).httpdate}\r
\r
EOS
@client.test_loopback_http_response << <<EOS
HTTP/1.1 200 OK\r
Content-Length: 5\r
Connection: close\r
\r
hello
EOS
@client.debug_dev = str = ''
@client.set_auth("http://www.example.org/baz/", 'admin', 'admin')
assert_equal('hello', @client.get('http://www.example.org/baz/foo').content)
assert_match(/^Cookie: foo=bar/, str)
assert_match(/^Authorization: Basic YWRtaW46YWRtaW4=/, str)
end
end
def test_proxy_ssl
escape_noproxy do
@client.proxy = 'http://admin:admin@localhost:8080/'
# disconnected at initial 'CONNECT' so there're 2 loopback responses
@client.test_loopback_http_response << <<EOS
HTTP/1.0 407 Proxy Authentication Required\r
Date: Fri, 19 Dec 2008 11:57:29 GMT\r
Content-Type: text/plain\r
Content-Length: 0\r
Proxy-Authenticate: Basic realm="hello"\r
Proxy-Connection: close\r
\r
EOS
@client.test_loopback_http_response << <<EOS
HTTP/1.0 200 Connection established\r
\r
HTTP/1.1 200 OK\r
Content-Length: 5\r
Connection: close\r
\r
hello
EOS
assert_equal('hello', @client.get('https://localhost:17171/baz').content)
end
end
def test_loopback_response
@client.test_loopback_response << 'message body 1'
@client.test_loopback_response << 'message body 2'
assert_equal('message body 1', @client.get_content('http://somewhere'))
assert_equal('message body 2', @client.get_content('http://somewhere'))
#
@client.debug_dev = str = ''
@client.test_loopback_response << 'message body 3'
assert_equal('message body 3', @client.get_content('http://somewhere'))
assert_match(/message body 3/, str)
end
def test_loopback_response_stream
@client.test_loopback_response << 'message body 1'
@client.test_loopback_response << 'message body 2'
conn = @client.get_async('http://somewhere')
Thread.pass while !conn.finished?
assert_equal('message body 1', conn.pop.content.read)
conn = @client.get_async('http://somewhere')
Thread.pass while !conn.finished?
assert_equal('message body 2', conn.pop.content.read)
end
def test_loopback_http_response
@client.test_loopback_http_response << "HTTP/1.0 200 OK\ncontent-length: 100\n\nmessage body 1"
@client.test_loopback_http_response << "HTTP/1.0 200 OK\ncontent-length: 100\n\nmessage body 2"
assert_equal('message body 1', @client.get_content('http://somewhere'))
assert_equal('message body 2', @client.get_content('http://somewhere'))
end
def test_multiline_header
@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"
res = @client.get('http://somewhere')
assert_equal('message body 1', res.content)
assert_equal(['XXX YYY'], res.header['x-foo'])
assert_equal(['XXX YYY'], res.header['x-bar'])
end
def test_broken_header
@client.test_loopback_http_response << "HTTP/1.0 200 OK\nXXXXX\ncontent-length: 100\n\nmessage body 1"
res = @client.get('http://somewhere')
assert_equal('message body 1', res.content)
end
def test_redirect_non_https
url = @url + 'redirect1'
https_url = URI.parse(url)
https_url.scheme = 'https'
#
redirect_to_http = "HTTP/1.0 302 OK\nLocation: #{url}\n\n"
redirect_to_https = "HTTP/1.0 302 OK\nLocation: #{https_url}\n\n"
#
# https -> http is denied
@client.test_loopback_http_response << redirect_to_http
assert_raises(HTTPClient::BadResponseError) do
@client.get_content(https_url)
end
#
# http -> http is OK
@client.reset_all
@client.test_loopback_http_response << redirect_to_http
assert_equal('hello', @client.get_content(url))
#
# http -> https is OK
@client.reset_all
@client.test_loopback_http_response << redirect_to_https
assert_raises(OpenSSL::SSL::SSLError) do
# trying to normal endpoint with SSL -> SSL negotiation failure
@client.get_content(url)
end
#
# https -> https is OK
@client.reset_all
@client.test_loopback_http_response << redirect_to_https
assert_raises(OpenSSL::SSL::SSLError) do
# trying to normal endpoint with SSL -> SSL negotiation failure
@client.get_content(https_url)
end
#
# https -> http with strict_redirect_uri_callback
@client.redirect_uri_callback = @client.method(:strict_redirect_uri_callback)
@client.test_loopback_http_response << redirect_to_http
assert_raises(HTTPClient::BadResponseError) do
@client.get_content(https_url)
end
end
def test_redirect_relative
@client.test_loopback_http_response << "HTTP/1.0 302 OK\nLocation: hello\n\n"
assert_equal('hello', @client.get_content(@url + 'redirect1'))
#
@client.reset_all
@client.redirect_uri_callback = @client.method(:strict_redirect_uri_callback)
assert_equal('hello', @client.get_content(@url + 'redirect1'))
@client.reset_all
@client.test_loopback_http_response << "HTTP/1.0 302 OK\nLocation: hello\n\n"
begin
@client.get_content(@url + 'redirect1')
assert(false)
rescue HTTPClient::BadResponseError => e
assert_equal(302, e.res.status)
end
end
def test_redirect_https_relative
url = @url + 'redirect1'
https_url = URI.parse(url)
https_url.scheme = 'https'
@client.test_loopback_http_response << "HTTP/1.0 302 OK\nLocation: /foo\n\n"
@client.test_loopback_http_response << "HTTP/1.0 200 OK\n\nhello"
assert_equal('hello', @client.get_content(https_url))
end
def test_no_content
assert_nothing_raised do
timeout(2) do
@client.get(@url + 'status', :status => 101)
@client.get(@url + 'status', :status => 204)
@client.get(@url + 'status', :status => 304)
end
end
end
def test_get_content
assert_equal('hello', @client.get_content(@url + 'hello'))
assert_equal('hello', @client.get_content(@url + 'redirect1'))
assert_equal('hello', @client.get_content(@url + 'redirect2'))
url = @url.sub(/localhost/, '127.0.0.1')
assert_equal('hello', @client.get_content(url + 'hello'))
assert_equal('hello', @client.get_content(url + 'redirect1'))
assert_equal('hello', @client.get_content(url + 'redirect2'))
@client.reset(@url)
@client.reset(url)
@client.reset(@url)
@client.reset(url)
assert_raises(HTTPClient::BadResponseError) do
@client.get_content(@url + 'notfound')
end
assert_raises(HTTPClient::BadResponseError) do
@client.get_content(@url + 'redirect_self')
end
called = false
@client.redirect_uri_callback = lambda { |uri, res|
newuri = res.header['location'][0]
called = true
newuri
}
assert_equal('hello', @client.get_content(@url + 'relative_redirect'))
assert(called)
end
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"
DEFLATE_CONTENT = "\x78\x9c\xcb\x48\xcd\xc9\xc9\x07\x00\x06\x2c\x02\x15"
GZIP_CONTENT.force_encoding('BINARY') if GZIP_CONTENT.respond_to?(:force_encoding)
DEFLATE_CONTENT.force_encoding('BINARY') if DEFLATE_CONTENT.respond_to?(:force_encoding)
def test_get_gzipped_content
@client.transparent_gzip_decompression = false
content = @client.get_content(@url + 'compressed?enc=gzip')
assert_not_equal('hello', content)
assert_equal(GZIP_CONTENT, content)
@client.transparent_gzip_decompression = true
assert_equal('hello', @client.get_content(@url + 'compressed?enc=gzip'))
assert_equal('hello', @client.get_content(@url + 'compressed?enc=deflate'))
@client.transparent_gzip_decompression = false
end
def test_get_content_with_block
@client.get_content(@url + 'hello') do |str|
assert_equal('hello', str)
end
@client.get_content(@url + 'redirect1') do |str|
assert_equal('hello', str)
end
@client.get_content(@url + 'redirect2') do |str|
assert_equal('hello', str)
end
end
def test_post_content
assert_equal('hello', @client.post_content(@url + 'hello'))
assert_equal('hello', @client.post_content(@url + 'redirect1'))
assert_equal('hello', @client.post_content(@url + 'redirect2'))
assert_raises(HTTPClient::BadResponseError) do
@client.post_content(@url + 'notfound')
end
assert_raises(HTTPClient::BadResponseError) do
@client.post_content(@url + 'redirect_self')
end
called = false
@client.redirect_uri_callback = lambda { |uri, res|
newuri = res.header['location'][0]
called = true
newuri
}
assert_equal('hello', @client.post_content(@url + 'relative_redirect'))
assert(called)
end
def test_post_content_io
post_body = StringIO.new("1234567890")
assert_equal('post,1234567890', @client.post_content(@url + 'servlet', post_body))
post_body = StringIO.new("1234567890")
assert_equal('post,1234567890', @client.post_content(@url + 'servlet_redirect', post_body))
#
post_body = StringIO.new("1234567890")
post_body.read(5)
assert_equal('post,67890', @client.post_content(@url + 'servlet_redirect', post_body))
end
def test_head
assert_equal("head", @client.head(@url + 'servlet').header["x-head"][0])
res = @client.head(@url + 'servlet', {1=>2, 3=>4})
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_head_async
conn = @client.head_async(@url + 'servlet', {1=>2, 3=>4})
Thread.pass while !conn.finished?
res = conn.pop
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_get
assert_equal("get", @client.get(@url + 'servlet').content)
res = @client.get(@url + 'servlet', {1=>2, 3=>4})
assert_equal('1=2&3=4', res.header["x-query"][0])
assert_nil(res.contenttype)
#
url = @url.to_s + 'servlet?5=6&7=8'
res = @client.get(url, {1=>2, 3=>4})
assert_equal('1=2&3=4&5=6&7=8', res.header["x-query"][0])
assert_nil(res.contenttype)
end
def test_get_async
conn = @client.get_async(@url + 'servlet', {1=>2, 3=>4})
Thread.pass while !conn.finished?
res = conn.pop
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_get_async_for_largebody
conn = @client.get_async(@url + 'largebody')
res = conn.pop
assert_equal(1000*1000, res.content.read.length)
end
def test_get_with_block
called = false
res = @client.get(@url + 'servlet') { |str|
assert_equal('get', str)
called = true
}
assert(called)
# res does not have a content
assert_nil(res.content)
end
def test_post
assert_equal("post", @client.post(@url + 'servlet').content[0, 4])
res = @client.post(@url + 'servlet', {1=>2, 3=>4})
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_post_with_content_type
ext = {'content-type' => 'application/x-www-form-urlencoded', 'hello' => 'world'}
assert_equal("post", @client.post(@url + 'servlet').content[0, 4], ext)
res = @client.post(@url + 'servlet', {1=>2, 3=>4}, ext)
assert_equal('1=2&3=4', res.header["x-query"][0])
#
ext = [['content-type', 'multipart/form-data'], ['hello', 'world']]
assert_equal("post", @client.post(@url + 'servlet').content[0, 4], ext)
res = @client.post(@url + 'servlet', {1=>2, 3=>4}, ext)
assert_match(/Content-Disposition: form-data; name="1"/, res.content)
assert_match(/Content-Disposition: form-data; name="3"/, res.content)
#
ext = {'content-type' => 'multipart/form-data; boundary=hello'}
assert_equal("post", @client.post(@url + 'servlet').content[0, 4], ext)
res = @client.post(@url + 'servlet', {1=>2, 3=>4}, ext)
assert_match(/Content-Disposition: form-data; name="1"/, res.content)
assert_match(/Content-Disposition: form-data; name="3"/, res.content)
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)
end
def test_post_with_file
STDOUT.sync = true
File.open(__FILE__) do |file|
res = @client.post(@url + 'servlet', {1=>2, 3=>file})
assert_match(/^Content-Disposition: form-data; name="1"\r\n/nm, res.content)
assert_match(/^Content-Disposition: form-data; name="3";/, res.content)
assert_match(/FIND_TAG_IN_THIS_FILE/, res.content)
end
end
def test_post_with_io # chunked post
myio = StringIO.new("4")
def myio.size
nil
end
res = @client.post(@url + 'servlet', {1=>2, 3=>myio})
assert_match(/\r\nContent-Disposition: form-data; name="1"\r\n/m, res.content)
assert_match(/\r\n2\r\n/m, res.content)
assert_match(/\r\nContent-Disposition: form-data; name="3"; filename=""\r\n/m, res.content)
assert_match(/\r\n4\r\n/m, res.content)
end
def test_post_async
conn = @client.post_async(@url + 'servlet', {1=>2, 3=>4})
Thread.pass while !conn.finished?
res = conn.pop
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_post_with_block
called = false
res = @client.post(@url + 'servlet') { |str|
assert_equal('post,', str)
called = true
}
assert(called)
assert_nil(res.content)
#
called = false
res = @client.post(@url + 'servlet', {1=>2, 3=>4}) { |str|
assert_equal('post,1=2&3=4', str)
called = true
}
assert(called)
assert_equal('1=2&3=4', res.header["x-query"][0])
assert_nil(res.content)
end
def test_post_with_custom_multipart
ext = {'content-type' => 'multipart/form-data'}
assert_equal("post", @client.post(@url + 'servlet').content[0, 4], ext)
body = [{ 'Content-Disposition' => 'form-data; name="1"', :content => "2"},
{ 'Content-Disposition' => 'form-data; name="3"', :content => "4"}]
res = @client.post(@url + 'servlet', body, ext)
assert_match(/Content-Disposition: form-data; name="1"/, res.content)
assert_match(/Content-Disposition: form-data; name="3"/, res.content)
#
ext = {'content-type' => 'multipart/form-data; boundary=hello'}
assert_equal("post", @client.post(@url + 'servlet').content[0, 4], ext)
res = @client.post(@url + 'servlet', body, ext)
assert_match(/Content-Disposition: form-data; name="1"/, res.content)
assert_match(/Content-Disposition: form-data; name="3"/, res.content)
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)
end
def test_post_with_custom_multipart_and_file
STDOUT.sync = true
File.open(__FILE__) do |file|
ext = { 'Content-Type' => 'multipart/alternative' }
body = [{ 'Content-Type' => 'text/plain', :content => "this is only a test" },
{ 'Content-Type' => 'application/x-ruby', :content => file }]
res = @client.post(@url + 'servlet', body, ext)
assert_match(/^Content-Type: text\/plain\r\n/m, res.content)
assert_match(/^this is only a test\r\n/m, res.content)
assert_match(/^Content-Type: application\/x-ruby\r\n/m, res.content)
assert_match(/FIND_TAG_IN_THIS_FILE/, res.content)
end
end
def test_put
assert_equal("put", @client.put(@url + 'servlet').content)
res = @client.put(@url + 'servlet', {1=>2, 3=>4})
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_put_bytesize
res = @client.put(@url + 'servlet', 'txt' => 'あいうえお')
assert_equal('txt=%E3%81%82%E3%81%84%E3%81%86%E3%81%88%E3%81%8A', res.header["x-query"][0])
assert_equal('15', res.header["x-size"][0])
end
def test_put_async
conn = @client.put_async(@url + 'servlet', {1=>2, 3=>4})
Thread.pass while !conn.finished?
res = conn.pop
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_delete
assert_equal("delete", @client.delete(@url + 'servlet').content)
end
def test_delete_async
conn = @client.delete_async(@url + 'servlet')
Thread.pass while !conn.finished?
res = conn.pop
assert_equal('delete', res.content.read)
end
def test_options
assert_equal("options", @client.options(@url + 'servlet').content)
end
def test_options_async
conn = @client.options_async(@url + 'servlet')
Thread.pass while !conn.finished?
res = conn.pop
assert_equal('options', res.content.read)
end
def test_propfind
assert_equal("propfind", @client.propfind(@url + 'servlet').content)
end
def test_propfind_async
conn = @client.propfind_async(@url + 'servlet')
Thread.pass while !conn.finished?
res = conn.pop
assert_equal('propfind', res.content.read)
end
def test_proppatch
assert_equal("proppatch", @client.proppatch(@url + 'servlet').content)
res = @client.proppatch(@url + 'servlet', {1=>2, 3=>4})
assert_equal('proppatch', res.content)
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_proppatch_async
conn = @client.proppatch_async(@url + 'servlet', {1=>2, 3=>4})
Thread.pass while !conn.finished?
res = conn.pop
assert_equal('proppatch', res.content.read)
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_trace
assert_equal("trace", @client.trace(@url + 'servlet').content)
res = @client.trace(@url + 'servlet', {1=>2, 3=>4})
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_trace_async
conn = @client.trace_async(@url + 'servlet', {1=>2, 3=>4})
Thread.pass while !conn.finished?
res = conn.pop
assert_equal('1=2&3=4', res.header["x-query"][0])
end
def test_chunked
assert_equal('chunked', @client.get_content(@url + 'chunked', { 'msg' => 'chunked' }))
end
def test_chunked_empty
assert_equal('', @client.get_content(@url + 'chunked', { 'msg' => '' }))
end
def test_get_query
assert_equal({'1'=>'2'}, check_query_get({1=>2}))
assert_equal({'a'=>'A', 'B'=>'b'}, check_query_get({"a"=>"A", "B"=>"b"}))
assert_equal({'&'=>'&'}, check_query_get({"&"=>"&"}))
assert_equal({'= '=>' =+'}, check_query_get({"= "=>" =+"}))
assert_equal(
['=', '&'].sort,
check_query_get([["=", "="], ["=", "&"]])['='].to_ary.sort
)
assert_equal({'123'=>'45'}, check_query_get('123=45'))
assert_equal({'12 3'=>'45', ' '=>' '}, check_query_get('12+3=45&+=+'))
assert_equal({}, check_query_get(''))
assert_equal({'1'=>'2'}, check_query_get({1=>StringIO.new('2')}))
assert_equal({'1'=>'2', '3'=>'4'}, check_query_get(StringIO.new('3=4&1=2')))
end
def test_post_body
assert_equal({'1'=>'2'}, check_query_post({1=>2}))
assert_equal({'a'=>'A', 'B'=>'b'}, check_query_post({"a"=>"A", "B"=>"b"}))
assert_equal({'&'=>'&'}, check_query_post({"&"=>"&"}))
assert_equal({'= '=>' =+'}, check_query_post({"= "=>" =+"}))
assert_equal(
['=', '&'].sort,
check_query_post([["=", "="], ["=", "&"]])['='].to_ary.sort
)
assert_equal({'123'=>'45'}, check_query_post('123=45'))
assert_equal({'12 3'=>'45', ' '=>' '}, check_query_post('12+3=45&+=+'))
assert_equal({}, check_query_post(''))
#
post_body = StringIO.new("foo=bar&foo=baz")
assert_equal(
["bar", "baz"],
check_query_post(post_body)["foo"].to_ary.sort
)
end
def test_extra_headers
str = ""
@client.debug_dev = str
@client.head(@url, nil, {"ABC" => "DEF"})
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_match("ABC: DEF", lines[4])
#
str = ""
@client.debug_dev = str
@client.get(@url, nil, [["ABC", "DEF"], ["ABC", "DEF"]])
lines = str.split(/(?:\r?\n)+/)
assert_equal("= Request", lines[0])
assert_match("ABC: DEF", lines[4])
assert_match("ABC: DEF", lines[5])
end
def test_timeout
assert_equal(60, @client.connect_timeout)
assert_equal(120, @client.send_timeout)
assert_equal(60, @client.receive_timeout)
#
@client.connect_timeout = 1
@client.send_timeout = 2
@client.receive_timeout = 3
assert_equal(1, @client.connect_timeout)
assert_equal(2, @client.send_timeout)
assert_equal(3, @client.receive_timeout)
end
def test_connect_timeout
# ToDo
end
def test_send_timeout
# ToDo
end
def test_receive_timeout
# this test takes 2 sec
assert_equal('hello', @client.get_content(@url + 'sleep?sec=2'))
@client.receive_timeout = 1
assert_equal('hello', @client.get_content(@url + 'sleep?sec=0'))
assert_raise(HTTPClient::ReceiveTimeoutError) do
@client.get_content(@url + 'sleep?sec=2')
end
@client.receive_timeout = 3
assert_equal('hello', @client.get_content(@url + 'sleep?sec=2'))
end
def test_receive_timeout_post
# this test takes 2 sec
assert_equal('hello', @client.post(@url + 'sleep', :sec => 2).content)
@client.receive_timeout = 1
assert_equal('hello', @client.post(@url + 'sleep', :sec => 0).content)
assert_raise(HTTPClient::ReceiveTimeoutError) do
@client.post(@url + 'sleep', :sec => 2)
end
@client.receive_timeout = 3
assert_equal('hello', @client.post(@url + 'sleep', :sec => 2).content)
end
def test_async_error
assert_raise( SocketError ) do
conn = @client.get_async("http://non-existing-host/")
conn.pop
end
end
def test_reset
url = @url + 'servlet'
assert_nothing_raised do
5.times do
@client.get(url)
@client.reset(url)
end
end
end
def test_reset_all
assert_nothing_raised do
5.times do
@client.get(@url + 'servlet')
@client.reset_all
end
end
end
def test_cookies
cookiefile = File.join(File.dirname(File.expand_path(__FILE__)), 'test_cookies_file')
File.open(cookiefile, "wb") do |f|
f << "http://rubyforge.org/account/login.php session_ser LjEwMy45Ni40Ni0q%2A-fa0537de8cc31 2000000000 .rubyforge.org / 13\n"
end
@client.set_cookie_store(cookiefile)
cookie = @client.cookie_manager.cookies.first
url = cookie.url
assert(cookie.domain_match(url.host, cookie.domain))
#
@client.reset_all
@client.test_loopback_http_response << "HTTP/1.0 200 OK\nSet-Cookie: foo=bar; expires=#{Time.mktime(2030, 12, 31).httpdate}\n\nOK"
@client.get_content('http://rubyforge.org/account/login.php')
@client.save_cookie_store
str = File.read(cookiefile)
assert_match(%r(http://rubyforge.org/account/login.php foo bar 1924873200 rubyforge.org /account 1), str)
end
def test_eof_error_length
io = StringIO.new('')
def io.gets(*arg)
@buf ||= ["HTTP/1.0 200 OK\n", "content-length: 123\n", "\n"]
@buf.shift
end
def io.readpartial(size, buf)
@second ||= false
if !@second
@second = '1st'
buf << "abc"
buf
elsif @second == '1st'
@second = '2nd'
raise EOFError.new
else
raise Exception.new
end
end
def io.eof?
true
end
@client.test_loopback_http_response << io
assert_nothing_raised do
@client.get('http://foo/bar')
end
end
def test_eof_error_rest
io = StringIO.new('')
def io.gets(*arg)
@buf ||= ["HTTP/1.0 200 OK\n", "\n"]
@buf.shift
end
def io.readpartial(size, buf)
@second ||= false
if !@second
@second = '1st'
buf << "abc"
buf
elsif @second == '1st'
@second = '2nd'
raise EOFError.new
else
raise Exception.new
end
end
def io.eof?
true
end
@client.test_loopback_http_response << io
assert_nothing_raised do
@client.get('http://foo/bar')
end
end
def test_urify
extend HTTPClient::Util
assert_nil(urify(nil))
uri = 'http://foo'
assert_equal(URI.parse(uri), urify(uri))
assert_equal(URI.parse(uri), urify(URI.parse(uri)))
end
def test_connection
c = HTTPClient::Connection.new
assert(c.finished?)
assert_nil(c.join)