Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ module MicrosoftKiotaAbstractions
class ApiError < StandardError
include MicrosoftKiotaAbstractions::Parsable

# the status code and headers of the response the error was raised for
attr_accessor :response_status_code, :response_headers

def initialize(message = nil, response_status_code: nil, response_headers: nil)
super(message)
@response_status_code = response_status_code
@response_headers = response_headers
end

##
## The deserialization information for the current model
## @return a i_dictionary
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ class ParseNodeHelper
def self.merge_deserializers_for_intersection_wrapper(*targets)
result = {}
targets.each do |target|
result.merge!(target.get_field_deserializers) unless target.nil?
next if target.nil?

# a field that several targets declare belongs to each of them
result.merge!(target.get_field_deserializers) do |_, earlier, later|
lambda do |node|
earlier.call(node)
later.call(node)
end
end
end
result
end
Expand Down
23 changes: 23 additions & 0 deletions components/abstractions/spec/api_error_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# frozen_string_literal: true

require_relative '../lib/microsoft_kiota_abstractions/api_error'

RSpec.describe MicrosoftKiotaAbstractions::ApiError do
it 'takes the response status code and headers with the message' do
error = described_class.new('not found', response_status_code: 404, response_headers: { 'x-id' => '1' })

expect([error.message, error.response_status_code, error.response_headers]).to eq(['not found', 404, { 'x-id' => '1' }])
end

it 'still builds through the bare super a generated error calls' do
generated = Class.new(described_class) do
def initialize
super
@additional_data = {}
end
end

error = generated.new
expect([error.response_status_code, error.response_headers]).to eq([nil, nil])
end
end
11 changes: 6 additions & 5 deletions components/abstractions/spec/parse_node_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,15 @@
expect(result).to eq({ 'name' => :name_handler, 'email' => :email_handler })
end

it 'later targets override earlier targets on key conflict' do
it 'feeds a field that several targets declare to each of them' do
calls = []
target1 = double('Parsable1')
target2 = double('Parsable2')
allow(target1).to receive(:get_field_deserializers).and_return({ 'name' => :handler_v1 })
allow(target2).to receive(:get_field_deserializers).and_return({ 'name' => :handler_v2 })
allow(target1).to receive(:get_field_deserializers).and_return({ 'name' => ->(n) { calls << [:first, n] } })
allow(target2).to receive(:get_field_deserializers).and_return({ 'name' => ->(n) { calls << [:second, n] } })

result = described_class.merge_deserializers_for_intersection_wrapper(target1, target2)
expect(result).to eq({ 'name' => :handler_v2 })
described_class.merge_deserializers_for_intersection_wrapper(target1, target2)['name'].call(:node)
expect(calls).to eq([%i[first node], %i[second node]])
end

it 'skips nil targets mixed with valid targets' do
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,15 +149,20 @@ def throw_if_failed_reponse(response, errors_mapping)
error_factory = errors_mapping['XXX']
end
if error_factory.nil?
raise MicrosoftKiotaAbstractions::ApiError,
"The server returned an unexpected status code and no error factory is registered for this code:#{status_code}"
raise MicrosoftKiotaAbstractions::ApiError.new(
"The server returned an unexpected status code and no error factory is registered for this code:#{status_code}",
response_status_code: status_code, response_headers: response.headers
)
end

root_node = get_root_parse_node(response)
error = root_node.get_object_value(error_factory) unless root_node.nil?
raise error unless error.nil?
if error.nil?
raise MicrosoftKiotaAbstractions::ApiError.new("The server returned an unexpected status code:#{status_code}",
response_status_code: status_code, response_headers: response.headers)
end

raise MicrosoftKiotaAbstractions::ApiError, "The server returned an unexpected status code:#{status_code}"
raise add_response_details(error, response)
end

def get_request_from_request_info(request_info)
Expand Down Expand Up @@ -213,5 +218,14 @@ def convert_to_native_request_async(request_info)
def set_base_url_for_request_information(request_info)
request_info.path_parameters['baseurl'] = @base_url
end

# an error the factory built learns the response details only once it is deserialized
def add_response_details(error, response)
return error unless error.is_a?(MicrosoftKiotaAbstractions::ApiError)

error.response_status_code = response.status
error.response_headers = response.headers
error
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,28 @@
ok = instance_double(Faraday::Response, status: 200, body:, headers:)
expect { adapter.throw_if_failed_reponse(ok, {}) }.not_to raise_error
end

it 'gives the deserialized error the response status code and headers' do
expect { adapter.throw_if_failed_reponse(response, { '400' => factory }) }.to raise_error(error) do |raised|
expect(raised.response_status_code).to eq(400)
expect(raised.response_headers).to eq(headers)
end
end

it 'gives the generic error the response status code and headers' do
expect { adapter.throw_if_failed_reponse(response, {}) }.to raise_error(MicrosoftKiotaAbstractions::ApiError) do |raised|
expect(raised.response_status_code).to eq(400)
expect(raised.response_headers).to eq(headers)
end
end

it 'gives the error raised for an empty body the response status code and headers' do
empty = instance_double(Faraday::Response, status: 503, body: '', headers:)
expect { adapter.throw_if_failed_reponse(empty, { '5XX' => factory }) }.to raise_error(MicrosoftKiotaAbstractions::ApiError) do |raised|
expect(raised.response_status_code).to eq(503)
expect(raised.response_headers).to eq(headers)
end
end
end

describe '#get_request_from_request_info' do
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,23 +36,23 @@ def get_float_value
end

def get_guid_value
UUIDTools::UUID.parse(@current_node)
UUIDTools::UUID.parse(@current_node) if @current_node.is_a?(String)
end

def get_date_value
Date.parse(@current_node)
Date.parse(@current_node) if @current_node.is_a?(String)
end

def get_time_value
Time.parse(@current_node)
Time.parse(@current_node) if @current_node.is_a?(String)
end

def get_date_time_value
DateTime.parse(@current_node)
DateTime.parse(@current_node) if @current_node.is_a?(String)
end

def get_duration_value
MicrosoftKiotaAbstractions::ISODuration.new(@current_node)
MicrosoftKiotaAbstractions::ISODuration.new(@current_node) if @current_node.is_a?(String)
end

# The generator passes the type as a class, except for booleans which it passes as a plain
Expand All @@ -73,6 +73,8 @@ def get_duration_value
}.freeze

def get_collection_of_primitive_values(type)
return unless @current_node.is_a?(Array)

reader = PRIMITIVE_READERS[type]
@current_node.map do |object|
next if object.nil?
Expand All @@ -88,6 +90,7 @@ def get_collection_of_primitive_values(type)

def get_collection_of_object_values(factory)
raise StandardError, 'Factory cannot be null' if factory.nil?
return unless @current_node.is_a?(Array)

@current_node.map do |object|
next if object.nil?
Expand Down Expand Up @@ -136,20 +139,24 @@ def get_enum_value(type)
end

def get_collection_of_enum_values(type)
return get_enum_values(type) unless @current_node.is_a?(Array)
return get_enum_values(type) if @current_node.is_a?(String)
return unless @current_node.is_a?(Array)

@current_node.map { |value| JsonParseNode.new(value).get_enum_value(type) }
end

def resolve_enum_member(type, raw)
return raw.to_sym unless type.is_a?(Hash)

type.each_value { |value| return value if value.to_s == raw }
type[raw.to_sym] || type[(raw[0].to_s.upcase + raw[1..].to_s).to_sym]
end

def get_child_node(name)
raise StandardError, 'Name cannot be null' if name.nil? || name.empty?

return unless @current_node.is_a?(Hash)

raw_value = @current_node[name]
JsonParseNode.new(raw_value) if raw_value
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@
writer.write_collection_of_enum_values('colours', [:Red, nil])
expect(writer.writer).to eq({ 'colours' => %w[Red] })
end

it 'writes member values as they are on the wire' do
writer.write_collection_of_enum_values('actions', %w[read read-all])
writer.write_enum_value('type', 'incoming-payment')
expect(writer.writer).to eq({ 'actions' => %w[read read-all], 'type' => 'incoming-payment' })
end
end

RSpec.describe 'writing a primitive collection as the document root' do
Expand Down
11 changes: 11 additions & 0 deletions components/serialization/json/spec/json_enum_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ def node_for(json) = MicrosoftKiotaSerializationJson::JsonParseNode.new(JSON.par
it 'returns nil for a member the enum does not declare' do
expect(node_for('"purple"').get_enum_value(colour)).to be_nil
end

it 'resolves a wire value that only a member value carries' do
access = { IncomingPayment: 'incoming-payment', ReadAll: 'read-all' }.freeze
expect(node_for('"incoming-payment"').get_enum_value(access)).to eq('incoming-payment')
expect(node_for('"read-all"').get_enum_value(access)).to eq(access[:ReadAll])
end
end

describe '#get_collection_of_enum_values' do
Expand All @@ -35,6 +41,11 @@ def node_for(json) = MicrosoftKiotaSerializationJson::JsonParseNode.new(JSON.par
expect(node_for('["red","purple"]').get_collection_of_enum_values(colour).compact).to eq([:Red])
end

it 'reads wire values that only member values carry' do
actions = { Read: 'read', ReadAll: 'read-all' }.freeze
expect(node_for('["read","read-all"]').get_collection_of_enum_values(actions)).to eq(%w[read read-all])
end

it 'returns an empty collection for an empty string' do
expect(node_for('""').get_collection_of_enum_values(colour)).to eq([])
end
Expand Down
93 changes: 93 additions & 0 deletions components/serialization/json/spec/json_reader_shape_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# frozen_string_literal: true

require_relative 'spec_helper'
require 'microsoft_kiota_abstractions'

module ReaderShapeModels
class Item
include MicrosoftKiotaAbstractions::Parsable

attr_accessor :name

def get_field_deserializers = { 'name' => ->(n) { @name = n.get_string_value } }
def serialize(writer) = writer.write_string_value('name', @name)
def self.create_from_discriminator_value(_parse_node) = Item.new
end
end

# A composed type wrapper reads every member before choosing one, so each reader meets payloads
# shaped for the other members. It has to answer nil for those rather than raise or invent a value.
RSpec.describe 'readers given a node of another shape' do
let(:colour) { { Red: 'red', Blue: 'blue' }.freeze }

def node_for(json) = MicrosoftKiotaSerializationJson::JsonParseNode.new(JSON.parse(json))

others = { 'a number' => '42', 'an object' => '{"name": "a"}', 'an array' => '["2026-01-02"]', 'a boolean' => 'true' }

describe 'the date, time, duration and guid readers' do
readers = {
get_date_value: '"2026-01-02"',
get_time_value: '"10:11:12"',
get_date_time_value: '"2026-01-02T10:11:12Z"',
get_duration_value: '"PT1H"',
get_guid_value: '"2b6d5b1a-2b6d-4b1a-8b6d-5b1a2b6d5b1a"'
}

readers.each do |reader, valid|
others.each do |shape, json|
it "#{reader} answers nil for #{shape}" do
expect(node_for(json).public_send(reader)).to be_nil
end
end

it "#{reader} still reads a string" do
expect(node_for(valid).public_send(reader)).not_to be_nil
end
end
end

describe 'the collection readers' do
non_arrays = { 'a number' => '42', 'an object' => '{"name": "a"}', 'a string' => '"a"' }

non_arrays.each do |shape, json|
it "reads no objects from #{shape}" do
expect(node_for(json).get_collection_of_object_values(ReaderShapeModels::Item.method(:create_from_discriminator_value))).to be_nil
end

it "reads no primitives from #{shape}" do
expect(node_for(json).get_collection_of_primitive_values(String)).to be_nil
end
end

it 'reads no enum values from an object' do
expect(node_for('{"name": "red"}').get_collection_of_enum_values(colour)).to be_nil
end

it 'reads no enum values from a number' do
expect(node_for('42').get_collection_of_enum_values(colour)).to be_nil
end

it 'still reads an array' do
items = node_for('[{"name": "a"}]').get_collection_of_object_values(ReaderShapeModels::Item.method(:create_from_discriminator_value))
expect(items.map(&:name)).to eq(%w[a])
end
end

describe 'get_child_node' do
it 'finds no child in an array' do
expect(node_for('[{"type": "file"}]').get_child_node('type')).to be_nil
end

it 'finds no child in a string that happens to contain the name' do
expect(node_for('"filetype"').get_child_node('type')).to be_nil
end

it 'finds no child in a number' do
expect(node_for('42').get_child_node('type')).to be_nil
end

it 'still finds a child in an object' do
expect(node_for('{"type": "file"}').get_child_node('type').get_string_value).to eq('file')
end
end
end
Loading