featurevisor 3.1.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/bin/commands/test.rb CHANGED
@@ -2,10 +2,21 @@ require "json"
2
2
  require "find"
3
3
  require "open3"
4
4
  require "shellwords"
5
+ require_relative "../test_checks"
6
+ require_relative "../segment_tests"
5
7
 
6
8
  module FeaturevisorCLI
7
9
  module Commands
8
10
  class Test
11
+ class InfrastructureError < StandardError
12
+ attr_reader :code
13
+
14
+ def initialize(message, code: nil)
15
+ super(message)
16
+ @code = code
17
+ end
18
+ end
19
+
9
20
  def self.run(options)
10
21
  new(options).run
11
22
  end
@@ -13,61 +24,74 @@ module FeaturevisorCLI
13
24
  def initialize(options)
14
25
  @options = options
15
26
  @project_path = options.project_directory_path
27
+ @coverage_selections = []
16
28
  end
17
29
 
18
30
  def run
19
- puts "Running tests..."
20
-
21
- # Get project configuration
22
- config = get_config
23
- environments = get_environments(config)
24
- available_targets = get_targets
25
- unknown_target = @options.targets.find { |target| !available_targets.include?(target) }
26
- if unknown_target
27
- puts "Unknown target \"#{unknown_target}\". Available targets: #{available_targets.empty? ? "none" : available_targets.join(", ")}."
28
- exit 1
31
+ progress "Running tests..."
32
+ root_config = get_config(nil)
33
+ sets = selected_sets(root_config)
34
+ report = empty_report
35
+ report[:uncovered] = [] if @options.uncovered
36
+ matched_case = @options.case_id.nil?
37
+
38
+ sets.each do |set|
39
+ @active_set = set
40
+ config = get_config(set)
41
+ report[:uncovered] << get_uncovered(set) if @options.uncovered
42
+ begin
43
+ tests = get_tests(set)
44
+ rescue InfrastructureError => e
45
+ if @options.case_id && !@options.set && e.code == "test_case_not_found"
46
+ next
47
+ end
48
+ raise
49
+ end
50
+ matched_case = true
51
+ environments = get_environments(config)
52
+ available_targets = get_targets(set)
53
+ unknown_target = @options.targets.find { |target| !available_targets.include?(target) }
54
+ if unknown_target
55
+ raise InfrastructureError,
56
+ "Unknown target #{unknown_target.inspect}. Available targets: #{available_targets.empty? ? 'none' : available_targets.join(', ')}."
57
+ end
58
+ targets = @options.targets.empty? ? available_targets : @options.targets
59
+ segments_by_key = get_segments(set)
60
+ datafiles_by_key = build_datafiles(environments, targets, @options.inflate, set)
61
+ merge_report!(report, run_tests(tests, datafiles_by_key, segments_by_key, get_logger_level, config, set))
29
62
  end
30
- targets = @options.targets.empty? ? available_targets : @options.targets
31
- segments_by_key = get_segments
32
-
33
- # Build base and Target datafiles for all environments.
34
- datafiles_by_key = build_datafiles(environments, targets, @options.inflate)
35
-
36
- puts ""
37
-
38
- # Get log level
39
- level = get_logger_level
40
- tests = get_tests
41
-
42
- if tests.empty?
43
- puts "No tests found"
44
- return
63
+ if @options.case_id && !matched_case
64
+ raise InfrastructureError, "No test case matches --case and the selected filters"
45
65
  end
46
66
 
47
- # Run tests
48
- run_tests(tests, datafiles_by_key, segments_by_key, level, config)
67
+ report[:coverage] = coverage_report if @options.coverage
68
+ finalize_report!(report)
69
+ print_report(report)
70
+ exit 1 unless report[:passed]
71
+ rescue InfrastructureError => e
72
+ report ||= empty_report
73
+ report[:errors] << { message: e.message }
74
+ finalize_report!(report)
75
+ print_report(report)
76
+ exit 1
49
77
  end
50
78
 
51
79
  private
52
80
 
53
- def get_config
54
- puts "Getting config..."
55
- command = "(cd #{Shellwords.escape(@project_path)} && npx featurevisor config --json)"
56
- config_output = execute_command(command)
81
+ def get_config(set = @active_set)
82
+ progress "Getting config#{set ? " for set #{set.inspect}" : ''}..."
83
+ config_output = execute_command(node_command("config", "--json"))
57
84
 
58
85
  begin
59
86
  JSON.parse(config_output, symbolize_names: true)
60
87
  rescue JSON::ParserError => e
61
- puts "Error: Failed to parse config JSON: #{e.message}"
62
- puts "Command output: #{config_output}"
63
- exit 1
88
+ raise InfrastructureError, "Failed to parse config JSON: #{e.message}"
64
89
  end
65
90
  end
66
91
 
67
- def get_segments
68
- puts "Getting segments..."
69
- command = "(cd #{Shellwords.escape(@project_path)} && npx featurevisor list --segments --json)"
70
- segments_output = execute_command(command)
92
+ def get_segments(set = @active_set)
93
+ progress "Getting segments..."
94
+ segments_output = execute_command(node_command("list", "--segments", "--json", *set_arguments(set)))
71
95
 
72
96
  begin
73
97
  segments = JSON.parse(segments_output, symbolize_names: true)
@@ -79,16 +103,13 @@ module FeaturevisorCLI
79
103
  end
80
104
  segments_by_key
81
105
  rescue JSON::ParserError => e
82
- puts "Error: Failed to parse segments JSON: #{e.message}"
83
- puts "Command output: #{segments_output}"
84
- exit 1
106
+ raise InfrastructureError, "Failed to parse segments JSON: #{e.message}"
85
107
  end
86
108
  end
87
109
 
88
- def get_targets
89
- puts "Getting targets..."
90
- command = "(cd #{Shellwords.escape(@project_path)} && npx featurevisor list --targets --json)"
91
- targets_output = execute_command(command)
110
+ def get_targets(set = @active_set)
111
+ progress "Getting targets..."
112
+ targets_output = execute_command(node_command("list", "--targets", "--json", *set_arguments(set)))
92
113
 
93
114
  begin
94
115
  targets = JSON.parse(targets_output, symbolize_names: true)
@@ -107,12 +128,23 @@ module FeaturevisorCLI
107
128
  []
108
129
  end
109
130
  rescue JSON::ParserError => e
110
- puts "Error: Failed to parse targets JSON: #{e.message}"
111
- puts "Command output: #{targets_output}"
112
- exit 1
131
+ raise InfrastructureError, "Failed to parse targets JSON: #{e.message}"
113
132
  end
114
133
  end
115
134
 
135
+ def selected_sets(config)
136
+ return [@options.set] if @options.set
137
+ return [nil] unless config[:sets]
138
+
139
+ directory = config[:setsDirectoryPath] || "sets"
140
+ path = File.expand_path(directory, @project_path)
141
+ sets = Dir.children(path).select { |entry| File.directory?(File.join(path, entry)) }.sort
142
+ raise InfrastructureError, "No sets found in #{directory}." if sets.empty?
143
+ sets
144
+ rescue SystemCallError => e
145
+ raise InfrastructureError, "Failed to list project sets in #{directory}: #{e.message}"
146
+ end
147
+
116
148
  def get_environments(config)
117
149
  environments = config[:environments]
118
150
 
@@ -123,35 +155,33 @@ module FeaturevisorCLI
123
155
  end
124
156
 
125
157
  def base_datafile_key(environment)
126
- environment == false ? false : environment
158
+ [environment == false ? nil : environment, nil].freeze
127
159
  end
128
160
 
129
161
  def target_datafile_key(environment, target)
130
- if environment == false
131
- "false-target-#{target}"
132
- else
133
- "#{environment}-target-#{target}"
134
- end
162
+ [environment == false ? nil : environment, target].freeze
135
163
  end
136
164
 
137
- def build_datafiles(environments, targets, inflate)
165
+ def build_datafiles(environments, targets, inflate, set = @active_set)
138
166
  datafiles_by_key = {}
139
167
 
140
168
  environments.each do |environment|
141
169
  environment_label = environment == false ? "default (no environment)" : environment
142
- puts "Building datafile for environment: #{environment_label}..."
170
+ progress "Building datafile for environment: #{environment_label}..."
143
171
 
144
172
  datafiles_by_key[base_datafile_key(environment)] = build_single_datafile(
145
173
  environment: environment,
146
- inflate: inflate
174
+ inflate: inflate,
175
+ set: set
147
176
  )
148
177
 
149
178
  targets.each do |target|
150
- puts "Building datafile for target: #{target}..."
179
+ progress "Building datafile for target: #{target}..."
151
180
  datafiles_by_key[target_datafile_key(environment, target)] = build_single_datafile(
152
181
  environment: environment,
153
182
  inflate: inflate,
154
- target: target
183
+ target: target,
184
+ set: set
155
185
  )
156
186
  end
157
187
  end
@@ -159,30 +189,17 @@ module FeaturevisorCLI
159
189
  datafiles_by_key
160
190
  end
161
191
 
162
- def build_single_datafile(environment:, inflate:, target: nil)
163
- command_parts = ["npx", "featurevisor", "build", "--json"]
164
-
165
- if environment != false && !environment.nil?
166
- command_parts << "--environment=#{Shellwords.escape(environment.to_s)}"
167
- end
168
-
169
- if inflate && inflate > 0
170
- command_parts << "--inflate=#{inflate}"
171
- end
172
-
173
- if target
174
- command_parts << "--target=#{Shellwords.escape(target.to_s)}"
175
- end
176
-
177
- command = "(cd #{Shellwords.escape(@project_path)} && #{command_parts.join(' ')})"
178
- datafile_output = execute_command(command)
192
+ def build_single_datafile(environment:, inflate:, target: nil, set: @active_set)
193
+ arguments = ["build", "--json"]
194
+ arguments << "--environment=#{environment}" if environment != false && !environment.nil?
195
+ arguments << "--inflate=#{inflate}" if inflate && inflate > 0
196
+ arguments << "--target=#{target}" if target
197
+ datafile_output = execute_command(node_command(*arguments, *set_arguments(set)))
179
198
 
180
199
  begin
181
200
  JSON.parse(datafile_output, symbolize_names: true)
182
201
  rescue JSON::ParserError => e
183
- puts "Error: Failed to parse datafile JSON: #{e.message}"
184
- puts "Command output: #{datafile_output}"
185
- exit 1
202
+ raise InfrastructureError, "Failed to parse datafile JSON: #{e.message}"
186
203
  end
187
204
  end
188
205
 
@@ -196,29 +213,56 @@ module FeaturevisorCLI
196
213
  end
197
214
  end
198
215
 
199
- def get_tests
200
- command_parts = ["npx", "featurevisor", "list", "--tests", "--applyMatrix", "--json"]
201
-
202
- if @options.key_pattern && !@options.key_pattern.empty?
203
- command_parts << "--keyPattern=#{Shellwords.escape(@options.key_pattern)}"
204
- end
205
-
216
+ def get_tests(set = @active_set)
217
+ # Schema specs come too, validated with the featurevisor-schemas gem.
218
+ arguments = ["list", "--tests", "--execution-protocol", "--json"]
219
+ arguments << "--with-schemas" unless @schema_specs_rejected
220
+ arguments << "--keyPattern=#{@options.key_pattern}" if @options.key_pattern && !@options.key_pattern.empty?
206
221
  if @options.assertion_pattern && !@options.assertion_pattern.empty?
207
- command_parts << "--assertionPattern=#{Shellwords.escape(@options.assertion_pattern)}"
222
+ arguments << "--assertionPattern=#{@options.assertion_pattern}"
223
+ end
224
+ arguments << "--entityType=#{@options.entity_type}" if @options.entity_type && !@options.entity_type.empty?
225
+ arguments << "--case=#{@options.case_id}" if @options.case_id
226
+ tests_output = begin
227
+ execute_command(node_command(*arguments, *set_arguments(set)))
228
+ rescue InfrastructureError => e
229
+ # A CLI from before schema specs rejects the option, and has none to list.
230
+ raise unless arguments.include?("--with-schemas") && e.message.include?("Unknown argument") && e.message.include?("with-schemas")
231
+
232
+ @schema_specs_rejected = true
233
+ execute_command(node_command(*(arguments - ["--with-schemas"]), *set_arguments(set)))
208
234
  end
209
-
210
- command = "(cd #{Shellwords.escape(@project_path)} && #{command_parts.join(' ')})"
211
- tests_output = execute_command(command)
212
235
 
213
236
  begin
214
- JSON.parse(tests_output, symbolize_names: true)
237
+ payload = JSON.parse(tests_output, symbolize_names: true)
238
+ unless payload.is_a?(Hash)
239
+ raise InfrastructureError, "Invalid test execution protocol: expected an envelope object"
240
+ end
241
+ unless payload[:kind] == "featurevisor.test-execution"
242
+ raise InfrastructureError, 'Invalid test execution protocol: kind must be "featurevisor.test-execution"'
243
+ end
244
+ version = payload[:schemaVersion]
245
+ unless version.is_a?(Numeric) && version == 1
246
+ raise InfrastructureError, "Unsupported test execution protocol schemaVersion; expected numeric 1"
247
+ end
248
+ tests = payload[:tests]
249
+ unless tests.is_a?(Array) && tests.all? { |test| test.is_a?(Hash) }
250
+ raise InfrastructureError, "Invalid test execution protocol: tests must be an array of objects"
251
+ end
252
+ tests
215
253
  rescue JSON::ParserError => e
216
- puts "Error: Failed to parse tests JSON: #{e.message}"
217
- puts "Command output: #{tests_output}"
218
- exit 1
254
+ raise InfrastructureError, "Failed to parse tests JSON: #{e.message}"
219
255
  end
220
256
  end
221
257
 
258
+ def set_arguments(set = @active_set)
259
+ set ? ["--set=#{set}"] : []
260
+ end
261
+
262
+ def node_command(*arguments)
263
+ [*FeaturevisorCLI::NodeCli.command(@project_path), *arguments]
264
+ end
265
+
222
266
  def resolve_datafile_for_assertion(assertion, datafiles_by_key)
223
267
  environment = assertion.key?(:environment) ? assertion[:environment] : false
224
268
  environment = false if environment.nil?
@@ -228,15 +272,18 @@ module FeaturevisorCLI
228
272
  datafiles_by_key[base_datafile_key(environment)]
229
273
  end
230
274
 
231
- def create_tester_instance(datafile, level, assertion)
232
- sticky = parse_sticky(assertion[:stickyFeatures] || assertion[:sticky])
275
+ def create_tester_instance(datafile, level, assertion, set = @active_set)
276
+ sticky = parse_sticky(assertion[:stickyFeatures])
233
277
  sticky_variables = assertion[:stickyVariables].is_a?(Hash) ? assertion[:stickyVariables] : {}
234
278
 
235
- Featurevisor.create_featurevisor(
279
+ diagnostics = []
280
+ check_level = assertion.key?(:checks) || !Array(assertion[:children]).empty? ? "error" : level
281
+ instance = Featurevisor.create_featurevisor(
236
282
  datafile: datafile,
237
283
  sticky_features: sticky,
238
284
  sticky_variables: sticky_variables,
239
- log_level: level,
285
+ log_level: check_level,
286
+ on_diagnostic: ->(diagnostic) { diagnostics << diagnostic },
240
287
  modules: [
241
288
  {
242
289
  name: "test-module",
@@ -247,132 +294,261 @@ module FeaturevisorCLI
247
294
  else
248
295
  options[:bucket_value]
249
296
  end
297
+ end,
298
+ after_evaluation: ->(evaluation, _evaluation_options) do
299
+ record_coverage_selection(evaluation, assertion, set) if @options.coverage && !(datafile[:_segment_test_keys] || {}).value?(evaluation[:feature_key].to_s)
300
+ evaluation
250
301
  end
251
302
  }
252
303
  ]
253
304
  )
305
+ instance.instance_variable_set(:@__segment_test_keys, datafile[:_segment_test_keys] || {})
306
+ instance.instance_variable_set(:@__segment_test_diagnostics, diagnostics)
307
+ instance.on("error", ->(event) { diagnostics << event[:diagnostic] if event[:diagnostic] })
308
+ [instance, diagnostics]
254
309
  end
255
310
 
256
- def run_tests(tests, datafiles_by_key, segments_by_key, level, config)
257
- passed_tests_count = 0
258
- failed_tests_count = 0
259
- passed_assertions_count = 0
260
- failed_assertions_count = 0
311
+ def run_tests(tests, datafiles_by_key, segments_by_key, level, _config, set)
312
+ report = empty_report
261
313
 
262
314
  tests.each do |test|
263
- test_key = test[:key]
315
+ discriminators = %i[feature variable segment scenario schema].select { |key| test.key?(key) }
316
+ type = discriminators.first
317
+ invalid_discriminator = discriminators.length != 1
264
318
  assertions = test[:assertions] || []
265
- if (test[:feature] || test[:variable]) && !@options.targets.empty?
266
- assertions = assertions.select do |assertion|
267
- assertion[:target].nil? || @options.targets.include?(assertion[:target])
268
- end
319
+ if invalid_discriminator
320
+ assertions = [{ description: "malformed test spec", __invalid_discriminator: true }]
321
+ elsif type == :scenario && assertions.empty?
322
+ assertions = [{ description: "malformed scenario spec", __missing_assertions: true }]
323
+ end
324
+ if !invalid_discriminator && %i[feature variable scenario schema].include?(type) && !@options.targets.empty?
325
+ assertions = assertions.select { |assertion| assertion[:target].nil? || @options.targets.include?(assertion[:target]) }
269
326
  next if assertions.empty?
270
327
  end
271
- results = ""
272
- test_has_error = false
273
- test_duration = 0.0
328
+
329
+ result = {
330
+ type: (type || :unknown).to_s,
331
+ key: type ? test[type] : test[:key],
332
+ source: test.dig(:_test, :source) || test[:key],
333
+ set: test.dig(:_test, :set) || set,
334
+ passed: true,
335
+ cases: []
336
+ }
274
337
 
275
338
  assertions.each do |assertion|
276
- if assertion.is_a?(Hash)
277
- test_result = nil
278
-
279
- if test[:feature]
280
- datafile = resolve_datafile_for_assertion(assertion, datafiles_by_key)
281
- if datafile.nil?
282
- test_result = {
283
- has_error: true,
284
- errors: " ✘ no datafile found for assertion target/environment combination\n",
285
- duration: 0
286
- }
287
- end
339
+ next unless assertion.is_a?(Hash)
340
+ test_result = execute_assertion(test, type, assertion, datafiles_by_key, segments_by_key, level, set)
341
+ test_result ||= { has_error: true, errors: " ✘ test assertion could not be evaluated\n", duration: 0 }
342
+ errors = error_objects(test_result[:errors], type: type, assertion: assertion)
343
+ case_result = {
344
+ id: assertion.dig(:_case, :id),
345
+ description: assertion[:description],
346
+ environment: normalized_environment(assertion[:environment]),
347
+ target: assertion[:target],
348
+ context: assertion[:context].is_a?(Hash) ? assertion[:context] : {},
349
+ matrixValues: assertion.dig(:_case, :matrixValues) || {},
350
+ passed: !test_result[:has_error],
351
+ errors: errors,
352
+ rerun: rerun_instruction(assertion, result[:set])
353
+ }
354
+ result[:cases] << case_result
355
+ result[:passed] = false unless case_result[:passed]
356
+ end
288
357
 
289
- if datafile
290
- instance = create_tester_instance(datafile, level, assertion)
358
+ report[:results] << result
359
+ end
291
360
 
292
- # Show datafile if requested
293
- if @options.show_datafile
294
- puts ""
295
- puts JSON.pretty_generate(datafile)
296
- puts ""
297
- end
361
+ finalize_report!(report)
362
+ report
363
+ end
298
364
 
299
- begin
300
- test_result = run_test_feature(assertion, test[:feature], instance, level)
301
- ensure
302
- instance.close
303
- end
304
- end
305
- elsif test[:variable]
306
- datafile = resolve_datafile_for_assertion(assertion, datafiles_by_key)
307
- if datafile
308
- if @options.show_datafile
309
- puts ""
310
- puts JSON.pretty_generate(datafile)
311
- puts ""
312
- end
313
- instance = create_tester_instance(datafile, level, assertion)
314
- begin
315
- test_result = run_test_variable(assertion, test[:variable], instance)
316
- ensure
317
- instance.close
318
- end
319
- else
320
- test_result = { has_error: true, errors: " ✘ no datafile found for assertion target/environment combination\n", duration: 0 }
321
- end
322
- elsif test[:segment]
323
- segment_key = test[:segment]
324
- segment = segments_by_key[segment_key]
325
- if segment.is_a?(Hash)
326
- test_result = run_test_segment(assertion, segment, level)
327
- end
328
- end
365
+ def execute_assertion(test, type, assertion, datafiles_by_key, segments_by_key, level, set)
366
+ if assertion[:__invalid_discriminator]
367
+ return { has_error: true, errors: " ✘ test spec requires exactly one of feature, variable, segment, scenario or schema\n", duration: 0 }
368
+ end
369
+
370
+ datafile = resolve_datafile_for_assertion(assertion, datafiles_by_key)
371
+ return run_test_schema(test[:schema], assertion, datafile) if type == :schema
372
+ if type == :segment
373
+ if !datafile && ((assertion[:environment].is_a?(String) && !assertion[:environment].empty?) || assertion[:target])
374
+ return { has_error: true, errors: " ✘ no datafile found for assertion target/environment combination\n", duration: 0 }
375
+ end
376
+ authored = test[:_segments].is_a?(Hash) ? test[:_segments] : segments_by_key
377
+ return run_test_segment(assertion, authored[test[:segment].to_sym] || authored[test[:segment]], level, datafile, authored, test[:segment], set)
378
+ end
379
+ return { has_error: true, errors: " ✘ no datafile found for assertion target/environment combination\n", duration: 0 } unless datafile
329
380
 
330
- if test_result
331
- test_duration += test_result[:duration]
381
+ authored_segments = test[:_segments].is_a?(Hash) ? test[:_segments] : {}
382
+ preflight_details = {}
383
+ begin
384
+ preflight_assertion!(test, assertion, datafile, authored_segments, preflight_details)
385
+ rescue FeaturevisorCLI::TestChecks::CheckError => e
386
+ error = FeaturevisorCLI::TestChecks.comparison_error(
387
+ e.message, "valid checks", e.message, **preflight_details
388
+ )
389
+ return { has_error: true, errors: [error], duration: 0 }
390
+ end
332
391
 
333
- if test_result[:has_error]
334
- results += " ✘ #{assertion[:description]} (#{(test_result[:duration] * 1000).round(2)}ms)\n"
335
- results += test_result[:errors]
336
- test_has_error = true
337
- failed_assertions_count += 1
338
- else
339
- results += " ✔ #{assertion[:description]} (#{(test_result[:duration] * 1000).round(2)}ms)\n"
340
- passed_assertions_count += 1
341
- end
392
+ datafile = SegmentTests.prepare(datafile, authored_segments)
393
+ progress JSON.pretty_generate(datafile) if @options.show_datafile
394
+ instance, diagnostics = create_tester_instance(datafile, level, assertion, set)
395
+ begin
396
+ return run_test_feature(assertion, test[:feature], instance, level) if type == :feature
397
+ return run_test_variable(assertion, test[:variable], instance, datafile, diagnostics, authored_segments) if type == :variable
398
+ return run_test_scenario(assertion, instance, datafile, diagnostics, authored_segments) if type == :scenario
399
+ ensure
400
+ instance.close
401
+ end
402
+ end
403
+
404
+ def preflight_assertion!(test, assertion, datafile, segments, details = {})
405
+ if test[:feature]
406
+ feature = FeaturevisorCLI::TestChecks.keyed(FeaturevisorCLI::TestChecks.keyed(datafile, :features), test[:feature])
407
+ variables = FeaturevisorCLI::TestChecks.keyed(feature, :variablesSchema)
408
+ [assertion, *Array(assertion[:children])].each do |current|
409
+ next unless current.is_a?(Hash)
410
+ (current[:expectedVariables] || {}).each_key do |variable|
411
+ unless FeaturevisorCLI::TestChecks.keyed(variables, variable)
412
+ raise FeaturevisorCLI::TestChecks::CheckError,
413
+ "variable #{variable.inspect} is absent from feature #{test[:feature].inspect} in the selected datafile"
342
414
  end
343
415
  end
344
416
  end
345
-
346
- if !@options.only_failures || (@options.only_failures && test_has_error)
347
- puts "\nTesting: #{test_key} (#{(test_duration * 1000).round(2)}ms)"
348
- print results
417
+ end
418
+ owner = test[:variable]
419
+ FeaturevisorCLI::TestChecks.preflight!(datafile, assertion[:checks], owner_variable: owner, segments: segments) if assertion.key?(:checks)
420
+ children = assertion[:children] || []
421
+ raise FeaturevisorCLI::TestChecks::CheckError, "children must be an array" unless children.is_a?(Array)
422
+ children.each_with_index do |child, index|
423
+ raise FeaturevisorCLI::TestChecks::CheckError, "children[#{index}] must be an object" unless child.is_a?(Hash)
424
+ if child.key?(:checks) || test[:scenario]
425
+ details[:child_index] = index
426
+ FeaturevisorCLI::TestChecks.preflight!(datafile, child[:checks], owner_variable: owner, segments: segments)
349
427
  end
428
+ end
429
+ end
350
430
 
351
- if test_has_error
352
- failed_tests_count += 1
353
- else
354
- passed_tests_count += 1
431
+ # A schema spec's assertion: validates its value with the featurevisor-schemas gem
432
+ # against the datafile its environment and Target build, under its context, as the
433
+ # JavaScript CLI does, so a test proves what applications see.
434
+ def run_test_schema(schema, assertion, datafile)
435
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
436
+ errors = []
437
+ record = ->(message, expected, actual) { errors << { type: "schema", message: message, expected: expected, actual: actual } }
438
+ environment = assertion[:environment]
439
+ target = assertion[:target]
440
+ if !datafile
441
+ message = if environment.is_a?(String) && !environment.empty?
442
+ %(datafile not found for environment "#{environment}"#{target ? %( and target "#{target}") : ""})
443
+ elsif target
444
+ %(datafile not found for target "#{target}")
445
+ else
446
+ "No datafile without an environment. When the project configures environments, add environment to the assertion."
447
+ end
448
+ record.call(message, "datafile", nil)
449
+ elsif !(datafile[:schemas].is_a?(Hash) && datafile[:schemas].key?(schema.to_sym))
450
+ record.call(%(Target "#{target || "undefined"}" does not deliver schema "#{schema}". Tag the schema for it, or list it in its includeSchemas.), schema, nil)
451
+ elsif !schemas_gem?
452
+ record.call("Schema specs need the featurevisor-schemas gem. Add it beside featurevisor.", "featurevisor-schemas", nil)
453
+ else
454
+ issues = validate_schema(schema, assertion, datafile)
455
+ valid = issues.empty?
456
+ if [true, false].include?(assertion[:expectedToBeValid]) && assertion[:expectedToBeValid] != valid
457
+ message = if valid
458
+ "Expected the value to be invalid, and it is valid."
459
+ else
460
+ count = issues.length == 1 ? "an issue" : "#{issues.length} issues"
461
+ "Expected the value to be valid, and it has #{count}:\n" + issues.map { |issue| " #{JSON.generate(issue)}" }.join("\n")
462
+ end
463
+ record.call(message, assertion[:expectedToBeValid], valid)
464
+ end
465
+ if assertion[:expectedIssues].is_a?(Array)
466
+ # Each expected issue pairs with one issue found, and every issue found must be expected.
467
+ left = issues.dup
468
+ missing = []
469
+ assertion[:expectedIssues].each do |expected|
470
+ index = left.index { |actual| issue_matches?(expected, actual) }
471
+ index ? left.delete_at(index) : missing << expected
472
+ end
473
+ unless missing.empty? && left.empty?
474
+ lines = missing.map { |issue| " missing: #{JSON.generate(issue)}" } +
475
+ left.map { |issue| " unexpected: #{JSON.generate(issue)}" }
476
+ record.call("The issues differ from expectedIssues:\n" + lines.join("\n"), assertion[:expectedIssues], issues)
477
+ end
355
478
  end
356
479
  end
480
+ duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
481
+ { has_error: !errors.empty?, errors: errors.empty? ? "" : errors, duration: duration }
482
+ end
357
483
 
358
- puts ""
359
- puts "Test specs: #{passed_tests_count} passed, #{failed_tests_count} failed"
360
- puts "Assertions: #{passed_assertions_count} passed, #{failed_assertions_count} failed"
361
- puts ""
484
+ # Whether the featurevisor-schemas gem loads, which the featurevisor gem does not depend on.
485
+ def schemas_gem?
486
+ return @schemas_gem unless @schemas_gem.nil?
487
+
488
+ @schemas_gem = begin
489
+ require "featurevisor-schemas"
490
+ true
491
+ rescue LoadError
492
+ false
493
+ end
494
+ end
495
+
496
+ # The issues a value has, as a test result shows them, without the schema key every issue repeats.
497
+ def validate_schema(schema, assertion, datafile)
498
+ instance = Featurevisor.create_featurevisor(datafile: datafile, context: assertion[:context] || {}, log_level: "fatal")
499
+ schemas = Featurevisor::Schemas.create(instance)
500
+ schemas.validate(schema, assertion[:value]).issues.map do |issue|
501
+ described = { path: issue.path, code: issue.code }
502
+ described[:mutation] = issue.mutation unless issue.mutation.nil?
503
+ described.merge(message: issue.message, params: issue.params)
504
+ end
505
+ ensure
506
+ schemas&.close
507
+ instance&.close
508
+ end
362
509
 
363
- if failed_tests_count > 0
364
- exit 1
510
+ # Whether an issue has every field an expected issue gives, params by JSON equality.
511
+ def issue_matches?(expected, actual)
512
+ return false unless expected.is_a?(Hash)
513
+ return false if expected.key?(:path) && JSON.generate(expected[:path]) != JSON.generate(actual[:path])
514
+ return false if %i[code mutation message].any? { |field| expected.key?(field) && expected[field] != actual[field] }
515
+
516
+ params = actual[:params] || {}
517
+ (expected[:params] || {}).all? do |name, value|
518
+ found = params.key?(name) ? params[name] : params[name.to_s]
519
+ (params.key?(name) || params.key?(name.to_s)) && json_equal?(value, found)
520
+ end
521
+ end
522
+
523
+ def json_equal?(left, right)
524
+ normalize = lambda do |value|
525
+ case value
526
+ when Float then value == value.to_i ? value.to_i : value
527
+ when Hash then value.to_h { |key, item| [key.to_s, normalize.call(item)] }
528
+ when Array then value.map { |item| normalize.call(item) }
529
+ else value
530
+ end
365
531
  end
532
+ normalize.call(left) == normalize.call(right)
366
533
  end
367
534
 
368
- def run_test_variable(assertion, variable_key, instance)
369
- instance.set_context(parse_context(assertion[:context]), true)
535
+ def run_test_variable(assertion, variable_key, instance, datafile, diagnostics, segments = {})
536
+ root_context = parse_context(assertion[:context])
537
+ matcher = segment_matcher(instance, segments)
538
+ instance.set_context(root_context, true)
370
539
  options = {}
371
540
  options[:default_variable_value] = assertion[:defaultVariableValue] if assertion.key?(:defaultVariableValue)
372
541
  started = Time.now
373
- errors = ""
542
+ errors = []
374
543
 
375
- errors += test_variable_expectation(assertion, variable_key, instance, options)
544
+ errors.concat(error_objects(test_variable_expectation(assertion, variable_key, instance, options)))
545
+ if assertion.key?(:checks)
546
+ check_result = FeaturevisorCLI::TestChecks.evaluate_result(
547
+ instance, datafile, assertion[:checks], owner_variable: variable_key, diagnostics: diagnostics,
548
+ segments: segments, context: root_context, segment_matcher: matcher
549
+ )
550
+ errors.concat(check_result[:errors])
551
+ end
376
552
 
377
553
  Array(assertion[:children]).each_with_index do |child_assertion, child_index|
378
554
  child = instance.spawn(
@@ -385,38 +561,103 @@ module FeaturevisorCLI
385
561
  if child_assertion.key?(:defaultVariableValue)
386
562
  child_options[:default_variable_value] = child_assertion[:defaultVariableValue]
387
563
  end
388
- errors += test_variable_expectation(
389
- child_assertion,
390
- variable_key,
564
+ errors.concat(error_objects(test_variable_expectation(
565
+ child_assertion, variable_key, child, child_options, child_index
566
+ )))
567
+ if child_assertion.key?(:checks)
568
+ check_result = FeaturevisorCLI::TestChecks.evaluate_result(
569
+ child,
570
+ datafile,
571
+ child_assertion[:checks],
572
+ owner_variable: variable_key,
573
+ diagnostics: diagnostics,
574
+ child_index: child_index,
575
+ segments: segments,
576
+ context: root_context.merge(parse_context(child_assertion[:context])),
577
+ segment_matcher: segment_matcher(child, segments, instance.instance_variable_get(:@__segment_test_keys), diagnostics)
578
+ )
579
+ errors.concat(check_result[:errors])
580
+ end
581
+ ensure
582
+ child.close
583
+ end
584
+ end
585
+
586
+ { has_error: !errors.empty?, errors: errors, duration: Time.now - started }
587
+ end
588
+
589
+ def run_test_scenario(assertion, instance, datafile, diagnostics, segments = {})
590
+ started = Time.now
591
+ errors = []
592
+ root_context = parse_context(assertion[:context])
593
+ matcher = segment_matcher(instance, segments)
594
+ instance.set_context(root_context, true)
595
+ if assertion[:__missing_assertions]
596
+ errors << { message: "scenario spec requires assertions" }
597
+ elsif assertion.key?(:checks)
598
+ check_result = FeaturevisorCLI::TestChecks.evaluate_result(
599
+ instance, datafile, assertion[:checks], owner_variable: nil, diagnostics: diagnostics,
600
+ segments: segments, context: root_context, segment_matcher: matcher
601
+ )
602
+ errors.concat(check_result[:errors])
603
+ elsif Array(assertion[:children]).empty?
604
+ errors << { message: "scenario assertion requires checks or children" }
605
+ end
606
+ Array(assertion[:children]).each_with_index do |child_assertion, child_index|
607
+ child = instance.spawn(
608
+ parse_context(child_assertion[:context]),
609
+ sticky_features: parse_sticky(child_assertion[:stickyFeatures]),
610
+ sticky_variables: child_assertion[:stickyVariables].is_a?(Hash) ? child_assertion[:stickyVariables] : {}
611
+ )
612
+ begin
613
+ check_result = FeaturevisorCLI::TestChecks.evaluate_result(
391
614
  child,
392
- child_options,
393
- "children[#{child_index}]."
615
+ datafile,
616
+ child_assertion[:checks],
617
+ owner_variable: nil,
618
+ diagnostics: diagnostics,
619
+ child_index: child_index,
620
+ segments: segments,
621
+ context: root_context.merge(parse_context(child_assertion[:context])),
622
+ segment_matcher: segment_matcher(child, segments, instance.instance_variable_get(:@__segment_test_keys), diagnostics)
394
623
  )
624
+ errors.concat(check_result[:errors])
395
625
  ensure
396
626
  child.close
397
627
  end
398
628
  end
399
-
400
629
  { has_error: !errors.empty?, errors: errors, duration: Time.now - started }
401
630
  end
402
631
 
403
- def test_variable_expectation(assertion, variable_key, evaluator, options, prefix = "")
632
+ def test_variable_expectation(assertion, variable_key, evaluator, options, child_index = nil)
404
633
  evaluation = evaluator.evaluate_variable(variable_key, {}, options)
405
- errors = ""
406
- if assertion.key?(:expectedValue) && !compare_values(evaluation[:variable_value], assertion[:expectedValue])
407
- errors += " ✘ #{prefix}expectedValue: expected #{format_test_value(assertion[:expectedValue])} but received #{format_test_value(evaluation[:variable_value])}\n"
634
+ details = { variableKey: variable_key }
635
+ details[:childIndex] = child_index unless child_index.nil?
636
+ errors = []
637
+ if assertion.key?(:expectedValue)
638
+ value = evaluator.get_variable(variable_key, {}, options)
639
+ errors << expectation_error("variable", assertion[:expectedValue], value, details) unless compare_values(value, assertion[:expectedValue])
408
640
  end
409
641
  if assertion[:expectedEvaluation].is_a?(Hash)
410
642
  assertion[:expectedEvaluation].each do |key, expected|
411
643
  actual = get_evaluation_value(evaluation, key)
412
644
  unless compare_values(actual, expected)
413
- errors += " ✘ #{prefix}expectedEvaluation.#{key}: expected #{format_test_value(expected)} but received #{format_test_value(actual)}\n"
645
+ errors << expectation_error(
646
+ "evaluation",
647
+ expected,
648
+ actual,
649
+ details.merge(evaluationType: "variable", evaluationKey: key)
650
+ )
414
651
  end
415
652
  end
416
653
  end
417
654
  errors
418
655
  end
419
656
 
657
+ def expectation_error(type, expected, actual, details = {})
658
+ { type: type, expected: expected, actual: actual, details: details }
659
+ end
660
+
420
661
  def format_test_value(value)
421
662
  JSON.generate(value)
422
663
  rescue JSON::GeneratorError
@@ -425,7 +666,7 @@ module FeaturevisorCLI
425
666
 
426
667
  def run_test_feature(assertion, feature_key, instance, level)
427
668
  context = parse_context(assertion[:context])
428
- sticky = parse_sticky(assertion[:sticky])
669
+ sticky = parse_sticky(assertion[:stickyFeatures])
429
670
 
430
671
  # Set context and sticky for this assertion
431
672
  instance.set_context(context, false)
@@ -437,7 +678,7 @@ module FeaturevisorCLI
437
678
  override_options = create_override_options(assertion)
438
679
 
439
680
  has_error = false
440
- errors = ""
681
+ errors = []
441
682
  start_time = Time.now
442
683
 
443
684
  # Test expectedToBeEnabled
@@ -447,7 +688,7 @@ module FeaturevisorCLI
447
688
 
448
689
  if is_enabled != expected_to_be_enabled
449
690
  has_error = true
450
- errors += " ✘ expectedToBeEnabled: expected #{expected_to_be_enabled} but received #{is_enabled}\n"
691
+ errors << expectation_error("flag", expected_to_be_enabled, is_enabled)
451
692
  end
452
693
  end
453
694
 
@@ -459,7 +700,7 @@ module FeaturevisorCLI
459
700
  variation_value = variation.nil? ? nil : variation
460
701
  if !compare_values(variation_value, expected_variation)
461
702
  has_error = true
462
- errors += " ✘ expectedVariation: expected #{expected_variation} but received #{variation_value}\n"
703
+ errors << expectation_error("variation", expected_variation, variation_value)
463
704
  end
464
705
  end
465
706
 
@@ -490,8 +731,7 @@ module FeaturevisorCLI
490
731
 
491
732
  if !passed
492
733
  has_error = true
493
- actual_json = actual_value.to_json
494
- errors += " ✘ expectedVariables.#{variable_key}: expected #{expected_value} but received #{actual_json}\n"
734
+ errors << expectation_error("variable", expected_value, actual_value, variableKey: variable_key)
495
735
  end
496
736
  next
497
737
  rescue JSON::ParserError
@@ -502,7 +742,7 @@ module FeaturevisorCLI
502
742
  # Regular comparison for non-JSON strings or when JSON parsing fails
503
743
  if !compare_values(actual_value, expected_value)
504
744
  has_error = true
505
- errors += " ✘ expectedVariables.#{variable_key}: expected #{expected_value} but received #{actual_value}\n"
745
+ errors << expectation_error("variable", expected_value, actual_value, variableKey: variable_key)
506
746
  end
507
747
  end
508
748
  end
@@ -518,7 +758,10 @@ module FeaturevisorCLI
518
758
  actual_value = get_evaluation_value(evaluation, key)
519
759
  if !compare_values(actual_value, expected_value)
520
760
  has_error = true
521
- errors += " ✘ expectedEvaluations.flag.#{key}: expected #{expected_value} but received #{actual_value}\n"
761
+ errors << expectation_error(
762
+ "evaluation", expected_value, actual_value,
763
+ evaluationType: "flag", evaluationKey: key
764
+ )
522
765
  end
523
766
  end
524
767
  end
@@ -530,7 +773,10 @@ module FeaturevisorCLI
530
773
  actual_value = get_evaluation_value(evaluation, key)
531
774
  if !compare_values(actual_value, expected_value)
532
775
  has_error = true
533
- errors += " ✘ expectedEvaluations.variation.#{key}: expected #{expected_value} but received #{actual_value}\n"
776
+ errors << expectation_error(
777
+ "evaluation", expected_value, actual_value,
778
+ evaluationType: "variation", evaluationKey: key
779
+ )
534
780
  end
535
781
  end
536
782
  end
@@ -544,7 +790,10 @@ module FeaturevisorCLI
544
790
  actual_value = get_evaluation_value(evaluation, key)
545
791
  if !compare_values(actual_value, expected_value)
546
792
  has_error = true
547
- errors += " ✘ expectedEvaluations.variables.#{variable_key}.#{key}: expected #{expected_value} but received #{actual_value}\n"
793
+ errors << expectation_error(
794
+ "evaluation", expected_value, actual_value,
795
+ variableKey: variable_key, evaluationKey: key
796
+ )
548
797
  end
549
798
  end
550
799
  end
@@ -554,24 +803,25 @@ module FeaturevisorCLI
554
803
 
555
804
  # Test children
556
805
  if assertion[:children]
557
- assertion[:children].each do |child|
806
+ assertion[:children].each_with_index do |child, child_index|
558
807
  if child.is_a?(Hash)
559
808
  child_context = parse_context(child[:context])
560
809
 
561
810
  # Create override options for child with sticky values
562
811
  child_instance = instance.spawn(
563
812
  child_context,
564
- sticky_features: sticky || {}
813
+ sticky_features: parse_sticky(child[:stickyFeatures]) || {},
814
+ sticky_variables: child[:stickyVariables].is_a?(Hash) ? child[:stickyVariables] : {}
565
815
  )
566
816
  begin
567
- child_result = run_test_feature_child(child, feature_key, child_instance, level)
817
+ child_result = run_test_feature_child(child, feature_key, child_instance, level, child_index)
568
818
  ensure
569
819
  child_instance.close
570
820
  end
571
821
 
572
822
  if child_result[:has_error]
573
823
  has_error = true
574
- errors += child_result[:errors]
824
+ errors.concat(child_result[:errors])
575
825
  end
576
826
  end
577
827
  end
@@ -586,12 +836,13 @@ module FeaturevisorCLI
586
836
  }
587
837
  end
588
838
 
589
- def run_test_feature_child(assertion, feature_key, instance, level)
839
+ def run_test_feature_child(assertion, feature_key, instance, level, child_index = nil)
590
840
  context = parse_context(assertion[:context])
591
841
  override_options = create_override_options(assertion)
592
842
 
593
843
  has_error = false
594
- errors = ""
844
+ errors = []
845
+ child_details = child_index.nil? ? {} : { childIndex: child_index }
595
846
  start_time = Time.now
596
847
 
597
848
  # Test expectedToBeEnabled
@@ -601,7 +852,7 @@ module FeaturevisorCLI
601
852
 
602
853
  if is_enabled != expected_to_be_enabled
603
854
  has_error = true
604
- errors += " ✘ expectedToBeEnabled: expected #{expected_to_be_enabled} but received #{is_enabled}\n"
855
+ errors << expectation_error("flag", expected_to_be_enabled, is_enabled, child_details)
605
856
  end
606
857
  end
607
858
 
@@ -613,7 +864,7 @@ module FeaturevisorCLI
613
864
  variation_value = variation.nil? ? nil : variation
614
865
  if !compare_values(variation_value, expected_variation)
615
866
  has_error = true
616
- errors += " ✘ expectedVariation: expected #{expected_variation} but received #{variation_value}\n"
867
+ errors << expectation_error("variation", expected_variation, variation_value, child_details)
617
868
  end
618
869
  end
619
870
 
@@ -644,8 +895,10 @@ module FeaturevisorCLI
644
895
 
645
896
  if !passed
646
897
  has_error = true
647
- actual_json = actual_value.to_json
648
- errors += " ✘ expectedVariables.#{variable_key}: expected #{expected_value} but received #{actual_json}\n"
898
+ errors << expectation_error(
899
+ "variable", expected_value, actual_value,
900
+ child_details.merge(variableKey: variable_key)
901
+ )
649
902
  end
650
903
  next
651
904
  rescue JSON::ParserError
@@ -656,7 +909,10 @@ module FeaturevisorCLI
656
909
  # Regular comparison for non-JSON strings or when JSON parsing fails
657
910
  if !compare_values(actual_value, expected_value)
658
911
  has_error = true
659
- errors += " ✘ expectedVariables.#{variable_key}: expected #{expected_value} but received #{actual_value}\n"
912
+ errors << expectation_error(
913
+ "variable", expected_value, actual_value,
914
+ child_details.merge(variableKey: variable_key)
915
+ )
660
916
  end
661
917
  end
662
918
  end
@@ -671,7 +927,10 @@ module FeaturevisorCLI
671
927
  actual_value = get_evaluation_value(evaluation, key)
672
928
  if !compare_values(actual_value, expected_value)
673
929
  has_error = true
674
- errors += " ✘ expectedEvaluations.flag.#{key}: expected #{expected_value} but received #{actual_value}\n"
930
+ errors << expectation_error(
931
+ "evaluation", expected_value, actual_value,
932
+ child_details.merge(evaluationType: "flag", evaluationKey: key)
933
+ )
675
934
  end
676
935
  end
677
936
  end
@@ -682,7 +941,10 @@ module FeaturevisorCLI
682
941
  actual_value = get_evaluation_value(evaluation, key)
683
942
  if !compare_values(actual_value, expected_value)
684
943
  has_error = true
685
- errors += " ✘ expectedEvaluations.variation.#{key}: expected #{expected_value} but received #{actual_value}\n"
944
+ errors << expectation_error(
945
+ "evaluation", expected_value, actual_value,
946
+ child_details.merge(evaluationType: "variation", evaluationKey: key)
947
+ )
686
948
  end
687
949
  end
688
950
  end
@@ -702,7 +964,10 @@ module FeaturevisorCLI
702
964
  actual_value = get_evaluation_value(evaluation, key)
703
965
  if !compare_values(actual_value, expected_value)
704
966
  has_error = true
705
- errors += " ✘ expectedEvaluations.variables.#{variable_key}.#{key}: expected #{expected_value} but received #{actual_value}\n"
967
+ errors << expectation_error(
968
+ "evaluation", expected_value, actual_value,
969
+ child_details.merge(variableKey: variable_key, evaluationKey: key)
970
+ )
706
971
  end
707
972
  end
708
973
  end
@@ -719,35 +984,27 @@ module FeaturevisorCLI
719
984
  }
720
985
  end
721
986
 
722
- def run_test_segment(assertion, segment, level)
987
+ def run_test_segment(assertion, segment, level, selected = nil, segments = {}, segment_key = "subject", set = @active_set)
988
+ return { has_error: true, errors: "segment was not found", duration: 0 } unless segment.is_a?(Hash)
723
989
  context = parse_context(assertion[:context])
724
- conditions = segment[:conditions]
725
-
726
- # Create a minimal datafile for segment testing
727
- datafile = {
728
- schemaVersion: "2",
729
- revision: "tester",
730
- features: {},
731
- segments: {}
732
- }
733
-
734
- # Create SDK instance for segment testing
735
- instance = Featurevisor.create_featurevisor(
736
- datafile: datafile,
737
- log_level: level
738
- )
990
+ segments = segments.merge(segment_key.to_sym => segment)
991
+ datafile = selected || { schemaVersion: "4", revision: "tester", features: {}, segments: {}, variables: {} }
992
+ SegmentTests.references!(segment_key, datafile, segments)
993
+ datafile = SegmentTests.prepare(datafile, segments)
994
+ instance, = create_tester_instance(datafile, level, assertion, set)
995
+ instance.instance_variable_set(:@__segment_test_keys, datafile[:_segment_test_keys])
739
996
 
740
997
  has_error = false
741
- errors = ""
998
+ errors = []
742
999
  start_time = Time.now
743
1000
 
744
1001
  if assertion.key?(:expectedToMatch)
745
1002
  expected_to_match = assertion[:expectedToMatch]
746
- actual = instance.instance_variable_get(:@datafile).all_conditions_are_matched(conditions, context)
1003
+ actual = segment_matcher(instance).call(segment_key, context)
747
1004
 
748
1005
  if actual != expected_to_match
749
1006
  has_error = true
750
- errors += " ✘ expectedToMatch: expected #{expected_to_match} but received #{actual}\n"
1007
+ errors << expectation_error("segment", expected_to_match, actual)
751
1008
  end
752
1009
  end
753
1010
 
@@ -758,6 +1015,29 @@ module FeaturevisorCLI
758
1015
  errors: errors,
759
1016
  duration: duration
760
1017
  }
1018
+ rescue FeaturevisorCLI::TestChecks::CheckError => error
1019
+ { has_error: true, errors: [expectation_error("segment", "valid references", error.message)], duration: 0 }
1020
+ ensure
1021
+ instance&.close
1022
+ end
1023
+
1024
+ def segment_matcher(instance, segments = {}, keys = nil, diagnostics = nil)
1025
+ keys ||= instance.instance_variable_get(:@__segment_test_keys)
1026
+ keys = {} if !keys && segments.empty?
1027
+ unless keys
1028
+ datafile = SegmentTests.prepare(instance.instance_variable_get(:@datafile).get_datafile, segments)
1029
+ instance.set_datafile(datafile, true)
1030
+ keys = datafile[:_segment_test_keys]
1031
+ instance.instance_variable_set(:@__segment_test_keys, keys)
1032
+ end
1033
+ diagnostics ||= instance.instance_variable_get(:@__segment_test_diagnostics) || []
1034
+ lambda do |key, context|
1035
+ diagnostics.clear
1036
+ evaluation = instance.evaluate_flag(keys.fetch(key.to_s), context)
1037
+ failed = diagnostics.any? { |item| %w[error fatal].include?(item[:level].to_s) }
1038
+ raise TestChecks::CheckError, "segment #{key.inspect} evaluation failed" if evaluation[:reason] == "error" || failed
1039
+ evaluation[:enabled] == true
1040
+ end
761
1041
  end
762
1042
 
763
1043
  def parse_context(context_data)
@@ -865,12 +1145,10 @@ module FeaturevisorCLI
865
1145
  evaluation[:force_index]
866
1146
  when :force
867
1147
  evaluation[:force]
868
- when :required
869
- evaluation[:required]
870
- when :requiredFeatures
871
- evaluation[:required_features]
872
- when :sticky
873
- evaluation[:sticky]
1148
+ when :conditions
1149
+ evaluation[:conditions]
1150
+ when :stickyFeature
1151
+ evaluation[:sticky_feature]
874
1152
  when :variation
875
1153
  evaluation[:variation]
876
1154
  when :variationValue
@@ -887,6 +1165,8 @@ module FeaturevisorCLI
887
1165
  evaluation[:variable_override_key]
888
1166
  when :variableOverridePath
889
1167
  evaluation[:variable_override_path]
1168
+ when :variableOverridePaths
1169
+ evaluation[:variable_override_paths]
890
1170
  else
891
1171
  nil
892
1172
  end
@@ -989,16 +1269,327 @@ module FeaturevisorCLI
989
1269
  end
990
1270
  end
991
1271
 
1272
+ def empty_report
1273
+ {
1274
+ schemaVersion: 1,
1275
+ runner: "ruby",
1276
+ passed: true,
1277
+ summary: {
1278
+ specs: { passed: 0, failed: 0 },
1279
+ assertions: { passed: 0, failed: 0 },
1280
+ entitySpecs: { passed: 0, failed: 0 },
1281
+ entityAssertions: { passed: 0, failed: 0 },
1282
+ scenarioSpecs: { passed: 0, failed: 0 },
1283
+ scenarioCases: { passed: 0, failed: 0 }
1284
+ },
1285
+ results: [],
1286
+ errors: []
1287
+ }
1288
+ end
1289
+
1290
+ def merge_report!(destination, source)
1291
+ destination[:results].concat(source[:results])
1292
+ destination[:errors].concat(source[:errors])
1293
+ end
1294
+
1295
+ def finalize_report!(report)
1296
+ summary = empty_report[:summary]
1297
+ report[:results].each do |result|
1298
+ spec_bucket = result[:type] == "scenario" ? :scenarioSpecs : :entitySpecs
1299
+ case_bucket = result[:type] == "scenario" ? :scenarioCases : :entityAssertions
1300
+ spec_state = result[:passed] ? :passed : :failed
1301
+ summary[:specs][spec_state] += 1
1302
+ summary[spec_bucket][spec_state] += 1
1303
+ result[:cases].each do |item|
1304
+ case_state = item[:passed] ? :passed : :failed
1305
+ summary[:assertions][case_state] += 1
1306
+ summary[case_bucket][case_state] += 1
1307
+ end
1308
+ end
1309
+ report[:summary] = summary
1310
+ report[:passed] = report[:errors].empty? && summary[:specs][:failed].zero? && summary[:assertions][:failed].zero?
1311
+ report[:uncovered] = report[:uncovered].sort_by { |item| item[:set].to_s } if report.key?(:uncovered)
1312
+ report
1313
+ end
1314
+
1315
+ def error_objects(value, type: nil, assertion: nil)
1316
+ errors = if value.is_a?(Array)
1317
+ value.map { |error| error.is_a?(Hash) ? deep_copy(error) : { message: error.to_s } }
1318
+ else
1319
+ value.to_s.lines.filter_map do |line|
1320
+ message = line.sub(/^\s*✘\s*/, "").strip
1321
+ next if message.empty?
1322
+ { message: message }
1323
+ end
1324
+ end
1325
+ return errors unless type && assertion
1326
+
1327
+ errors.map do |error|
1328
+ if error[:type] == "check"
1329
+ decorate_check_error(error, type, assertion)
1330
+ else
1331
+ decorate_expectation_error(error, type, assertion)
1332
+ end
1333
+ end
1334
+ end
1335
+
1336
+ def decorate_check_error(error, type, assertion)
1337
+ return error unless error[:type] == "check"
1338
+
1339
+ details = error[:details].is_a?(Hash) ? error[:details] : {}
1340
+ assertion_index = assertion.dig(:_case, :assertionIndex)
1341
+ base = type == :scenario ? [] : ["assertions", assertion_index || 0]
1342
+ base += ["children", details[:childIndex]] if details.key?(:childIndex)
1343
+ collection = "checks"
1344
+ error[:path] = base + [collection]
1345
+ error[:path] << details[:checkIndex] if details.key?(:checkIndex)
1346
+ if details[:evaluated].is_a?(Array)
1347
+ details[:evaluated] = details[:evaluated].map do |leaf|
1348
+ leaf.merge(path: base + [collection] + Array(leaf[:path]))
1349
+ end
1350
+ end
1351
+ if error[:expected] == true && error[:actual] == false
1352
+ error[:message] = "Check did not match"
1353
+ end
1354
+ error
1355
+ end
1356
+
1357
+ def decorate_expectation_error(error, type, assertion)
1358
+ details = error[:details].is_a?(Hash) ? error[:details] : {}
1359
+ assertion_index = assertion.dig(:_case, :assertionIndex) || 0
1360
+ path = ["assertions", assertion_index]
1361
+ path += ["children", details[:childIndex]] if details.key?(:childIndex)
1362
+ suffix = case error[:type]
1363
+ when "flag" then ["expectedToBeEnabled"]
1364
+ when "segment" then ["expectedToMatch"]
1365
+ when "variation" then ["expectedVariation"]
1366
+ when "variable"
1367
+ type == :variable ? ["expectedValue"] : ["expectedVariables", details[:variableKey]]
1368
+ when "evaluation"
1369
+ if type == :variable
1370
+ ["expectedEvaluation", details[:evaluationKey]]
1371
+ elsif details.key?(:variableKey)
1372
+ ["expectedEvaluations", "variables", details[:variableKey], details[:evaluationKey]]
1373
+ else
1374
+ ["expectedEvaluations", details[:evaluationType], details[:evaluationKey]]
1375
+ end
1376
+ else
1377
+ []
1378
+ end
1379
+ error[:path] = path + suffix unless suffix.empty?
1380
+ error[:path] = path if error[:type] == "schema"
1381
+ error[:message] ||= "expected #{format_test_value(error[:expected])}, received #{format_test_value(error[:actual])}"
1382
+ error
1383
+ end
1384
+
1385
+ def deep_copy(value)
1386
+ Marshal.load(Marshal.dump(value))
1387
+ end
1388
+
1389
+ def normalized_environment(environment)
1390
+ environment == false ? nil : environment
1391
+ end
1392
+
1393
+ def rerun_instruction(assertion, set)
1394
+ args = ["test"]
1395
+ args << "--case=#{assertion.dig(:_case, :id)}" if assertion.dig(:_case, :id)
1396
+ if @options.project_directory_path_explicit
1397
+ args << "--projectDirectoryPath=#{@options.project_directory_path}"
1398
+ end
1399
+ args << "--set=#{set}" if set
1400
+ @options.targets.each { |target| args << "--target=#{target}" }
1401
+ { command: "bundle exec featurevisor", args: args }
1402
+ end
1403
+
1404
+ def progress(message)
1405
+ stream = @options.json ? $stderr : $stdout
1406
+ stream.puts(message)
1407
+ end
1408
+
1409
+ def print_report(report)
1410
+ if @options.json
1411
+ puts(@options.pretty ? JSON.pretty_generate(report) : JSON.generate(report))
1412
+ return
1413
+ end
1414
+
1415
+ if report[:results].empty? && report[:errors].empty?
1416
+ puts "No tests found"
1417
+ end
1418
+ report[:results].each do |result|
1419
+ next if @options.only_failures && result[:passed]
1420
+ puts "\nTesting: #{result[:source]}"
1421
+ result[:cases].each_with_index do |item, index|
1422
+ next if @options.only_failures && item[:passed]
1423
+ puts " #{item[:passed] ? '✔' : '✘'} #{human_case_label(item, index)}"
1424
+ item[:errors].each do |error|
1425
+ human_error_lines(error).each { |line| puts " ✘ #{line}" }
1426
+ end
1427
+ next if item[:passed] || item.dig(:rerun, :args).nil?
1428
+ command = "#{item.dig(:rerun, :command)} #{item.dig(:rerun, :args).map { |arg| Shellwords.escape(arg) }.join(' ')}"
1429
+ puts " Rerun (POSIX shell): #{command}"
1430
+ end
1431
+ end
1432
+ report[:errors].each { |error| puts "Error: #{error[:message]}" }
1433
+ summary = report[:summary]
1434
+ puts ""
1435
+ puts "Entity specs: #{summary[:entitySpecs][:passed]} passed, #{summary[:entitySpecs][:failed]} failed"
1436
+ puts "Entity assertions: #{summary[:entityAssertions][:passed]} passed, #{summary[:entityAssertions][:failed]} failed"
1437
+ puts "Scenario specs: #{summary[:scenarioSpecs][:passed]} passed, #{summary[:scenarioSpecs][:failed]} failed"
1438
+ puts "Scenario cases: #{summary[:scenarioCases][:passed]} passed, #{summary[:scenarioCases][:failed]} failed"
1439
+ puts "Total cases: #{summary[:assertions][:passed]} passed, #{summary[:assertions][:failed]} failed"
1440
+ if report[:uncovered]
1441
+ puts "\nDefinitions without associated specs (not evaluation coverage):"
1442
+ report[:uncovered].each do |item|
1443
+ puts " Set: #{item[:set]}" if item[:set]
1444
+ puts " Features: #{item[:features].empty? ? 'none' : item[:features].join(', ')}"
1445
+ puts " Global variables: #{item[:variables].empty? ? 'none' : item[:variables].join(', ')}"
1446
+ end
1447
+ end
1448
+ if report[:coverage]
1449
+ puts "\nObserved rule and override selections (not branch coverage):"
1450
+ selections = report.dig(:coverage, :selections)
1451
+ selections.each { |selection| puts " #{human_coverage_selection(selection)}" }
1452
+ puts " No selections observed" if selections.empty?
1453
+ end
1454
+ puts ""
1455
+ end
1456
+
1457
+ def human_case_label(item, index)
1458
+ label = item[:description].to_s.empty? ? "assertion #{index + 1}" : item[:description]
1459
+ details = ["case #{index + 1}"]
1460
+ matrix = item[:matrixValues]
1461
+ if matrix.is_a?(Hash) && !matrix.empty?
1462
+ details << "matrix #{matrix.map { |key, value| "#{key}=#{JSON.generate(value)}" }.join(', ')}"
1463
+ end
1464
+ details << "target #{item[:target]}" if item[:target]
1465
+ "#{label} (#{details.join('; ')})"
1466
+ end
1467
+
1468
+ def human_coverage_selection(selection)
1469
+ owner = if selection[:featureKey]
1470
+ "feature #{selection[:featureKey]}#{selection[:variableKey] ? " variable #{selection[:variableKey]}" : ''}"
1471
+ else
1472
+ "global variable #{selection[:variableKey]}"
1473
+ end
1474
+ scope = %i[set environment target].filter_map { |key| "#{key} #{selection[key]}" if selection[key] }
1475
+ picks = []
1476
+ picks << "rule #{selection[:ruleKey]}" if selection[:ruleKey]
1477
+ picks << "variation #{JSON.generate(selection[:variation])}" if selection.key?(:variation)
1478
+ picks << "override #{Array(selection[:overridePath]).join(' > ')}" if selection[:overridePath]
1479
+ picks << "override #{selection[:overrideIndex] + 1}" if selection.key?(:overrideIndex)
1480
+ "#{owner}#{scope.empty? ? '' : " (#{scope.join(', ')})"}: #{picks.join(', ')}"
1481
+ end
1482
+
1483
+ def human_error_lines(error)
1484
+ details = error[:details]
1485
+ return [error[:message]] unless error[:type] == "check" && details.is_a?(Hash)
1486
+
1487
+ named = details[:checkKey] ? " #{details[:checkKey].inspect}" : ""
1488
+ description = details[:checkDescription] ? " (#{details[:checkDescription]})" : ""
1489
+ lines = ["#{human_check_message(error[:message])}#{named}#{description} at #{human_path(error[:path])}"]
1490
+ Array(details[:evaluated]).each do |leaf|
1491
+ reference = human_reference(leaf[:reference])
1492
+ comparison = leaf[:compareTo] ? human_reference(leaf[:compareTo]) : "literal"
1493
+ reference = "#{reference}.#{leaf[:property]}" if leaf[:property]
1494
+ lines << "#{human_path(leaf[:path])}: #{reference} #{leaf[:operator]} #{comparison} " \
1495
+ "(left=#{JSON.generate(leaf[:actual])}, right=#{JSON.generate(leaf[:expected])})"
1496
+ end
1497
+ lines
1498
+ end
1499
+
1500
+ def human_check_message(message)
1501
+ message.to_s.gsub(/\b(checks|children)\[(\d+)\]/) do
1502
+ "#{Regexp.last_match(1) == 'children' ? 'Child' : 'check'} #{Regexp.last_match(2).to_i + 1}"
1503
+ end
1504
+ end
1505
+
1506
+ def human_path(path)
1507
+ Array(path).each_with_index.map do |part, index|
1508
+ part.is_a?(Integer) ? "[#{part + 1}]" : index.zero? ? part.to_s : ".#{part}"
1509
+ end.join
1510
+ end
1511
+
1512
+ def human_reference(reference)
1513
+ return "<unknown>" unless reference.is_a?(Hash)
1514
+ variable = reference[:variable]
1515
+ root = reference[:feature] ? [reference[:feature], variable].compact.join(".") : variable
1516
+ reference.key?(:path) ? "#{root}:#{JSON.generate(reference[:path])}" : root.to_s
1517
+ end
992
1518
 
1519
+ def get_uncovered(set)
1520
+ {
1521
+ set: set,
1522
+ features: get_uncovered_entities("features", set),
1523
+ variables: get_uncovered_entities("variables", set)
1524
+ }
1525
+ end
993
1526
 
1527
+ def get_uncovered_entities(selector, set)
1528
+ command = node_command("list", "--#{selector}", "--without-tests", "--json", *set_arguments(set))
1529
+ output = JSON.parse(execute_command(command), symbolize_names: true)
1530
+ Array(output).filter_map { |item| item.is_a?(Hash) ? item[:key] : item }.map(&:to_s).sort
1531
+ rescue JSON::ParserError => e
1532
+ raise InfrastructureError, "Failed to parse uncovered #{selector} JSON: #{e.message}"
1533
+ end
1534
+
1535
+ def record_coverage_selection(evaluation, assertion, set)
1536
+ rule_key = evaluation[:rule_key]
1537
+ paths = Array(evaluation[:variable_override_paths])
1538
+ paths = [evaluation[:variable_override_path]] if paths.empty? && evaluation[:variable_override_path]
1539
+ paths = [evaluation[:variable_override_key]] if paths.empty? && evaluation[:variable_override_key]
1540
+ paths = [nil] if paths.empty? && evaluation.key?(:variable_override_index)
1541
+ paths = [nil] if paths.empty? && rule_key
1542
+ paths.each do |path|
1543
+ next unless rule_key || path || evaluation.key?(:variable_override_index)
1544
+ item = {
1545
+ set: set,
1546
+ environment: normalized_environment(assertion[:environment]),
1547
+ target: assertion[:target]
1548
+ }
1549
+ item[:featureKey] = evaluation[:feature_key] if evaluation[:feature_key]
1550
+ item[:variableKey] = evaluation[:variable_key] if evaluation[:variable_key]
1551
+ item[:ruleKey] = rule_key if rule_key
1552
+ item[:variation] = evaluation.dig(:variation, :value) if evaluation[:variation].is_a?(Hash) && evaluation[:variation].key?(:value)
1553
+ item[:overridePath] = path if path
1554
+ item[:overrideIndex] = evaluation[:variable_override_index] if !path && evaluation.key?(:variable_override_index)
1555
+ @coverage_selections << item
1556
+ end
1557
+ end
1558
+
1559
+ def coverage_report
1560
+ unique = @coverage_selections.each_with_object({}) do |selection, items|
1561
+ items[JSON.generate(selection)] = selection
1562
+ end.values
1563
+ {
1564
+ mode: "observed-selections",
1565
+ selections: unique.sort_by { |item| JSON.generate(item) }
1566
+ }
1567
+ end
1568
+
1569
+
1570
+
1571
+ # Node CLI calls pass an argument list run in the project directory.
994
1572
  def execute_command(command)
995
- stdout, stderr, status = Open3.capture3(command)
1573
+ stdout, stderr, status =
1574
+ command.is_a?(Array) ? Open3.capture3(*command, chdir: @project_path) : Open3.capture3(command)
1575
+ stdout.force_encoding(Encoding::UTF_8)
1576
+ stderr.force_encoding(Encoding::UTF_8)
996
1577
 
997
1578
  unless status.success?
998
- puts "Error: Command failed with exit code #{status.exitstatus}"
999
- puts "Command: #{command}"
1000
- puts "Stderr: #{stderr}" unless stderr.empty?
1001
- exit 1
1579
+ begin
1580
+ payload = JSON.parse(stderr)
1581
+ error = payload["error"] || {}
1582
+ if error["message"] || error["code"]
1583
+ raise InfrastructureError.new(
1584
+ error["message"] || "Command failed with exit code #{status.exitstatus}",
1585
+ code: error["code"]
1586
+ )
1587
+ end
1588
+ rescue JSON::ParserError
1589
+ nil
1590
+ end
1591
+ details = stderr.empty? ? "" : ": #{stderr.strip}"
1592
+ raise InfrastructureError, "Command failed with exit code #{status.exitstatus}#{details}"
1002
1593
  end
1003
1594
 
1004
1595
  stdout