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

cli_spec.rb « internal_events « scripts « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 54169e0dc2decc232a8cd1cc062c4de55bb29b52 (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
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
# frozen_string_literal: true

require 'fast_spec_helper'
require 'tty/prompt/test'
require_relative '../../../scripts/internal_events/cli'
require_relative '../../support/helpers/wait_helpers'

RSpec.describe Cli, feature_category: :service_ping do
  include WaitHelpers

  let(:prompt) { TTY::Prompt::Test.new }
  let(:files_to_cleanup) { [] }
  let(:max_wait_time) { 20 }

  let(:event1_filepath) { 'config/events/internal_events_cli_used.yml' }
  let(:event1_content) { internal_event_fixture('events/event_with_identifiers.yml') }
  let(:event2_filepath) { 'ee/config/events/internal_events_cli_opened.yml' }
  let(:event2_content) { internal_event_fixture('events/ee_event_without_identifiers.yml') }
  let(:event3_filepath) { 'config/events/internal_events_cli_closed.yml' }
  let(:event3_content) { internal_event_fixture('events/secondary_event_with_identifiers.yml') }

  before do
    stub_milestone('16.6')
    collect_file_writes(files_to_cleanup)
    stub_product_groups(File.read('spec/fixtures/scripts/internal_events/stages.yml'))
    stub_helper(:fetch_window_size, '50')
  end

  after do
    delete_files(files_to_cleanup)
  end

  # Shared examples used for examples defined in new_events.yml & new_metrics.yml fixtures.
  # Note: Expects CLI to be exited using the 'Exit' option or completing definition flow
  shared_examples 'creates the right defintion files' do |description, test_case = {}|
    # For expected keystroke mapping, see https://github.com/piotrmurach/tty-reader/blob/master/lib/tty/reader/keys.rb
    let(:keystrokes) { test_case.dig('inputs', 'keystrokes') || [] }
    let(:input_files) { test_case.dig('inputs', 'files') || [] }
    let(:output_files) { test_case.dig('outputs', 'files') || [] }
    let(:timeout_error) { 'Internal Events CLI timed out while awaiting completion.' }

    # Script execution should stop without a reduced timeout
    let(:interaction_timeout) { example_timeout }

    it "in scenario: #{description}" do
      delete_old_ouputs # just in case
      prep_input_files
      queue_cli_inputs(keystrokes)
      expect_file_creation

      wait_for_cli_completion
    end

    private

    def delete_old_ouputs
      [input_files, output_files].flatten.each do |file_info|
        FileUtils.rm_f(Rails.root.join(file_info['path']))
      end
    end

    def prep_input_files
      input_files.each do |file|
        File.write(
          Rails.root.join(file['path']),
          File.read(Rails.root.join(file['content']))
        )
      end
    end

    def expect_file_creation
      if output_files.any?
        output_files.each do |file|
          expect(File).to receive(:write).with(file['path'], File.read(file['content']))
        end
      else
        expect(File).not_to receive(:write)
      end
    end

    def wait_for_cli_completion
      with_cli_thread do |thread|
        wait_for(timeout_error, max_wait_time: max_wait_time) { !thread.alive? }
      end
    end
  end

  context 'when creating new events' do
    YAML.safe_load(File.read('spec/fixtures/scripts/internal_events/new_events.yml')).each do |test_case|
      it_behaves_like 'creates the right defintion files', test_case['description'], test_case
    end
  end

  context 'when creating new metrics' do
    YAML.safe_load(File.read('spec/fixtures/scripts/internal_events/new_metrics.yml')).each do |test_case|
      it_behaves_like 'creates the right defintion files', test_case['description'], test_case
    end

    context 'when creating a metric from multiple events' do
      let(:events) do
        [{
          action: '00_event1', category: 'InternalEventTracking',
          product_section: 'dev', product_stage: 'plan', product_group: 'optimize'
        }, {
          action: '00_event2', category: 'InternalEventTracking',
          product_section: 'dev', product_stage: 'create', product_group: 'ide'
        }, {
          action: '00_event3', category: 'InternalEventTracking',
          product_section: 'dev', product_stage: 'create', product_group: 'source_code'
        }]
      end

      before do
        events.each do |event|
          File.write("config/events/#{event[:action]}.yml", event.transform_keys(&:to_s).to_yaml)
        end
      end

      it 'filters the product group options based on common section' do
        # Select 00_event1 & #00_event2
        queue_cli_inputs([
          "2\n", # Enum-select: New Metric -- calculate how often one or more existing events occur over time
          "2\n", # Enum-select: Multiple events -- count occurrences of several separate events or interactions
          " ", # Multi-select: __event1
          "\e[B", # Arrow down to: __event2
          " ", # Multi-select: __event2
          "\n", # Submit selections
          "\n", # Select: Weekly/Monthly count of unique users
          "aggregate metric description\n", # Submit description
          "\n", # Accept description for weekly
          "\n" # Copy & continue
        ])

        # Filter down to "dev" options
        expected_output = <<~TEXT.chomp
        ‣ dev:plan:project_management
          dev:plan:product_planning
          dev:plan:knowledge
          dev:plan:optimize
          dev:create:source_code
          dev:create:code_review
          dev:create:ide
          dev:create:editor_extensions
          dev:create:code_creation
        TEXT

        expect_cli_output { plain_last_lines(9) == expected_output }
      end

      it 'filters the product group options based on common section & stage' do
        # Select 00_event2 & #00_event3
        queue_cli_inputs([
          "2\n", # Enum-select: New Metric -- calculate how often one or more existing events occur over time
          "2\n", # Enum-select: Multiple events -- count occurrences of several separate events or interactions
          "\e[B", # Arrow down to: __event2
          " ", # Multi-select: __event2
          "\e[B", # Arrow down to: __event3
          " ", # Multi-select: __event3
          "\n", # Submit selections
          "\n", # Select: Weekly/Monthly count of unique users
          "aggregate metric description\n", # Submit description
          "\n", # Accept description for weekly
          "\n" # Copy & continue
        ])

        # Filter down to "dev:create" options
        expected_output = <<~TEXT.chomp
        ‣ dev:create:source_code
          dev:create:code_review
          dev:create:ide
          dev:create:editor_extensions
          dev:create:code_creation
        TEXT

        expect_cli_output { plain_last_lines(5) == expected_output }
      end
    end

    context 'when product group for event no longer exists' do
      let(:event) do
        {
          action: '00_event1', category: 'InternalEventTracking',
          product_section: 'other', product_stage: 'other', product_group: 'other'
        }
      end

      before do
        File.write("config/events/#{event[:action]}.yml", event.transform_keys(&:to_s).to_yaml)
      end

      it 'prompts user to select another group' do
        queue_cli_inputs([
          "2\n", # Enum-select: New Metric -- calculate how often one or more existing events occur over time
          "1\n", # Enum-select: Single event    -- count occurrences of a specific event or user interaction
          "\n", # Select: 00__event1
          "\n", # Select: Weekly/Monthly count of unique users
          "aggregate metric description\n", # Submit description
          "\n", # Accept description for weekly
          "2\n" # Modify attributes
        ])

        # Filter down to "dev" options
        expect_cli_output do
          plain_last_lines(50).include?('Select one: Which group owns the metric?')
        end
      end
    end

    context 'when creating a metric for an event which has metrics' do
      before do
        File.write(event1_filepath, File.read(event1_content))
      end

      it 'shows all metrics options' do
        select_event_from_list

        expected_output = <<~TEXT.chomp
        ‣ Monthly/Weekly count of unique users [who triggered internal_events_cli_used]
          Monthly/Weekly count of unique projects [where internal_events_cli_used occurred]
          Monthly/Weekly count of unique namespaces [where internal_events_cli_used occurred]
          Monthly/Weekly count of [internal_events_cli_used occurrences]
          Total count of [internal_events_cli_used occurrences]
        TEXT

        expect_cli_output { plain_last_lines(5) == expected_output }
      end

      context 'with an existing weekly metric' do
        before do
          File.write(
            'ee/config/metrics/counts_7d/count_total_internal_events_cli_used_weekly.yml',
            File.read('spec/fixtures/scripts/internal_events/metrics/ee_total_7d_single_event.yml')
          )
        end

        it 'partially filters metric options' do
          select_event_from_list

          expected_output = <<~TEXT.chomp
          ‣ Monthly/Weekly count of unique users [who triggered internal_events_cli_used]
            Monthly/Weekly count of unique projects [where internal_events_cli_used occurred]
            Monthly/Weekly count of unique namespaces [where internal_events_cli_used occurred]
            Monthly count of [internal_events_cli_used occurrences]
          ✘ Weekly count of [internal_events_cli_used occurrences] (already defined)
            Total count of [internal_events_cli_used occurrences]
          TEXT

          expect_cli_output { plain_last_lines(6) == expected_output }
        end
      end

      context 'with an existing total metric' do
        before do
          File.write(
            'ee/config/metrics/counts_all/count_total_internal_events_cli_used.yml',
            File.read('spec/fixtures/scripts/internal_events/metrics/ee_total_single_event.yml')
          )
        end

        it 'filters whole metric options' do
          select_event_from_list

          expected_output = <<~TEXT.chomp
          ‣ Monthly/Weekly count of unique users [who triggered internal_events_cli_used]
            Monthly/Weekly count of unique projects [where internal_events_cli_used occurred]
            Monthly/Weekly count of unique namespaces [where internal_events_cli_used occurred]
            Monthly/Weekly count of [internal_events_cli_used occurrences]
          ✘ Total count of [internal_events_cli_used occurrences] (already defined)
          TEXT

          expect_cli_output { plain_last_lines(5) == expected_output }
        end
      end

      private

      def select_event_from_list
        queue_cli_inputs([
          "2\n", # Enum-select: New Metric -- calculate how often one or more existing events occur over time
          "1\n", # Enum-select: Single event -- count occurrences of a specific event or user interaction
          'internal_events_cli_used', # Filters to this event
          "\n" # Select: config/events/internal_events_cli_used.yml
        ])
      end
    end

    context 'when event excludes identifiers' do
      before do
        File.write(event2_filepath, File.read(event2_content))
      end

      it 'filters unavailable identifiers' do
        queue_cli_inputs([
          "2\n", # Enum-select: New Metric -- calculate how often one or more existing events occur over time
          "1\n", # Enum-select: Single event -- count occurrences of a specific event or user interaction
          'internal_events_cli_opened', # Filters to this event
          "\n" # Select: config/events/internal_events_cli_opened.yml
        ])

        expected_output = <<~TEXT.chomp
        ✘ Monthly/Weekly count of unique users [who triggered internal_events_cli_opened] (user unavailable)
        ✘ Monthly/Weekly count of unique projects [where internal_events_cli_opened occurred] (project unavailable)
        ✘ Monthly/Weekly count of unique namespaces [where internal_events_cli_opened occurred] (namespace unavailable)
        ‣ Monthly/Weekly count of [internal_events_cli_opened occurrences]
          Total count of [internal_events_cli_opened occurrences]
        TEXT

        expect_cli_output { plain_last_lines(5) == expected_output }
      end
    end

    context 'when all metrics already exist' do
      let(:event) { { action: '00_event1', category: 'InternalEventTracking' } }
      let(:metric) { { options: { 'events' => ['00_event1'] }, events: [{ 'name' => '00_event1' }] } }

      let(:files) do
        [
          ['config/events/00_event1.yml', event],
          ['config/metrics/counts_all/count_total_00_event1.yml', metric.merge(time_frame: 'all')],
          ['config/metrics/counts_7d/count_total_00_event1_weekly.yml', metric.merge(time_frame: '7d')],
          ['config/metrics/counts_28d/count_total_00_event1_monthly.yml', metric.merge(time_frame: '28d')]
        ]
      end

      before do
        files.each do |path, content|
          File.write(path, content.transform_keys(&:to_s).to_yaml)
        end
      end

      it 'exits the script and directs user to search for existing metrics' do
        queue_cli_inputs([
          "2\n", # Enum-select: New Metric -- calculate how often one or more existing events occur over time
          "1\n", # Enum-select: Single event -- count occurrences of a specific event or user interaction
          '00_event1', # Filters to this event
          "\n" # Select: config/events/00_event1.yml
        ])

        expected_output = 'Looks like the potential metrics for this event either already exist or are unsupported.'

        expect_cli_output { plain_last_lines(15).include?(expected_output) }
      end
    end
  end

  context 'when showing usage examples' do
    let(:expected_example_prompt) do
      <<~TEXT.chomp
      Select one: Select a use-case to view examples for: (Press ↑/↓ arrow or 1-8 number to move and Enter to select)
      ‣ 1. ruby/rails
        2. rspec
        3. javascript (vue)
        4. javascript (plain)
        5. vue template
        6. haml
        7. View examples for a different event
        8. Exit
      TEXT
    end

    context 'for an event with identifiers' do
      let(:expected_rails_example) do
        <<~TEXT.chomp
        --------------------------------------------------
        # RAILS

        Gitlab::InternalEvents.track_event(
          'internal_events_cli_used',
          project: project,
          namespace: project.namespace,
          user: user
        )

        --------------------------------------------------
        TEXT
      end

      let(:expected_rspec_example) do
        <<~TEXT.chomp
        --------------------------------------------------
        # RSPEC

        it_behaves_like 'internal event tracking' do
          let(:event) { 'internal_events_cli_used' }
          let(:project) { project }
          let(:namespace) { project.namespace }
          let(:user) { user }
        end

        --------------------------------------------------
        TEXT
      end

      before do
        File.write(event1_filepath, File.read(event1_content))
      end

      it 'shows backend examples' do
        queue_cli_inputs([
          "3\n", # Enum-select: View Usage -- look at code examples for an existing event
          'internal_events_cli_used', # Filters to this event
          "\n", # Select: config/events/internal_events_cli_used.yml
          "\n", # Select: ruby/rails
          "\e[B", # Arrow down to: rspec
          "\n", # Select: rspec
          "8\n" # Exit
        ])

        expect_cli_output do
          output = plain_last_lines(100)

          output.include?(expected_example_prompt) &&
            output.include?(expected_rails_example) &&
            output.include?(expected_rspec_example)
        end
      end
    end

    context 'for an event without identifiers' do
      let(:expected_rails_example) do
        <<~TEXT.chomp
        --------------------------------------------------
        # RAILS

        Gitlab::InternalEvents.track_event('internal_events_cli_opened')

        --------------------------------------------------
        TEXT
      end

      let(:expected_rspec_example) do
        <<~TEXT.chomp
        --------------------------------------------------
        # RSPEC

        it_behaves_like 'internal event tracking' do
          let(:event) { 'internal_events_cli_opened' }
        end

        --------------------------------------------------
        TEXT
      end

      let(:expected_vue_example) do
        <<~TEXT.chomp
        --------------------------------------------------
        // VUE

        <script>
        import { InternalEvents } from '~/tracking';
        import { GlButton } from '@gitlab/ui';

        const trackingMixin = InternalEvents.mixin();

        export default {
          mixins: [trackingMixin],
          components: { GlButton },
          methods: {
            performAction() {
              this.trackEvent('internal_events_cli_opened');
            },
          },
        };
        </script>

        <template>
          <gl-button @click=performAction>Click Me</gl-button>
        </template>

        --------------------------------------------------
        TEXT
      end

      let(:expected_js_example) do
        <<~TEXT.chomp
        --------------------------------------------------
        // FRONTEND -- RAW JAVASCRIPT

        import { InternalEvents } from '~/tracking';

        export const performAction = () => {
          InternalEvents.trackEvent('internal_events_cli_opened');

          return true;
        };

        --------------------------------------------------
        TEXT
      end

      let(:expected_vue_template_example) do
        <<~TEXT.chomp
        --------------------------------------------------
        // VUE TEMPLATE -- ON-CLICK

        <script>
        import { GlButton } from '@gitlab/ui';

        export default {
          components: { GlButton }
        };
        </script>

        <template>
          <gl-button data-event-tracking="internal_events_cli_opened">
            Click Me
          </gl-button>
        </template>

        --------------------------------------------------
        // VUE TEMPLATE -- ON-LOAD

        <script>
        import { GlButton } from '@gitlab/ui';

        export default {
          components: { GlButton }
        };
        </script>

        <template>
          <gl-button data-event-tracking-load="internal_events_cli_opened">
            Click Me
          </gl-button>
        </template>

        --------------------------------------------------
        TEXT
      end

      let(:expected_haml_example) do
        <<~TEXT.chomp
        --------------------------------------------------
        # HAML -- ON-CLICK

        .gl-display-inline-block{ data: { event_tracking: 'internal_events_cli_opened' } }
          = _('Important Text')

        --------------------------------------------------
        # HAML -- COMPONENT ON-CLICK

        = render Pajamas::ButtonComponent.new(button_options: { data: { event_tracking: 'internal_events_cli_opened' } })

        --------------------------------------------------
        # HAML -- COMPONENT ON-LOAD

        = render Pajamas::ButtonComponent.new(button_options: { data: { event_tracking_load: true, event_tracking: 'internal_events_cli_opened' } })

        --------------------------------------------------
        TEXT
      end

      before do
        File.write(event2_filepath, File.read(event2_content))
      end

      it 'shows all examples' do
        queue_cli_inputs([
          "3\n", # Enum-select: View Usage -- look at code examples for an existing event
          'internal_events_cli_opened', # Filters to this event
          "\n", # Select: config/events/internal_events_cli_used.yml
          "\n", # Select: ruby/rails
          "\e[B", # Arrow down to: rspec
          "\n", # Select: rspec
          "\e[B", # Arrow down to: js vue
          "\n", # Select: js vue
          "\e[B", # Arrow down to: js plain
          "\n", # Select: js plain
          "\e[B", # Arrow down to: vue template
          "\n", # Select: vue template
          "\e[B", # Arrow down to: haml
          "\n", # Select: haml
          "8\n" # Exit
        ])

        expect_cli_output do
          output = plain_last_lines(1000)

          output.include?(expected_example_prompt) &&
            output.include?(expected_rails_example) &&
            output.include?(expected_rspec_example) &&
            output.include?(expected_vue_example) &&
            output.include?(expected_js_example) &&
            output.include?(expected_vue_template_example) &&
            output.include?(expected_haml_example)
        end
      end
    end

    context 'when viewing examples for multiple events' do
      let(:expected_event1_example) do
        <<~TEXT.chomp
        --------------------------------------------------
        # RAILS

        Gitlab::InternalEvents.track_event(
          'internal_events_cli_used',
          project: project,
          namespace: project.namespace,
          user: user
        )

        --------------------------------------------------
        TEXT
      end

      let(:expected_event2_example) do
        <<~TEXT.chomp
        --------------------------------------------------
        # RAILS

        Gitlab::InternalEvents.track_event('internal_events_cli_opened')

        --------------------------------------------------
        TEXT
      end

      before do
        File.write(event1_filepath, File.read(event1_content))
        File.write(event2_filepath, File.read(event2_content))
      end

      it 'switches between events gracefully' do
        queue_cli_inputs([
          "3\n", # Enum-select: View Usage -- look at code examples for an existing event
          'internal_events_cli_used', # Filters to this event
          "\n", # Select: config/events/internal_events_cli_used.yml
          "\n", # Select: ruby/rails
          "7\n", # Select: View examples for a different event
          'internal_events_cli_opened', # Filters to this event
          "\n", # Select: config/events/internal_events_cli_opened.yml
          "\n", # Select: ruby/rails
          "8\n" # Exit
        ])

        expect_cli_output do
          output = plain_last_lines(300)

          output.include?(expected_example_prompt) &&
            output.include?(expected_event1_example) &&
            output.include?(expected_event2_example)
        end
      end
    end
  end

  context 'when offline' do
    before do
      stub_product_groups(nil)
    end

    it_behaves_like 'creates the right defintion files',
      'Creates a new event with product stage/section/group input manually' do
      let(:keystrokes) do
        [
          "1\n", # Enum-select: New Event -- start tracking when an action or scenario occurs on gitlab instances
          "Internal Event CLI is opened\n", # Submit description
          "internal_events_cli_opened\n", # Submit action name
          "6\n", # Select: None
          "\n", # Skip MR URL
          "analytics\n", # Input section
          "monitor\n", # Input stage
          "analytics_instrumentation\n", # Input group
          "2\n", # Select [premium, ultimate]
          "y\n", # Create file
          "3\n" # Exit
        ]
      end

      let(:output_files) { [{ 'path' => event2_filepath, 'content' => event2_content }] }
    end

    it_behaves_like 'creates the right defintion files',
      'Creates a new metric with product stage/section/group input manually' do
      let(:keystrokes) do
        [
          "2\n", # Enum-select: New Metric   -- calculate how often one or more existing events occur over time
          "2\n", # Enum-select: Multiple events -- count occurrences of several separate events or interactions
          'internal_events_cli', # Filters to the relevant events
          ' ', # Multi-select: internal_events_cli_closed
          "\e[B", # Arrow down to: internal_events_cli_used
          ' ', # Multi-select: internal_events_cli_used
          "\n", # Submit selections
          "\e[B", # Arrow down to: Weekly count of unique projects
          "\n", # Select: Weekly count of unique projects
          "where a defition file was created with the CLI\n", # Input description
          "\n", # Submit weekly description for monthly
          "2\n", # Select: Modify attributes
          "\n", # Accept section
          "\n", # Accept stage
          "\n", # Accept group
          "\n", # Skip URL
          "1\n", # Select: [free, premium, ultimate]
          "y\n", # Create file
          "y\n", # Create file
          "2\n" # Exit
        ]
      end

      let(:input_files) do
        [
          { 'path' => event1_filepath, 'content' => event1_content },
          { 'path' => event3_filepath, 'content' => event3_content }
        ]
      end

      let(:output_files) do
        # rubocop:disable Layout/LineLength -- Long filepaths read better unbroken
        [{
          'path' => 'config/metrics/counts_28d/count_distinct_project_id_from_internal_events_cli_closed_and_internal_events_cli_used_monthly.yml',
          'content' => 'spec/fixtures/scripts/internal_events/metrics/project_id_28d_multiple_events.yml'
        }, {
          'path' => 'config/metrics/counts_7d/count_distinct_project_id_from_internal_events_cli_closed_and_internal_events_cli_used_weekly.yml',
          'content' => 'spec/fixtures/scripts/internal_events/metrics/project_id_7d_multiple_events.yml'
        }]
        # rubocop:enable Layout/LineLength
      end
    end
  end

  context 'when window size is unavailable' do
    before do
      # `tput <cmd>` returns empty string on error
      stub_helper(:fetch_window_size, '')
      stub_helper(:fetch_window_height, '')
    end

    it_behaves_like 'creates the right defintion files',
      'Terminal size does not prevent file creation' do
      let(:keystrokes) do
        [
          "1\n", # Enum-select: New Event -- start tracking when an action or scenario occurs on gitlab instances
          "Internal Event CLI is opened\n", # Submit description
          "internal_events_cli_opened\n", # Submit action name
          "6\n", # Select: None
          "\n", # Skip MR URL
          "instrumentation\n", # Filter & select group
          "2\n", # Select [premium, ultimate]
          "y\n", # Create file
          "3\n" # Exit
        ]
      end

      let(:output_files) { [{ 'path' => event2_filepath, 'content' => event2_content }] }
    end
  end

  context "when user doesn't know what they're trying to do" do
    it "handles when user isn't trying to track product usage" do
      queue_cli_inputs([
        "4\n", # Enum-select: ...am I in the right place?
        "n\n" # No --> Are you trying to track customer usage of a GitLab feature?
      ])

      expect_cli_output do
        plain_last_lines(50).include?("Oh no! This probably isn't the tool you need!")
      end
    end

    it "handles when product usage can't be tracked with events" do
      queue_cli_inputs([
        "4\n", # Enum-select: ...am I in the right place?
        "y\n", # Yes --> Are you trying to track customer usage of a GitLab feature?
        "n\n" # No --> Can usage for the feature be measured by tracking a specific user action?
      ])

      expect_cli_output do
        plain_last_lines(50).include?("Oh no! This probably isn't the tool you need!")
      end
    end

    it 'handles when user needs to add a new event' do
      queue_cli_inputs([
        "4\n", # Enum-select: ...am I in the right place?
        "y\n", # Yes --> Are you trying to track customer usage of a GitLab feature?
        "y\n", # Yes --> Can usage for the feature be measured by tracking a specific user action?
        "n\n", # No --> Is the event already tracked?
        "n\n" # No --> Ready to start?
      ])

      expect_cli_output do
        plain_last_lines(30).include?("Okay! The next step is adding a new event! (~5 min)")
      end
    end

    it 'handles when user needs to add a new metric' do
      queue_cli_inputs([
        "4\n", # Enum-select: ...am I in the right place?
        "y\n", # Yes --> Are you trying to track customer usage of a GitLab feature?
        "y\n", # Yes --> Can usage for the feature be measured by tracking a specific user action?
        "y\n", # Yes --> Is the event already tracked?
        "n\n" # No --> Ready to start?
      ])

      expect_cli_output do
        plain_last_lines(30).include?("Amazing! The next step is adding a new metric! (~8 min)")
      end
    end
  end

  private

  def queue_cli_inputs(keystrokes)
    prompt.input << keystrokes.join('')
    prompt.input.rewind
  end

  def plain_last_lines(size)
    prompt.output.string
      .lines
      .last(size)
      .join('')
      .gsub(/\e[^\sm]{2,4}[mh]/, '') # Ignore text colors
      .gsub(/(\e\[(2K|1G|1A))+\z/, '') # Remove trailing characters if timeout occurs
  end

  def collect_file_writes(collector)
    allow(File).to receive(:write).and_wrap_original do |original_method, *args, &block|
      filepath = args.first
      collector << filepath

      dirname = Pathname.new(filepath).dirname
      unless dirname.directory?
        FileUtils.mkdir_p dirname
        collector << dirname.to_s
      end

      original_method.call(*args, &block)
    end
  end

  def stub_milestone(milestone)
    stub_const("InternalEventsCli::Helpers::MILESTONE", milestone)
  end

  def stub_product_groups(body)
    allow(Net::HTTP).to receive(:get)
      .with(URI(InternalEventsCli::Helpers::GroupOwnership::STAGES_YML))
      .and_return(body)
  end

  def stub_helper(helper, value)
    # rubocop:disable RSpec/AnyInstanceOf -- 'Next' helper not included in fast_spec_helper & next is insufficient
    allow_any_instance_of(InternalEventsCli::Helpers).to receive(helper).and_return(value)
    # rubocop:enable RSpec/AnyInstanceOf
  end

  def delete_files(files)
    files.each do |filepath|
      FileUtils.rm_f(Rails.root.join(filepath))
    end
  end

  def internal_event_fixture(filepath)
    Rails.root.join('spec', 'fixtures', 'scripts', 'internal_events', filepath)
  end

  def with_cli_thread
    thread = Thread.new { described_class.new(prompt).run }

    yield thread
  ensure
    thread.exit
  end

  def expect_cli_output(&blk)
    with_cli_thread { wait_for(blk.source, max_wait_time: max_wait_time, &blk) }
  end
end