nukadoko 0.2.0 → 0.3.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.
Files changed (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +126 -0
  3. data/README.ja.md +5 -3
  4. data/README.md +5 -3
  5. data/lib/nukadoko/aria_snapshot.rb +4 -4
  6. data/lib/nukadoko/base.rb +49 -29
  7. data/lib/nukadoko/check.rb +4 -4
  8. data/lib/nukadoko/claim_check.rb +2 -2
  9. data/lib/nukadoko/claim_rules.rb +1 -1
  10. data/lib/nukadoko/claim_sides.rb +469 -0
  11. data/lib/nukadoko/claims.rb +182 -20
  12. data/lib/nukadoko/cli.rb +16 -7
  13. data/lib/nukadoko/codes.json +20 -15
  14. data/lib/nukadoko/criteria.rb +1 -1
  15. data/lib/nukadoko/env_check.rb +1 -3
  16. data/lib/nukadoko/fixtures.rb +53 -21
  17. data/lib/nukadoko/init.rb +0 -1
  18. data/lib/nukadoko/js_json.rb +274 -0
  19. data/lib/nukadoko/js_pattern.rb +531 -0
  20. data/lib/nukadoko/parts.rb +1 -1
  21. data/lib/nukadoko/pattern.rb +62 -2
  22. data/lib/nukadoko/poll.rb +5 -3
  23. data/lib/nukadoko/program.rb +5 -5
  24. data/lib/nukadoko/project_files.rb +17 -0
  25. data/lib/nukadoko/project_program.rb +119 -0
  26. data/lib/nukadoko/run.rb +47 -17
  27. data/lib/nukadoko/run_record.rb +25 -22
  28. data/lib/nukadoko/schema.rb +60 -18
  29. data/lib/nukadoko/secrets.rb +20 -4
  30. data/lib/nukadoko/spaces.rb +28 -0
  31. data/lib/nukadoko/step.rb +7 -1
  32. data/lib/nukadoko/text_fit.rb +1 -1
  33. data/lib/nukadoko/tree_passes.rb +6 -3
  34. data/lib/nukadoko/version.rb +1 -1
  35. data/lib/nukadoko.rb +24 -2
  36. data/llms.txt +12 -11
  37. data/sig/generated/nukadoko/aria_snapshot.rbs +2 -2
  38. data/sig/generated/nukadoko/base.rbs +24 -18
  39. data/sig/generated/nukadoko/check.rbs +1 -1
  40. data/sig/generated/nukadoko/claim_sides.rbs +207 -0
  41. data/sig/generated/nukadoko/claims.rbs +46 -3
  42. data/sig/generated/nukadoko/cli.rbs +1 -1
  43. data/sig/generated/nukadoko/env_check.rbs +0 -4
  44. data/sig/generated/nukadoko/fixtures.rbs +25 -2
  45. data/sig/generated/nukadoko/init.rbs +0 -2
  46. data/sig/generated/nukadoko/js_json.rbs +109 -0
  47. data/sig/generated/nukadoko/js_pattern.rbs +194 -0
  48. data/sig/generated/nukadoko/pattern.rbs +34 -0
  49. data/sig/generated/nukadoko/poll.rbs +3 -2
  50. data/sig/generated/nukadoko/program.rbs +1 -1
  51. data/sig/generated/nukadoko/project_files.rbs +19 -0
  52. data/sig/generated/nukadoko/project_program.rbs +55 -0
  53. data/sig/generated/nukadoko/run.rbs +10 -3
  54. data/sig/generated/nukadoko/run_record.rbs +5 -4
  55. data/sig/generated/nukadoko/schema.rbs +22 -4
  56. data/sig/generated/nukadoko/secrets.rbs +17 -2
  57. data/sig/generated/nukadoko/spaces.rbs +31 -0
  58. data/sig/generated/nukadoko/tree_passes.rbs +2 -2
  59. data/sig/generated/nukadoko.rbs +11 -0
  60. data/skills/nukadoko/SKILL.md +2 -2
  61. data/skills/nukadoko/references/diagnosing.md +1 -1
  62. data/skills/nukadoko/references/examples/http-api.md +19 -16
  63. data/skills/nukadoko/references/fixtures.md +1 -1
  64. data/skills/nukadoko/references/perturbed-worlds.md +8 -6
  65. data/skills/nukadoko/references/program.md +20 -20
  66. data/skills/nukadoko/references/running.md +2 -2
  67. data/skills/nukadoko/references/scenario-rules.md +2 -2
  68. data/skills/nukadoko/references/verdicts.md +3 -3
  69. data/skills/nukadoko/references/writing-steps.md +1 -1
  70. data/skills/nukadoko-verification/SKILL.md +6 -6
  71. metadata +13 -1
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # The names of the files a project keeps nukadoko's settings in, one place
5
+ # for every part of the engine that reads, writes, or names them.
6
+ module Nukadoko
7
+ module Engine
8
+ CONFIG = "nukadoko.config.rb"
9
+ # The program file of releases before the program moved into the
10
+ # config. A project may no longer hold one; a `--base` ref may.
11
+ LEGACY_PROGRAM = "nukadoko.program.rb"
12
+ # What a `--base` run writes into a tree for the program it runs:
13
+ # another config whose program the tree runs, or a ref's legacy file.
14
+ TREE_PROGRAM = "nukadoko.tree-program.rb"
15
+ TREE_LEGACY_PROGRAM = "nukadoko.tree-legacy-program.rb"
16
+ end
17
+ end
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "json"
5
+ require "open3"
6
+ require "prism"
7
+ require "rbconfig"
8
+
9
+ # A tree's program under test: the `program` lambda of its
10
+ # nukadoko.config.rb, called once. A config with no program has none, and a
11
+ # run starts no world for it.
12
+ #
13
+ # The program goes with the code and the criteria with the config, so a
14
+ # `nuka run --base` tree can hold one side's config and the other side's
15
+ # program. The run writes that program beside the tree's config: the other
16
+ # side's config as nukadoko.tree-program.rb, or a ref's program file from
17
+ # before the program moved into the config as
18
+ # nukadoko.tree-legacy-program.rb. A project's own program file is refused,
19
+ # with the move to make. Boundary: reading the program; starting it is
20
+ # Program's.
21
+ module Nukadoko
22
+ module Engine
23
+ module ProjectProgram
24
+ LIB = File.expand_path("..", __dir__.to_s)
25
+ UPGRADING = 'CHANGELOG.md, under "The program moves into the config"'
26
+
27
+ # The program of the tree at `root`, whose config is already loaded.
28
+ #: (String) -> Hash[Symbol, untyped]
29
+ def self.read(root)
30
+ raise called_in_config unless Nukadoko.legacy_program.nil?
31
+
32
+ legacy_copy = File.join(root, TREE_LEGACY_PROGRAM)
33
+ return elsewhere(legacy_copy, legacy: true) || {} if File.exist?(legacy_copy)
34
+
35
+ tree_copy = File.join(root, TREE_PROGRAM)
36
+ return elsewhere(tree_copy, legacy: false) || {} if File.exist?(tree_copy)
37
+
38
+ legacy = File.join(root, LEGACY_PROGRAM)
39
+ raise moved if File.exist?(legacy)
40
+
41
+ called(Nukadoko.config_options[:program], CONFIG) || {}
42
+ end
43
+
44
+ # Nukadoko.program called from the config would describe a program
45
+ # nothing reads, so it is refused rather than left unstarted.
46
+ #: () -> Refusal
47
+ def self.called_in_config
48
+ Refusal.new("config-invalid",
49
+ "Invalid config at #{CONFIG}: Nukadoko.program is no longer read: the program under test is the program: lambda of Nukadoko.config now",
50
+ fix: "Move the options Nukadoko.program took into #{CONFIG} as program: -> { { ... } }; #{UPGRADING}, shows the move.")
51
+ end
52
+
53
+ #: () -> Refusal
54
+ def self.moved
55
+ Refusal.new("program-file-moved",
56
+ "#{LEGACY_PROGRAM} is no longer read: the program under test is part of #{CONFIG} now, " \
57
+ "so nukadoko does not start what #{LEGACY_PROGRAM} describes.",
58
+ fix: "Move what #{LEGACY_PROGRAM} describes into #{CONFIG} as its program, and delete #{LEGACY_PROGRAM}; #{UPGRADING}, shows the move.")
59
+ end
60
+
61
+ # What a config's `program` returns, or nil when it has none.
62
+ #: (untyped, String) -> Hash[Symbol, untyped]?
63
+ def self.called(program, name)
64
+ return nil if program.nil?
65
+ unless program.respond_to?(:call)
66
+ raise Refusal.new("config-invalid", "Invalid config at #{name}: program: must be a lambda that returns the program",
67
+ fix: "Write program in #{name} as program: -> { { serve: { command: ..., ready: ... } } }.")
68
+ end
69
+
70
+ value = program.call
71
+ return value if value.is_a?(Hash)
72
+
73
+ raise Refusal.new("config-invalid", "Invalid program at #{name}: the program lambda returned #{value.class}, not a Hash of the program's options",
74
+ fix: "Return the program's options as a Hash from program in #{name}.")
75
+ end
76
+
77
+ # The program `file` gives, read in a process of its own, since
78
+ # loading it here would replace this tree's config and fixtures: a
79
+ # config's program, or the options a legacy file passes to
80
+ # Nukadoko.program. Raises a Refusal naming the file when it does not
81
+ # load.
82
+ #: (String, legacy: bool) -> Hash[Symbol, untyped]?
83
+ def self.elsewhere(file, legacy:)
84
+ read = legacy ? "Nukadoko.legacy_program" : "Nukadoko::Engine::ProjectProgram.called(Nukadoko.config_options[:program], ARGV[1])"
85
+ script = "require \"nukadoko\"; load ARGV[0]; puts JSON.generate(#{read})"
86
+ out, err, status = Open3.capture3(RbConfig.ruby, "-I", LIB, "-rjson", "-e", script, file, File.basename(file), chdir: File.dirname(file))
87
+ unless status.success?
88
+ raise Refusal.new("config-invalid", "Could not load #{File.basename(file)}: #{err.lines.first.to_s.strip}",
89
+ fix: "Correct #{File.basename(file)} as the message says.")
90
+ end
91
+
92
+ JSON.parse(out, symbolize_names: true)
93
+ end
94
+
95
+ # The text of a config with its program lambda cut out, so a change to
96
+ # the program alone leaves the config's mapping as it was: the
97
+ # program goes with the code, and a `--base` run compares only what
98
+ # decides how the criteria are read. A config with no program, or
99
+ # with more than one `program:` key, is read whole.
100
+ #: (String) -> String
101
+ def self.mapping_text(text)
102
+ found = [] #: Array[Prism::Node]
103
+ walk = lambda do |node|
104
+ key = node.key if node.is_a?(Prism::AssocNode)
105
+ if key.is_a?(Prism::SymbolNode) && key.unescaped == "program"
106
+ found << node.value
107
+ end
108
+ node.compact_child_nodes.each { walk.(_1) }
109
+ end
110
+ walk.(Prism.parse(text).value)
111
+ return text unless found.size == 1
112
+
113
+ location = found.first.location
114
+ bytes = text.b
115
+ "#{bytes.byteslice(0, location.start_offset)}#{bytes.byteslice(location.end_offset..)}".force_encoding(text.encoding)
116
+ end
117
+ end
118
+ end
119
+ end
data/lib/nukadoko/run.rb CHANGED
@@ -13,14 +13,16 @@ module Nukadoko
13
13
  module Engine
14
14
  class Run
15
15
  # `world` is head for a run, or base or old for a tree's pass, which
16
- # writes into the head run's directory `dir`. `base` is the
16
+ # writes into the head run's directory `dir`, and reads its env files
17
+ # from `head`'s root, with head's secrets as well as its own. `base` is the
17
18
  # comparison a `--base` run judges its rows by. `scenarios` are in the
18
19
  # run's order, which every round of every pass keeps; `records`, when
19
20
  # given, gets each scenario's run.json entry as one line as it ends,
20
21
  # and `rerun` is what a shuffled run's rerun lines name.
21
- #: (String, Array[singleton(Step)], Array[Scenario], Hash[Symbol, untyped], ?environments: Array[Environment]?, ?left_out: Integer, ?out: untyped, ?world: String, ?dir: String?, ?base: Base?, ?env_flags: Array[String], ?repeat: Integer, ?concurrency: Integer, ?order: Hash[Symbol, untyped], ?records: IO?, ?rerun: untyped, ?walk: WalkFiles::Handle?) -> void
22
+ #: (String, Array[singleton(Step)], Array[Scenario], Hash[Symbol, untyped], ?environments: Array[Environment]?, ?left_out: Integer, ?out: untyped, ?world: String, ?dir: String?, ?base: Base?, ?env_flags: Array[String], ?repeat: Integer, ?concurrency: Integer, ?order: Hash[Symbol, untyped], ?records: IO?, ?rerun: untyped, ?walk: WalkFiles::Handle?, ?head: Hash[Symbol, untyped]?) -> void
22
23
  def initialize(project, steps, scenarios, program, environments: nil, left_out: 0, out: $stdout, world: "head", dir: nil, base: nil, env_flags: [],
23
- repeat: 1, concurrency: 1, order: Order::FILE, records: nil, rerun: nil, walk: nil)
24
+ repeat: 1, concurrency: 1, order: Order::FILE, records: nil, rerun: nil, walk: nil, head: nil)
25
+ @head = head
24
26
  @project = project
25
27
  @steps = steps
26
28
  @scenarios = scenarios
@@ -58,7 +60,7 @@ module Nukadoko
58
60
  tree_cells = {}
59
61
  if @base
60
62
  begin
61
- trees = TreePasses.new(@base, @scenarios, cells, @environments, @dir, @out, ->(scenario) { Run.then_judged_by(scenario, executions) })
63
+ trees = TreePasses.new(@base, @scenarios, cells, @environments, @dir, @out, ->(scenario) { Run.then_judged_by(scenario, executions) }, head_root: @project)
62
64
  tree_cells = trees.call(executions)
63
65
  @world_entries.concat(trees.worlds)
64
66
  ensure
@@ -124,7 +126,7 @@ module Nukadoko
124
126
  play_in_workers(environment, roles, world, due, ran, runs)
125
127
  else
126
128
  @process_fixtures = FixtureCache.new
127
- @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}))
129
+ @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}), secrets: -> { secrets })
128
130
  play_one = lambda do |scenario|
129
131
  @out.puts boundary(scenario.uri, scenario.line, scenario.name, roles[scenario])
130
132
  ran.(scenario, play(scenario, environment, roles[scenario], world))
@@ -249,7 +251,7 @@ module Nukadoko
249
251
  @out = WorkerOut.new(pipe)
250
252
  @records = nil
251
253
  @process_fixtures = FixtureCache.new
252
- @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}))
254
+ @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}), secrets: -> { secrets })
253
255
  list.each do |scenario|
254
256
  execution = play(scenario, environment, roles[scenario], world)
255
257
  Marshal.dump([:execution, [scenario.uri, scenario.line], execution, @out.take], pipe)
@@ -660,7 +662,7 @@ module Nukadoko
660
662
  @scratch = Scratch.new(@project)
661
663
  @scenario_fixtures = FixtureCache.new
662
664
  @process_fixtures = FixtureCache.new
663
- @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}))
665
+ @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}), secrets: -> { secrets })
664
666
  record = { step_record_id: @id, step: step.step_name, started_at: now }
665
667
  execute(step, record, @dir, world, then_line: true, at_line: nil, results: [], origins: origins) { [args, texts] }
666
668
  ensure
@@ -677,6 +679,19 @@ module Nukadoko
677
679
 
678
680
  private
679
681
 
682
+ # A value as a record stores it: JSON has no NaN or Infinity, and
683
+ # JavaScript writes either as null, so an arg a {float} read as "-"
684
+ # reaches the record the TypeScript engine writes.
685
+ #: (untyped) -> untyped
686
+ def stored(value)
687
+ case value
688
+ when Float then value.finite? ? value : nil
689
+ when Hash then value.transform_values { stored(_1) }
690
+ when Array then value.map { stored(_1) }
691
+ else value
692
+ end
693
+ end
694
+
680
695
  # Runs one step whose args the block binds, and writes its record and
681
696
  # HTTP log into `dir`.
682
697
  #: (singleton(Step), Hash[Symbol, untyped], String, World, then_line: bool, at_line: Integer?, results: Array[untyped], origins: Hash[String, String]) { () -> [Hash[String, untyped], Hash[String, String]] } -> Hash[Symbol, untyped]
@@ -693,11 +708,11 @@ module Nukadoko
693
708
  begin
694
709
  record[:mutates] = step.mutating?
695
710
  args, texts = yield
696
- record[:args] = args
697
- problems = step.args.problems(args)
711
+ record[:args] = stored(args)
712
+ problems = step.args.problems(args, strict: true)
698
713
  if problems.any?
699
714
  record[:error_kind] = "args_invalid"
700
- raise TypeError, "args: #{problems.join("; ")}"
715
+ raise TypeError, "args validation failed: #{problems.join("; ")}"
701
716
  end
702
717
 
703
718
  @browser&.step = { step_record_id: record[:step_record_id], step: record[:step], line: at_line }
@@ -773,10 +788,15 @@ module Nukadoko
773
788
  observed = observed.is_a?(Hash) ? observed.transform_keys(&:to_s).merge(from_values) : observed
774
789
  Claims.take_aria_snapshots(step.claims, observed)
775
790
  end
791
+ sides = lambda do |observed|
792
+ ClaimSides::Inputs.new(observed: observed, args: args, observes: observes, from_keys: step.from.keys.map(&:to_s),
793
+ labels: ->(key) { origins.fetch(key, "sentence:#{key}") },
794
+ received: observes ? step.inputs.fields.map { _1.name.to_s } : [])
795
+ end
776
796
  # A reading with a page open is timed, so the record can say what the page had received by then.
777
797
  read = (plain = read; -> { @browser.reading(&plain) }) if own[:page]
778
798
  observed = begin
779
- step.poll ? Poll.new(step.poll, step.claims, args).call(record, &read) : read.()
799
+ step.poll ? Poll.new(step.poll, step.claims, args, sides).call(record, &read) : read.()
780
800
  rescue StandardError => e
781
801
  raise unless observes && !step.poll
782
802
 
@@ -786,7 +806,7 @@ module Nukadoko
786
806
  record[:error_kind] = "unobserved"
787
807
  raise e.class, "the step observed nothing, so no claim was judged: #{e.message}"
788
808
  end
789
- judged = Claims.judge(step.claims, observed, args)
809
+ judged = Claims.judge(step.claims, observed, args, sides.(observed))
790
810
  record[:claims] = judged
791
811
  # The value each claim read before its view, for `measured`.
792
812
  record[:raw_actuals] = step.claims.map do |declared|
@@ -803,7 +823,7 @@ module Nukadoko
803
823
  patterns = [step.pattern].compact
804
824
  record[:claim_records] = step.claims.zip(judged).map do |declared, result|
805
825
  if declared[:each]
806
- RunRecord.each_claim(declared, observed, args, origins, texts, observed_from: observes && !from_values.key?(declared[:actual].to_s.split(".").first), patterns: patterns)
826
+ RunRecord.each_claim(declared, sides.(observed), origins, texts, patterns: patterns)
807
827
  else
808
828
  RunRecord.claim(declared, result, origins, texts, observed: observes && !from_values.key?(declared[:actual].to_s.split(".").first), patterns: patterns)
809
829
  end
@@ -814,8 +834,11 @@ module Nukadoko
814
834
  message = RunRecord.broken_message(record[:claim_records])
815
835
  first, *rest = message.split("\n", -1)
816
836
  message = ["#{first}#{RunRecord.poll_end(step, record)}", *rest].join("\n")
817
- record.merge!(status: "failed", outcome: then_line ? :fail : :broke, claim: broken,
818
- broken_actual: judged[broken][:actual], error_kind: "claim_broken", error: message)
837
+ # A claim nukadoko could not judge is never the criterion failing, so
838
+ # it decides the kind even when another claim broke.
839
+ unjudged = record[:claim_records].any? { _1[:outcome] == "unjudged" }
840
+ record.merge!(status: "failed", outcome: then_line && !unjudged ? :fail : :broke, claim: broken,
841
+ broken_actual: judged[broken][:actual], error_kind: unjudged ? "claim_unjudged" : "claim_broken", error: message)
819
842
  else
820
843
  value, problems = step.returned(step.new.run(**step.keywords(fixtures.slice(*step.fixtures), step.inputs.load(args))))
821
844
  if problems.any?
@@ -962,8 +985,15 @@ module Nukadoko
962
985
  def read_env(environment)
963
986
  EnvCheck.validate!
964
987
  config = Nukadoko.config_options.fetch(:secrets, {}) #: Hash[Symbol, untyped]
965
- @env_vars = EnvFile.load(@project, environment.env_files)
966
- @secrets = Secrets.of(@project, environment.env_files, public_keys: (config[:public] || []).map(&:to_s), redact_keys: (config[:redact] || []).map(&:to_s))
988
+ # A tree's checkout holds no env file git ignores, and head's are
989
+ # the ones the person keeps.
990
+ root = @head ? @head[:root].to_s : @project
991
+ @env_vars = EnvFile.load(root, environment.env_files)
992
+ @secrets = Secrets.of(root, environment.env_files, public_keys: (config[:public] || []).map(&:to_s), redact_keys: (config[:redact] || []).map(&:to_s))
993
+ head = @head
994
+ return unless head
995
+
996
+ @secrets = @secrets.with(Secrets.of(root, head[:env_files], public_keys: head[:public], redact_keys: head[:redact]))
967
997
  rescue EnvFile::Unreadable => e
968
998
  raise Refusal.new("env-file-unreadable", e.message)
969
999
  end
@@ -143,42 +143,43 @@ module Nukadoko
143
143
  # and item claim as declared, how many items the list held and how
144
144
  # many `where` selected, and the judged items, the broken first, at
145
145
  # most 20, in index order.
146
- #: (Hash[Symbol, untyped], untyped, untyped, Hash[String, String], Hash[String, String?], observed_from: bool, ?patterns: Array[String]) -> Hash[Symbol, untyped]
147
- def each_claim(declared, observed, args, origins, texts, observed_from:, patterns: [])
148
- key = declared[:actual].to_s
149
- actual_from = place(observed_from ? "observe:#{key}" : origins.fetch(key, "sentence:#{key}"), declared[:view], declared[:at])
146
+ #: (Hash[Symbol, untyped], Engine::ClaimSides::Inputs, Hash[String, String], Hash[String, String?], ?patterns: Array[String]) -> Hash[Symbol, untyped]
147
+ def each_claim(declared, inputs, origins, texts, patterns: [])
148
+ sides = Engine::ClaimSides
149
+ args = inputs.args
150
+ observed = inputs.observed
150
151
  each = declared[:each]
151
152
  where = each[:where] || []
152
153
  declarations = { **(where.empty? ? {} : { where: where.map { item_declaration(_1, args, origins, texts, patterns, observed) } }),
153
154
  claims: each[:claims].map { item_declaration(_1, args, origins, texts, patterns, observed) } }
154
- base = { actual_from: actual_from, view: declared[:view], at: declared[:at]&.to_s }.compact
155
- value = begin
156
- Claims.dig(Claims.view(declared[:view], Claims.read(observed, declared[:actual])), declared[:at])
157
- rescue StandardError => e
158
- unread = e
155
+ array = sides.array_side(declared, inputs)
156
+ base = { actual_from: array.place.label, view: declared[:view], at: declared[:at]&.to_s }.compact
157
+ value = array.found[:value]
158
+ count = value.is_a?(Array) ? value.size : 0
159
+ ended = lambda do |reason, results = [], outcome = "broken"|
160
+ base.merge(each: { **declarations, items: count, selected: 0, results: results }, outcome: outcome, reason: reason, measured: nil)
159
161
  end
160
- ended = lambda do |reason, items = 0, results = [], outcome = "broken"|
161
- base.merge(each: { **declarations, items: items, selected: 0, results: results }, outcome: outcome, reason: reason, measured: nil)
162
- end
163
- return ended.("#{actual_from} could not be read: #{unread.message}") if unread
162
+ stop = array.found.slice(:broken, :unjudged).then { _1.empty? ? nil : _1 } || sides.each_stop(declared, array.place, inputs)
163
+ return ended.(stop[:broken] || stop[:unjudged], [], stop[:unjudged] ? "unjudged" : "broken") if stop
164
164
  return ended.("each reads an array, and the value is #{article(json_type(value))}") unless value.is_a?(Array)
165
165
  return ended.("the array is empty, and a claim on every item of nothing measures nothing") if value.empty?
166
166
 
167
167
  judged = []
168
168
  value.each_with_index do |item, index|
169
- at = "#{actual_from}.#{index}"
170
- where_records = where.map { item_comparison(_1, item, at, args, origins, texts, patterns, observed) }
169
+ place = sides.place_at(array.place, index.to_s)
170
+ compare = ->(entry) { item_comparison(entry, sides.item_side(item, place, entry), inputs, origins, texts, patterns) }
171
+ where_records = where.map(&compare)
171
172
  # A where claim that could not compare says nothing about whether
172
173
  # the item belongs, so leaving it out would turn "every item" into
173
174
  # "the items that happen to compare".
174
175
  if (unjudgeable = where_records.find { _1[:reason] })
175
176
  outcome = unjudgeable[:outcome] == "unjudged" ? "unjudged" : "broken"
176
- return ended.("where could not #{outcome == "unjudged" ? "judge" : "compare"} item #{index}: #{unjudgeable[:reason]}", value.size,
177
+ return ended.("where could not #{outcome == "unjudged" ? "judge" : "compare"} item #{index}: #{unjudgeable[:reason]}",
177
178
  [{ index: index, selected: false, where: where_records }], outcome)
178
179
  end
179
180
  next judged << { index: index, selected: false, where: where_records } unless where_records.all? { _1[:outcome] == "held" }
180
181
 
181
- claims = each[:claims].map { item_comparison(_1, item, at, args, origins, texts, patterns, observed) }
182
+ claims = each[:claims].map(&compare)
182
183
  outcome = claims.any? { _1[:outcome] == "broken" } ? "broken" : claims.any? { _1[:outcome] == "unjudged" } ? "unjudged" : "held"
183
184
  identity = outcome == "broken" && item.is_a?(Hash) && IDENTITY_FIELDS.lazy.filter_map do |field|
184
185
  v = item.transform_keys(&:to_s)[field]
@@ -213,12 +214,14 @@ module Nukadoko
213
214
  expected_text: expected_text)
214
215
  end
215
216
 
216
- #: (Hash[Symbol, untyped], untyped, String, untyped, Hash[String, String], Hash[String, String?], Array[String], untyped) -> Hash[Symbol, untyped]
217
- def item_comparison(entry, item, at, args, origins, texts, patterns, top)
218
- judged = Claims.judge_one(entry, item, args, top)
217
+ # One where or item claim on one item, judged on the side the item gives.
218
+ #: (Hash[Symbol, untyped], Engine::ClaimSides::Side, Engine::ClaimSides::Inputs, Hash[String, String], Hash[String, String?], Array[String]) -> Hash[Symbol, untyped]
219
+ def item_comparison(entry, side, inputs, origins, texts, patterns)
220
+ sides = Engine::ClaimSides
221
+ judged = sides.judge_comparison(entry, side, inputs)
222
+ label = sides.place_counted(sides.place_at(sides.place_viewed(side.place, entry[:view]), entry[:at]&.to_s), entry[:count]).label
219
223
  expected_from, expected_text = expected_origin(entry, origins, texts, patterns)
220
- { **judged.slice(:actual), actual_from: counted(place(entry[:actual] ? "#{at}.#{entry[:actual]}" : at, entry[:view], entry[:at]), entry[:count]),
221
- **{ view: entry[:view], at: entry[:at]&.to_s, count: entry[:count] }.compact }
224
+ { **judged.slice(:actual), actual_from: label, **{ view: entry[:view], at: entry[:at]&.to_s, count: entry[:count] }.compact }
222
225
  .merge(compare: entry[:compare], **judged.slice(:expected), expected_from: expected_from,
223
226
  **(entry[:expected_view] ? { expected_view: entry[:expected_view] } : {}), expected_text: expected_text,
224
227
  **outcome(judged))
@@ -68,18 +68,27 @@ module Nukadoko
68
68
  data_class.new(**fields.to_h { [_1.name, hash.fetch(_1.name.to_s)] })
69
69
  end
70
70
 
71
- # Every way `value` departs from the schema, as `path: problem` lines.
71
+ # Every way `value` departs from the schema, as `path: problem` lines in
72
+ # zod's words, so a step fails with the text the TypeScript engine gives.
72
73
  # A key the schema does not declare is no problem: as a zod object does,
73
- # the schema drops it (`strip`), and `dropped` names where.
74
- #: (untyped, ?String?) -> Array[String]
75
- def problems(value, path = nil)
76
- return ["#{path || "value"} must be an object, got #{value.inspect}"] unless value.is_a?(Hash)
74
+ # the schema drops it (`strip`), and `dropped` names where. `strict`
75
+ # refuses one at the root instead, as the TypeScript engine's args do.
76
+ #: (untyped, ?String?, ?strict: bool) -> Array[String]
77
+ def problems(value, path = nil, strict: false)
78
+ return ["#{path || "(root)"}: #{Schema.invalid("object", value)}"] unless value.is_a?(Hash)
77
79
 
78
80
  hash = value.transform_keys(&:to_s)
79
- fields.flat_map do |field|
81
+ found = fields.flat_map do |field|
80
82
  key = join(path, field.name)
81
- hash.key?(field.name.to_s) ? Schema.type_problems(field.type, hash[field.name.to_s], key) : ["#{key} is missing"]
83
+ if hash.key?(field.name.to_s) then Schema.type_problems(field.type, hash[field.name.to_s], key)
84
+ elsif field.type == :unknown then []
85
+ else Schema.type_problems(field.type, MISSING, key)
86
+ end
82
87
  end
88
+ extra = hash.keys - fields.map { _1.name.to_s }
89
+ return found unless strict && extra.any?
90
+
91
+ found + ["#{path || "(root)"}: Unrecognized key#{"s" if extra.size > 1}: #{extra.map { JSON.generate(_1) }.join(", ")}"]
83
92
  end
84
93
 
85
94
  # The value with every key the schema does not declare left out, at any
@@ -142,24 +151,57 @@ module Nukadoko
142
151
  end
143
152
  end
144
153
 
154
+ # A key the value does not hold, which zod reads as undefined.
155
+ MISSING = Object.new.freeze
156
+ SAFE = 2**53 - 1
157
+
158
+ # What zod calls a value's type in "received ...".
159
+ #: (untyped) -> String
160
+ def self.received(value)
161
+ case value
162
+ when MISSING then "undefined"
163
+ when nil then "null"
164
+ when String then "string"
165
+ when true, false then "boolean"
166
+ when Float then value.nan? ? "NaN" : "number"
167
+ when Numeric then "number"
168
+ when Array then "array"
169
+ else "object"
170
+ end
171
+ end
172
+
173
+ #: (String, untyped) -> String
174
+ def self.invalid(expected, value) = "Invalid input: expected #{expected}, received #{received(value)}"
175
+
145
176
  #: (untyped, untyped, String) -> Array[String]
146
177
  def self.type_problems(type, value, path)
147
- ok =
178
+ problem =
148
179
  case type
149
- in :string then value.is_a?(String)
150
- in :boolean then [true, false].include?(value)
151
- in :integer then value.is_a?(Integer)
152
- in :number then value.is_a?(Numeric)
153
- in :unknown then true
180
+ in :string then invalid("string", value) unless value.is_a?(String)
181
+ in :boolean then invalid("boolean", value) unless [true, false].include?(value)
182
+ in :number then invalid("number", value) unless value.is_a?(Numeric) && value.finite?
183
+ in :integer then integer_problem(value)
184
+ in :unknown then nil
154
185
  in [:nullable, inner] then return value.nil? ? [] : type_problems(inner, value, path)
155
- in [:enum, values] then values.include?(value.is_a?(Symbol) ? value.to_s : value)
186
+ in [:enum, values]
187
+ "Invalid option: expected one of #{values.map { JSON.generate(_1) }.join("|")}" unless values.include?(value.is_a?(Symbol) ? value.to_s : value)
156
188
  in [:array, item]
157
- return ["#{path} must be an array, got #{value.inspect}"] unless value.is_a?(Array)
189
+ return ["#{path}: #{invalid("array", value)}"] unless value.is_a?(Array)
158
190
 
159
- return value.each_with_index.flat_map { |v, i| type_problems(item, v, "#{path}[#{i}]") }
160
- in Schema then return type.problems(value, path)
191
+ return value.each_with_index.flat_map { |v, i| type_problems(item, v, "#{path}.#{i}") }
192
+ in Schema then return value.is_a?(Hash) ? type.problems(value, path) : ["#{path}: #{invalid("object", value)}"]
161
193
  end
162
- ok ? [] : ["#{path} must be #{type}, got #{value.inspect}"]
194
+ problem ? ["#{path}: #{problem}"] : []
195
+ end
196
+
197
+ # zod's int: a finite whole number within Number.MAX_SAFE_INTEGER.
198
+ #: (untyped) -> String?
199
+ def self.integer_problem(value)
200
+ return invalid("number", value) unless value.is_a?(Numeric) && value.finite?
201
+ return "Invalid input: expected int, received number" unless value == value.floor
202
+ return "Too big: expected int to be <=#{SAFE}" if value > SAFE
203
+
204
+ "Too small: expected int to be >=-#{SAFE}" if value < -SAFE
163
205
  end
164
206
 
165
207
  # The JSON Schema `nuka describe` prints, as zod's own conversion gives it:
@@ -213,15 +213,31 @@ module Nukadoko
213
213
  #: Hash[String, String]
214
214
  attr_reader :values
215
215
 
216
- #: (?Hash[String, String]) -> void
216
+ # Each name with its value, a name twice when two sets held it with
217
+ # different values (`with`), so neither value goes unredacted.
218
+ #: Array[[String, String]]
219
+ attr_reader :pairs
220
+
221
+ #: (?Hash[String, String] | Array[[String, String]]) -> void
217
222
  def initialize(values = {})
218
- @values = values
223
+ @pairs = values.to_a.uniq
224
+ @values = @pairs.to_h
219
225
  @replacements = replacements
220
226
  @pattern = @replacements.empty? ? nil : Regexp.union((@replacements.keys + @replacements.values.uniq).sort_by { -_1.length })
221
227
  end
222
228
 
223
229
  #: () -> bool
224
- def empty? = @values.empty?
230
+ def empty? = @pairs.empty?
231
+
232
+ # Both sets: a tree's pass redacts with head's secrets as well as its
233
+ # own, since the tree's config must not decide which of head's values
234
+ # may print.
235
+ #: (Secrets) -> Secrets
236
+ def with(other) = Secrets.new(@pairs + other.pairs)
237
+
238
+ # Every loaded value, each once.
239
+ #: () -> Array[String]
240
+ def shown_values = @pairs.map(&:last).uniq
225
241
 
226
242
  # A copy of `value` with every secret spelling in its strings and
227
243
  # keys written as its token. Two keys that redact to one would lose
@@ -265,7 +281,7 @@ module Nukadoko
265
281
  # among equals the alphabetically first name wins.
266
282
  #: () -> Hash[String, String]
267
283
  def replacements
268
- named = @values.select { |_, value| value.length >= MIN_LENGTH }.sort_by(&:first)
284
+ named = @pairs.select { |_, value| value.length >= MIN_LENGTH }.sort_by(&:first)
269
285
  tokens = {} #: Hash[String, String]
270
286
  named.each { |name, value| tokens[value] ||= "{{secret.#{name}}}" }
271
287
  named.each do |name, value|
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # Responsibility: the spaces JavaScript's trim, trimEnd, and \s take, so a
5
+ # text the Ruby engine trims ends where the TypeScript engine's does.
6
+ # Ruby's strip takes a NUL and no Unicode space, and [[:space:]] takes
7
+ # U+0085, which JavaScript keeps; a page's text often ends in a no-break
8
+ # space, so either would judge a claim the other way.
9
+ module Nukadoko
10
+ module Engine
11
+ module Spaces
12
+ CLASS = "\\s\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff"
13
+ SPACE = /[#{CLASS}]/
14
+ LEADING = /\A[#{CLASS}]+/
15
+ TRAILING = /[#{CLASS}]+\z/
16
+ BLANK = /\A[#{CLASS}]*\z/
17
+
18
+ #: (String) -> String
19
+ def self.trim(text) = text.sub(LEADING, "").sub(TRAILING, "")
20
+
21
+ #: (String) -> String
22
+ def self.trim_end(text) = text.sub(TRAILING, "")
23
+
24
+ #: (String) -> bool
25
+ def self.blank?(text) = text.match?(BLANK)
26
+ end
27
+ end
28
+ end
data/lib/nukadoko/step.rb CHANGED
@@ -96,7 +96,13 @@ module Nukadoko
96
96
  #: (untyped) -> [untyped, Array[String]]
97
97
  def returned(value)
98
98
  schema = returns
99
- return [value, schema.problems(value)] if schema
99
+ # nil is a body that gave back nothing, which zod's "(root): expected
100
+ # object" would leave without its cause or either fix.
101
+ if schema
102
+ nothing = "this step declares returns, but run returned nothing; return a value that matches returns, " \
103
+ "or delete returns if no later step reads from this one"
104
+ return [value, value.nil? ? [nothing] : schema.problems(value)]
105
+ end
100
106
  return [{}, []] unless value.is_a?(Hash)
101
107
  return [value, []] if value.empty?
102
108
 
@@ -172,7 +172,7 @@ module Nukadoko
172
172
  # Whether an expected text states nothing beyond its stand-ins.
173
173
  #: (String) -> bool
174
174
  def only_stand_ins?(expected)
175
- lines(expected).all? { _1 == ANY_LINES || fixed_line(_1).parts.join.strip.empty? }
175
+ lines(expected).all? { _1 == ANY_LINES || Spaces.blank?(fixed_line(_1).parts.join) }
176
176
  end
177
177
  end
178
178
  end
@@ -21,8 +21,9 @@ module Nukadoko
21
21
 
22
22
  # `judged_by` says why head's passing executions of a row judged no
23
23
  # claim in Then position (Run.then_judged_by).
24
- #: (Base, Array[Scenario], Hash[Scenario, Array[Hash[Symbol, untyped]]], Array[Environment], String, IO, ?^(Scenario) -> untyped) -> void
25
- def initialize(base, scenarios, head_cells, environments, dir, out, judged_by = ->(_) {})
24
+ #: (Base, Array[Scenario], Hash[Scenario, Array[Hash[Symbol, untyped]]], Array[Environment], String, IO, ?^(Scenario) -> untyped, ?head_root: String) -> void
25
+ def initialize(base, scenarios, head_cells, environments, dir, out, judged_by = ->(_) {}, head_root: Dir.pwd)
26
+ @head_root = head_root
26
27
  @judged_by = judged_by
27
28
  @base = base
28
29
  @scenarios = scenarios
@@ -105,7 +106,9 @@ module Nukadoko
105
106
  plan = File.join(@dir, "trees", "#{world}-#{environment.name}.plan.json")
106
107
  result = File.join(@dir, "trees", "#{world}-#{environment.name}.result.json")
107
108
  targets = rows.map { |scenario| place(world, scenario).then { { feature: _1, line: _2 } } }
108
- File.write(plan, JSON.generate(world: world, environment: environment.name, targets: targets, dir: @dir, result: result))
109
+ config = Nukadoko.config_options.fetch(:secrets, {}) #: Hash[Symbol, untyped]
110
+ head = { root: File.expand_path(@head_root), env_files: environment.env_files, public: (config[:public] || []).map(&:to_s), redact: (config[:redact] || []).map(&:to_s) }
111
+ File.write(plan, JSON.generate(world: world, environment: environment.name, targets: targets, dir: @dir, result: result, head: head))
109
112
  output, status = Open3.capture2e(RbConfig.ruby, "-I", LIB, EXE, "__tree", plan, chdir: root)
110
113
  @out.write(output.gsub(@dir, File.join(".nukadoko", "runs", File.basename(@dir))))
111
114
  return JSON.parse(File.read(result), symbolize_names: true) if File.exist?(result)
@@ -2,5 +2,5 @@
2
2
  # rbs_inline: enabled
3
3
 
4
4
  module Nukadoko
5
- VERSION = "0.2.0"
5
+ VERSION = "0.3.0"
6
6
  end