Back to Repositories

Testing Hash Formatter Plugin Implementation in Fluentd

This test suite validates the HashFormatter plugin in Fluentd, focusing on proper hash formatting with different newline configurations. The tests ensure correct string representation of hash data structures with customizable output formatting.

Test Coverage Overview

The test suite provides comprehensive coverage of the HashFormatter functionality.

Key areas tested include:
  • Line ending configurations (LF and CRLF)
  • Optional newline character handling
  • Hash to string conversion accuracy
  • UTF-8 encoding compliance

Implementation Analysis

The testing approach uses Fluent’s Test::Driver::Formatter framework to validate hash formatting behavior. The implementation employs data-driven testing patterns with specific test cases for different newline configurations and formatting options.

The suite leverages Ruby’s Test::Unit framework with custom test driver configurations for formatter testing.

Technical Details

Testing tools and configuration:
  • Fluent::Test::Driver::Formatter for formatter testing
  • Test::Unit as the testing framework
  • Custom driver configuration for formatter instantiation
  • Event time helper methods for timestamp handling
  • UTF-8 encoding validation

Best Practices Demonstrated

The test suite exemplifies several testing best practices including isolated test cases, clear setup methods, and comprehensive edge case coverage.

Notable practices include:
  • Separate test cases for different newline configurations
  • Clean test data setup
  • Explicit encoding validation
  • Modular test case organization

fluent/fluentd

test/plugin/test_formatter_hash.rb

            
require_relative '../helper'
require 'fluent/test/driver/formatter'
require 'fluent/plugin/formatter_hash'

class HashFormatterTest < ::Test::Unit::TestCase
  def setup
    @time = event_time
  end

  def create_driver(conf = "")
    Fluent::Test::Driver::Formatter.new(Fluent::Plugin::HashFormatter).configure(conf)
  end

  def tag
    "tag"
  end

  def record
    {'message' => 'awesome', 'greeting' => 'hello'}
  end

  data("newline (LF)" => ["lf", "\n"],
       "newline (CRLF)" => ["crlf", "\r\n"])
  def test_format(data)
    newline_conf, newline = data
    d = create_driver({"newline" => newline_conf})
    formatted = d.instance.format(tag, @time, record)

    assert_equal(%Q!{"message"=>"awesome", "greeting"=>"hello"}#{newline}!, formatted.gsub(' => ', '=>').encode(Encoding::UTF_8))
  end

  def test_format_without_newline
    d = create_driver('add_newline' => false)
    formatted = d.instance.format(tag, @time, record)

    assert_equal(%Q!{"message"=>"awesome", "greeting"=>"hello"}!, formatted.gsub(' => ', '=>').encode(Encoding::UTF_8))
  end
end