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

support overriding validation schemas #92

Merged
merged 3 commits into from
Aug 21, 2024
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
7 changes: 7 additions & 0 deletions lib/twiglet/logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,13 @@ def with(default_properties)
)
end

def validation_schema(validation_schema)
self.class.new(
@service_name,
**@args.merge(validation_schema: validation_schema)
)
end

def context_provider(&blk)
new_context_providers = Array(@args[:context_providers])
new_context_providers << blk
Expand Down
2 changes: 1 addition & 1 deletion lib/twiglet/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module Twiglet
VERSION = '3.12.0'
VERSION = '3.13.0'
end
62 changes: 61 additions & 1 deletion test/logger_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -681,11 +681,71 @@
end
end

describe '#validation_schema' do
it 'allows for reconfiguring the validation_schema on new logger instances' do
validation_schema = <<-JSON
{
"type": "object",
"required": ["pet"],
"properties": {
"pet": {
"type": "object",
"required": ["name", "best_boy_or_girl?"],
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"best_boy_or_girl?": {
"type": "boolean"
}
}
}
}
}
JSON

logger = Twiglet::Logger.new(
'petshop',
now: @now,
output: @buffer
)

message = { message: 'hi' }

pet_message = {
pet: { name: 'Davis', best_boy_or_girl?: true, species: 'dog' }
}

logger.info(message)
log = read_json(@buffer)
assert_equal 'hi', log[:message]

error = assert_raises JSON::Schema::ValidationError do
logger.info(pet_message)
end
assert_equal "The property '#/' did not contain a required property of 'message'", error.message

logger = logger.validation_schema(validation_schema)

error = assert_raises JSON::Schema::ValidationError do
logger.info(message)
end
assert_equal "The property '#/' did not contain a required property of 'pet'", error.message

logger.info(pet_message)
log = read_json(@buffer)
assert_equal 'Davis', log[:pet][:name]
end
end

private

def read_json(buffer)
buffer.rewind
JSON.parse(buffer.read, symbolize_names: true)
string = buffer.read
buffer.rewind
JSON.parse(string, symbolize_names: true)
end
end
# rubocop:enable Metrics/BlockLength
Loading