Fluentd

How to Write Tests for Plugin

This article explains how to write Fluentd plugin test code using test-unit.

You can write test code with any other testing framework such as RSpec, minitest, etc.

Basics of Plugin Testing

Fluentd provides useful Test Drivers according to plugin type. We can write maintainable test code for plugins using them. We can write helper.rb for output plugin as follows:

require "test-unit"
require "fluent/test"
require "fluent/test/driver/output"
require "fluent/test/helpers"

Test::Unit::TestCase.include(Fluent::Test::Helpers)
Test::Unit::TestCase.extend(Fluent::Test::Helpers)

Note that Fluentd provides useful Test Drivers for input, output, multi_output, filter, parser, formatter and storage.

The recommended fluentd plugin project structure is:

.
โ”œโ”€โ”€ Gemfile
โ”œโ”€โ”€ LICENSE
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ Rakefile
โ”œโ”€โ”€ fluent-plugin-<your_fluentd_plugin_name>.gemspec
โ”œโ”€โ”€ lib
โ”‚   โ””โ”€โ”€ fluent
โ”‚       โ””โ”€โ”€ plugin
โ”‚           โ””โ”€โ”€ <plugin_type>_<your_fluentd_plugin_name>.rb
โ””โ”€โ”€ test
    โ”œโ”€โ”€ helper.rb
    โ””โ”€โ”€ plugin
        โ””โ”€โ”€ test_<plugin_type>_<your_fluentd_plugin_name>.rb

Plugin Test Driver Overview

There are some useful Test Drivers for plugin testing. We can write test code for plugins as follows:

# Load the module that defines common initialization method (Required)
require 'fluent/test'
# Load the module that defines helper methods for testing (Required)
require 'fluent/test/helpers'
# Load the test driver (Required)
require 'fluent/test/driver/output'
# Load the plugin (Required)
require 'fluent/plugin/out_file'

class FileOutputTest < Test::Unit::TestCase
  include Fluent::Test::Helpers

  def setup
    Fluent::Test.setup   # Setup test for Fluentd (Required)
    # Setup test for plugin (Optional)
    # ...
  end

  def teardown
    # Terminate test for plugin (Optional)
  end

  def create_driver(conf = CONFIG)
    Fluent::Test::Driver::Output.new(Fluent::Plugin::FileOutput).configure(conf)
  end

  # Configuration related test group
  sub_test_case 'configuration' do
    test 'basic configuration' do
      d = create_driver(basic_configuration)
      assert_equal 'something', d.instance.parameter_name
    end
  end

  # Another test group goes here
  sub_test_case 'path' do
    test 'normal' do
      d = create_driver('...')
      d.run(default_tag: 'test') do
        d.feed(event_time, record)
      end
      events = d.events
      assert_equal(1, events.size)
    end
  end
end

Testing Utility Methods

You can get a plugin instance by calling Test Driver instance's #instance method. If utility methods are private, use __send__.

# ...
class FileOutputTest < Test::Unit::TestCase
  # ...
  # Group by utility method
  sub_test_case '#compression_suffix' do
    test 'returns empty string for nil (no compression method specified)' do
      d = create_driver
      assert_equal('', d.instance.compression_suffix(nil))
    end
  end
end

Test Driver Base API

The methods in this section are available for all Test Drivers.

initialize(klass, opts: {}, &block)

Initializes Test Driver instance.

  • klass: A class of Fluentd plugin
  • opts: Overwrite system config. This parameter is useful for testing multi

    workers.

  • block: Customize plugin behavior. We can overwrite plugin code in this

    block.

Example:

def create_driver(conf={})
  d = Fluent::Test::Driver::Output.new(Fluent::Plugin::MyOutput) do
    attr_accessor :exceptions
    # Almost same as to reopen plugin class
    def prefer_buffered_processing
      false
    end
    def process(tag, es)
      # Drop events
    end
  end
  d.configure(conf)
end

configure(conf, syntax: :v1)

Configures plugin instance managed by the Test Driver.

  • conf: Fluent::Config::Element or String
  • syntax: { :v1, :v0, :ruby } :v0 is obsolete.

Example:

def create_driver(conf={})
  Fluent::Test::Driver::Output.new(Fluent::Plugin::MyOutput).configure(conf)
end

def test_process
  conf = %[
    path /path/to/something
    host localhost
    port 24229
  ]
  d = create_driver(conf)
end

end_if(&block)

Registers the conditions to stop the running Test Driver gracefully.

All registered conditions must be true before Test Driver stops.

break_if(&block)

Registers the conditions to stop the running Test Driver.

Test Driver should stop running if some of the breaking conditions are true.

broken?

Returns true when some of the breaking conditions are true. Otherwise false.

run(timeout: nil, start: true, shutdown: true, &block)

Runs the Test Driver. This Test Driver will stop running immediately after evaluating the block if given.

Otherwise, you must register the conditions to stop the running Test Driver.

This method may be overridden in subclasses.

  • timeout: timeout (seconds)
  • start: if true, start the Test Driver. Otherwise, invoke instance_start

    method to start it.

  • shutdown: if true, shut down the running Test Driver.

Example:

# Run Test Driver and feed an event (output)
d = create_driver
d.run do
  d.feed(time, record)
end

# Emit multiple events (output)
d = create_driver

d.run(default_tag: 'test', expect_emits: 1, timeout: 10, start: true,  shutdown: false) { d.feed(time, { "k1" => 1 })}

d.run(default_tag: 'test', expect_emits: 1, timeout: 10, start: false, shutdown: false) { d.feed(time, { "k1" => 2 })}

d.run(default_tag: 'test', expect_emits: 1, timeout: 10, start: true,  shutdown: true ) { d.feed(time, { "k1" => 3 })}

stop?

Returns true when all the stopping conditions are true. Otherwise false.

logs

Returns logs managed by this Test Driver.

instance

Returns the plugin instance managed by this Test Driver.

Test Driver Base Owner API

  • input
  • filter
  • output
  • multi_output

run(expect_emits: nil, expect_records: nil, timeout: nil, start: true, shutdown: true, &block)

Run Test Driver. This Test Driver will stop running immediately after evaluating block if given.

Otherwise, you must register conditions to stop running Test Driver.

This method may be overridden in subclasses.

  • expect_emits: set the number of expected emits
  • expect_records: set the number of expected records
  • timeout: timeout (seconds)
  • start: if true, start the Test Driver. Otherwise, invoke the

    instance_start method to start it.

  • shutdown: if true, shut down the running Test Driver.

Example:

# Run Test Driver and feed an event (owner plugin)
d = create_driver
d.run do
  d.feed(time, record)
end

# Emit multiple events (owner plugin)
d = create_driver

d.run(default_tag: 'test', expect_emits: 1, timeout: 10, start: true,  shutdown: false) { d.feed(time, { "k1" => 1 })}

d.run(default_tag: 'test', expect_emits: 1, timeout: 10, start: false, shutdown: false) { d.feed(time, { "k1" => 2 })}

d.run(default_tag: 'test', expect_emits: 1, timeout: 10, start: true,  shutdown: true ) { d.feed(time, { "k1" => 3 })}

events(tag: nil)

Returns the events filtered by the given tag.

  • tag: filter by this tag. If omitted, it returns all the events.

event_streams(tag: nil)

Returns the event streams filtered by the given tag.

  • tag: filter by this tag. If omitted, it returns all the event streams.

emit_count

Returns the number of invoking router.emit.

If you want to delay the stopping of the Test Driver until a certain number of records are emitted, you can use d.run(expected_records: n) instead.

Example:

d.run do
  d.feed('test', record)
end
assert_equal(1, d.emit_count)

record_count

Returns the number of records.

If you want to delay the stopping of the Test Driver until a certain number of records are emitted, you can use d.run(expected_records: n) instead.

error_events(tag: nil)

Returns error events filtered by the given tag.

  • tag: filter by this tag. If omitted, it returns all error events.

Test Driver Base owned API

  • parser
  • formatter
  • storage

configure(conf, syntax: :v1)

Configures plugin instance managed by this Test Driver.

  • conf: Fluent::Config::Element, String, or Hash
  • syntax: Supported: { :v1, :v0, :ruby } :v0 is obsolete.

Test Driver Event Feeder API

  • filter
  • output
  • multi_output

run(default_tag: nil, **kwargs, &block)

Runs EventFeeder.

  • default_tag: the default tag of the event

Example:

d.run(default_tag: 'test') do
  d.feed(event_time, { 'message' => 'Hello, Fluentd!' })
end

feed(tag, time, record)

Feeds an event to plugin instance.

  • tag: the tag of the event
  • time: event timestamp
  • record: event record

Example:

d.run do
  d.feed('test', event_time, { 'message' => 'Hello, Fluentd!' })
end

feed(tag, array_event_stream)

Feeds an array of event stream to plugin instance.

  • tag: the tag of the event
  • array_event_stream: array of [time, record]
    • time: event timestamp
    • record: event record

Example:

d.run do
  d.feed('test', [
    [event_time, { 'message' => 'Hello, user1!' }],
    [event_time, { 'message' => 'Hello, user2!' }]
  ])
end

feed(tag, es)

Feeds an event stream to plugin instance.

  • tag: the tag of the event
  • es: event stream object

Example:

es = Fluent::OneEventStream.new(event_time, { 'message' => 'Hello, Fluentd!' })
d.run do
  d.feed('test', es)
end

feed(record)

Feeds an event with default tag to plugin instance.

  • record: event record

Example:

d.run(default_tag: 'test') do
  d.feed({ 'message' => 'Hello, Fluentd!' })
  # Same as above ^
  d.feed(event_time, { 'message' => 'Hello, Fluentd!' })
end

feed(time, record)

Feeds an event with default tag to plugin instance.

  • time: event timestamp
  • record: event record

Example:

d.run(default_tag: 'test') do
  d.feed(event_time, { 'message' => 'Hello, Fluentd!' })
end

feed(array_event_stream)

Feeds an array of event stream with default tag to plugin instance.

  • array_event_stream: array of [time, record]
    • time: event timestamp
    • record: event record

Example:

d.run(default_tag: 'test') do
  d.feed([
    [event_time, { 'message' => 'Hello, user1!' }],
    [event_time, { 'message' => 'Hello, user2!' }]
  ])
end

feed(es)

Feeds an event stream with default tag to plugin instance.

  • es: event stream object

Example:

es = Fluent::OneEventStream.new(event_time, { 'message' => 'Hello, Fluentd!' })
d.run(default_tag: 'test') do
  d.feed(es)
end

Test Driver Filter API

filtered_records

Collects the filtered records.

d = create_driver(config)
d.run do
  d.feed('filter.test', event_time, { 'foo' => 'bar', 'message' => msg })
end
d.filtered_records

Test Driver Output API

run(flush: true, wait_flush_completion: true, force_flush_retry: false, **kwargs, &block)

  • flush: flush forcibly
  • wait_flush_completion: if true, waiting for flush to complete
  • force_flush_retry: if true, retrying flush forcibly

Run Test Driver. This Test Driver will stop running immediately after evaluating the block if given.

Otherwise, you must register conditions to stop running Test Driver.

Example:

d = create_driver(config)
d.run do
  d.feed('filter.test', event_time, { 'foo' => 'bar', 'message' => msg })
end

formatted

Returns the formatted records.

Example:

d = create_driver(config)
d.run do
  d.feed('filter.test', event_time, { 'foo' => 'bar', 'message' => msg })
end
d.formatted

flush

Flushes forcibly.

Example:

d = create_driver(config)
d.run do
  d.feed('filter.test', event_time, { 'foo' => 'bar', 'message' => msg })
end
d.flush

Test Helpers

assert_equal_event_time(expected, actual, message = nil)

Asserts the