Class: LogStash::Filters::Ruby::Script::TestContext

Inherits:
Object
  • Object
show all
Defined in:
lib/logstash/filters/ruby/script/test_context.rb

Overview

Handle top level test blocks

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(script_context, name) ⇒ TestContext

Returns a new instance of TestContext.



6
7
8
9
10
11
12
13
# File 'lib/logstash/filters/ruby/script/test_context.rb', line 6

def initialize(script_context, name)
  @name = name
  @script_context = script_context
  @expect_contexts = []
  @parameters = {}
  @execution_context = script_context.make_execution_context("Test/#{name}", true)
  @script_context.load_execution_context(@execution_context)
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/logstash/filters/ruby/script/test_context.rb', line 4

def name
  @name
end

#script_contextObject (readonly)

Returns the value of attribute script_context.



4
5
6
# File 'lib/logstash/filters/ruby/script/test_context.rb', line 4

def script_context
  @script_context
end

Instance Method Details

#executeObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/logstash/filters/ruby/script/test_context.rb', line 42

def execute
  if !@in_events
    raise "You must declare an `in_event` to run tests!"
  end

  results = []
  @in_events.each do |e|
    single_result = @execution_context.filter(e)
    ::LogStash::Filters::Ruby.check_result_events!(single_result)
    results += single_result
  end

  @expect_contexts.map do |ec|
    ec.execute(results)
  end.reduce({:passed => 0, :failed => 0, :errored => 0}) do |acc,res|
    acc[res] += 1
    acc
  end
end

#expect(name, &block) ⇒ Object



62
63
64
# File 'lib/logstash/filters/ruby/script/test_context.rb', line 62

def expect(name, &block)
  @expect_contexts << ExpectContext.new(self, name, block)
end

#in_event(&block) ⇒ Object Also known as: in_events



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/logstash/filters/ruby/script/test_context.rb', line 27

def in_event(&block)
  return @in_events unless block

  orig = block.call
  event_hashes = orig.is_a?(Hash) ? [orig] : orig
  event_hashes.each do |e|
    if !e.is_a?(Hash)
      raise ArgumentError,
        "In event for #{self.name} must receive either a hash or an array of hashes! got a '#{e.class}' in #{event_hashes.inspect}"
    end
  end
  @in_events = Array(event_hashes).map {|h| ::LogStash::Event.new(h) }
end

#parameters(&block) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/logstash/filters/ruby/script/test_context.rb', line 15

def parameters(&block)
  # Can act as a reader if no block passed
  return @parameters unless block

  @parameters = block.call
  if !@parameters.is_a?(Hash)
    raise ArgumentError, "Test parameters must be a hash in #{@name}!"
  end

  @execution_context.register(@parameters)
end