Skip to content

Commit

Permalink
refactor to support testing from_json and legacy parser - take2
Browse files Browse the repository at this point in the history
  • Loading branch information
colinsurprenant committed Feb 8, 2016
1 parent 5a737f5 commit e219e88
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
19 changes: 4 additions & 15 deletions lib/logstash/codecs/json_lines.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,32 +34,18 @@ def register
@buffer = FileWatch::BufferedTokenizer.new(@delimiter)
@converter = LogStash::Util::Charset.new(@charset)
@converter.logger = @logger

# pick the correct parser here and not at class evaluation so that we can control this
# mechanism in rspec and actually force use both strategies.
self.class.module_eval do
# keep compatibility with all v2.x distributions. only in 2.3 will the Event#from_json method be introduced
# and we need to keep compatibility for all v2 releases.
alias_method :parse, from_json_exposed? ? :from_json_parse : :legacy_parse
end
end

def decode(data, &block)
@buffer.extract(data).each do |line|
parse(@converter.convert(line), &block)
end
end # def decode
end

def encode(event)
# Tack on a @delimiter for now because previously most of logstash's JSON
# outputs emitted one per line, and whitespace is OK in json.
@on_event.call(event, "#{event.to_json}#{@delimiter}")
end # def encode

# this method is made public to that we can mock it in rspec and control
# testing using from_json or legacy mechanism.
def self.from_json_exposed?
LogStash::Event.respond_to?(:from_json)
end

private
Expand All @@ -77,4 +63,7 @@ def legacy_parse(json, &block)
rescue LogStash::Json::ParserError
yield LogStash::Event.new("message" => json, "tags" => ["_jsonparsefailure"])
end

alias_method :parse, LogStash::Event.respond_to?(:from_json) ? :from_json_parse : :legacy_parse

end # class LogStash::Codecs::JSONLines
10 changes: 9 additions & 1 deletion spec/codecs/json_lines_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,18 @@
context "forcing legacy parsing" do
it_behaves_like :codec do
subject do
expect(LogStash::Codecs::JSONLines).to receive(:from_json_exposed?).and_return(false)
# register method is called in the constructor
LogStash::Codecs::JSONLines.new(codec_options)
end

before(:each) do
# stub codec parse method to force use of the legacy parser.
# this is very implementation specific but I am not sure how
# this can be tested otherwise.
allow(subject).to receive(:parse) do |line, &block|
subject.send(:legacy_parse, line, &block)
end
end
end
end

Expand Down

0 comments on commit e219e88

Please sign in to comment.