Skip to content

Instantly share code, notes, and snippets.

@mstruve mstruve/search_testing.rb Secret

Last active Sep 23, 2019
Embed
What would you like to do?
Elasticsearch Ruby Testing Script: Make Requests to 2 indexes at once
class SearchTesting
TEST_INDEXES_CACHE_KEY = 'test_indexes'.freeze
TEST_CACHE_TOGGLES = %i[
test_searching
test_indexing
].freeze
def self.set_test_index(original_index_name, test_index_name)
index_hashes = cache_index_hashes
index_hashes[original_index_name] = {
:index_name => test_index_name,
:test_searching => true,
:test_indexing => true
}
update_index_cache(index_hashes)
end
def self.remove_test_index(original_index_name)
index_hashes = cache_index_hashes
index_hashes.delete(original_index_name)
update_index_cache(index_hashes)
end
TEST_CACHE_TOGGLES.each do |key|
define_singleton_method("#{key}!") do |original_index_name|
index_hashes = cache_index_hashes
index_hashes[original_index_name][key] = true
update_index_cache(index_hashes)
end
end
TEST_CACHE_TOGGLES.each do |key|
define_singleton_method("dont_#{key}!") do |original_index_name|
index_hashes = cache_index_hashes
index_hashes[original_index_name][key] = false
update_index_cache(index_hashes)
end
end
attr_accessor :connection, :index_name
def initialize(connection)
self.connection = connection
end
def method_missing(m, *args, &block)
connection.send(m, *args, &block)
end
def search(*args)
self.index_name = args&.first&.dig(:index)
test_hash = cache_index_hashes.dig(index_name)
test_search_thread = (Thread.new { test_search(*args.deep_dup, test_hash) } if test_searching_enabled?(test_hash))
connection.search(*args)
end
def bulk(*args)
test_bulk_thread = Thread.new { test_bulk(*args.deep_dup) }
connection.bulk(*args)
end
def test_bulk(*args)
new_bulk_hashes = test_bulk_hashes(*args)
return unless new_bulk_hashes.any?
connection.bulk({ :body => new_bulk_hashes })
end
def test_bulk_hashes(*args)
@test_bulk_hashes ||= args.first[:body].map do |index_hash|
index_name = test_index_name(index_hash.values.first[:_index])
next unless index_name
index_hash.values.first[:_index] = index_name
index_hash
end.compact
end
def test_index_name(index_name)
test_hash = cache_index_hashes.dig(index_name)
return unless test_hash && test_hash[:test_indexing]
test_hash[:index_name]
end
def test_search(*args, test_hash)
test_index_name = test_hash[:index_name]
args.first[:index] = test_index_name
connection.search(*args)
end
def test_searching_enabled?(test_hash)
test_hash && test_hash[:test_searching]
end
def cache_index_hashes
@cache_index_hashes ||= self.class.cache_index_hashes
end
def self.update_index_cache(indexes)
Rails.cache.write(TEST_INDEXES_CACHE_KEY, indexes, :expires_in => 1.year)
end
def self.cache_index_hashes
Rails.cache.read(TEST_INDEXES_CACHE_KEY) || {}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.