Module: Karafka::Testing::Helpers

Defined in:
lib/karafka/testing/helpers.rb

Overview

Common helper methods that are shared in between RSpec and Minitest

Class Method Summary collapse

Class Method Details

.karafka_consumer_find_candidate_topics(requested_topic, requested_consumer_group) ⇒ Array<Karafka::Routing::Topic>

Note:

Since we run the lookup on subscription groups, the search will automatically expand with matching patterns

Finds all the routing topics matching requested topic within all topics or within provided consumer group based on name

Parameters:

  • requested_topic (String)

    requested topic name

  • requested_consumer_group (String)

    requested consumer group or nil to look in all

Returns:

  • (Array<Karafka::Routing::Topic>)

    all matching topics



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/karafka/testing/helpers.rb', line 17

def karafka_consumer_find_candidate_topics(requested_topic, requested_consumer_group)
  subscription_groups = karafka_consumer_find_subscription_groups(requested_consumer_group)

  candidate_topics = []

  subscription_groups.each do |group|
    topic = group.topics.find(requested_topic.to_s)

    next unless topic

    candidate_topics << topic
  rescue Karafka::Errors::TopicNotFoundError
    # Skip groups that don't have the requested topic
    next
  end

  # Remove duplicate topics from multiplexed subscriptions
  # (Multiplexed subscriptions share the same name, and during testing
  # there's no parallel execution anyway, so we only need the first one)
  candidate_topics.uniq { |topic| topic.subscription_group.name }
end

.karafka_consumer_find_subscription_groups(requested_consumer_group) ⇒ Array<Karafka::Routing::SubscriptionGroup>

Finds subscription groups from the requested consumer group or selects all if no consumer group specified

Parameters:

  • requested_consumer_group (String)

    requested consumer group or nil to look in all

Returns:

  • (Array<Karafka::Routing::SubscriptionGroup>)

    requested subscription groups



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/karafka/testing/helpers.rb', line 43

def karafka_consumer_find_subscription_groups(requested_consumer_group)
  if requested_consumer_group && !requested_consumer_group.empty?
    ::Karafka::App
      .subscription_groups
      # Find matching consumer group
      .find { |cg, _sgs| cg.name == requested_consumer_group.to_s }
      # Raise error if not found
      .then do |cg|
        cg || raise(Errors::ConsumerGroupNotFoundError, requested_consumer_group)
        # Since lookup was on a hash, get the value, that is subscription groups
        cg.last
      end
  else
    ::Karafka::App
      .subscription_groups
      .values
      .flatten
  end
end