Welcome to mirror list, hosted at ThFree Co, Russian Federation.

stubbed_feature.rb « helpers « support « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 67ceb7d9b35e4feeeef0b3f0a340231092cb636b (plain)
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
# frozen_string_literal: true

# Extend the Feature class with the ability to stub feature flags.
module StubbedFeature
  extend ActiveSupport::Concern

  prepended do
    cattr_reader(:persist_used) do
      # persist feature flags in CI
      # nil: indicates that we do not want to persist used feature flags
      Gitlab::Utils.to_boolean(ENV['CI']) ? {} : nil
    end
  end

  class_methods do
    # Turn stubbed feature flags on or off.
    def stub=(stub)
      @stub = stub
    end

    def stub?
      @stub.nil? ? true : @stub
    end

    # Wipe any previously set feature flags.
    def reset_flipper
      @flipper = nil
    end

    # Replace #flipper method with the optional stubbed/unstubbed version.
    def flipper
      if stub?
        @flipper ||= Flipper.new(Flipper::Adapters::Memory.new)
      else
        super
      end
    end

    # Replace #enabled? method with the optional stubbed/unstubbed version.
    def enabled?(*args, **kwargs)
      feature_flag = super
      return feature_flag unless stub?

      persist_used!(args.first)

      # If feature flag is not persisted we mark the feature flag as enabled
      # We do `m.call` as we want to validate the execution of method arguments
      # and a feature flag state if it is not persisted
      unless Feature.persisted_name?(args.first)
        feature_flag = true
      end

      feature_flag
    end

    # This method creates a temporary file in `tmp/feature_flags`
    # if feature flag was touched during execution
    def persist_used!(name)
      return unless persist_used
      return if persist_used[name]

      persist_used[name] = true
      FileUtils.touch(
        Rails.root.join('tmp', 'feature_flags', name.to_s + ".used")
      )
    end
  end
end