searchindex_backend.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. require 'rake'
  3. module SearchindexBackendHelper
  4. class Initialized
  5. class << self
  6. attr_accessor :flag
  7. end
  8. end
  9. # Configure ES specific settings in Zammad. Must be done for every test.
  10. def configure_es_settings
  11. if ENV['ES_URL'].blank?
  12. raise "Need ES_URL - hint ES_URL='http://127.0.0.1:9200'"
  13. end
  14. if ENV['ES_INDEX'].blank?
  15. raise "Need ES_INDEX - hint ES_INDEX='estest.local_zammad'"
  16. end
  17. Setting.set('es_url', ENV['ES_URL'])
  18. Setting.set('es_index', ENV['ES_INDEX'])
  19. Setting.set('es_attachment_max_size_in_mb', 1)
  20. return if ENV['ES_USER'].blank? && ENV['ES_PASSWORD'].blank?
  21. Setting.set('es_user', ENV['ES_USER'])
  22. Setting.set('es_password', ENV['ES_PASSWORD'])
  23. end
  24. def build_indexes
  25. puts 'Preparing initial Elasticsearch environment...'
  26. # Just in case, support subseqent runs.
  27. Rake::Task['zammad:searchindex:drop'].execute
  28. Rake::Task['zammad:searchindex:create'].execute
  29. end
  30. # Remove all existing data of all indexes.
  31. # WARNING: don't use in scenarios with shared ES instances.
  32. def drop_es_content
  33. # Ensure consistent state before + after dropping data.
  34. SearchIndexBackend.refresh
  35. url = "#{Setting.get('es_url')}/_all/_delete_by_query"
  36. SearchIndexBackend.make_request_and_validate(url, data: { query: { match_all: {} }, }, method: :post)
  37. # We need to recreate the pipeline.
  38. SearchIndexBackend.create_pipeline
  39. SearchIndexBackend.refresh
  40. end
  41. =begin
  42. reloads the search index for the given models.
  43. searchindex_model_reload([::Ticket, ::User, ::Organization])
  44. =end
  45. def searchindex_model_reload(models)
  46. models.each { |model| model.search_index_reload(silent: true) }
  47. SearchIndexBackend.refresh
  48. end
  49. end
  50. RSpec.configure do |config|
  51. config.include SearchindexBackendHelper, searchindex: true
  52. # Ensure a state with empty indexes at the start of every test.
  53. # Tests should use 'searchindex_model_reload' to populate required model indexes.
  54. config.before(:each, searchindex: true) do
  55. configure_es_settings # always needed
  56. if !SearchindexBackendHelper::Initialized.flag
  57. # First run - create indexes.
  58. build_indexes
  59. SearchindexBackendHelper::Initialized.flag = true
  60. next
  61. end
  62. # Was previously run - drop all indexed content.
  63. drop_es_content
  64. end
  65. end