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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
|
require 'spec_helper'
RSpec.describe HTTParty::Request do
before do
@request = HTTParty::Request.new(Net::HTTP::Get, 'http://api.foo.com/v1', format: :xml)
end
describe "::NON_RAILS_QUERY_STRING_NORMALIZER" do
let(:normalizer) { HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER }
it "doesn't modify strings" do
query_string = normalizer["foo=bar&foo=baz"]
expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz")
end
context "when the query is an array" do
it "doesn't include brackets" do
query_string = normalizer[{page: 1, foo: %w(bar baz)}]
expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz&page=1")
end
it "URI encodes array values" do
query_string = normalizer[{people: ["Otis Redding", "Bob Marley", "Tim & Jon"], page: 1, xyzzy: 3}]
expect(query_string).to eq("page=1&people=Otis%20Redding&people=Bob%20Marley&people=Tim%20%26%20Jon&xyzzy=3")
end
end
context "when the query is a hash" do
it "correctly handles nil values" do
query_string = normalizer[{page: 1, per_page: nil}]
expect(query_string).to eq("page=1&per_page")
end
end
end
describe "::JSON_API_QUERY_STRING_NORMALIZER" do
let(:normalizer) { HTTParty::Request::JSON_API_QUERY_STRING_NORMALIZER }
it "doesn't modify strings" do
query_string = normalizer["foo=bar&foo=baz"]
expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz")
end
context "when the query is an array" do
it "doesn't include brackets" do
query_string = normalizer[{page: 1, foo: %w(bar baz)}]
expect(CGI.unescape(query_string)).to eq("foo=bar,baz&page=1")
end
it "URI encodes array values" do
query_string = normalizer[{people: ["Otis Redding", "Bob Marley", "Tim & Jon"], page: 1, xyzzy: 3}]
expect(query_string).to eq("page=1&people=Otis%20Redding,Bob%20Marley,Tim%20%26%20Jon&xyzzy=3")
end
end
context "when the query is a hash" do
it "correctly handles nil values" do
query_string = normalizer[{page: 1, per_page: nil}]
expect(query_string).to eq('page=1&per_page')
end
end
end
describe "initialization" do
it "sets parser to HTTParty::Parser" do
request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com')
expect(request.parser).to eq(HTTParty::Parser)
end
it "sets parser to the optional parser" do
my_parser = lambda {}
request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', parser: my_parser)
expect(request.parser).to eq(my_parser)
end
it "sets connection_adapter to HTTParty::ConnectionAdapter" do
request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com')
expect(request.connection_adapter).to eq(HTTParty::ConnectionAdapter)
end
it "sets connection_adapter to the optional connection_adapter" do
my_adapter = lambda {}
request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', connection_adapter: my_adapter)
expect(request.connection_adapter).to eq(my_adapter)
end
context "when using a query string" do
context "and it has an empty array" do
it "sets correct query string" do
request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', query: { fake_array: [] })
expect(request.uri).to eq(URI.parse("http://google.com/?fake_array%5B%5D="))
end
end
context "when sending an array with only one element" do
it "sets correct query" do
request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', query: { fake_array: [1] })
expect(request.uri).to eq(URI.parse("http://google.com/?fake_array%5B%5D=1"))
end
end
end
context "when basic authentication credentials provided in uri" do
context "when basic auth options wasn't set explicitly" do
it "sets basic auth from uri" do
request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com')
expect(request.options[:basic_auth]).to eq({username: 'user1', password: 'pass1'})
end
end
context "when basic auth options was set explicitly" do
it "uses basic auth from url anyway" do
basic_auth = {username: 'user2', password: 'pass2'}
request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com', basic_auth: basic_auth)
expect(request.options[:basic_auth]).to eq({username: 'user1', password: 'pass1'})
end
end
end
end
describe "#format" do
context "request yet to be made" do
it "returns format option" do
request = HTTParty::Request.new 'get', '/', format: :xml
expect(request.format).to eq(:xml)
end
it "returns nil format" do
request = HTTParty::Request.new 'get', '/'
expect(request.format).to be_nil
end
end
context "request has been made" do
it "returns format option" do
request = HTTParty::Request.new 'get', '/', format: :xml
request.last_response = double
expect(request.format).to eq(:xml)
end
it "returns the content-type from the last response when the option is not set" do
request = HTTParty::Request.new 'get', '/'
response = double
expect(response).to receive(:[]).with('content-type').and_return('text/json')
request.last_response = response
expect(request.format).to eq(:json)
end
end
end
context "options" do
it "should use basic auth when configured" do
@request.options[:basic_auth] = {username: 'foobar', password: 'secret'}
@request.send(:setup_raw_request)
expect(@request.instance_variable_get(:@raw_request)['authorization']).not_to be_nil
end
context 'digest_auth' do
before do
response_sequence = [
{
status: ['401', 'Unauthorized' ], headers: {
www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false',
set_cookie: 'custom-cookie=1234567'
}
},
{ status: ['200', 'OK'] }
]
stub_request(:get, 'http://api.foo.com/v1').to_return(response_sequence)
end
it 'should not send credentials more than once' do
response_sequence = [
{
status: ['401', 'Unauthorized' ], headers: {
www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false',
set_cookie: 'custom-cookie=1234567'
}
},
{
status: ['401', 'Unauthorized' ], headers: {
www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false',
set_cookie: 'custom-cookie=1234567'
}
},
{ status: ['404', 'Not found'] }
]
stub_request(:get, 'http://api.foo.com/v1').to_return(response_sequence)
@request.options[:digest_auth] = {username: 'foobar', password: 'secret'}
response = @request.perform { |v| }
expect(response.code).to eq(401)
raw_request = @request.instance_variable_get(:@raw_request)
expect(raw_request['Authorization']).not_to be_nil
end
it 'should not be used when configured and the response is 200' do
stub_request(:get, 'http://api.foo.com/v1').to_return(status: 200)
@request.options[:digest_auth] = {username: 'foobar', password: 'secret'}
response = @request.perform { |v| }
expect(response.code).to eq(200)
raw_request = @request.instance_variable_get(:@raw_request)
expect(raw_request['Authorization']).to be_nil
end
it "should be used when configured and the response is 401" do
@request.options[:digest_auth] = {username: 'foobar', password: 'secret'}
response = @request.perform { |v| }
expect(response.code).to eq(200)
raw_request = @request.instance_variable_get(:@raw_request)
expect(raw_request['Authorization']).not_to be_nil
end
it 'should maintain cookies returned from a 401 response' do
@request.options[:digest_auth] = {username: 'foobar', password: 'secret'}
response = @request.perform {|v|}
expect(response.code).to eq(200)
raw_request = @request.instance_variable_get(:@raw_request)
expect(raw_request.get_fields('cookie')).to eql ["custom-cookie=1234567"]
end
it 'should merge cookies from request and a 401 response' do
@request.options[:digest_auth] = {username: 'foobar', password: 'secret'}
@request.options[:headers] = {'cookie' => 'request-cookie=test'}
response = @request.perform {|v|}
expect(response.code).to eq(200)
raw_request = @request.instance_variable_get(:@raw_request)
expect(raw_request.get_fields('cookie')).to eql ['request-cookie=test', 'custom-cookie=1234567']
end
end
it 'should use body_stream when configured' do
stream = StringIO.new('foo')
request = HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', body_stream: stream)
request.send(:setup_raw_request)
expect(request.instance_variable_get(:@raw_request).body_stream).to eq(stream)
end
it 'should normalize base uri when specified as request option' do
stub_request(:get, 'http://foo.com/resource').to_return(body: 'Bar')
response = HTTParty.get('/resource', {
base_uri: 'foo.com'
})
expect(response.code).to eq(200)
end
end
describe "#uri" do
context "redirects" do
it "returns correct path when the server sets the location header to a filename" do
@request.last_uri = URI.parse("http://example.com/foo/bar")
@request.path = URI.parse("bar?foo=bar")
@request.redirect = true
expect(@request.uri).to eq(URI.parse("http://example.com/foo/bar?foo=bar"))
end
context "location header is an absolute path" do
it "returns correct path when location has leading slash" do
@request.last_uri = URI.parse("http://example.com/foo/bar")
@request.path = URI.parse("/bar?foo=bar")
@request.redirect = true
expect(@request.uri).to eq(URI.parse("http://example.com/bar?foo=bar"))
end
it "returns the correct path when location has no leading slash" do
@request.last_uri = URI.parse("http://example.com")
@request.path = URI.parse("bar/")
@request.redirect = true
expect(@request.uri).to eq(URI.parse("http://example.com/bar/"))
end
end
it "returns correct path when the server sets the location header to a full uri" do
@request.last_uri = URI.parse("http://example.com/foo/bar")
@request.path = URI.parse("http://example.com/bar?foo=bar")
@request.redirect = true
expect(@request.uri).to eq(URI.parse("http://example.com/bar?foo=bar"))
end
it "returns correct path when the server sets the location header to a network-path reference" do
@request.last_uri = URI.parse("https://example.com")
@request.path = URI.parse("//www.example.com")
@request.redirect = true
expect(@request.uri).to eq(URI.parse("https://www.example.com"))
end
end
context "query strings" do
it "does not add an empty query string when default_params are blank" do
@request.options[:default_params] = {}
expect(@request.uri.query).to be_nil
end
it "respects the query string normalization proc" do
empty_proc = lambda {|qs| "I"}
@request.options[:query_string_normalizer] = empty_proc
@request.options[:query] = {foo: :bar}
expect(CGI.unescape(@request.uri.query)).to eq("I")
end
it "does not append an ampersand when queries are embedded in paths" do
@request.path = "/path?a=1"
@request.options[:query] = {}
expect(@request.uri.query).to eq("a=1")
end
it "does not duplicate query string parameters when uri is called twice" do
@request.options[:query] = {foo: :bar}
@request.uri
expect(@request.uri.query).to eq("foo=bar")
end
context "when representing an array" do
it "returns a Rails style query string" do
@request.options[:query] = {foo: %w(bar baz)}
expect(CGI.unescape(@request.uri.query)).to eq("foo[]=bar&foo[]=baz")
expect(@request.uri.query).to eq("foo%5B%5D=bar&foo%5B%5D=baz")
end
end
end
end
describe "#setup_raw_request" do
context "when query_string_normalizer is set" do
it "sets the body to the return value of the proc" do
@request.options[:query_string_normalizer] = HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER
@request.options[:body] = {page: 1, foo: %w(bar baz)}
@request.send(:setup_raw_request)
body = @request.instance_variable_get(:@raw_request).body
expect(CGI.unescape(body)).to eq("foo=bar&foo=baz&page=1")
end
end
context "when multipart" do
subject(:headers) do
@request.send(:setup_raw_request)
headers = @request.instance_variable_get(:@raw_request).each_header.to_a
Hash[*headers.flatten] # Ruby 2.0 doesn't have Array#to_h
end
context "when body contains file" do
it "sets header Content-Type: multipart/form-data; boundary=" do
@request.options[:body] = {file: File.open(File::NULL, 'r')}
expect(headers['content-type']).to match(%r{^multipart/form-data; boundary=---})
end
context "and header Content-Type is provided" do
it "overwrites the header to: multipart/form-data; boundary=" do
@request.options[:body] = {file: File.open(File::NULL, 'r')}
@request.options[:headers] = {'Content-Type' => 'application/x-www-form-urlencoded'}
expect(headers['content-type']).to match(%r{^multipart/form-data; boundary=---})
end
end
end
context 'when mulipart option is provided' do
it "sets header Content-Type: multipart/form-data; boundary=" do
@request.options[:body] = { text: 'something' }
@request.options[:multipart] = true
expect(headers['content-type']).to match(%r{^multipart/form-data; boundary=---})
end
end
end
end
describe 'http' do
it "should get a connection from the connection_adapter" do
http = Net::HTTP.new('google.com')
adapter = double('adapter')
request = HTTParty::Request.new(Net::HTTP::Get, 'https://api.foo.com/v1:443', connection_adapter: adapter)
expect(adapter).to receive(:call).with(request.uri, request.options).and_return(http)
expect(request.send(:http)).to be http
end
end
describe '#format_from_mimetype' do
it 'should handle text/xml' do
["text/xml", "text/xml; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:xml)
end
end
it 'should handle application/xml' do
["application/xml", "application/xml; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:xml)
end
end
it 'should handle text/json' do
["text/json", "text/json; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:json)
end
end
it 'should handle application/vnd.api+json' do
["application/vnd.api+json", "application/vnd.api+json; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:json)
end
end
it 'should handle application/hal+json' do
["application/hal+json", "application/hal+json; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:json)
end
end
it 'should handle application/json' do
["application/json", "application/json; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:json)
end
end
it 'should handle text/csv' do
["text/csv", "text/csv; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:csv)
end
end
it 'should handle application/csv' do
["application/csv", "application/csv; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:csv)
end
end
it 'should handle text/comma-separated-values' do
["text/comma-separated-values", "text/comma-separated-values; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:csv)
end
end
it 'should handle text/javascript' do
["text/javascript", "text/javascript; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:plain)
end
end
it 'should handle application/javascript' do
["application/javascript", "application/javascript; charset=iso8859-1"].each do |ct|
expect(@request.send(:format_from_mimetype, ct)).to eq(:plain)
end
end
it "returns nil for an unrecognized mimetype" do
expect(@request.send(:format_from_mimetype, "application/atom+xml")).to be_nil
end
it "returns nil when using a default parser" do
@request.options[:parser] = lambda {}
expect(@request.send(:format_from_mimetype, "text/json")).to be_nil
end
end
describe 'parsing responses' do
it 'should handle xml automatically' do
xml = '<books><book><id>1234</id><name>Foo Bar!</name></book></books>'
@request.options[:format] = :xml
expect(@request.send(:parse_response, xml)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}})
end
it 'should handle utf-8 bom in xml' do
xml = "\xEF\xBB\xBF<books><book><id>1234</id><name>Foo Bar!</name></book></books>"
@request.options[:format] = :xml
expect(@request.send(:parse_response, xml)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}})
end
it 'should handle csv automatically' do
csv = ['"id","Name"', '"1234","Foo Bar!"'].join("\n")
@request.options[:format] = :csv
expect(@request.send(:parse_response, csv)).to eq([%w(id Name), ["1234", "Foo Bar!"]])
end
it 'should handle json automatically' do
json = '{"books": {"book": {"name": "Foo Bar!", "id": "1234"}}}'
@request.options[:format] = :json
expect(@request.send(:parse_response, json)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}})
end
it 'should handle utf-8 bom in json' do
json = "\xEF\xBB\xBF{\"books\": {\"book\": {\"name\": \"Foo Bar!\", \"id\": \"1234\"}}}"
@request.options[:format] = :json
expect(@request.send(:parse_response, json)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}})
end
it "should include any HTTP headers in the returned response" do
@request.options[:format] = :html
response = stub_response "Content"
response.initialize_http_header("key" => "value")
expect(@request.perform.headers).to eq({ "key" => ["value"] })
end
describe 'decompression' do
it 'should remove the Content-Encoding header if uncompressed' do
@request.options[:format] = :html
response = stub_response 'Content'
response.initialize_http_header('Content-Encoding' => 'none')
resp = @request.perform
expect(resp.body).to eq('Content')
expect(resp.headers).to eq({})
expect(resp.parsed_response).to eq('Content')
end
it 'should decompress the body and remove the Content-Encoding header' do
@request.options[:format] = :html
stub_const('Brotli', double('Brotli', inflate: 'foobar'))
response = stub_response 'Content'
response.initialize_http_header('Content-Encoding' => 'br')
resp = @request.perform
expect(resp.body).to eq('foobar')
expect(resp.headers).to eq({})
expect(resp.parsed_response).to eq('foobar')
end
it 'should not decompress the body if the :skip_decompression option is set' do
@request.options[:format] = :html
@request.options[:skip_decompression] = true
stub_const('Brotli', double('Brotli', inflate: 'foobar'))
response = stub_response 'Content'
response.initialize_http_header('Content-Encoding' => 'br')
resp = @request.perform
expect(resp.body).to eq('Content')
expect(resp.headers).to eq({ 'Content-Encoding' => 'br' })
expect(resp.parsed_response).to eq('foobar')
end
it 'should not decompress unrecognized Content-Encoding' do
@request.options[:format] = :html
response = stub_response 'Content'
response.initialize_http_header('Content-Encoding' => 'bad')
resp = @request.perform
expect(resp.body).to eq('Content')
expect(resp.headers).to eq({ 'Content-Encoding' => 'bad' })
expect(resp.parsed_response).to eq(nil)
end
end
if "".respond_to?(:encoding)
context 'when body has ascii-8bit encoding' do
let(:response) { stub_response "Content".force_encoding('ascii-8bit') }
it "processes charset in content type properly" do
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-8")
resp = @request.perform
expect(resp.body.encoding).to eq(Encoding.find("UTF-8"))
end
it "processes charset in content type properly if it has a different case" do
response.initialize_http_header("Content-Type" => "text/plain;CHARSET = utf-8")
resp = @request.perform
expect(resp.body.encoding).to eq(Encoding.find("UTF-8"))
end
it "processes quoted charset in content type properly" do
response.initialize_http_header("Content-Type" => "text/plain;charset = \"utf-8\"")
resp = @request.perform
expect(resp.body.encoding).to eq(Encoding.find("UTF-8"))
end
context 'when stubed body is frozen' do
let(:response) do
stub_response "Content".force_encoding('ascii-8bit').freeze
end
it 'processes frozen body correctly' do
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-8")
resp = @request.perform
expect(resp.body.encoding).to eq(Encoding.find("UTF-8"))
end
end
end
it "should process response with a nil body" do
response = stub_response nil
response.initialize_http_header("Content-Type" => "text/html;charset=UTF-8")
resp = @request.perform
expect(resp.body).to be_nil
end
context 'when assume_utf16_is_big_endian is true' do
before { @request.options[:assume_utf16_is_big_endian] = true }
it "should process utf-16 charset with little endian bom correctly" do
response = stub_response "\xFF\xFEC\x00o\x00n\x00t\x00e\x00n\x00t\x00"
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16")
resp = @request.perform
expect(resp.body.encoding).to eq(Encoding.find("UTF-16LE"))
end
it 'processes stubbed frozen body correctly' do
response = stub_response "\xFF\xFEC\x00o\x00n\x00t\x00e\x00n\x00t\x00".freeze
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16")
resp = @request.perform
expect(resp.body.encoding).to eq(Encoding.find("UTF-16LE"))
end
end
it "should process utf-16 charset with big endian bom correctly" do
@request.options[:assume_utf16_is_big_endian] = false
response = stub_response "\xFE\xFF\x00C\x00o\x00n\x00t\x00e\x00n\x00t"
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16")
resp = @request.perform
expect(resp.body.encoding).to eq(Encoding.find("UTF-16BE"))
end
it "should assume utf-16 little endian if options has been chosen" do
@request.options[:assume_utf16_is_big_endian] = false
response = stub_response "C\x00o\x00n\x00t\x00e\x00n\x00t\x00"
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16")
resp = @request.perform
expect(resp.body.encoding).to eq(Encoding.find("UTF-16LE"))
end
it "should perform no encoding if the charset is not available" do
response = stub_response "Content"
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-lols")
resp = @request.perform
# This encoding does not exist, thus the string should not be encodd with it
expect(resp.body).to eq("Content")
expect(resp.body.encoding).to eq("Content".encoding)
end
it "should perform no encoding if the content type is specified but no charset is specified" do
response = stub_response "Content"
response.initialize_http_header("Content-Type" => "text/plain")
resp = @request.perform
expect(resp.body).to eq("Content")
expect(resp.body.encoding).to eq("Content".encoding)
end
end
describe 'with non-200 responses' do
context "3xx responses" do
it 'returns a valid object for 304 not modified' do
stub_response '', 304
resp = @request.perform
expect(resp.code).to eq(304)
expect(resp.body).to eq('')
expect(resp).to be_nil
end
it "redirects if a 300 contains a location header" do
redirect = stub_response '', 300
redirect['location'] = 'http://foo.com/foo'
ok = stub_response('<hash><foo>bar</foo></hash>', 200)
allow(@http).to receive(:request).and_return(redirect, ok)
response = @request.perform
expect(response.request.base_uri.to_s).to eq("http://foo.com")
expect(response.request.path.to_s).to eq("http://foo.com/foo")
expect(response.request.uri.request_uri).to eq("/foo")
expect(response.request.uri.to_s).to eq("http://foo.com/foo")
expect(response.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
xit "calls block given to perform with each redirect" do
@request = HTTParty::Request.new(Net::HTTP::Get, 'http://test.com/redirect', format: :xml)
stub_request(:get, 'http://test.com/redirect')
.to_return(
status: [300, 'REDIRECT'],
headers: { location: 'http://api.foo.com/v2' }
)
stub_request(:get, 'http://api.foo.com/v2')
.to_return(body: '<hash><foo>bar</foo></hash>')
body = ""
@request.perform { |chunk| body += chunk }
expect(body.length).to eq(27)
end
it "redirects if a 300 contains a relative location header" do
redirect = stub_response '', 300
redirect['location'] = '/foo/bar'
ok = stub_response('<hash><foo>bar</foo></hash>', 200)
allow(@http).to receive(:request).and_return(redirect, ok)
response = @request.perform
expect(response.request.base_uri.to_s).to eq("http://api.foo.com")
expect(response.request.path.to_s).to eq("/foo/bar")
expect(response.request.uri.request_uri).to eq("/foo/bar")
expect(response.request.uri.to_s).to eq("http://api.foo.com/foo/bar")
expect(response.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "handles multiple redirects and relative location headers on different hosts" do
@request = HTTParty::Request.new(Net::HTTP::Get, 'http://test.com/redirect', format: :xml)
stub_request(:get, 'http://test.com/redirect')
.to_return(
status: [300, 'REDIRECT'],
headers: { location: "http://api.foo.com/v2" }
)
stub_request(:get, 'http://api.foo.com/v2')
.to_return(
status: [300, 'REDIRECT'],
headers: { location: '/v3' }
)
stub_request(:get, 'http://api.foo.com/v3')
.to_return(body: '<hash><foo>bar</foo></hash>')
response = @request.perform
expect(response.request.base_uri.to_s).to eq("http://api.foo.com")
expect(response.request.path.to_s).to eq("/v3")
expect(response.request.uri.request_uri).to eq("/v3")
expect(response.request.uri.to_s).to eq("http://api.foo.com/v3")
expect(response.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "raises an error if redirect has duplicate location header" do
@request = HTTParty::Request.new(Net::HTTP::Get, 'http://test.com/redirect', format: :xml)
stub_request(:get, 'http://test.com/redirect')
.to_return(
status: [300, 'REDIRECT'],
headers: {
location: ['http://api.foo.com/v2', 'http://api.foo.com/v2']
}
)
expect {@request.perform}.to raise_error(HTTParty::DuplicateLocationHeader)
end
it "returns the HTTParty::Response when the 300 does not contain a location header" do
stub_response '', 300
expect(HTTParty::Response).to be === @request.perform
end
it "redirects including port" do
stub_request(:get, 'http://withport.com:3000/v1')
.to_return(
status: [301, 'Moved Permanently'],
headers: { location: 'http://withport.com:3000/v2' }
)
stub_request(:get, 'http://withport.com:3000/v2')
.to_return(status: 200)
request = HTTParty::Request.new(Net::HTTP::Get, 'http://withport.com:3000/v1')
response = request.perform
expect(response.request.base_uri.to_s).to eq("http://withport.com:3000")
end
end
it 'should return a valid object for 4xx response' do
stub_response '<foo><bar>yes</bar></foo>', 401
resp = @request.perform
expect(resp.code).to eq(401)
expect(resp.body).to eq("<foo><bar>yes</bar></foo>")
expect(resp['foo']['bar']).to eq("yes")
end
it 'should return a valid object for 5xx response' do
stub_response '<foo><bar>error</bar></foo>', 500
resp = @request.perform
expect(resp.code).to eq(500)
expect(resp.body).to eq("<foo><bar>error</bar></foo>")
expect(resp['foo']['bar']).to eq("error")
end
it "parses response lazily so codes can be checked prior" do
stub_response 'not xml', 500
@request.options[:format] = :xml
expect {
response = @request.perform
expect(response.code).to eq(500)
expect(response.body).to eq('not xml')
}.not_to raise_error
end
end
end
it "should not attempt to parse empty responses" do
[204, 304].each do |code|
stub_response "", code
@request.options[:format] = :xml
expect(@request.perform).to be_nil
end
end
it "should not fail for missing mime type" do
stub_response "Content for you"
@request.options[:format] = :html
expect(@request.perform.parsed_response).to eq('Content for you')
end
[300, 301, 302, 305].each do |code|
describe "a request that #{code} redirects" do
before(:each) do
@redirect = stub_response("", code)
@redirect['location'] = '/foo'
@ok = stub_response('<hash><foo>bar</foo></hash>', 200)
end
describe "once" do
before(:each) do
allow(@http).to receive(:request).and_return(@redirect, @ok)
end
it "should be handled by GET transparently" do
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by POST transparently" do
@request.http_method = Net::HTTP::Post
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by DELETE transparently" do
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by MOVE transparently" do
@request.http_method = Net::HTTP::Move
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by COPY transparently" do
@request.http_method = Net::HTTP::Copy
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by PATCH transparently" do
@request.http_method = Net::HTTP::Patch
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by PUT transparently" do
@request.http_method = Net::HTTP::Put
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by HEAD transparently" do
@request.http_method = Net::HTTP::Head
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by OPTIONS transparently" do
@request.http_method = Net::HTTP::Options
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by MKCOL transparently" do
@request.http_method = Net::HTTP::Mkcol
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by LOCK transparently" do
@request.http_method = Net::HTTP::Lock
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by UNLOCK transparently" do
@request.http_method = Net::HTTP::Unlock
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should keep track of cookies between redirects" do
@redirect['Set-Cookie'] = 'foo=bar; name=value; HTTPOnly'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=bar/)
expect(@request.options[:headers]['Cookie']).to match(/name=value/)
end
it 'should update cookies with redirects' do
@request.options[:headers] = {'Cookie' => 'foo=bar;'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=tar/)
end
it 'should keep cookies between redirects' do
@request.options[:headers] = {'Cookie' => 'keep=me'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/keep=me/)
end
it "should handle multiple Set-Cookie headers between redirects" do
@redirect.add_field 'set-cookie', 'foo=bar; name=value; HTTPOnly'
@redirect.add_field 'set-cookie', 'one=1; two=2; HTTPOnly'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=bar/)
expect(@request.options[:headers]['Cookie']).to match(/name=value/)
expect(@request.options[:headers]['Cookie']).to match(/one=1/)
expect(@request.options[:headers]['Cookie']).to match(/two=2/)
end
it 'should make resulting request a get request if it not already' do
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Get)
end
it 'should not make resulting request a get request if options[:maintain_method_across_redirects] is true' do
@request.options[:maintain_method_across_redirects] = true
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Delete)
end
it 'should log the redirection' do
logger_double = double
expect(logger_double).to receive(:info).twice
@request.options[:logger] = logger_double
@request.perform
end
end
describe "infinitely" do
before(:each) do
allow(@http).to receive(:request).and_return(@redirect)
end
it "should raise an exception" do
expect { @request.perform }.to raise_error(HTTParty::RedirectionTooDeep)
end
end
end
end
describe "a request that 303 redirects" do
before(:each) do
@redirect = stub_response("", 303)
@redirect['location'] = '/foo'
@ok = stub_response('<hash><foo>bar</foo></hash>', 200)
end
describe "once" do
before(:each) do
allow(@http).to receive(:request).and_return(@redirect, @ok)
end
it "should be handled by GET transparently" do
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by POST transparently" do
@request.http_method = Net::HTTP::Post
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by DELETE transparently" do
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by MOVE transparently" do
@request.http_method = Net::HTTP::Move
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by COPY transparently" do
@request.http_method = Net::HTTP::Copy
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by PATCH transparently" do
@request.http_method = Net::HTTP::Patch
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by PUT transparently" do
@request.http_method = Net::HTTP::Put
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by HEAD transparently" do
@request.http_method = Net::HTTP::Head
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by OPTIONS transparently" do
@request.http_method = Net::HTTP::Options
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by MKCOL transparently" do
@request.http_method = Net::HTTP::Mkcol
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by LOCK transparently" do
@request.http_method = Net::HTTP::Lock
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by UNLOCK transparently" do
@request.http_method = Net::HTTP::Unlock
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should keep track of cookies between redirects" do
@redirect['Set-Cookie'] = 'foo=bar; name=value; HTTPOnly'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=bar/)
expect(@request.options[:headers]['Cookie']).to match(/name=value/)
end
it 'should update cookies with redirects' do
@request.options[:headers] = {'Cookie' => 'foo=bar;'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=tar/)
end
it 'should keep cookies between redirects' do
@request.options[:headers] = {'Cookie' => 'keep=me'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/keep=me/)
end
it "should handle multiple Set-Cookie headers between redirects" do
@redirect.add_field 'set-cookie', 'foo=bar; name=value; HTTPOnly'
@redirect.add_field 'set-cookie', 'one=1; two=2; HTTPOnly'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=bar/)
expect(@request.options[:headers]['Cookie']).to match(/name=value/)
expect(@request.options[:headers]['Cookie']).to match(/one=1/)
expect(@request.options[:headers]['Cookie']).to match(/two=2/)
end
it 'should make resulting request a get request if it not already' do
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Get)
end
it 'should make resulting request a get request if options[:maintain_method_across_redirects] is false' do
@request.options[:maintain_method_across_redirects] = false
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Get)
end
it 'should make resulting request a get request if options[:maintain_method_across_redirects] is true but options[:resend_on_redirect] is false' do
@request.options[:maintain_method_across_redirects] = true
@request.options[:resend_on_redirect] = false
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Get)
end
it 'should not make resulting request a get request if options[:maintain_method_across_redirects] and options[:resend_on_redirect] is true' do
@request.options[:maintain_method_across_redirects] = true
@request.options[:resend_on_redirect] = true
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Delete)
end
it 'should log the redirection' do
logger_double = double
expect(logger_double).to receive(:info).twice
@request.options[:logger] = logger_double
@request.perform
end
end
describe "infinitely" do
before(:each) do
allow(@http).to receive(:request).and_return(@redirect)
end
it "should raise an exception" do
expect { @request.perform }.to raise_error(HTTParty::RedirectionTooDeep)
end
end
end
describe "a request that returns 304" do
before(:each) do
@redirect = stub_response("", 304)
@redirect['location'] = '/foo'
end
before(:each) do
allow(@http).to receive(:request).and_return(@redirect)
end
it "should report 304 with a GET request" do
expect(@request.perform.code).to eq(304)
end
it "should report 304 with a POST request" do
@request.http_method = Net::HTTP::Post
expect(@request.perform.code).to eq(304)
end
it "should report 304 with a DELETE request" do
@request.http_method = Net::HTTP::Delete
expect(@request.perform.code).to eq(304)
end
it "should report 304 with a MOVE request" do
@request.http_method = Net::HTTP::Move
expect(@request.perform.code).to eq(304)
end
it "should report 304 with a COPY request" do
@request.http_method = Net::HTTP::Copy
expect(@request.perform.code).to eq(304)
end
it "should report 304 with a PATCH request" do
@request.http_method = Net::HTTP::Patch
expect(@request.perform.code).to eq(304)
end
it "should report 304 with a PUT request" do
@request.http_method = Net::HTTP::Put
expect(@request.perform.code).to eq(304)
end
it "should report 304 with a HEAD request" do
@request.http_method = Net::HTTP::Head
expect(@request.perform.code).to eq(304)
end
it "should report 304 with a OPTIONS request" do
@request.http_method = Net::HTTP::Options
expect(@request.perform.code).to eq(304)
end
it "should report 304 with a MKCOL request" do
@request.http_method = Net::HTTP::Mkcol
expect(@request.perform.code).to eq(304)
end
it "should be handled by LOCK transparently" do
@request.http_method = Net::HTTP::Lock
expect(@request.perform.code).to eq(304)
end
it "should be handled by UNLOCK transparently" do
@request.http_method = Net::HTTP::Unlock
expect(@request.perform.code).to eq(304)
end
it 'should not log the redirection' do
logger_double = double
expect(logger_double).to receive(:info).once
@request.options[:logger] = logger_double
@request.perform
end
end
[307, 308].each do |code|
describe "a request that #{code} redirects" do
before(:each) do
@redirect = stub_response("", code)
@redirect['location'] = '/foo'
@ok = stub_response('<hash><foo>bar</foo></hash>', 200)
end
describe "once" do
before(:each) do
allow(@http).to receive(:request).and_return(@redirect, @ok)
end
it "should be handled by GET transparently" do
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by POST transparently" do
@request.http_method = Net::HTTP::Post
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by DELETE transparently" do
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by MOVE transparently" do
@request.http_method = Net::HTTP::Move
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by COPY transparently" do
@request.http_method = Net::HTTP::Copy
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by PATCH transparently" do
@request.http_method = Net::HTTP::Patch
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by PUT transparently" do
@request.http_method = Net::HTTP::Put
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by HEAD transparently" do
@request.http_method = Net::HTTP::Head
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by OPTIONS transparently" do
@request.http_method = Net::HTTP::Options
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by MKCOL transparently" do
@request.http_method = Net::HTTP::Mkcol
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by LOCK transparently" do
@request.http_method = Net::HTTP::Lock
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should be handled by UNLOCK transparently" do
@request.http_method = Net::HTTP::Unlock
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
end
it "should keep track of cookies between redirects" do
@redirect['Set-Cookie'] = 'foo=bar; name=value; HTTPOnly'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=bar/)
expect(@request.options[:headers]['Cookie']).to match(/name=value/)
end
it 'should update cookies with redirects' do
@request.options[:headers] = {'Cookie' => 'foo=bar;'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=tar/)
end
it 'should keep cookies between redirects' do
@request.options[:headers] = {'Cookie' => 'keep=me'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/keep=me/)
end
it "should handle multiple Set-Cookie headers between redirects" do
@redirect.add_field 'set-cookie', 'foo=bar; name=value; HTTPOnly'
@redirect.add_field 'set-cookie', 'one=1; two=2; HTTPOnly'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=bar/)
expect(@request.options[:headers]['Cookie']).to match(/name=value/)
expect(@request.options[:headers]['Cookie']).to match(/one=1/)
expect(@request.options[:headers]['Cookie']).to match(/two=2/)
end
it 'should maintain method in resulting request' do
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Delete)
end
it 'should maintain method in resulting request if options[:maintain_method_across_redirects] is false' do
@request.options[:maintain_method_across_redirects] = false
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Delete)
end
it 'should maintain method in resulting request if options[:maintain_method_across_redirects] is true' do
@request.options[:maintain_method_across_redirects] = true
@request.http_method = Net::HTTP::Delete
expect(@request.perform.parsed_response).to eq({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Delete)
end
it 'should log the redirection' do
logger_double = double
expect(logger_double).to receive(:info).twice
@request.options[:logger] = logger_double
@request.perform
end
end
describe "infinitely" do
before(:each) do
allow(@http).to receive(:request).and_return(@redirect)
end
it "should raise an exception" do
expect { @request.perform }.to raise_error(HTTParty::RedirectionTooDeep)
end
end
end
end
describe "#send_authorization_header?" do
context "basic_auth" do
before do
@credentials = { username: "username", password: "password" }
@authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
@request.options[:basic_auth] = @credentials
@redirect = stub_response("", 302)
@ok = stub_response('<hash><foo>bar</foo></hash>', 200)
end
before(:each) do
allow(@http).to receive(:request).and_return(@redirect, @ok)
end
it "should not send Authorization header when redirecting to a different host" do
@redirect['location'] = 'http://example.com/'
@request.perform
@request.send(:setup_raw_request)
expect(@request.instance_variable_get(:@raw_request)['authorization']).to be_nil
end
it "should send Authorization header when redirecting to a relative path" do
@redirect['location'] = '/v3'
@request.perform
@request.send(:setup_raw_request)
expect(@request.instance_variable_get(:@raw_request)['authorization']).to eq(@authorization)
end
it "should send Authorization header when redirecting to the same host" do
@redirect['location'] = 'http://api.foo.com/v2'
@request.perform
@request.send(:setup_raw_request)
expect(@request.instance_variable_get(:@raw_request)['authorization']).to eq(@authorization)
end
it "should send Authorization header when redirecting to a different port on the same host" do
@redirect['location'] = 'http://api.foo.com:3000/v3'
@request.perform
@request.send(:setup_raw_request)
expect(@request.instance_variable_get(:@raw_request)['authorization']).to eq(@authorization)
end
end
end
context "with POST http method" do
it "should raise argument error if query is not a hash" do
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', format: :xml, query: 'astring').perform
}.to raise_error(ArgumentError)
end
end
describe "argument validation" do
it "should raise argument error if basic_auth and digest_auth are both present" do
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', basic_auth: {}, digest_auth: {}).perform
}.to raise_error(ArgumentError, "only one authentication method, :basic_auth or :digest_auth may be used at a time")
end
it "should raise argument error if basic_auth is not a hash" do
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', basic_auth: %w(foo bar)).perform
}.to raise_error(ArgumentError, ":basic_auth must be a hash")
end
it "should raise argument error if digest_auth is not a hash" do
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', digest_auth: %w(foo bar)).perform
}.to raise_error(ArgumentError, ":digest_auth must be a hash")
end
it "should raise argument error if headers is not a hash" do
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', headers: %w(foo bar)).perform
}.to raise_error(ArgumentError, ":headers must be a hash")
end
it "should raise argument error if options method is not http accepted method" do
expect {
HTTParty::Request.new('SuperPost', 'http://api.foo.com/v1').perform
}.to raise_error(ArgumentError, "only get, post, patch, put, delete, head, and options methods are supported")
end
it "should raise argument error if http method is post and query is not hash" do
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', query: "message: hello").perform
}.to raise_error(ArgumentError, ":query must be hash if using HTTP Post")
end
it "should raise RedirectionTooDeep error if limit is negative" do
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', limit: -1).perform
}.to raise_error(HTTParty::RedirectionTooDeep, 'HTTP redirects too deep')
end
end
context 'Net::HTTP decompression' do
subject(:raw_request) do
request = HTTParty::Request.new(Net::HTTP::Get, 'http://api.foo.com/v1', headers.merge(options))
request.send(:setup_raw_request)
request.instance_variable_get(:@raw_request)
end
shared_examples 'sets custom Accept-Encoding' do
it { expect(subject['Accept-Encoding']).to eq('custom') }
end
shared_examples 'sets default Accept-Encoding' do
it { expect(subject['Accept-Encoding']).to eq('gzip;q=1.0,deflate;q=0.6,identity;q=0.3') }
end
shared_examples 'enables Net::HTTP decompression' do
it { expect(subject.decode_content).to eq(true) }
end
shared_examples 'disables Net::HTTP decompression' do
it { expect(subject.decode_content).to eq(false) }
end
context 'with skip_decompression false (default)' do
let(:options) { {} }
context 'with Accept-Encoding specified' do
let(:headers) { { headers: { 'Accept-Encoding' => 'custom' } } }
it_behaves_like 'sets custom Accept-Encoding'
it_behaves_like 'enables Net::HTTP decompression'
end
context 'with accept-encoding (lowercase) specified' do
let(:headers) { { headers: { 'accept-encoding' => 'custom' } } }
it_behaves_like 'sets custom Accept-Encoding'
it_behaves_like 'enables Net::HTTP decompression'
end
context 'with Accept-Encoding and other headers specified' do
let(:headers) { { headers: { 'Accept-Encoding' => 'custom', 'Content-Type' => 'application/json' } } }
it_behaves_like 'sets custom Accept-Encoding'
it_behaves_like 'enables Net::HTTP decompression'
end
context 'with other headers specified' do
let(:headers) { { 'Content-Type' => 'application/json' } }
it_behaves_like 'sets default Accept-Encoding'
it_behaves_like 'enables Net::HTTP decompression'
end
context 'with no headers specified' do
let(:headers) { {} }
it_behaves_like 'sets default Accept-Encoding'
it_behaves_like 'enables Net::HTTP decompression'
end
end
context 'with skip_decompression true' do
let(:options) { { skip_decompression: true } }
context 'with Accept-Encoding specified' do
let(:headers) { { headers: { 'Accept-Encoding' => 'custom' } } }
it_behaves_like 'sets custom Accept-Encoding'
it_behaves_like 'disables Net::HTTP decompression'
end
context 'with accept-encoding (lowercase) specified' do
let(:headers) { { headers: { 'accept-encoding' => 'custom' } } }
it_behaves_like 'sets custom Accept-Encoding'
it_behaves_like 'disables Net::HTTP decompression'
end
context 'with Accept-Encoding and other headers specified' do
let(:headers) { { headers: { 'Accept-Encoding' => 'custom', 'Content-Type' => 'application/json' } } }
it_behaves_like 'sets custom Accept-Encoding'
it_behaves_like 'disables Net::HTTP decompression'
end
context 'with other headers specified' do
let(:headers) { { 'Content-Type' => 'application/json' } }
it_behaves_like 'sets default Accept-Encoding'
it_behaves_like 'disables Net::HTTP decompression'
end
context 'with no headers specified' do
let(:headers) { {} }
it_behaves_like 'sets default Accept-Encoding'
it_behaves_like 'disables Net::HTTP decompression'
end
end
end
describe "marshalling" do
it "properly marshals the request object" do
MarshalFakeResponse = Struct.new(:body) do
def marshal_dump
{
"body" => body,
}
end
def marshal_load(hash)
self.body = hash["body"]
end
end
@request.last_uri = URI("http://api.foo.com/v1")
@request.last_response = MarshalFakeResponse.new("body")
@request.instance_variable_set("@raw_request", @request.http_method.new(URI("http://api.foo.com/v1")))
marshalled = Marshal.load(Marshal.dump(@request))
expect(marshalled.http_method).to eq @request.http_method
expect(marshalled.path).to eq @request.path
expect(marshalled.options).to eq @request.options
expect(marshalled.last_response.body).to eq "body"
expect(marshalled.last_uri).to eq URI("http://api.foo.com/v1")
expect(marshalled.instance_variable_get("@raw_request").path).to eq "/v1"
end
end
end
|