Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nicer error when specifying non-nil non-string opt value #861

Merged
merged 1 commit into from
Oct 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion lib/stripe/api_operations/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ def request(method, url, params = {}, opts = {})
warn_on_opts_in_params(params)

opts = Util.normalize_opts(opts)
error_on_non_string_user_opts(opts)

opts[:client] ||= StripeClient.active_client

headers = opts.clone
Expand All @@ -31,10 +33,24 @@ def request(method, url, params = {}, opts = {})
[resp, opts_to_persist]
end

private def error_on_non_string_user_opts(opts)
Util::OPTS_USER_SPECIFIED.each do |opt|
next unless opts.key?(opt)

val = opts[opt]
next if val.nil?
next if val.is_a?(String)

raise ArgumentError,
"request option '#{opt}' should be a string value " \
"(was a #{val.class})"
end
end

private def warn_on_opts_in_params(params)
Util::OPTS_USER_SPECIFIED.each do |opt|
if params.key?(opt)
warn("WARNING: #{opt} should be in opts instead of params.")
warn("WARNING: '#{opt}' should be in opts instead of params.")
end
end
end
Expand Down
17 changes: 17 additions & 0 deletions test/stripe/api_resource_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,23 @@ class NestedTestAPIResource < APIResource
end
end

should "error if a user-specified opt is given a non-nil non-string value" do
stub_request(:post, "#{Stripe.api_base}/v1/charges")
.to_return(body: JSON.generate(charge_fixture))

# Works fine if not included or a string.
Stripe::Charge.create({ amount: 100, currency: "usd" }, {})
Stripe::Charge.create({ amount: 100, currency: "usd" }, idempotency_key: "12345")

# Errors on a non-string.
e = assert_raises(ArgumentError) do
Stripe::Charge.create({ amount: 100, currency: "usd" }, idempotency_key: :foo)
end
assert_equal "request option 'idempotency_key' should be a string value " \
"(was a Symbol)",
e.message
end

should "requesting with a unicode ID should result in a request" do
stub_request(:get, "#{Stripe.api_base}/v1/customers/%E2%98%83")
.to_return(body: JSON.generate(make_missing_id_error), status: 404)
Expand Down