gds-api-adapters 38.1.0 → 39.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. checksums.yaml +4 -4
  2. data/lib/gds_api/test_helpers/need_api.rb +0 -15
  3. data/lib/gds_api/test_helpers/organisations.rb +5 -0
  4. data/lib/gds_api/version.rb +1 -1
  5. metadata +3 -103
  6. data/test/asset_manager_test.rb +0 -94
  7. data/test/business_support_api_test.rb +0 -45
  8. data/test/content_api_test.rb +0 -712
  9. data/test/content_store_test.rb +0 -55
  10. data/test/email_alert_api_test.rb +0 -189
  11. data/test/fixtures/finder_api/cma-case-schema.json +0 -103
  12. data/test/fixtures/hello.txt +0 -1
  13. data/test/fixtures/new_policies_for_dwp.json +0 -298
  14. data/test/fixtures/no_services_and_info_data_found_fixture.json +0 -14
  15. data/test/fixtures/old_policies_for_dwp.json +0 -413
  16. data/test/fixtures/services_and_info_fixture.json +0 -73
  17. data/test/fixtures/sub_sector_organisations.json +0 -57
  18. data/test/fixtures/world_organisations_australia.json +0 -490
  19. data/test/gds_api_base_test.rb +0 -110
  20. data/test/gov_uk_delivery_test.rb +0 -67
  21. data/test/govuk_headers_test.rb +0 -30
  22. data/test/helpers_test.rb +0 -23
  23. data/test/imminence_api_test.rb +0 -196
  24. data/test/json_client_test.rb +0 -879
  25. data/test/licence_application_api_test.rb +0 -196
  26. data/test/list_response_test.rb +0 -189
  27. data/test/local_links_manager_api_test.rb +0 -236
  28. data/test/mapit_test.rb +0 -117
  29. data/test/maslow_test.rb +0 -12
  30. data/test/middleware/govuk_header_sniffer_test.rb +0 -18
  31. data/test/need_api_test.rb +0 -345
  32. data/test/organisations_api_test.rb +0 -58
  33. data/test/panopticon_registerer_test.rb +0 -118
  34. data/test/panopticon_test.rb +0 -190
  35. data/test/pp_data_in_test.rb +0 -52
  36. data/test/pp_data_out_test.rb +0 -24
  37. data/test/publishing_api/special_route_publisher_test.rb +0 -104
  38. data/test/publishing_api_test.rb +0 -186
  39. data/test/publishing_api_v2/get_expanded_links_test.rb +0 -85
  40. data/test/publishing_api_v2/get_links_test.rb +0 -89
  41. data/test/publishing_api_v2/lookup_test.rb +0 -70
  42. data/test/publishing_api_v2_test.rb +0 -1649
  43. data/test/response_test.rb +0 -245
  44. data/test/router_test.rb +0 -456
  45. data/test/rummager_helpers_test.rb +0 -20
  46. data/test/rummager_test.rb +0 -150
  47. data/test/support_api_test.rb +0 -189
  48. data/test/support_test.rb +0 -95
  49. data/test/test_helper.rb +0 -55
  50. data/test/test_helpers/email_alert_api_test.rb +0 -24
  51. data/test/test_helpers/pact_helper.rb +0 -13
  52. data/test/test_helpers/panopticon_test.rb +0 -44
  53. data/test/test_helpers/publishing_api_test.rb +0 -129
  54. data/test/test_helpers/publishing_api_v2_test.rb +0 -170
  55. data/test/worldwide_api_test.rb +0 -82
@@ -1,110 +0,0 @@
1
- require 'test_helper'
2
- require 'gds_api/base'
3
- require 'uri'
4
-
5
- class GdsApiBaseTest < Minitest::Test
6
- class ConcreteApi < GdsApi::Base
7
- def base_url
8
- endpoint
9
- end
10
- end
11
-
12
- def setup
13
- @orig_cache = GdsApi::JsonClient.cache
14
- end
15
-
16
- def teardown
17
- GdsApi::Base.default_options = nil
18
- GdsApi::JsonClient.cache = @orig_cache
19
- end
20
-
21
- def test_should_construct_escaped_query_string
22
- api = ConcreteApi.new('http://foo')
23
- url = api.url_for_slug("slug", "a" => " ", "b" => "/")
24
- u = URI.parse(url)
25
- assert_equal "a=+&b=%2F", u.query
26
- end
27
-
28
- def test_should_construct_escaped_query_string_for_rails
29
- api = ConcreteApi.new('http://foo')
30
-
31
- url = api.url_for_slug("slug", "b" => ['123'])
32
- u = URI.parse(url)
33
- assert_equal "b%5B%5D=123", u.query
34
-
35
- url = api.url_for_slug("slug", "b" => %w(123 456))
36
- u = URI.parse(url)
37
- assert_equal "b%5B%5D=123&b%5B%5D=456", u.query
38
- end
39
-
40
- def test_should_not_add_a_question_mark_if_there_are_no_parameters
41
- api = ConcreteApi.new('http://foo')
42
- url = api.url_for_slug("slug")
43
- refute_match(/\?/, url)
44
- end
45
-
46
- def test_should_use_endpoint_in_url
47
- api = ConcreteApi.new("http://foobarbaz")
48
- url = api.url_for_slug("slug")
49
- u = URI.parse(url)
50
- assert_match(/foobarbaz$/, u.host)
51
- end
52
-
53
- def test_should_accept_options_as_second_arg
54
- api = ConcreteApi.new("http://foo", foo: "bar")
55
- assert_equal "bar", api.options[:foo]
56
- end
57
-
58
- def test_setting_cache_size_from_options
59
- GdsApi::JsonClient.cache = false
60
- api = ConcreteApi.new("https://foo", cache_size: 2)
61
- assert_equal 2, api.client.cache.max_size
62
- end
63
-
64
- def test_setting_cache_size_from_default_options
65
- GdsApi::JsonClient.cache = false
66
- GdsApi::Base.default_options = { cache_size: 4 }
67
- api = ConcreteApi.new("http://bar")
68
- assert_equal 4, api.client.cache.max_size
69
- end
70
-
71
- def test_disabling_cache
72
- # Ensure that there is a non-null cache by default
73
- GdsApi::JsonClient.cache = true
74
- api = ConcreteApi.new("http://bar", disable_cache: true)
75
- assert api.client.cache.is_a? GdsApi::NullCache
76
- end
77
-
78
- def test_disabling_cache_old_style
79
- # Ensure that there is a non-null cache by default
80
- GdsApi::JsonClient.cache = true
81
- api = ConcreteApi.new("http://bar", cache_size: 0)
82
- assert api.client.cache.is_a? GdsApi::NullCache
83
- end
84
-
85
- def test_should_barf_if_not_given_valid_url
86
- assert_raises GdsApi::Base::InvalidAPIURL do
87
- ConcreteApi.new('invalid-url')
88
- end
89
- end
90
-
91
- def test_should_set_json_client_logger_to_own_logger_by_default
92
- api = ConcreteApi.new("http://bar")
93
- assert_same GdsApi::Base.logger, api.client.logger
94
- end
95
-
96
- def test_should_set_json_client_logger_to_logger_in_default_options
97
- custom_logger = stub('custom-logger')
98
- GdsApi::Base.default_options = { logger: custom_logger }
99
- api = ConcreteApi.new("http://bar")
100
- assert_same custom_logger, api.client.logger
101
- end
102
-
103
- def test_should_set_json_client_logger_to_logger_in_options
104
- custom_logger = stub('custom-logger')
105
- GdsApi::Base.default_options = { logger: custom_logger }
106
- another_logger = stub('another-logger')
107
- api = ConcreteApi.new("http://bar", logger: another_logger)
108
- assert_same another_logger, api.client.logger
109
- end
110
- end
@@ -1,67 +0,0 @@
1
- require 'test_helper'
2
- require 'gds_api/gov_uk_delivery'
3
- require 'gds_api/test_helpers/gov_uk_delivery'
4
-
5
- describe GdsApi::GovUkDelivery do
6
- include GdsApi::TestHelpers::GovUkDelivery
7
-
8
- before do
9
- @base_api_url = Plek.current.find("govuk-delivery")
10
- @api = GdsApi::GovUkDelivery.new(@base_api_url)
11
- end
12
-
13
- it "can create a topic" do
14
- expected_payload = { feed_url: 'http://example.com/feed', title: 'Title', description: nil }
15
- stub = stub_gov_uk_delivery_post_request('lists', expected_payload).to_return(created_response_hash)
16
-
17
- assert @api.topic("http://example.com/feed", "Title")
18
- assert_requested stub
19
- end
20
-
21
- it "can subscribe a new email" do
22
- expected_payload = { email: 'me@example.com', feed_urls: ['http://example.com/feed'] }
23
- stub = stub_gov_uk_delivery_post_request('subscriptions', expected_payload).to_return(created_response_hash)
24
-
25
- assert @api.subscribe('me@example.com', ['http://example.com/feed'])
26
- assert_requested stub
27
- end
28
-
29
- it "can post a notification" do
30
- expected_payload = { feed_urls: ['http://example.com/feed'], subject: 'Test', body: '<p>Something</p>' }
31
- stub = stub_gov_uk_delivery_post_request('notifications', expected_payload).to_return(created_response_hash)
32
-
33
- assert @api.notify(['http://example.com/feed'], 'Test', '<p>Something</p>')
34
- assert_requested stub
35
- end
36
-
37
- it "can get a subscription URL" do
38
- expected_payload = { feed_url: 'http://example.com/feed' }
39
- stub = stub_gov_uk_delivery_get_request('list-url', expected_payload).to_return(created_response_json_hash(list_url: 'thing'))
40
-
41
- assert @api.signup_url('http://example.com/feed')
42
- assert_requested stub
43
- end
44
-
45
- it "raises if the API 404s" do
46
- expected_payload = { feed_url: 'http://example.com/feed' }
47
- stub_gov_uk_delivery_get_request('list-url', expected_payload).to_return(not_found_hash)
48
-
49
- assert_raises(GdsApi::HTTPNotFound) do
50
- @api.signup_url('http://example.com/feed')
51
- end
52
- end
53
-
54
- private
55
-
56
- def created_response_hash
57
- { body: '', status: 201 }
58
- end
59
-
60
- def not_found_hash
61
- { body: '', status: 404 }
62
- end
63
-
64
- def created_response_json_hash(data)
65
- { body: data.to_json, status: 201 }
66
- end
67
- end
@@ -1,30 +0,0 @@
1
- require_relative "test_helper"
2
- require "gds_api/govuk_headers"
3
-
4
- describe GdsApi::GovukHeaders do
5
- before :each do
6
- Thread.current[:headers] = nil if Thread.current[:headers]
7
- end
8
-
9
- after :each do
10
- GdsApi::GovukHeaders.clear_headers
11
- end
12
-
13
- it "supports read/write of headers" do
14
- GdsApi::GovukHeaders.set_header("GDS-Request-Id", "123-456")
15
- GdsApi::GovukHeaders.set_header("Content-Type", "application/pdf")
16
-
17
- assert_equal({
18
- "GDS-Request-Id" => "123-456",
19
- "Content-Type" => "application/pdf",
20
- }, GdsApi::GovukHeaders.headers)
21
- end
22
-
23
- it "supports clearing of headers" do
24
- GdsApi::GovukHeaders.set_header("GDS-Request-Id", "123-456")
25
-
26
- GdsApi::GovukHeaders.clear_headers
27
-
28
- assert_equal({}, GdsApi::GovukHeaders.headers)
29
- end
30
- end
@@ -1,23 +0,0 @@
1
- require 'test_helper'
2
- require 'gds_api/helpers'
3
-
4
- describe GdsApi::Helpers do
5
- class TestDouble
6
- include GdsApi::Helpers
7
- end
8
-
9
- it "should define helpers for the various apis" do
10
- test_with_helpers = TestDouble.new
11
-
12
- refute_nil test_with_helpers.asset_manager_api
13
- refute_nil test_with_helpers.business_support_api
14
- refute_nil test_with_helpers.content_api
15
- refute_nil test_with_helpers.content_store
16
- refute_nil test_with_helpers.imminence_api
17
- refute_nil test_with_helpers.licence_application_api
18
- refute_nil test_with_helpers.need_api
19
- refute_nil test_with_helpers.panopticon_api
20
- refute_nil test_with_helpers.worldwide_api
21
- refute_nil test_with_helpers.email_alert_api
22
- end
23
- end
@@ -1,196 +0,0 @@
1
- require "test_helper"
2
- require "gds_api/imminence"
3
-
4
- class ImminenceApiTest < Minitest::Test
5
- ROOT = "https://imminence.test.alphagov.co.uk".freeze
6
- LATITUDE = 52.1327584352089
7
- LONGITUDE = -0.4702813074674147
8
-
9
- def api_client
10
- GdsApi::Imminence.new(ROOT)
11
- end
12
-
13
- def dummy_place
14
- {
15
- "access_notes" => nil,
16
- "address1" => "Cauldwell Street",
17
- "address2" => "Bedford",
18
- "fax" => nil,
19
- "general_notes" => nil,
20
- "geocode_error" => nil,
21
- "location" => [LATITUDE, LONGITUDE],
22
- "name" => "Town Hall",
23
- "phone" => nil,
24
- "postcode" => "MK42 9AP",
25
- "source_address" => "Town Hall, Cauldwell Street, Bedford",
26
- "text_phone" => nil,
27
- "town" => nil,
28
- "url" => "http://www.bedford.gov.uk/advice_and_benefits/registration_service.aspx"
29
- }
30
- end
31
-
32
- def test_no_second_address_line
33
- c = api_client
34
- url = "#{ROOT}/places/wibble.json?limit=5&lat=52&lng=0"
35
- place_info = dummy_place.merge "address2" => nil
36
- c.expects(:get_json).with(url).returns([place_info])
37
- places = c.places("wibble", 52, 0)
38
-
39
- assert_equal 1, places.size
40
- assert_equal "Cauldwell Street", places[0]["address"]
41
- end
42
-
43
- def test_search_for_places
44
- c = api_client
45
- url = "#{ROOT}/places/wibble.json?limit=5&lat=52&lng=0"
46
- c.expects(:get_json).with(url).returns([dummy_place])
47
- places = c.places("wibble", 52, 0)
48
-
49
- assert_equal 1, places.size
50
- place = places[0]
51
- assert_equal LATITUDE, place["latitude"]
52
- assert_equal LONGITUDE, place["longitude"]
53
- assert_equal "Cauldwell Street, Bedford", place["address"]
54
- end
55
-
56
- def test_empty_location
57
- # Test behaviour when the location field is an empty array
58
- c = api_client
59
- url = "#{ROOT}/places/wibble.json?limit=5&lat=52&lng=0"
60
- place_info = dummy_place.merge("location" => [])
61
- c.expects(:get_json).with(url).returns([place_info])
62
- places = c.places("wibble", 52, 0)
63
-
64
- assert_equal 1, places.size
65
- place = places[0]
66
- assert_nil place["latitude"]
67
- assert_nil place["longitude"]
68
- end
69
-
70
- def test_nil_location
71
- # Test behaviour when the location field is nil
72
- c = api_client
73
- url = "#{ROOT}/places/wibble.json?limit=5&lat=52&lng=0"
74
- place_info = dummy_place.merge("location" => nil)
75
- c.expects(:get_json).with(url).returns([place_info])
76
- places = c.places("wibble", 52, 0)
77
-
78
- assert_equal 1, places.size
79
- place = places[0]
80
- assert_nil place["latitude"]
81
- assert_nil place["longitude"]
82
- end
83
-
84
- def test_hash_location
85
- # Test behaviour when the location field is a longitude/latitude hash
86
- c = api_client
87
- url = "#{ROOT}/places/wibble.json?limit=5&lat=52&lng=0"
88
- place_info = dummy_place.merge(
89
- "location" => { "longitude" => LONGITUDE, "latitude" => LATITUDE }
90
- )
91
- c.expects(:get_json).with(url).returns([place_info])
92
- places = c.places("wibble", 52, 0)
93
-
94
- assert_equal 1, places.size
95
- place = places[0]
96
- assert_equal LATITUDE, place["latitude"]
97
- assert_equal LONGITUDE, place["longitude"]
98
- end
99
-
100
- def test_postcode_search
101
- # Test behaviour when searching by postcode
102
- c = api_client
103
- url = "#{ROOT}/places/wibble.json?limit=5&postcode=MK42+9AA"
104
- c.expects(:get_json).with(url).returns([dummy_place])
105
- places = c.places_for_postcode("wibble", "MK42 9AA")
106
-
107
- assert_equal 1, places.size
108
- end
109
-
110
- def test_invalid_postcode_search
111
- # Test behaviour when searching by invalid postcode
112
- c = api_client
113
- url = "#{ROOT}/places/wibble.json?limit=5&postcode=MK99+9AA"
114
- c.expects(:get_json).with(url).raises(GdsApi::HTTPErrorResponse.new(400))
115
- assert_raises GdsApi::HTTPErrorResponse do
116
- c.places_for_postcode("wibble", "MK99 9AA")
117
- end
118
- end
119
-
120
- def test_places_kml
121
- kml_body = <<-EOS
122
- <?xml version="1.0" encoding="UTF-8"?>
123
- <kml xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
124
- <Document>
125
- <name>DVLA Offices</name>
126
- <Placemark>
127
- <atom:link/>
128
- <name>DVLA Aberdeen local office</name>
129
- <description>For enquiries about vehicles: 0300 790 6802 (Textphone minicom users 0300 123 1279).For enquiries about driving licences: 0300 790 6801 (Textphone minicom users 0300 123 1278).Please note, all calls are handled initially by our call centre based in Swansea</description>
130
- <address>Greyfriars House, Gallowgate, Aberdeen, AB10 1WG, UK</address>
131
- <Point>
132
- <coordinates>-2.0971999005177566,57.150739708305785,0</coordinates>
133
- </Point>
134
- </Placemark>
135
- </document>
136
- </kml>
137
- EOS
138
-
139
- stub_request(:get, "#{ROOT}/places/test.kml").
140
- with(headers: GdsApi::JsonClient.default_request_headers).
141
- to_return(status: 200, body: kml_body)
142
-
143
- response_body = api_client.places_kml("test")
144
- assert_equal kml_body, response_body
145
- end
146
-
147
- def test_areas_for_postcode
148
- areas = [
149
- { "id" => 12, "type" => "LBO", "name" => "Westminster City Council", "country_name" => "England" },
150
- { "id" => 66, "type" => "EUR", "name" => "London", "country_name" => "England" }
151
- ]
152
- results = {
153
- "_response_info" => { "status" => "ok" },
154
- "total" => areas.size, "startIndex" => 1, "pageSize" => areas.size,
155
- "currentPage" => 1, "pages" => 1, "results" => areas
156
- }
157
-
158
- stub_request(:get, "#{ROOT}/areas/WC2B%206SE.json").
159
- with(headers: GdsApi::JsonClient.default_request_headers).
160
- to_return(status: 200, body: results.to_json)
161
-
162
- response = api_client.areas_for_postcode("WC2B 6SE")
163
-
164
- assert_equal "ok", response["_response_info"]["status"]
165
- areas_from_response = response["results"]
166
- assert_equal 2, areas_from_response.size
167
- assert_equal "LBO", areas_from_response.first["type"]
168
- assert_equal 12, areas_from_response.first["id"]
169
- end
170
-
171
- def test_areas_by_type
172
- areas = [
173
- { "id" => 122, "type" => "EUR", "name" => "Yorkshire and the Humber", "country_name" => "England" },
174
- { "id" => 665, "type" => "EUR", "name" => "London", "country_name" => "England" }
175
- ]
176
- results = {
177
- "_response_info" => { "status" => "ok" },
178
- "total" => areas.size, "startIndex" => 1, "pageSize" => areas.size,
179
- "currentPage" => 1, "pages" => 1, "results" => areas
180
- }
181
-
182
- stub_request(:get, "#{ROOT}/areas/EUR.json").
183
- with(headers: GdsApi::JsonClient.default_request_headers).
184
- to_return(status: 200, body: results.to_json)
185
-
186
- response = api_client.areas_for_type("EUR")
187
-
188
- assert_equal "ok", response["_response_info"]["status"]
189
- areas_from_response = response["results"]
190
- assert_equal 2, areas_from_response.size
191
- assert_equal "EUR", areas_from_response.first["type"]
192
- assert_equal "EUR", areas_from_response.last["type"]
193
- assert_equal 122, areas_from_response.first["id"]
194
- assert_equal 665, areas_from_response.last["id"]
195
- end
196
- end
@@ -1,879 +0,0 @@
1
- require_relative 'test_helper'
2
- require 'gds_api/base'
3
- require 'gds_api/json_client'
4
- require 'base64'
5
- require 'null_logger'
6
-
7
- class JsonClientTest < MiniTest::Spec
8
- def setup
9
- @json_client_cache = GdsApi::JsonClient.cache
10
-
11
- # Set the cache to nil so the JsonClient recreates it on each test run
12
- # This used to initialise the cache to an empty Hash, eliminating the
13
- # potential problem of cache entries expiring during a test run, but that
14
- # no longer works now our code calls the `store` method with an expiry time
15
- GdsApi::JsonClient.cache = nil
16
-
17
- @client = GdsApi::JsonClient.new
18
-
19
- WebMock.disable_net_connect!
20
- end
21
-
22
- def teardown
23
- super
24
- GdsApi::JsonClient.cache = @json_client_cache
25
- end
26
-
27
- def options;
28
- {}
29
- end
30
-
31
- def test_long_get_requests_timeout
32
- url = "http://www.example.com/timeout.json"
33
- stub_request(:get, url).to_timeout
34
- assert_raises GdsApi::TimedOutException do
35
- @client.get_json(url)
36
- end
37
- end
38
-
39
- def test_long_connections_timeout
40
- url = "http://www.example.com/timeout.json"
41
- exception = defined?(Net::OpenTimeout) ? Net::OpenTimeout : TimeoutError
42
- stub_request(:get, url).to_raise(exception)
43
- assert_raises GdsApi::TimedOutException do
44
- @client.get_json(url)
45
- end
46
- end
47
-
48
- def test_request_an_invalid_url
49
- url = "http://www.example.com/there-is-a-space-in-this-slug /"
50
- assert_raises GdsApi::InvalidUrl do
51
- @client.get_json(url)
52
- end
53
- end
54
-
55
- def test_get_should_raise_endpoint_not_found_if_connection_refused
56
- url = "http://some.endpoint/some.json"
57
- stub_request(:get, url).to_raise(Errno::ECONNREFUSED)
58
- assert_raises GdsApi::EndpointNotFound do
59
- @client.get_json(url)
60
- end
61
- end
62
-
63
- def test_post_should_raise_endpoint_not_found_if_connection_refused
64
- url = "http://some.endpoint/some.json"
65
- stub_request(:get, url).to_raise(Errno::ECONNREFUSED)
66
- assert_raises GdsApi::EndpointNotFound do
67
- @client.get_json(url)
68
- end
69
- end
70
-
71
- def test_post_requests_timeout
72
- url = "http://some.endpoint/some.json"
73
- stub_request(:post, url).to_timeout
74
- assert_raises GdsApi::TimedOutException do
75
- @client.post_json(url, {})
76
- end
77
- end
78
-
79
- def test_get_should_raise_error_on_restclient_error
80
- url = "http://some.endpoint/some.json"
81
- stub_request(:get, url).to_raise(RestClient::ServerBrokeConnection)
82
- assert_raises GdsApi::HTTPErrorResponse do
83
- @client.get_json(url)
84
- end
85
- end
86
-
87
- def test_should_fetch_and_parse_json_into_response
88
- url = "http://some.endpoint/some.json"
89
- stub_request(:get, url).to_return(body: "{}", status: 200)
90
- assert_equal GdsApi::Response, @client.get_json(url).class
91
- end
92
-
93
- def test_should_cache_multiple_requests_to_same_url_across_instances
94
- url = "http://some.endpoint/some.json"
95
- result = { "foo" => "bar" }
96
- stub_request(:get, url).to_return(body: JSON.dump(result), status: 200)
97
- response_a = GdsApi::JsonClient.new.get_json(url)
98
- response_b = GdsApi::JsonClient.new.get_json(url)
99
- assert_equal response_a.to_hash, response_b.to_hash
100
- assert_requested :get, url, times: 1
101
- end
102
-
103
- def test_allow_overriding_the_number_of_cached_items
104
- # Clear out the default cache instance, because otherwise the customisation
105
- # doesn't take effect, due to some non-obvious behaviour in JsonClient.
106
- GdsApi::JsonClient.cache = nil
107
-
108
- url = "http://some.endpoint/"
109
-
110
- stub_request(:get, %r{\A#{url}}).to_return do |request|
111
- { body: { "url" => request.uri }.to_json, status: 200 }
112
- end
113
-
114
- response_a = GdsApi::JsonClient.new(cache_size: 5).get_json("#{url}/first.json")
115
- response_b = GdsApi::JsonClient.new.get_json("#{url}/second.json")
116
- 4.times { |n| GdsApi::JsonClient.new.get_json("#{url}/#{n}.json") }
117
-
118
- response_c = GdsApi::JsonClient.new.get_json("#{url}/second.json")
119
- response_d = GdsApi::JsonClient.new.get_json("#{url}/first.json")
120
-
121
- assert_requested :get, "#{url}/second.json", times: 1
122
- assert_requested :get, "#{url}/first.json", times: 2
123
- assert_equal response_b.to_hash, response_c.to_hash
124
- assert_equal response_a.to_hash, response_d.to_hash
125
- end
126
-
127
- def test_should_cache_requests_for_15_mins_by_default
128
- url = "http://some.endpoint/some.json"
129
- result = { "foo" => "bar" }
130
- stub_request(:get, url).to_return(body: JSON.dump(result), status: 200)
131
- response_a = GdsApi::JsonClient.new.get_json(url)
132
- response_b = GdsApi::JsonClient.new.get_json(url)
133
-
134
- assert_requested :get, url, times: 1
135
- assert_equal response_a.to_hash, response_b.to_hash
136
-
137
- Timecop.travel(15 * 60 - 30) do # now + 14 mins 30 secs
138
- response_c = GdsApi::JsonClient.new.get_json(url)
139
-
140
- assert_requested :get, url, times: 1
141
- assert_equal response_a.to_hash, response_c.to_hash
142
- end
143
-
144
- Timecop.travel(15 * 60 + 30) do # now + 15 mins 30 secs
145
- response_d = GdsApi::JsonClient.new.get_json(url)
146
-
147
- assert_requested :get, url, times: 2
148
- assert_equal response_a.to_hash, response_d.to_hash
149
- end
150
- end
151
-
152
- def test_should_allow_overriding_cache_ttl
153
- # Clear out the default cache instance, because otherwise the customisation
154
- # doesn't take effect, due to some non-obvious behaviour in JsonClient.
155
- GdsApi::JsonClient.cache = nil
156
-
157
- url = "http://some.endpoint/some.json"
158
- result = { "foo" => "bar" }
159
- stub_request(:get, url).to_return(body: JSON.dump(result), status: 200)
160
- response_a = GdsApi::JsonClient.new(cache_ttl: 5 * 60).get_json(url)
161
- response_b = GdsApi::JsonClient.new.get_json(url)
162
-
163
- assert_requested :get, url, times: 1
164
- assert_equal response_a.to_hash, response_b.to_hash
165
-
166
- Timecop.travel(5 * 60 - 30) do # now + 4 mins 30 secs
167
- response_c = GdsApi::JsonClient.new.get_json(url)
168
-
169
- assert_requested :get, url, times: 1
170
- assert_equal response_a.to_hash, response_c.to_hash
171
- end
172
-
173
- Timecop.travel(5 * 60 + 30) do # now + 5 mins 30 secs
174
- response_d = GdsApi::JsonClient.new.get_json(url)
175
-
176
- assert_requested :get, url, times: 2
177
- assert_equal response_a.to_hash, response_d.to_hash
178
- end
179
- end
180
-
181
- def test_should_allow_disabling_caching
182
- url = "http://some.endpoint/some.json"
183
- result = { "foo" => "bar" }
184
- stub_request(:get, url).to_return(body: JSON.dump(result), status: 200)
185
-
186
- client = GdsApi::JsonClient.new(disable_cache: true)
187
-
188
- response_a = client.get_json(url)
189
- response_b = client.get_json(url)
190
-
191
- assert_requested :get, url, times: 2
192
-
193
- [response_a, response_b].each do |r|
194
- assert_equal result, r.to_hash
195
- end
196
- end
197
-
198
- def test_should_respect_expiry_headers
199
- url = "http://some.endpoint/some.json"
200
- result = { "foo" => "bar" }
201
- stub_request(:get, url).to_return(
202
- body: JSON.dump(result),
203
- status: 200,
204
- headers: { "Expires" => (Time.now + 7 * 60).utc.httpdate }
205
- )
206
-
207
- response_a = GdsApi::JsonClient.new.get_json(url)
208
-
209
- Timecop.travel(7 * 60 - 30) do # now + 6 mins 30 secs
210
- response_b = GdsApi::JsonClient.new.get_json(url)
211
-
212
- assert_requested :get, url, times: 1
213
- assert_equal response_a.to_hash, response_b.to_hash
214
- end
215
-
216
- Timecop.travel(7 * 60 + 30) do # now + 7 mins 30 secs
217
- response_c = GdsApi::JsonClient.new.get_json(url)
218
-
219
- assert_requested :get, url, times: 2
220
- assert_equal response_a.to_hash, response_c.to_hash
221
- end
222
- end
223
-
224
- def test_should_respect_cache_control_headers_with_max_age
225
- url = "http://some.endpoint/max_age.json"
226
- result = { "foo" => "bar" }
227
- stub_request(:get, url).to_return(
228
- body: JSON.dump(result),
229
- status: 200,
230
- headers: { "Cache-Control" => "max-age=420, public" } # 7 minutes
231
- )
232
-
233
- response_a = GdsApi::JsonClient.new.get_json(url)
234
-
235
- Timecop.travel(7 * 60 - 30) do # now + 6 mins 30 secs
236
- response_b = GdsApi::JsonClient.new.get_json(url)
237
-
238
- assert_requested :get, url, times: 1
239
- assert_equal response_a.to_hash, response_b.to_hash
240
- end
241
-
242
- Timecop.travel(7 * 60 + 30) do # now + 7 mins 30 secs
243
- response_c = GdsApi::JsonClient.new.get_json(url)
244
-
245
- assert_requested :get, url, times: 2
246
- assert_equal response_a.to_hash, response_c.to_hash
247
- end
248
- end
249
-
250
- def test_should_respect_cache_control_headers_with_no_cache
251
- url = "http://some.endpoint/no_cache.json"
252
- result = { "foo" => "bar" }
253
- stub_request(:get, url).to_return(
254
- body: JSON.dump(result),
255
- status: 200,
256
- headers: { "Cache-Control" => "no-cache, public" }
257
- )
258
-
259
- response_a = GdsApi::JsonClient.new.get_json(url)
260
-
261
- Timecop.travel(7 * 60 - 30) do # now + 6 mins 30 secs
262
- response_b = GdsApi::JsonClient.new.get_json(url)
263
-
264
- assert_requested :get, url, times: 2
265
- assert_equal response_a.to_hash, response_b.to_hash
266
- end
267
- end
268
-
269
- def test_does_not_cache_responses_with_cache_control_private
270
- url = "http://some.endpoint/private.json"
271
- result = { "foo" => "bar" }
272
- stub_request(:get, url).to_return(
273
- body: JSON.dump(result),
274
- status: 200,
275
- headers: { "Cache-Control" => "max-age=600, private" }
276
- )
277
-
278
- response_a = GdsApi::JsonClient.new.get_json(url)
279
-
280
- Timecop.travel(7 * 60 - 30) do # now + 6 mins 30 secs
281
- response_b = GdsApi::JsonClient.new.get_json(url)
282
-
283
- assert_requested :get, url, times: 2
284
- assert_equal response_a.to_hash, response_b.to_hash
285
- end
286
- end
287
-
288
- def test_does_not_cache_responses_with_cache_control_no_store
289
- url = "http://some.endpoint/private.json"
290
- result = { "foo" => "bar" }
291
- stub_request(:get, url).to_return(
292
- body: JSON.dump(result),
293
- status: 200,
294
- headers: { "Cache-Control" => "max-age=600, no-store" }
295
- )
296
-
297
- response_a = GdsApi::JsonClient.new.get_json(url)
298
-
299
- Timecop.travel(7 * 60 - 30) do # now + 6 mins 30 secs
300
- response_b = GdsApi::JsonClient.new.get_json(url)
301
-
302
- assert_requested :get, url, times: 2
303
- assert_equal response_a.to_hash, response_b.to_hash
304
- end
305
- end
306
-
307
- def test_should_respect_cache_control_headers_with_no_cache_and_max_age
308
- url = "http://some.endpoint/no_cache_and_max_age.json"
309
- result = { "foo" => "bar" }
310
- stub_request(:get, url).to_return(
311
- body: JSON.dump(result),
312
- status: 200,
313
- headers: { "Cache-Control" => "max-age=600, no-cache, public" }
314
- )
315
-
316
- response_a = GdsApi::JsonClient.new.get_json(url)
317
-
318
- Timecop.travel(7 * 60 - 30) do # now + 6 mins 30 secs
319
- response_b = GdsApi::JsonClient.new.get_json(url)
320
-
321
- assert_requested :get, url, times: 2
322
- assert_equal response_a.to_hash, response_b.to_hash
323
- end
324
- end
325
-
326
- def test_should_use_cache_control_headers_over_expires_headers
327
- url = "http://some.endpoint/url.json"
328
- result = { "foo" => "bar" }
329
- stub_request(:get, url).to_return(
330
- body: JSON.dump(result),
331
- status: 200,
332
- headers: {
333
- "Cache-Control" => "no-cache",
334
- "Expires" => (Time.now + 7 * 60).utc.httpdate
335
- }
336
- )
337
-
338
- response_a = GdsApi::JsonClient.new.get_json(url)
339
-
340
- Timecop.travel(7 * 60 - 30) do # now + 6 mins 30 secs
341
- response_b = GdsApi::JsonClient.new.get_json(url)
342
-
343
- assert_requested :get, url, times: 2
344
- assert_equal response_a.to_hash, response_b.to_hash
345
- end
346
- end
347
-
348
- def test_should_fallback_to_expires_headers_if_cache_control_is_malformed
349
- url = "http://some.endpoint/url.json"
350
- result = { "foo" => "bar" }
351
- stub_request(:get, url).to_return(
352
- body: JSON.dump(result),
353
- status: 200,
354
- headers: {
355
- "Cache-Control" => "foo, bar, baz",
356
- "Expires" => (Time.now + 7 * 60).utc.httpdate
357
- }
358
- )
359
-
360
- response_a = GdsApi::JsonClient.new.get_json(url)
361
-
362
- Timecop.travel(7 * 60 - 30) do # now + 6 mins 30 secs
363
- response_b = GdsApi::JsonClient.new.get_json(url)
364
-
365
- assert_requested :get, url, times: 1
366
- assert_equal response_a.to_hash, response_b.to_hash
367
- end
368
- end
369
-
370
- def test_get_bang_should_raise_http_not_found_if_404_returned_from_endpoint
371
- url = "http://some.endpoint/some.json"
372
- stub_request(:get, url).to_return(body: "{}", status: 404)
373
- assert_raises GdsApi::HTTPNotFound do
374
- @client.get_json(url)
375
- end
376
- end
377
-
378
- def test_get_bang_should_raise_http_gone_if_410_returned_from_endpoint
379
- url = "http://some.endpoint/some.json"
380
- stub_request(:get, url).to_return(body: "{}", status: 410)
381
- assert_raises GdsApi::HTTPGone do
382
- @client.get_json(url)
383
- end
384
- end
385
-
386
- def test_get_bang_should_raise_http_forbidden_if_403_returned_from_endpoint
387
- url = "http://some.endpoint/some.json"
388
- stub_request(:get, url).to_return(body: "{}", status: 403)
389
- assert_raises GdsApi::HTTPForbidden do
390
- @client.get_json(url)
391
- end
392
- end
393
-
394
- def test_get_should_raise_if_404_returned_from_endpoint
395
- url = "http://some.endpoint/some.json"
396
- stub_request(:get, url).to_return(body: "{}", status: 404)
397
- assert_raises GdsApi::HTTPNotFound do
398
- @client.get_json(url)
399
- end
400
- end
401
-
402
- def test_get_should_raise_if_410_returned_from_endpoint
403
- url = "http://some.endpoint/some.json"
404
- stub_request(:get, url).to_return(body: "{}", status: 410)
405
- assert_raises GdsApi::HTTPGone do
406
- @client.get_json(url)
407
- end
408
- end
409
-
410
- def test_get_raw_should_raise_if_404_returned_from_endpoint
411
- url = "http://some.endpoint/some.json"
412
- stub_request(:get, url).to_return(body: "{}", status: 404)
413
- assert_raises GdsApi::HTTPNotFound do
414
- @client.get_raw(url)
415
- end
416
- end
417
-
418
- def test_get_raw_should_be_nil_if_410_returned_from_endpoint
419
- url = "http://some.endpoint/some.json"
420
- stub_request(:get, url).to_return(body: "{}", status: 410)
421
- assert_raises GdsApi::HTTPGone do
422
- @client.get_raw(url)
423
- end
424
- end
425
-
426
- def test_get_should_raise_error_if_non_404_non_410_error_code_returned_from_endpoint
427
- url = "http://some.endpoint/some.json"
428
- stub_request(:get, url).to_return(body: "{}", status: 500)
429
- assert_raises GdsApi::HTTPServerError do
430
- @client.get_json(url)
431
- end
432
- end
433
-
434
- def test_get_should_raise_conflict_for_409
435
- url = "http://some.endpoint/some.json"
436
- stub_request(:delete, url).to_return(body: "{}", status: 409)
437
- assert_raises GdsApi::HTTPConflict do
438
- @client.delete_json(url)
439
- end
440
- end
441
-
442
- def test_get_should_follow_permanent_redirect
443
- url = "http://some.endpoint/some.json"
444
- new_url = "http://some.endpoint/other.json"
445
- stub_request(:get, url).to_return(
446
- body: "",
447
- status: 301,
448
- headers: { "Location" => new_url }
449
- )
450
- stub_request(:get, new_url).to_return(body: '{"a": 1}', status: 200)
451
- result = @client.get_json(url)
452
- assert_equal 1, result['a']
453
- end
454
-
455
- def test_get_should_follow_found_redirect
456
- url = "http://some.endpoint/some.json"
457
- new_url = "http://some.endpoint/other.json"
458
- stub_request(:get, url).to_return(
459
- body: "",
460
- status: 302,
461
- headers: { "Location" => new_url }
462
- )
463
- stub_request(:get, new_url).to_return(body: '{"a": 1}', status: 200)
464
- result = @client.get_json(url)
465
- assert_equal 1, result['a']
466
- end
467
-
468
- def test_get_should_follow_see_other
469
- url = "http://some.endpoint/some.json"
470
- new_url = "http://some.endpoint/other.json"
471
- stub_request(:get, url).to_return(
472
- body: "",
473
- status: 303,
474
- headers: { "Location" => new_url }
475
- )
476
- stub_request(:get, new_url).to_return(body: '{"a": 1}', status: 200)
477
- result = @client.get_json(url)
478
- assert_equal 1, result['a']
479
- end
480
-
481
- def test_get_should_follow_temporary_redirect
482
- url = "http://some.endpoint/some.json"
483
- new_url = "http://some.endpoint/other.json"
484
- stub_request(:get, url).to_return(
485
- body: "",
486
- status: 307,
487
- headers: { "Location" => new_url }
488
- )
489
- stub_request(:get, new_url).to_return(body: '{"a": 1}', status: 200)
490
- result = @client.get_json(url)
491
- assert_equal 1, result['a']
492
- end
493
-
494
- def test_should_handle_infinite_redirects
495
- url = "http://some.endpoint/some.json"
496
- redirect = {
497
- body: "",
498
- status: 302,
499
- headers: { "Location" => url }
500
- }
501
-
502
- # Theoretically, we could set this up to mock out any number of requests
503
- # with a redirect to the same URL, but we'd risk getting the test code into
504
- # an infinite loop if the code didn't do what it was supposed to. The
505
- # failure response block aborts the test if we have too many requests.
506
- failure = lambda { |_request| flunk("Request called too many times") }
507
- stub_request(:get, url).to_return(redirect).times(11).then.to_return(failure)
508
-
509
- assert_raises GdsApi::HTTPErrorResponse do
510
- @client.get_json(url)
511
- end
512
- end
513
-
514
- def test_should_handle_mutual_redirects
515
- first_url = "http://some.endpoint/some.json"
516
- second_url = "http://some.endpoint/some-other.json"
517
-
518
- first_redirect = {
519
- body: "",
520
- status: 302,
521
- headers: { "Location" => second_url }
522
- }
523
- second_redirect = {
524
- body: "",
525
- status: 302,
526
- headers: { "Location" => first_url }
527
- }
528
-
529
- # See the comment in the above test for an explanation of this
530
- failure = lambda { |_request| flunk("Request called too many times") }
531
- stub_request(:get, first_url).to_return(first_redirect).times(6).then.to_return(failure)
532
- stub_request(:get, second_url).to_return(second_redirect).times(6).then.to_return(failure)
533
-
534
- assert_raises GdsApi::HTTPErrorResponse do
535
- @client.get_json(first_url)
536
- end
537
- end
538
-
539
- def test_post_should_be_raise_if_404_returned_from_endpoint
540
- url = "http://some.endpoint/some.json"
541
- stub_request(:post, url).to_return(body: "{}", status: 404)
542
- assert_raises(GdsApi::HTTPNotFound) do
543
- @client.post_json(url, {})
544
- end
545
- end
546
-
547
- def test_post_should_raise_error_if_non_404_error_code_returned_from_endpoint
548
- url = "http://some.endpoint/some.json"
549
- stub_request(:post, url).to_return(body: "{}", status: 500)
550
- assert_raises GdsApi::HTTPServerError do
551
- @client.post_json(url, {})
552
- end
553
- end
554
-
555
- def test_post_should_error_on_found_redirect
556
- url = "http://some.endpoint/some.json"
557
- new_url = "http://some.endpoint/other.json"
558
- stub_request(:post, url).to_return(
559
- body: "",
560
- status: 302,
561
- headers: { "Location" => new_url }
562
- )
563
- assert_raises GdsApi::HTTPErrorResponse do
564
- @client.post_json(url, {})
565
- end
566
- end
567
-
568
- def test_put_should_be_raise_if_404_returned_from_endpoint
569
- url = "http://some.endpoint/some.json"
570
- stub_request(:put, url).to_return(body: "{}", status: 404)
571
-
572
- assert_raises(GdsApi::HTTPNotFound) do
573
- @client.put_json(url, {})
574
- end
575
- end
576
-
577
- def test_put_should_raise_error_if_non_404_error_code_returned_from_endpoint
578
- url = "http://some.endpoint/some.json"
579
- stub_request(:put, url).to_return(body: "{}", status: 500)
580
- assert_raises GdsApi::HTTPServerError do
581
- @client.put_json(url, {})
582
- end
583
- end
584
-
585
- def empty_response
586
- net_http_response = stub(body: '{}')
587
- GdsApi::Response.new(net_http_response)
588
- end
589
-
590
- def test_put_json_does_put_with_json_encoded_packet
591
- url = "http://some.endpoint/some.json"
592
- payload = { a: 1 }
593
- stub_request(:put, url).with(body: payload.to_json).to_return(body: "{}", status: 200)
594
- assert_equal({}, @client.put_json(url, payload).to_hash)
595
- end
596
-
597
- def test_does_not_encode_json_if_payload_is_nil
598
- url = "http://some.endpoint/some.json"
599
- stub_request(:put, url).with(body: nil).to_return(body: "{}", status: 200)
600
- assert_equal({}, @client.put_json(url, nil).to_hash)
601
- end
602
-
603
- def test_can_build_custom_response_object
604
- url = "http://some.endpoint/some.json"
605
- stub_request(:get, url).to_return(body: "Hello there!")
606
-
607
- response = @client.get_json(url, &:body)
608
- assert response.is_a? String
609
- assert_equal "Hello there!", response
610
- end
611
-
612
- def test_raises_on_custom_response_404
613
- url = "http://some.endpoint/some.json"
614
- stub_request(:get, url).to_return(body: "", status: 404)
615
-
616
- assert_raises(GdsApi::HTTPNotFound) do
617
- @client.get_json(url, &:body)
618
- end
619
- end
620
-
621
- def test_can_build_custom_response_object_in_bang_method
622
- url = "http://some.endpoint/some.json"
623
- stub_request(:get, url).to_return(body: "Hello there!")
624
-
625
- response = @client.get_json(url, &:body)
626
- assert response.is_a? String
627
- assert_equal "Hello there!", response
628
- end
629
-
630
- def test_can_access_attributes_of_response_directly
631
- url = "http://some.endpoint/some.json"
632
- payload = { a: 1 }
633
- stub_request(:put, url).with(body: payload.to_json).to_return(body: '{"a":{"b":2}}', status: 200)
634
- response = @client.put_json(url, payload)
635
- assert_equal 2, response['a']['b']
636
- end
637
-
638
- def test_a_response_is_always_considered_present_and_not_blank
639
- url = "http://some.endpoint/some.json"
640
- stub_request(:put, url).to_return(body: '{"a":1}', status: 200)
641
- response = @client.put_json(url, {})
642
- assert ! response.blank?
643
- assert response.present?
644
- end
645
-
646
- def test_client_can_use_basic_auth
647
- client = GdsApi::JsonClient.new(basic_auth: { user: 'user', password: 'password' })
648
-
649
- stub_request(:put, "http://user:password@some.endpoint/some.json").
650
- to_return(body: '{"a":1}', status: 200)
651
-
652
- response = client.put_json("http://some.endpoint/some.json", {})
653
- assert_equal 1, response['a']
654
- end
655
-
656
- def test_client_can_use_bearer_token
657
- client = GdsApi::JsonClient.new(bearer_token: 'SOME_BEARER_TOKEN')
658
- expected_headers = GdsApi::JsonClient.default_request_with_json_body_headers.
659
- merge('Authorization' => 'Bearer SOME_BEARER_TOKEN')
660
-
661
- stub_request(:put, "http://some.other.endpoint/some.json").
662
- with(headers: expected_headers).
663
- to_return(body: '{"a":2}', status: 200)
664
-
665
- response = client.put_json("http://some.other.endpoint/some.json", {})
666
- assert_equal 2, response['a']
667
- end
668
-
669
- def test_client_can_set_custom_headers_on_gets
670
- stub_request(:get, "http://some.other.endpoint/some.json").to_return(status: 200)
671
-
672
- GdsApi::JsonClient.new.get_json("http://some.other.endpoint/some.json",
673
- "HEADER-A" => "B", "HEADER-C" => "D")
674
-
675
- assert_requested(:get, %r{/some.json}) do |request|
676
- headers_with_uppercase_names = Hash[request.headers.collect { |key, value| [key.upcase, value] }]
677
- headers_with_uppercase_names["HEADER-A"] == "B" && headers_with_uppercase_names["HEADER-C"] == "D"
678
- end
679
- end
680
-
681
- def test_client_can_set_custom_headers_on_posts
682
- stub_request(:post, "http://some.other.endpoint/some.json").to_return(status: 200)
683
-
684
- GdsApi::JsonClient.new.post_json("http://some.other.endpoint/some.json", {},
685
- "HEADER-A" => "B", "HEADER-C" => "D")
686
-
687
- assert_requested(:post, %r{/some.json}) do |request|
688
- headers_with_uppercase_names = Hash[request.headers.collect { |key, value| [key.upcase, value] }]
689
- headers_with_uppercase_names["HEADER-A"] == "B" && headers_with_uppercase_names["HEADER-C"] == "D"
690
- end
691
- end
692
-
693
- def test_client_can_set_custom_headers_on_puts
694
- stub_request(:put, "http://some.other.endpoint/some.json").to_return(status: 200)
695
-
696
- GdsApi::JsonClient.new.put_json("http://some.other.endpoint/some.json", {},
697
- "HEADER-A" => "B", "HEADER-C" => "D")
698
-
699
- assert_requested(:put, %r{/some.json}) do |request|
700
- headers_with_uppercase_names = Hash[request.headers.collect { |key, value| [key.upcase, value] }]
701
- headers_with_uppercase_names["HEADER-A"] == "B" && headers_with_uppercase_names["HEADER-C"] == "D"
702
- end
703
- end
704
-
705
- def test_client_can_set_custom_headers_on_deletes
706
- stub_request(:delete, "http://some.other.endpoint/some.json").to_return(status: 200)
707
-
708
- GdsApi::JsonClient.new.delete_json("http://some.other.endpoint/some.json",
709
- "HEADER-A" => "B", "HEADER-C" => "D")
710
-
711
- assert_requested(:delete, %r{/some.json}) do |request|
712
- headers_with_uppercase_names = Hash[request.headers.collect { |key, value| [key.upcase, value] }]
713
- headers_with_uppercase_names["HEADER-A"] == "B" && headers_with_uppercase_names["HEADER-C"] == "D"
714
- end
715
- end
716
-
717
- def test_govuk_headers_are_included_in_requests_if_present
718
- # set headers which would be set by middleware GovukHeaderSniffer
719
- GdsApi::GovukHeaders.set_header(:govuk_request_id, "12345")
720
- GdsApi::GovukHeaders.set_header(:govuk_original_url, "http://example.com")
721
-
722
- stub_request(:get, "http://some.other.endpoint/some.json").to_return(status: 200)
723
-
724
- GdsApi::JsonClient.new.get_json("http://some.other.endpoint/some.json")
725
-
726
- assert_requested(:get, %r{/some.json}) do |request|
727
- request.headers['Govuk-Request-Id'] == '12345' &&
728
- request.headers['Govuk-Original-Url'] == 'http://example.com'
729
- end
730
- end
731
-
732
- def test_govuk_headers_ignored_in_requests_if_not_present
733
- GdsApi::GovukHeaders.set_header(:x_govuk_authenticated_user, "")
734
- stub_request(:get, "http://some.other.endpoint/some.json").to_return(status: 200)
735
-
736
- GdsApi::JsonClient.new.get_json("http://some.other.endpoint/some.json")
737
-
738
- assert_requested(:get, %r{/some.json}) do |request|
739
- !request.headers.has_key?('X-Govuk-Authenticated-User')
740
- end
741
- end
742
-
743
- def test_additional_headers_passed_in_do_not_get_modified
744
- stub_request(:get, "http://some.other.endpoint/some.json").to_return(status: 200)
745
-
746
- headers = { 'HEADER-A' => 'A' }
747
- GdsApi::JsonClient.new.get_json("http://some.other.endpoint/some.json", headers)
748
-
749
- assert_equal({ 'HEADER-A' => 'A' }, headers)
750
- end
751
-
752
- def test_client_can_decompress_gzip_responses
753
- url = "http://some.endpoint/some.json"
754
- # {"test": "hello"}
755
- stub_request(:get, url).to_return(
756
- body: "\u001F\x8B\b\u0000Q\u000F\u0019Q\u0000\u0003\xABVP*I-.Q\xB2RP\xCAH\xCD\xC9\xC9WR\xA8\u0005\u0000\xD1C\u0018\xFE\u0013\u0000\u0000\u0000",
757
- status: 200,
758
- headers: { 'Content-Encoding' => 'gzip' }
759
- )
760
- response = @client.get_json(url)
761
-
762
- assert_equal "hello", response["test"]
763
- end
764
-
765
- def test_client_can_post_multipart_responses
766
- url = "http://some.endpoint/some.json"
767
- stub_request(:post, url).
768
- with(body: %r{------RubyFormBoundary\w+\r\nContent-Disposition: form-data; name="a"\r\n\r\n123\r\n------RubyFormBoundary\w+--\r\n},
769
- headers: {
770
- 'Content-Type' => %r{multipart/form-data; boundary=----RubyFormBoundary\w+}
771
- }).
772
- to_return(body: '{"b": "1"}', status: 200)
773
-
774
- response = @client.post_multipart("http://some.endpoint/some.json", "a" => "123")
775
- assert_equal "1", response["b"]
776
- end
777
-
778
- def test_post_multipart_should_raise_exception_if_not_found
779
- url = "http://some.endpoint/some.json"
780
- stub_request(:post, url).to_return(body: '', status: 404)
781
-
782
- assert_raises GdsApi::HTTPNotFound do
783
- @client.post_multipart("http://some.endpoint/some.json", "a" => "123")
784
- end
785
- end
786
-
787
- def test_post_multipart_should_raise_error_responses
788
- url = "http://some.endpoint/some.json"
789
- stub_request(:post, url).to_return(body: '', status: 500)
790
-
791
- assert_raises GdsApi::HTTPServerError do
792
- @client.post_multipart("http://some.endpoint/some.json", "a" => "123")
793
- end
794
- end
795
-
796
- # EXACTLY the same as the post_multipart tests
797
- def test_client_can_put_multipart_responses
798
- url = "http://some.endpoint/some.json"
799
- stub_request(:put, url).
800
- with(body: %r{------RubyFormBoundary\w+\r\nContent-Disposition: form-data; name="a"\r\n\r\n123\r\n------RubyFormBoundary\w+--\r\n},
801
- headers: {
802
- 'Content-Type' => %r{multipart/form-data; boundary=----RubyFormBoundary\w+}
803
- }).
804
- to_return(body: '{"b": "1"}', status: 200)
805
-
806
- response = @client.put_multipart("http://some.endpoint/some.json", "a" => "123")
807
- assert_equal "1", response["b"]
808
- end
809
-
810
- def test_put_multipart_should_raise_exception_if_not_found
811
- url = "http://some.endpoint/some.json"
812
- stub_request(:put, url).to_return(body: '', status: 404)
813
-
814
- assert_raises GdsApi::HTTPNotFound do
815
- @client.put_multipart("http://some.endpoint/some.json", "a" => "123")
816
- end
817
- end
818
-
819
- def test_put_multipart_should_raise_error_responses
820
- url = "http://some.endpoint/some.json"
821
- stub_request(:put, url).to_return(body: '', status: 500)
822
-
823
- assert_raises GdsApi::HTTPServerError do
824
- @client.put_multipart("http://some.endpoint/some.json", "a" => "123")
825
- end
826
- end
827
-
828
- def test_should_raise_error_if_attempting_to_disable_timeout
829
- assert_raises RuntimeError do
830
- GdsApi::JsonClient.new(disable_timeout: true)
831
- end
832
- assert_raises RuntimeError do
833
- GdsApi::JsonClient.new(timeout: -1)
834
- end
835
- end
836
-
837
- def test_should_add_user_agent_using_env
838
- previous_govuk_app_name = ENV['GOVUK_APP_NAME']
839
- ENV['GOVUK_APP_NAME'] = "api-tests"
840
-
841
- url = "http://some.other.endpoint/some.json"
842
- stub_request(:get, url).to_return(status: 200)
843
-
844
- GdsApi::JsonClient.new.get_json(url)
845
-
846
- assert_requested(:get, %r{/some.json}) do |request|
847
- request.headers["User-Agent"] == "gds-api-adapters/#{GdsApi::VERSION} (api-tests)"
848
- end
849
- ensure
850
- ENV['GOVUK_APP_NAME'] = previous_govuk_app_name
851
- end
852
-
853
- def test_should_default_to_using_null_logger
854
- assert_same @client.logger, NullLogger.instance
855
- end
856
-
857
- def test_should_use_custom_logger_specified_in_options
858
- custom_logger = stub('custom-logger')
859
- client = GdsApi::JsonClient.new(logger: custom_logger)
860
- assert_same client.logger, custom_logger
861
- end
862
-
863
- def test_should_avoid_content_type_header_on_get_without_body
864
- url = "http://some.endpoint/some.json"
865
- stub_request(:any, url)
866
-
867
- @client.get_json(url)
868
- assert_requested(:get, url, headers: GdsApi::JsonClient.default_request_headers)
869
-
870
- @client.delete_json(url)
871
- assert_requested(:delete, url, headers: GdsApi::JsonClient.default_request_headers)
872
-
873
- @client.post_json(url, test: "123")
874
- assert_requested(:post, url, headers: GdsApi::JsonClient.default_request_with_json_body_headers)
875
-
876
- @client.put_json(url, test: "123")
877
- assert_requested(:put, url, headers: GdsApi::JsonClient.default_request_with_json_body_headers)
878
- end
879
- end