slack.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module RSpecSlackHelper
  3. def delete_all_test_chat_messages
  4. client = slack_client
  5. channel_id = slack_channel_id(client)
  6. channel_history = slack_channel_history(client, channel_id)
  7. message_count = 0
  8. channel_history['messages'].each do |message|
  9. next if message['subtype'] != 'bot_message'
  10. next if !message['ts']
  11. client.chat_delete channel: channel_id, ts: message['ts'], as_user: true
  12. message_count += 1
  13. end
  14. Rails.logger.debug { "Deleted #{message_count} existing bot message(s)..." } if message_count.positive?
  15. end
  16. def slack_client
  17. Slack.configure do |config|
  18. config.token = ENV['SLACK_CI_OAUTH_TOKEN']
  19. end
  20. client = Slack::Web::Client.new
  21. client.auth_test
  22. client
  23. end
  24. def slack_channel_id(client)
  25. channels = client.conversations_list['channels']
  26. channel_id = nil
  27. channels.each do |channel|
  28. next if channel['name'] != ENV['SLACK_CI_CHANNEL_NAME']
  29. channel_id = channel['id']
  30. end
  31. if !channel_id
  32. raise "ERROR: No such channel '#{ENV['SLACK_CI_CHANNEL_NAME']}'"
  33. end
  34. channel_id
  35. end
  36. def slack_channel_history(client, channel_id)
  37. channel_history = client.conversations_history(channel: channel_id)
  38. if !channel_history
  39. raise "ERROR: No history for channel #{ENV['SLACK_CI_CHANNEL_NAME']}/#{channel_id}"
  40. end
  41. if !channel_history['messages']
  42. raise "ERROR: No history messages for channel #{ENV['SLACK_CI_CHANNEL_NAME']}/#{channel_id}"
  43. end
  44. channel_history
  45. end
  46. RSpec::Matchers.define :have_message_count do
  47. match do
  48. check_message_count
  49. end
  50. def check_message_count
  51. client = slack_client
  52. channel_id = slack_channel_id(client)
  53. channel_history = slack_channel_history(client, channel_id)
  54. message_count = get_message_count(channel_history)
  55. expect(message_count).to eq(expected)
  56. end
  57. def get_message_count(channel_history)
  58. message_count = 0
  59. channel_history['messages'].each do |message|
  60. next if !message['text'] && message['attachments'].blank?
  61. if message['text']&.include?(actual) || message['attachments'].try(:first)['text'].include?(actual)
  62. message_count += 1
  63. end
  64. end
  65. message_count
  66. end
  67. end
  68. def live_mode?
  69. %w[1 true].include?(ENV['CI_IGNORE_CASSETTES'])
  70. end
  71. end
  72. RSpec.configure do |config|
  73. config.include RSpecSlackHelper
  74. end