test_helper.rb 11.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
require "bundler/setup"
Bundler.require(:default)
require "minitest/autorun"
require "minitest/pride"
require "logger"
require "active_support/core_ext" if defined?(NoBrainer)
require "active_support/notifications"

Searchkick.index_suffix = ENV["TEST_ENV_NUMBER"]

ENV["RACK_ENV"] = "test"

Minitest::Test = Minitest::Unit::TestCase unless defined?(Minitest::Test)

if !defined?(ParallelTests) || ParallelTests.first_process?
  File.delete("elasticsearch.log") if File.exist?("elasticsearch.log")
end

Searchkick.client.transport.logger = Logger.new("elasticsearch.log")
Searchkick.search_timeout = 5

if defined?(Redis)
  if defined?(ConnectionPool)
    Searchkick.redis = ConnectionPool.new { Redis.new }
  else
    Searchkick.redis = Redis.new
  end
end

puts "Running against Elasticsearch #{Searchkick.server_version}"

I18n.config.enforce_available_locales = true

if defined?(ActiveJob)
  ActiveJob::Base.logger = nil
  ActiveJob::Base.queue_adapter = :inline
end

ActiveSupport::LogSubscriber.logger = ActiveSupport::Logger.new(STDOUT) if ENV["NOTIFICATIONS"]

def elasticsearch_below60?
  Searchkick.server_below?("6.0.0-alpha1")
end

def elasticsearch_below61?
  Searchkick.server_below?("6.1.0-alpha1")
end

def nobrainer?
  defined?(NoBrainer)
end

def cequel?
  defined?(Cequel)
end

if defined?(Mongoid)
  Mongoid.logger.level = Logger::INFO
  Mongo::Logger.logger.level = Logger::INFO if defined?(Mongo::Logger)

  Mongoid.configure do |config|
    config.connect_to "searchkick_test"
  end

  class Product
    include Mongoid::Document
    include Mongoid::Timestamps

    field :name
    field :store_id, type: Integer
    field :in_stock, type: Boolean
    field :backordered, type: Boolean
    field :orders_count, type: Integer
    field :found_rate, type: BigDecimal
    field :price, type: Integer
    field :color
    field :latitude, type: BigDecimal
    field :longitude, type: BigDecimal
    field :description
    field :alt_description
  end

  class Store
    include Mongoid::Document
    has_many :products

    field :name
  end

  class Region
    include Mongoid::Document

    field :name
    field :text
  end

  class Speaker
    include Mongoid::Document

    field :name
  end

  class Animal
    include Mongoid::Document

    field :name
  end

  class Dog < Animal
  end

  class Cat < Animal
  end

  class Sku
    include Mongoid::Document

    field :name
  end

  class Song
    include Mongoid::Document

    field :name
  end
elsif defined?(NoBrainer)
  NoBrainer.configure do |config|
    config.app_name = :searchkick
    config.environment = :test
  end

  class Product
    include NoBrainer::Document
    include NoBrainer::Document::Timestamps

    field :id,           type: Object
    field :name,         type: String
    field :in_stock,     type: Boolean
    field :backordered,  type: Boolean
    field :orders_count, type: Integer
    field :found_rate
    field :price,        type: Integer
    field :color,        type: String
    field :latitude
    field :longitude
    field :description, type: String
    field :alt_description, type: String

    belongs_to :store, validates: false
  end

  class Store
    include NoBrainer::Document

    field :id,   type: Object
    field :name, type: String
  end

  class Region
    include NoBrainer::Document

    field :id,   type: Object
    field :name, type: String
    field :text, type: Text
  end

  class Speaker
    include NoBrainer::Document

    field :id,   type: Object
    field :name, type: String
  end

  class Animal
    include NoBrainer::Document

    field :id,   type: Object
    field :name, type: String
  end

  class Dog < Animal
  end

  class Cat < Animal
  end

  class Sku
    include NoBrainer::Document

    field :id,   type: String
    field :name, type: String
  end

  class Song
    include NoBrainer::Document

    field :id,   type: Object
    field :name, type: String
  end
elsif defined?(Cequel)
  cequel =
    Cequel.connect(
      host: "127.0.0.1",
      port: 9042,
      keyspace: "searchkick_test",
      default_consistency: :all
    )
  # cequel.logger = ActiveSupport::Logger.new(STDOUT)
  cequel.schema.drop! if cequel.schema.exists?
  cequel.schema.create!
  Cequel::Record.connection = cequel

  class Product
    include Cequel::Record

    key :id, :uuid, auto: true
    column :name, :text, index: true
    column :store_id, :int
    column :in_stock, :boolean
    column :backordered, :boolean
    column :orders_count, :int
    column :found_rate, :decimal
    column :price, :int
    column :color, :text
    column :latitude, :decimal
    column :longitude, :decimal
    column :description, :text
    column :alt_description, :text
    column :created_at, :timestamp
  end

  class Store
    include Cequel::Record

    key :id, :timeuuid, auto: true
    column :name, :text

    # has issue with id serialization
    def search_data
      {
        name: name
      }
    end
  end

  class Region
    include Cequel::Record

    key :id, :timeuuid, auto: true
    column :name, :text
    column :text, :text
  end

  class Speaker
    include Cequel::Record

    key :id, :timeuuid, auto: true
    column :name, :text
  end

  class Animal
    include Cequel::Record

    key :id, :timeuuid, auto: true
    column :name, :text

    # has issue with id serialization
    def search_data
      {
        name: name
      }
    end
  end

  class Dog < Animal
  end

  class Cat < Animal
  end

  class Sku
    include Cequel::Record

    key :id, :uuid
    column :name, :text
  end

  class Song
    include Cequel::Record

    key :id, :timeuuid, auto: true
    column :name, :text
  end

  [Product, Store, Region, Speaker, Animal, Sku, Song].each(&:synchronize_schema)
else
  require "active_record"

  # for debugging
  # ActiveRecord::Base.logger = Logger.new(STDOUT)

  # rails does this in activerecord/lib/active_record/railtie.rb
  ActiveRecord::Base.default_timezone = :utc
  ActiveRecord::Base.time_zone_aware_attributes = true

  # migrations
  ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"

  ActiveRecord::Base.raise_in_transactional_callbacks = true if ActiveRecord::VERSION::STRING.start_with?("4.2.")

  if defined?(Apartment)
    class Rails
      def self.env
        ENV["RACK_ENV"]
      end
    end

    tenants = ["tenant1", "tenant2"]
    Apartment.configure do |config|
      config.tenant_names = tenants
      config.database_schema_file = false
      config.excluded_models = ["Product", "Store", "Animal", "Dog", "Cat"]
    end

    class Tenant < ActiveRecord::Base
      searchkick index_prefix: -> { Apartment::Tenant.current }
    end

    tenants.each do |tenant|
      begin
        Apartment::Tenant.create(tenant)
      rescue Apartment::TenantExists
        # do nothing
      end
      Apartment::Tenant.switch!(tenant)

      ActiveRecord::Migration.create_table :tenants, force: true do |t|
        t.string :name
        t.timestamps null: true
      end

      Tenant.reindex
    end

    Apartment::Tenant.reset
  end

  ActiveRecord::Migration.create_table :products do |t|
    t.string :name
    t.integer :store_id
    t.boolean :in_stock
    t.boolean :backordered
    t.integer :orders_count
    t.decimal :found_rate
    t.integer :price
    t.string :color
    t.decimal :latitude, precision: 10, scale: 7
    t.decimal :longitude, precision: 10, scale: 7
    t.text :description
    t.text :alt_description
    t.timestamps null: true
  end

  ActiveRecord::Migration.create_table :stores do |t|
    t.string :name
  end

  ActiveRecord::Migration.create_table :regions do |t|
    t.string :name
    t.text :text
  end

  ActiveRecord::Migration.create_table :speakers do |t|
    t.string :name
  end

  ActiveRecord::Migration.create_table :animals do |t|
    t.string :name
    t.string :type
  end

  ActiveRecord::Migration.create_table :skus, id: :uuid do |t|
    t.string :name
  end

  ActiveRecord::Migration.create_table :songs do |t|
    t.string :name
  end

  class Product < ActiveRecord::Base
    belongs_to :store
  end

  class Store < ActiveRecord::Base
    has_many :products
  end

  class Region < ActiveRecord::Base
  end

  class Speaker < ActiveRecord::Base
  end

  class Animal < ActiveRecord::Base
  end

  class Dog < Animal
  end

  class Cat < Animal
  end

  class Sku < ActiveRecord::Base
  end

  class Song < ActiveRecord::Base
  end
end

class Product
  searchkick \
    synonyms: [
      ["clorox", "bleach"],
      ["scallion", "greenonion"],
      ["saran wrap", "plastic wrap"],
      ["qtip", "cottonswab"],
      ["burger", "hamburger"],
      ["bandaid", "bandag"],
      ["UPPERCASE", "lowercase"],
      "lightbulb => led,lightbulb",
      "lightbulb => halogenlamp"
    ],
    suggest: [:name, :color],
    conversions: [:conversions],
    locations: [:location, :multiple_locations],
    text_start: [:name],
    text_middle: [:name],
    text_end: [:name],
    word_start: [:name],
    word_middle: [:name],
    word_end: [:name],
    highlight: [:name],
    filterable: [:name, :color, :description],
    similarity: "BM25",
    match: ENV["MATCH"] ? ENV["MATCH"].to_sym : nil

  attr_accessor :conversions, :user_ids, :aisle, :details

  def search_data
    serializable_hash.except("id", "_id").merge(
      conversions: conversions,
      user_ids: user_ids,
      location: {lat: latitude, lon: longitude},
      multiple_locations: [{lat: latitude, lon: longitude}, {lat: 0, lon: 0}],
      aisle: aisle,
      details: details
    )
  end

  def should_index?
    name != "DO NOT INDEX"
  end

  def search_name
    {
      name: name
    }
  end
end

class Store
  searchkick \
    routing: true,
    merge_mappings: true,
    mappings: {
      store: {
        properties: {
          name: {type: "keyword"}
        }
      }
    }

  def search_document_id
    id
  end

  def search_routing
    name
  end
end

class Region
  searchkick \
    geo_shape: {
      territory: {tree: "quadtree", precision: "10km"}
    }

  attr_accessor :territory

  def search_data
    {
      name: name,
      text: text,
      territory: territory
    }
  end
end

class Speaker
  searchkick \
    conversions: ["conversions_a", "conversions_b"]

  attr_accessor :conversions_a, :conversions_b, :aisle

  def search_data
    serializable_hash.except("id", "_id").merge(
      conversions_a: conversions_a,
      conversions_b: conversions_b,
      aisle: aisle
    )
  end
end

class Animal
  searchkick \
    inheritance: true,
    text_start: [:name],
    suggest: [:name],
    index_name: -> { "#{name.tableize}-#{Date.today.year}#{Searchkick.index_suffix}" },
    callbacks: defined?(ActiveJob) ? :async : true
    # wordnet: true
end

class Sku
  searchkick callbacks: defined?(ActiveJob) ? :async : true
end

class Song
  searchkick language: "chinese"
end

Product.searchkick_index.delete if Product.searchkick_index.exists?
Product.reindex
Product.reindex # run twice for both index paths
Product.create!(name: "Set mapping")

Store.reindex
Animal.reindex
Speaker.reindex
Region.reindex

class Minitest::Test
  def setup
    Product.destroy_all
    Store.destroy_all
    Animal.destroy_all
    Speaker.destroy_all
    Sku.destroy_all
  end

  protected

  def store(documents, klass = Product)
    documents.shuffle.each do |document|
      klass.create!(document)
    end
    klass.searchkick_index.refresh
  end

  def store_names(names, klass = Product)
    store names.map { |name| {name: name} }, klass
  end

  # no order
  def assert_search(term, expected, options = {}, klass = Product)
    assert_equal expected.sort, klass.search(term, options).map(&:name).sort
  end

  def assert_order(term, expected, options = {}, klass = Product)
    assert_equal expected, klass.search(term, options).map(&:name)
  end

  def assert_equal_scores(term, options = {}, klass = Product)
    assert_equal 1, klass.search(term, options).hits.map { |a| a["_score"] }.uniq.size
  end

  def assert_first(term, expected, options = {}, klass = Product)
    assert_equal expected, klass.search(term, options).map(&:name).first
  end
end