mockserver-client 1.0.8.pre → 5.3.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (123) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +5 -1
  3. data/Gemfile.lock +79 -0
  4. data/README.md +89 -229
  5. data/Rakefile +8 -8
  6. data/docs/Body.md +7 -0
  7. data/docs/BodyWithContentType.md +7 -0
  8. data/docs/ConnectionOptions.md +12 -0
  9. data/docs/ControlApi.md +269 -0
  10. data/docs/Delay.md +9 -0
  11. data/docs/Expectation.md +7 -0
  12. data/docs/ExpectationApi.md +51 -0
  13. data/docs/Expectations.md +7 -0
  14. data/docs/HttpClassCallback.md +8 -0
  15. data/docs/HttpError.md +10 -0
  16. data/docs/HttpForward.md +11 -0
  17. data/docs/HttpObjectCallback.md +8 -0
  18. data/docs/HttpOverrideForwardedRequest.md +9 -0
  19. data/docs/HttpRequest.md +15 -0
  20. data/docs/HttpResponse.md +14 -0
  21. data/docs/HttpTemplate.md +10 -0
  22. data/docs/KeyToMultiValue.md +7 -0
  23. data/docs/KeyToValue.md +7 -0
  24. data/docs/Ports.md +8 -0
  25. data/docs/TimeToLive.md +10 -0
  26. data/docs/Times.md +9 -0
  27. data/docs/Verification.md +9 -0
  28. data/docs/VerificationSequence.md +8 -0
  29. data/docs/VerificationTimes.md +9 -0
  30. data/docs/VerifyApi.md +94 -0
  31. data/lib/mockserver-client.rb +62 -15
  32. data/lib/mockserver-client/api/control_api.rb +316 -0
  33. data/lib/mockserver-client/api/expectation_api.rb +73 -0
  34. data/lib/mockserver-client/api/verify_api.rb +127 -0
  35. data/lib/mockserver-client/api_client.rb +388 -0
  36. data/lib/mockserver-client/api_error.rb +38 -0
  37. data/lib/mockserver-client/configuration.rb +202 -0
  38. data/lib/mockserver-client/models/body.rb +174 -0
  39. data/lib/mockserver-client/models/body_with_content_type.rb +174 -0
  40. data/lib/mockserver-client/models/connection_options.rb +219 -0
  41. data/lib/mockserver-client/models/delay.rb +192 -0
  42. data/lib/mockserver-client/models/expectation.rb +174 -0
  43. data/lib/mockserver-client/models/expectations.rb +174 -0
  44. data/lib/mockserver-client/models/http_class_callback.rb +183 -0
  45. data/lib/mockserver-client/models/http_error.rb +201 -0
  46. data/lib/mockserver-client/models/http_forward.rb +244 -0
  47. data/lib/mockserver-client/models/http_object_callback.rb +183 -0
  48. data/lib/mockserver-client/models/http_override_forwarded_request.rb +192 -0
  49. data/lib/mockserver-client/models/http_request.rb +246 -0
  50. data/lib/mockserver-client/models/http_response.rb +237 -0
  51. data/lib/mockserver-client/models/http_template.rb +235 -0
  52. data/lib/mockserver-client/models/key_to_multi_value.rb +174 -0
  53. data/lib/mockserver-client/models/key_to_value.rb +174 -0
  54. data/lib/mockserver-client/models/ports.rb +185 -0
  55. data/lib/mockserver-client/models/time_to_live.rb +235 -0
  56. data/lib/mockserver-client/models/times.rb +192 -0
  57. data/lib/mockserver-client/models/verification.rb +192 -0
  58. data/lib/mockserver-client/models/verification_sequence.rb +185 -0
  59. data/lib/mockserver-client/models/verification_times.rb +192 -0
  60. data/lib/mockserver-client/version.rb +15 -0
  61. data/mockserver-client.gemspec +44 -36
  62. data/spec/api/control_api_spec.rb +102 -0
  63. data/spec/api/expectation_api_spec.rb +46 -0
  64. data/spec/api/verify_api_spec.rb +57 -0
  65. data/spec/api_client_spec.rb +226 -0
  66. data/spec/configuration_spec.rb +42 -0
  67. data/spec/models/body_spec.rb +35 -0
  68. data/spec/models/body_with_content_type_spec.rb +35 -0
  69. data/spec/models/connection_options_spec.rb +65 -0
  70. data/spec/models/delay_spec.rb +47 -0
  71. data/spec/models/expectation_spec.rb +35 -0
  72. data/spec/models/expectations_spec.rb +35 -0
  73. data/spec/models/http_class_callback_spec.rb +41 -0
  74. data/spec/models/http_error_spec.rb +53 -0
  75. data/spec/models/http_forward_spec.rb +63 -0
  76. data/spec/models/http_object_callback_spec.rb +41 -0
  77. data/spec/models/http_override_forwarded_request_spec.rb +47 -0
  78. data/spec/models/http_request_spec.rb +83 -0
  79. data/spec/models/http_response_spec.rb +77 -0
  80. data/spec/models/http_template_spec.rb +57 -0
  81. data/spec/models/key_to_multi_value_spec.rb +35 -0
  82. data/spec/models/key_to_value_spec.rb +35 -0
  83. data/spec/models/ports_spec.rb +41 -0
  84. data/spec/models/time_to_live_spec.rb +57 -0
  85. data/spec/models/times_spec.rb +47 -0
  86. data/spec/models/verification_sequence_spec.rb +41 -0
  87. data/spec/models/verification_spec.rb +47 -0
  88. data/spec/models/verification_times_spec.rb +47 -0
  89. data/spec/spec_helper.rb +103 -53
  90. metadata +225 -158
  91. data/.gitignore +0 -21
  92. data/.rubocop.yml +0 -7
  93. data/bin/mockserver +0 -9
  94. data/lib/cli.rb +0 -146
  95. data/lib/mockserver/abstract_client.rb +0 -111
  96. data/lib/mockserver/mock_server_client.rb +0 -46
  97. data/lib/mockserver/model/array_of.rb +0 -85
  98. data/lib/mockserver/model/body.rb +0 -56
  99. data/lib/mockserver/model/cookie.rb +0 -36
  100. data/lib/mockserver/model/delay.rb +0 -34
  101. data/lib/mockserver/model/enum.rb +0 -47
  102. data/lib/mockserver/model/expectation.rb +0 -139
  103. data/lib/mockserver/model/forward.rb +0 -41
  104. data/lib/mockserver/model/header.rb +0 -43
  105. data/lib/mockserver/model/parameter.rb +0 -43
  106. data/lib/mockserver/model/request.rb +0 -81
  107. data/lib/mockserver/model/response.rb +0 -45
  108. data/lib/mockserver/model/times.rb +0 -61
  109. data/lib/mockserver/proxy_client.rb +0 -9
  110. data/lib/mockserver/utility_methods.rb +0 -59
  111. data/lib/mockserver/version.rb +0 -5
  112. data/pom.xml +0 -118
  113. data/spec/fixtures/forward_mockserver.json +0 -7
  114. data/spec/fixtures/incorrect_login_response.json +0 -20
  115. data/spec/fixtures/post_login_request.json +0 -22
  116. data/spec/fixtures/register_expectation.json +0 -50
  117. data/spec/fixtures/retrieved_request.json +0 -22
  118. data/spec/fixtures/search_request.json +0 -6
  119. data/spec/fixtures/times_once.json +0 -6
  120. data/spec/integration/mock_client_integration_spec.rb +0 -82
  121. data/spec/mockserver/builder_spec.rb +0 -90
  122. data/spec/mockserver/mock_client_spec.rb +0 -80
  123. data/spec/mockserver/proxy_client_spec.rb +0 -38
@@ -0,0 +1,73 @@
1
+ =begin
2
+ #Mock Server API
3
+
4
+ #MockServer enables easy mocking of any system you integrate with via HTTP or HTTPS with clients written in Java, JavaScript and Ruby and a simple REST API (as shown below). MockServer Proxy is a proxy that introspects all proxied traffic including encrypted SSL traffic and supports Port Forwarding, Web Proxying (i.e. HTTP proxy), HTTPS Tunneling Proxying (using HTTP CONNECT) and SOCKS Proxying (i.e. dynamic port forwarding). Both MockServer and the MockServer Proxy record all received requests so that it is possible to verify exactly what requests have been sent by the system under test.
5
+
6
+ OpenAPI spec version: 5.3.0
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ OpenAPI Generator version: 3.3.1
10
+
11
+ =end
12
+
13
+ require 'uri'
14
+
15
+ module MockServer
16
+ class ExpectationApi
17
+ attr_accessor :api_client
18
+
19
+ def initialize(api_client = ApiClient.default)
20
+ @api_client = api_client
21
+ end
22
+ # create expectation
23
+ # @param expectations expectation to create
24
+ # @param [Hash] opts the optional parameters
25
+ # @return [nil]
26
+ def expectation_put(expectations, opts = {})
27
+ expectation_put_with_http_info(expectations, opts)
28
+ nil
29
+ end
30
+
31
+ # create expectation
32
+ # @param expectations expectation to create
33
+ # @param [Hash] opts the optional parameters
34
+ # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers
35
+ def expectation_put_with_http_info(expectations, opts = {})
36
+ if @api_client.config.debugging
37
+ @api_client.config.logger.debug 'Calling API: ExpectationApi.expectation_put ...'
38
+ end
39
+ # verify the required parameter 'expectations' is set
40
+ if @api_client.config.client_side_validation && expectations.nil?
41
+ fail ArgumentError, "Missing the required parameter 'expectations' when calling ExpectationApi.expectation_put"
42
+ end
43
+ # resource path
44
+ local_var_path = '/expectation'
45
+
46
+ # query parameters
47
+ query_params = {}
48
+
49
+ # header parameters
50
+ header_params = {}
51
+ # HTTP header 'Content-Type'
52
+ header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
53
+
54
+ # form parameters
55
+ form_params = {}
56
+
57
+ # http body (model)
58
+ post_body = @api_client.object_to_http_body(expectations)
59
+ auth_names = []
60
+ data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
61
+ :header_params => header_params,
62
+ :query_params => query_params,
63
+ :form_params => form_params,
64
+ :body => post_body,
65
+ :auth_names => auth_names)
66
+ if @api_client.config.debugging
67
+ @api_client.config.logger.debug "API called: ExpectationApi#expectation_put\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
68
+ end
69
+ return data, status_code, headers
70
+ end
71
+
72
+ end
73
+ end
@@ -0,0 +1,127 @@
1
+ =begin
2
+ #Mock Server API
3
+
4
+ #MockServer enables easy mocking of any system you integrate with via HTTP or HTTPS with clients written in Java, JavaScript and Ruby and a simple REST API (as shown below). MockServer Proxy is a proxy that introspects all proxied traffic including encrypted SSL traffic and supports Port Forwarding, Web Proxying (i.e. HTTP proxy), HTTPS Tunneling Proxying (using HTTP CONNECT) and SOCKS Proxying (i.e. dynamic port forwarding). Both MockServer and the MockServer Proxy record all received requests so that it is possible to verify exactly what requests have been sent by the system under test.
5
+
6
+ OpenAPI spec version: 5.3.0
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ OpenAPI Generator version: 3.3.1
10
+
11
+ =end
12
+
13
+ require 'uri'
14
+
15
+ module MockServer
16
+ class VerifyApi
17
+ attr_accessor :api_client
18
+
19
+ def initialize(api_client = ApiClient.default)
20
+ @api_client = api_client
21
+ end
22
+ # verify a request has been received a specific number of times
23
+ # @param verification request matcher and the number of times to match
24
+ # @param [Hash] opts the optional parameters
25
+ # @return [nil]
26
+ def verify_put(verification, opts = {})
27
+ verify_put_with_http_info(verification, opts)
28
+ nil
29
+ end
30
+
31
+ # verify a request has been received a specific number of times
32
+ # @param verification request matcher and the number of times to match
33
+ # @param [Hash] opts the optional parameters
34
+ # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers
35
+ def verify_put_with_http_info(verification, opts = {})
36
+ if @api_client.config.debugging
37
+ @api_client.config.logger.debug 'Calling API: VerifyApi.verify_put ...'
38
+ end
39
+ # verify the required parameter 'verification' is set
40
+ if @api_client.config.client_side_validation && verification.nil?
41
+ fail ArgumentError, "Missing the required parameter 'verification' when calling VerifyApi.verify_put"
42
+ end
43
+ # resource path
44
+ local_var_path = '/verify'
45
+
46
+ # query parameters
47
+ query_params = {}
48
+
49
+ # header parameters
50
+ header_params = {}
51
+ # HTTP header 'Accept' (if needed)
52
+ header_params['Accept'] = @api_client.select_header_accept(['text/plain'])
53
+ # HTTP header 'Content-Type'
54
+ header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
55
+
56
+ # form parameters
57
+ form_params = {}
58
+
59
+ # http body (model)
60
+ post_body = @api_client.object_to_http_body(verification)
61
+ auth_names = []
62
+ data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
63
+ :header_params => header_params,
64
+ :query_params => query_params,
65
+ :form_params => form_params,
66
+ :body => post_body,
67
+ :auth_names => auth_names)
68
+ if @api_client.config.debugging
69
+ @api_client.config.logger.debug "API called: VerifyApi#verify_put\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
70
+ end
71
+ return data, status_code, headers
72
+ end
73
+
74
+ # verify a sequence of request has been received in the specific order
75
+ # @param verification_sequence the sequence of requests matchers
76
+ # @param [Hash] opts the optional parameters
77
+ # @return [nil]
78
+ def verify_sequence_put(verification_sequence, opts = {})
79
+ verify_sequence_put_with_http_info(verification_sequence, opts)
80
+ nil
81
+ end
82
+
83
+ # verify a sequence of request has been received in the specific order
84
+ # @param verification_sequence the sequence of requests matchers
85
+ # @param [Hash] opts the optional parameters
86
+ # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers
87
+ def verify_sequence_put_with_http_info(verification_sequence, opts = {})
88
+ if @api_client.config.debugging
89
+ @api_client.config.logger.debug 'Calling API: VerifyApi.verify_sequence_put ...'
90
+ end
91
+ # verify the required parameter 'verification_sequence' is set
92
+ if @api_client.config.client_side_validation && verification_sequence.nil?
93
+ fail ArgumentError, "Missing the required parameter 'verification_sequence' when calling VerifyApi.verify_sequence_put"
94
+ end
95
+ # resource path
96
+ local_var_path = '/verifySequence'
97
+
98
+ # query parameters
99
+ query_params = {}
100
+
101
+ # header parameters
102
+ header_params = {}
103
+ # HTTP header 'Accept' (if needed)
104
+ header_params['Accept'] = @api_client.select_header_accept(['text/plain'])
105
+ # HTTP header 'Content-Type'
106
+ header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
107
+
108
+ # form parameters
109
+ form_params = {}
110
+
111
+ # http body (model)
112
+ post_body = @api_client.object_to_http_body(verification_sequence)
113
+ auth_names = []
114
+ data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
115
+ :header_params => header_params,
116
+ :query_params => query_params,
117
+ :form_params => form_params,
118
+ :body => post_body,
119
+ :auth_names => auth_names)
120
+ if @api_client.config.debugging
121
+ @api_client.config.logger.debug "API called: VerifyApi#verify_sequence_put\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
122
+ end
123
+ return data, status_code, headers
124
+ end
125
+
126
+ end
127
+ end
@@ -0,0 +1,388 @@
1
+ =begin
2
+ #Mock Server API
3
+
4
+ #MockServer enables easy mocking of any system you integrate with via HTTP or HTTPS with clients written in Java, JavaScript and Ruby and a simple REST API (as shown below). MockServer Proxy is a proxy that introspects all proxied traffic including encrypted SSL traffic and supports Port Forwarding, Web Proxying (i.e. HTTP proxy), HTTPS Tunneling Proxying (using HTTP CONNECT) and SOCKS Proxying (i.e. dynamic port forwarding). Both MockServer and the MockServer Proxy record all received requests so that it is possible to verify exactly what requests have been sent by the system under test.
5
+
6
+ OpenAPI spec version: 5.3.0
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ OpenAPI Generator version: 3.3.1
10
+
11
+ =end
12
+
13
+ require 'date'
14
+ require 'json'
15
+ require 'logger'
16
+ require 'tempfile'
17
+ require 'typhoeus'
18
+ require 'uri'
19
+
20
+ module MockServer
21
+ class ApiClient
22
+ # The Configuration object holding settings to be used in the API client.
23
+ attr_accessor :config
24
+
25
+ # Defines the headers to be used in HTTP requests of all API calls by default.
26
+ #
27
+ # @return [Hash]
28
+ attr_accessor :default_headers
29
+
30
+ # Initializes the ApiClient
31
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
32
+ def initialize(config = Configuration.default)
33
+ @config = config
34
+ @user_agent = "OpenAPI-Generator/#{VERSION}/ruby"
35
+ @default_headers = {
36
+ 'Content-Type' => 'application/json',
37
+ 'User-Agent' => @user_agent
38
+ }
39
+ end
40
+
41
+ def self.default
42
+ @@default ||= ApiClient.new
43
+ end
44
+
45
+ # Call an API with given options.
46
+ #
47
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
48
+ # the data deserialized from response body (could be nil), response status code and response headers.
49
+ def call_api(http_method, path, opts = {})
50
+ request = build_request(http_method, path, opts)
51
+ response = request.run
52
+
53
+ if @config.debugging
54
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
55
+ end
56
+
57
+ unless response.success?
58
+ if response.timed_out?
59
+ fail ApiError.new('Connection timed out')
60
+ elsif response.code == 0
61
+ # Errors from libcurl will be made visible here
62
+ fail ApiError.new(:code => 0,
63
+ :message => response.return_message)
64
+ else
65
+ fail ApiError.new(:code => response.code,
66
+ :response_headers => response.headers,
67
+ :response_body => response.body),
68
+ response.status_message
69
+ end
70
+ end
71
+
72
+ if opts[:return_type]
73
+ data = deserialize(response, opts[:return_type])
74
+ else
75
+ data = nil
76
+ end
77
+ return data, response.code, response.headers
78
+ end
79
+
80
+ # Builds the HTTP request
81
+ #
82
+ # @param [String] http_method HTTP method/verb (e.g. POST)
83
+ # @param [String] path URL path (e.g. /account/new)
84
+ # @option opts [Hash] :header_params Header parameters
85
+ # @option opts [Hash] :query_params Query parameters
86
+ # @option opts [Hash] :form_params Query parameters
87
+ # @option opts [Object] :body HTTP body (JSON/XML)
88
+ # @return [Typhoeus::Request] A Typhoeus Request
89
+ def build_request(http_method, path, opts = {})
90
+ url = build_request_url(path)
91
+ http_method = http_method.to_sym.downcase
92
+
93
+ header_params = @default_headers.merge(opts[:header_params] || {})
94
+ query_params = opts[:query_params] || {}
95
+ form_params = opts[:form_params] || {}
96
+
97
+
98
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
99
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
100
+
101
+ req_opts = {
102
+ :method => http_method,
103
+ :headers => header_params,
104
+ :params => query_params,
105
+ :params_encoding => @config.params_encoding,
106
+ :timeout => @config.timeout,
107
+ :ssl_verifypeer => @config.verify_ssl,
108
+ :ssl_verifyhost => _verify_ssl_host,
109
+ :sslcert => @config.cert_file,
110
+ :sslkey => @config.key_file,
111
+ :verbose => @config.debugging
112
+ }
113
+
114
+ # set custom cert, if provided
115
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
116
+
117
+ if [:post, :patch, :put, :delete].include?(http_method)
118
+ req_body = build_request_body(header_params, form_params, opts[:body])
119
+ req_opts.update :body => req_body
120
+ if @config.debugging
121
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
122
+ end
123
+ end
124
+
125
+ request = Typhoeus::Request.new(url, req_opts)
126
+ download_file(request) if opts[:return_type] == 'File'
127
+ request
128
+ end
129
+
130
+ # Check if the given MIME is a JSON MIME.
131
+ # JSON MIME examples:
132
+ # application/json
133
+ # application/json; charset=UTF8
134
+ # APPLICATION/JSON
135
+ # */*
136
+ # @param [String] mime MIME
137
+ # @return [Boolean] True if the MIME is application/json
138
+ def json_mime?(mime)
139
+ (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
140
+ end
141
+
142
+ # Deserialize the response to the given return type.
143
+ #
144
+ # @param [Response] response HTTP response
145
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
146
+ def deserialize(response, return_type)
147
+ body = response.body
148
+
149
+ # handle file downloading - return the File instance processed in request callbacks
150
+ # note that response body is empty when the file is written in chunks in request on_body callback
151
+ return @tempfile if return_type == 'File'
152
+
153
+ return nil if body.nil? || body.empty?
154
+
155
+ # return response body directly for String return type
156
+ return body if return_type == 'String'
157
+
158
+ # ensuring a default content type
159
+ content_type = response.headers['Content-Type'] || 'application/json'
160
+
161
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
162
+
163
+ begin
164
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
165
+ rescue JSON::ParserError => e
166
+ if %w(String Date DateTime).include?(return_type)
167
+ data = body
168
+ else
169
+ raise e
170
+ end
171
+ end
172
+
173
+ convert_to_type data, return_type
174
+ end
175
+
176
+ # Convert data to the given return type.
177
+ # @param [Object] data Data to be converted
178
+ # @param [String] return_type Return type
179
+ # @return [Mixed] Data in a particular type
180
+ def convert_to_type(data, return_type)
181
+ return nil if data.nil?
182
+ case return_type
183
+ when 'String'
184
+ data.to_s
185
+ when 'Integer'
186
+ data.to_i
187
+ when 'Float'
188
+ data.to_f
189
+ when 'BOOLEAN'
190
+ data == true
191
+ when 'DateTime'
192
+ # parse date time (expecting ISO 8601 format)
193
+ DateTime.parse data
194
+ when 'Date'
195
+ # parse date time (expecting ISO 8601 format)
196
+ Date.parse data
197
+ when 'Object'
198
+ # generic object (usually a Hash), return directly
199
+ data
200
+ when /\AArray<(.+)>\z/
201
+ # e.g. Array<Pet>
202
+ sub_type = $1
203
+ data.map { |item| convert_to_type(item, sub_type) }
204
+ when /\AHash\<String, (.+)\>\z/
205
+ # e.g. Hash<String, Integer>
206
+ sub_type = $1
207
+ {}.tap do |hash|
208
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
209
+ end
210
+ else
211
+ # models, e.g. Pet
212
+ MockServer.const_get(return_type).new.tap do |model|
213
+ model.build_from_hash data
214
+ end
215
+ end
216
+ end
217
+
218
+ # Save response body into a file in (the defined) temporary folder, using the filename
219
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
220
+ # The response body is written to the file in chunks in order to handle files which
221
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
222
+ # process can use.
223
+ #
224
+ # @see Configuration#temp_folder_path
225
+ def download_file(request)
226
+ tempfile = nil
227
+ encoding = nil
228
+ request.on_headers do |response|
229
+ content_disposition = response.headers['Content-Disposition']
230
+ if content_disposition && content_disposition =~ /filename=/i
231
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
232
+ prefix = sanitize_filename(filename)
233
+ else
234
+ prefix = 'download-'
235
+ end
236
+ prefix = prefix + '-' unless prefix.end_with?('-')
237
+ encoding = response.body.encoding
238
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
239
+ @tempfile = tempfile
240
+ end
241
+ request.on_body do |chunk|
242
+ chunk.force_encoding(encoding)
243
+ tempfile.write(chunk)
244
+ end
245
+ request.on_complete do |response|
246
+ tempfile.close if tempfile
247
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
248
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
249
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
250
+ "explicitly with `tempfile.delete`"
251
+ end
252
+ end
253
+
254
+ # Sanitize filename by removing path.
255
+ # e.g. ../../sun.gif becomes sun.gif
256
+ #
257
+ # @param [String] filename the filename to be sanitized
258
+ # @return [String] the sanitized filename
259
+ def sanitize_filename(filename)
260
+ filename.gsub(/.*[\/\\]/, '')
261
+ end
262
+
263
+ def build_request_url(path)
264
+ # Add leading and trailing slashes to path
265
+ path = "/#{path}".gsub(/\/+/, '/')
266
+ URI.encode(@config.base_url + path)
267
+ end
268
+
269
+ # Builds the HTTP request body
270
+ #
271
+ # @param [Hash] header_params Header parameters
272
+ # @param [Hash] form_params Query parameters
273
+ # @param [Object] body HTTP body (JSON/XML)
274
+ # @return [String] HTTP body data in the form of string
275
+ def build_request_body(header_params, form_params, body)
276
+ # http form
277
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
278
+ header_params['Content-Type'] == 'multipart/form-data'
279
+ data = {}
280
+ form_params.each do |key, value|
281
+ case value
282
+ when ::File, ::Array, nil
283
+ # let typhoeus handle File, Array and nil parameters
284
+ data[key] = value
285
+ else
286
+ data[key] = value.to_s
287
+ end
288
+ end
289
+ elsif body
290
+ data = body.is_a?(String) ? body : body.to_json
291
+ else
292
+ data = nil
293
+ end
294
+ data
295
+ end
296
+
297
+ # Update hearder and query params based on authentication settings.
298
+ #
299
+ # @param [Hash] header_params Header parameters
300
+ # @param [Hash] query_params Query parameters
301
+ # @param [String] auth_names Authentication scheme name
302
+ def update_params_for_auth!(header_params, query_params, auth_names)
303
+ Array(auth_names).each do |auth_name|
304
+ auth_setting = @config.auth_settings[auth_name]
305
+ next unless auth_setting
306
+ case auth_setting[:in]
307
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
308
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
309
+ else fail ArgumentError, 'Authentication token must be in `query` of `header`'
310
+ end
311
+ end
312
+ end
313
+
314
+ # Sets user agent in HTTP header
315
+ #
316
+ # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
317
+ def user_agent=(user_agent)
318
+ @user_agent = user_agent
319
+ @default_headers['User-Agent'] = @user_agent
320
+ end
321
+
322
+ # Return Accept header based on an array of accepts provided.
323
+ # @param [Array] accepts array for Accept
324
+ # @return [String] the Accept header (e.g. application/json)
325
+ def select_header_accept(accepts)
326
+ return nil if accepts.nil? || accepts.empty?
327
+ # use JSON when present, otherwise use all of the provided
328
+ json_accept = accepts.find { |s| json_mime?(s) }
329
+ json_accept || accepts.join(',')
330
+ end
331
+
332
+ # Return Content-Type header based on an array of content types provided.
333
+ # @param [Array] content_types array for Content-Type
334
+ # @return [String] the Content-Type header (e.g. application/json)
335
+ def select_header_content_type(content_types)
336
+ # use application/json by default
337
+ return 'application/json' if content_types.nil? || content_types.empty?
338
+ # use JSON when present, otherwise use the first one
339
+ json_content_type = content_types.find { |s| json_mime?(s) }
340
+ json_content_type || content_types.first
341
+ end
342
+
343
+ # Convert object (array, hash, object, etc) to JSON string.
344
+ # @param [Object] model object to be converted into JSON string
345
+ # @return [String] JSON string representation of the object
346
+ def object_to_http_body(model)
347
+ return model if model.nil? || model.is_a?(String)
348
+ local_body = nil
349
+ if model.is_a?(Array)
350
+ local_body = model.map { |m| object_to_hash(m) }
351
+ else
352
+ local_body = object_to_hash(model)
353
+ end
354
+ local_body.to_json
355
+ end
356
+
357
+ # Convert object(non-array) to hash.
358
+ # @param [Object] obj object to be converted into JSON string
359
+ # @return [String] JSON string representation of the object
360
+ def object_to_hash(obj)
361
+ if obj.respond_to?(:to_hash)
362
+ obj.to_hash
363
+ else
364
+ obj
365
+ end
366
+ end
367
+
368
+ # Build parameter value according to the given collection format.
369
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
370
+ def build_collection_param(param, collection_format)
371
+ case collection_format
372
+ when :csv
373
+ param.join(',')
374
+ when :ssv
375
+ param.join(' ')
376
+ when :tsv
377
+ param.join("\t")
378
+ when :pipes
379
+ param.join('|')
380
+ when :multi
381
+ # return the array directly as typhoeus will handle it as expected
382
+ param
383
+ else
384
+ fail "unknown collection format: #{collection_format.inspect}"
385
+ end
386
+ end
387
+ end
388
+ end