nukadoko 0.1.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 (159) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +417 -0
  3. data/README.ja.md +62 -7
  4. data/README.md +19 -5
  5. data/exe/nuka +8 -0
  6. data/lib/nukadoko/aria_snapshot.rb +1008 -0
  7. data/lib/nukadoko/aria_tree.rb +150 -0
  8. data/lib/nukadoko/base.rb +294 -0
  9. data/lib/nukadoko/check.rb +669 -22
  10. data/lib/nukadoko/claim_check.rb +177 -0
  11. data/lib/nukadoko/claim_check_run.rb +293 -0
  12. data/lib/nukadoko/claim_line.rb +381 -0
  13. data/lib/nukadoko/claim_rules.rb +519 -0
  14. data/lib/nukadoko/claim_sides.rb +469 -0
  15. data/lib/nukadoko/claims.rb +576 -37
  16. data/lib/nukadoko/cli.rb +814 -22
  17. data/lib/nukadoko/codes.json +947 -0
  18. data/lib/nukadoko/codes.rb +19 -0
  19. data/lib/nukadoko/command.rb +214 -12
  20. data/lib/nukadoko/criteria.rb +172 -0
  21. data/lib/nukadoko/definition.rb +33 -41
  22. data/lib/nukadoko/env_check.rb +88 -0
  23. data/lib/nukadoko/features.rb +80 -10
  24. data/lib/nukadoko/fixtures.rb +329 -11
  25. data/lib/nukadoko/http_recording.rb +68 -0
  26. data/lib/nukadoko/init.rb +129 -0
  27. data/lib/nukadoko/js_json.rb +274 -0
  28. data/lib/nukadoko/js_pattern.rb +531 -0
  29. data/lib/nukadoko/judge.rb +221 -0
  30. data/lib/nukadoko/judgment_file.rb +78 -0
  31. data/lib/nukadoko/judgments.rb +256 -0
  32. data/lib/nukadoko/literal.rb +129 -0
  33. data/lib/nukadoko/measured.rb +105 -0
  34. data/lib/nukadoko/order.rb +84 -0
  35. data/lib/nukadoko/parts.rb +43 -22
  36. data/lib/nukadoko/pattern.rb +73 -3
  37. data/lib/nukadoko/poll.rb +21 -8
  38. data/lib/nukadoko/program.rb +105 -17
  39. data/lib/nukadoko/project_files.rb +17 -0
  40. data/lib/nukadoko/project_fixtures.rb +17 -2
  41. data/lib/nukadoko/project_program.rb +119 -0
  42. data/lib/nukadoko/report_allure.rb +751 -0
  43. data/lib/nukadoko/report_messages.rb +167 -0
  44. data/lib/nukadoko/report_run.rb +169 -0
  45. data/lib/nukadoko/run.rb +898 -91
  46. data/lib/nukadoko/run_record.rb +535 -0
  47. data/lib/nukadoko/scaffold.rb +1015 -0
  48. data/lib/nukadoko/schema.rb +120 -21
  49. data/lib/nukadoko/secrets.rb +375 -0
  50. data/lib/nukadoko/selection.rb +163 -0
  51. data/lib/nukadoko/signature.rb +4 -1
  52. data/lib/nukadoko/skill.rb +36 -0
  53. data/lib/nukadoko/spaces.rb +28 -0
  54. data/lib/nukadoko/step.rb +68 -21
  55. data/lib/nukadoko/summary.rb +662 -0
  56. data/lib/nukadoko/table.rb +34 -2
  57. data/lib/nukadoko/text_fit.rb +179 -0
  58. data/lib/nukadoko/trace.rb +244 -0
  59. data/lib/nukadoko/trace_actions.rb +116 -0
  60. data/lib/nukadoko/tree_passes.rb +122 -0
  61. data/lib/nukadoko/verdict.rb +128 -0
  62. data/lib/nukadoko/version.rb +2 -1
  63. data/lib/nukadoko/vocabulary.rb +6 -0
  64. data/lib/nukadoko/walk.rb +305 -0
  65. data/lib/nukadoko/walk_files.rb +473 -0
  66. data/lib/nukadoko/walk_step.rb +149 -0
  67. data/lib/nukadoko.rb +60 -2
  68. data/llms.txt +297 -0
  69. data/sig/generated/nukadoko/aria_snapshot.rbs +331 -0
  70. data/sig/generated/nukadoko/aria_tree.rbs +142 -0
  71. data/sig/generated/nukadoko/base.rbs +142 -0
  72. data/sig/generated/nukadoko/check.rbs +255 -0
  73. data/sig/generated/nukadoko/claim_check.rbs +118 -0
  74. data/sig/generated/nukadoko/claim_check_run.rbs +88 -0
  75. data/sig/generated/nukadoko/claim_line.rbs +158 -0
  76. data/sig/generated/nukadoko/claim_rules.rbs +172 -0
  77. data/sig/generated/nukadoko/claim_sides.rbs +207 -0
  78. data/sig/generated/nukadoko/claims.rbs +208 -0
  79. data/sig/generated/nukadoko/cli.rbs +182 -0
  80. data/sig/generated/nukadoko/codes.rbs +16 -0
  81. data/sig/generated/nukadoko/command.rbs +109 -0
  82. data/sig/generated/nukadoko/criteria.rbs +83 -0
  83. data/sig/generated/nukadoko/definition.rbs +30 -0
  84. data/sig/generated/nukadoko/env_check.rbs +34 -0
  85. data/sig/generated/nukadoko/features.rbs +101 -0
  86. data/sig/generated/nukadoko/fixtures.rbs +175 -0
  87. data/sig/generated/nukadoko/http_recording.rbs +29 -0
  88. data/sig/generated/nukadoko/init.rbs +64 -0
  89. data/sig/generated/nukadoko/js_json.rbs +109 -0
  90. data/sig/generated/nukadoko/js_pattern.rbs +194 -0
  91. data/sig/generated/nukadoko/judge.rbs +64 -0
  92. data/sig/generated/nukadoko/judgment_file.rbs +39 -0
  93. data/sig/generated/nukadoko/judgments.rbs +120 -0
  94. data/sig/generated/nukadoko/literal.rbs +71 -0
  95. data/sig/generated/nukadoko/measured.rbs +42 -0
  96. data/sig/generated/nukadoko/order.rbs +54 -0
  97. data/sig/generated/nukadoko/parts.rbs +35 -0
  98. data/sig/generated/nukadoko/pattern.rbs +62 -0
  99. data/sig/generated/nukadoko/poll.rbs +41 -0
  100. data/sig/generated/nukadoko/program.rbs +101 -0
  101. data/sig/generated/nukadoko/project_files.rbs +19 -0
  102. data/sig/generated/nukadoko/project_fixtures.rbs +57 -0
  103. data/sig/generated/nukadoko/project_program.rbs +55 -0
  104. data/sig/generated/nukadoko/report_allure.rbs +268 -0
  105. data/sig/generated/nukadoko/report_messages.rbs +68 -0
  106. data/sig/generated/nukadoko/report_run.rbs +102 -0
  107. data/sig/generated/nukadoko/run.rbs +264 -0
  108. data/sig/generated/nukadoko/run_record.rbs +175 -0
  109. data/sig/generated/nukadoko/scaffold.rbs +328 -0
  110. data/sig/generated/nukadoko/schema.rbs +155 -0
  111. data/sig/generated/nukadoko/secrets.rbs +172 -0
  112. data/sig/generated/nukadoko/selection.rbs +73 -0
  113. data/sig/generated/nukadoko/signature.rbs +17 -0
  114. data/sig/generated/nukadoko/skill.rbs +20 -0
  115. data/sig/generated/nukadoko/spaces.rbs +31 -0
  116. data/sig/generated/nukadoko/step.rbs +115 -0
  117. data/sig/generated/nukadoko/summary.rbs +204 -0
  118. data/sig/generated/nukadoko/table.rbs +43 -0
  119. data/sig/generated/nukadoko/text_fit.rbs +70 -0
  120. data/sig/generated/nukadoko/trace.rbs +127 -0
  121. data/sig/generated/nukadoko/trace_actions.rbs +40 -0
  122. data/sig/generated/nukadoko/tree_passes.rbs +48 -0
  123. data/sig/generated/nukadoko/verdict.rbs +56 -0
  124. data/sig/generated/nukadoko/version.rbs +5 -0
  125. data/sig/generated/nukadoko/vocabulary.rbs +25 -0
  126. data/sig/generated/nukadoko/walk.rbs +139 -0
  127. data/sig/generated/nukadoko/walk_files.rbs +189 -0
  128. data/sig/generated/nukadoko/walk_step.rbs +50 -0
  129. data/sig/generated/nukadoko.rbs +26 -0
  130. data/sig/nukadoko.rbs +5 -48
  131. data/skills/nukadoko/SKILL.md +120 -0
  132. data/skills/nukadoko/references/checking-steps.md +200 -0
  133. data/skills/nukadoko/references/diagnosing.md +200 -0
  134. data/skills/nukadoko/references/done.md +99 -0
  135. data/skills/nukadoko/references/evidence.md +124 -0
  136. data/skills/nukadoko/references/examples/cli.md +230 -0
  137. data/skills/nukadoko/references/examples/http-api.md +342 -0
  138. data/skills/nukadoko/references/examples/workflow.md +173 -0
  139. data/skills/nukadoko/references/exploring.md +184 -0
  140. data/skills/nukadoko/references/fixtures.md +198 -0
  141. data/skills/nukadoko/references/from-prose.md +51 -0
  142. data/skills/nukadoko/references/judgments.md +95 -0
  143. data/skills/nukadoko/references/maintenance.md +97 -0
  144. data/skills/nukadoko/references/merge-risk.md +74 -0
  145. data/skills/nukadoko/references/parts.md +152 -0
  146. data/skills/nukadoko/references/perturbed-worlds.md +109 -0
  147. data/skills/nukadoko/references/program.md +200 -0
  148. data/skills/nukadoko/references/reviewing.md +200 -0
  149. data/skills/nukadoko/references/running.md +200 -0
  150. data/skills/nukadoko/references/scenario-rules.md +188 -0
  151. data/skills/nukadoko/references/states.md +66 -0
  152. data/skills/nukadoko/references/step-files.md +200 -0
  153. data/skills/nukadoko/references/verdicts.md +200 -0
  154. data/skills/nukadoko/references/writing-steps.md +200 -0
  155. data/skills/nukadoko/references/writing-the-feature.md +165 -0
  156. data/skills/nukadoko/scripts/claude-code-verdict-hook.mjs +99 -0
  157. data/skills/nukadoko/scripts/merge-risk.jq +56 -0
  158. data/skills/nukadoko-verification/SKILL.md +263 -0
  159. metadata +133 -1
data/lib/nukadoko/run.rb CHANGED
@@ -1,4 +1,5 @@
1
1
  # frozen_string_literal: true
2
+ # rbs_inline: enabled
2
3
 
3
4
  require "securerandom"
4
5
  require "fileutils"
@@ -11,176 +12,941 @@ require "time"
11
12
  module Nukadoko
12
13
  module Engine
13
14
  class Run
14
- def initialize(project, steps, scenarios, program, out: $stdout)
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`, and reads its env files
17
+ # from `head`'s root, with head's secrets as well as its own. `base` is the
18
+ # comparison a `--base` run judges its rows by. `scenarios` are in the
19
+ # run's order, which every round of every pass keeps; `records`, when
20
+ # given, gets each scenario's run.json entry as one line as it ends,
21
+ # and `rerun` is what a shuffled run's rerun lines name.
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
23
+ def initialize(project, steps, scenarios, program, environments: nil, left_out: 0, out: $stdout, world: "head", dir: nil, base: nil, env_flags: [],
24
+ repeat: 1, concurrency: 1, order: Order::FILE, records: nil, rerun: nil, walk: nil, head: nil)
25
+ @head = head
15
26
  @project = project
16
27
  @steps = steps
17
28
  @scenarios = scenarios
18
29
  @program = Program.new(program)
30
+ @environments = environments || @program.environments
31
+ @left_out = left_out
19
32
  @out = out
20
- @id = new_id("run")
21
- @dir = File.join(project, ".nukadoko", "runs", @id)
33
+ @world = world
34
+ @base = base
35
+ @env_flags = env_flags
36
+ @repeat = repeat
37
+ @concurrency = concurrency
38
+ @incomplete = []
39
+ @world_entries = []
40
+ @order = order
41
+ @records = records
42
+ @rerun = rerun || { targets: [], tags: [], whole_files: [] }
43
+ # Under --step, the walk this run's one scenario pauses for.
44
+ @walk = walk
45
+ @id = dir ? File.basename(dir) : new_id("run")
46
+ @dir = dir || File.join(project, ".nukadoko", "runs", @id)
22
47
  end
23
48
 
49
+ #: () -> Hash[Symbol, untyped]
24
50
  def call
51
+ # An env file that cannot be read stops the run before anything starts.
52
+ @environments.each { read_env(_1) }
25
53
  FileUtils.mkdir_p(File.join(@dir, "steps"))
54
+ @started_at = now
55
+ write_sources
56
+ @commit = RunRecord.commit(@project)
57
+ # Said before any scenario, so a run a signal stops still names its seed.
58
+ @out.puts "order #{Order.text(@order)}" unless @order[:kind] == "file"
59
+ executions, cells = pass
60
+ tree_cells = {}
61
+ if @base
62
+ begin
63
+ trees = TreePasses.new(@base, @scenarios, cells, @environments, @dir, @out, ->(scenario) { Run.then_judged_by(scenario, executions) }, head_root: @project)
64
+ tree_cells = trees.call(executions)
65
+ @world_entries.concat(trees.worlds)
66
+ ensure
67
+ @base.cleanup
68
+ end
69
+ end
70
+ finish(executions, cells, tree_cells)
71
+ end
72
+
73
+ # One pass of a tree: each scenario in the one environment, as base or
74
+ # old, its executions and its cell.
75
+ #: () -> Array[Hash[Symbol, untyped]]
76
+ def tree_pass
77
+ FileUtils.mkdir_p(File.join(@dir, "steps"))
78
+ executions, cells = pass
79
+ @scenarios.map do |scenario|
80
+ { feature: scenario.uri, line: scenario.line, cell: cells[scenario].first,
81
+ executions: executions.select { _1[:json][:feature] == scenario.uri && _1[:json][:line] == scenario.line }.map { _1[:json] } }
82
+ end
83
+ end
84
+
85
+ # Each world this run started, as run.json's worlds holds it.
86
+ attr_reader :world_entries #: Array[Hash[Symbol, untyped]]
87
+
88
+ #: (Scenario, Environment) -> String
89
+ def role_of(scenario, environment) = Table.role(Table.condition_tags(scenario.tags), environment.conditions)
90
+
91
+ private
92
+
93
+ #: () -> [Array[Hash[Symbol, untyped]], Hash[Scenario, Array[Hash[Symbol, untyped]]]]
94
+ def pass
95
+ @base_urls = {}
26
96
  executions = []
27
97
  cells = Hash.new { |h, k| h[k] = [] }
28
- @program.environments.each do |environment|
29
- @out.puts "environment #{environment.name}"
30
- world_dir = File.join(@dir, "worlds", environment.name)
98
+ # Each scenario line is numbered across every environment and
99
+ # --repeat round, as the TypeScript engine numbers it; a proof run
100
+ # has a line of its own, so it is never one scenario more.
101
+ @played = 0
102
+ @to_play = @scenarios.size * @repeat * @environments.size
103
+ @environments.each do |environment|
104
+ # One environment needs no line of its own: every scenario is in it.
105
+ if @world != "head" then @out.puts "#{@world} #{environment.name}"
106
+ elsif @environments.size > 1 then @out.puts "environment #{environment.name}"
107
+ end
108
+ world_dir = File.join(@dir, "worlds", @world == "head" ? environment.name : "#{environment.name}@#{@world}")
31
109
  FileUtils.mkdir_p(world_dir)
110
+ read_env(environment)
32
111
  world = @program.start(environment, world_dir, @project)
33
- @process_fixtures = FixtureCache.new
34
- @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}))
35
- @scenarios.each do |scenario|
36
- role = Table.role(Table.condition_tags(scenario.tags), environment.conditions)
37
- runs = [play(scenario, environment, role, world)]
38
- runs << play(scenario, environment, role, world) while proving?(role, runs)
39
- executions.concat(runs)
40
- cells[scenario] << Table.cell(runs.map { _1[:execution] }).merge(environment: environment.name, role: role)
112
+ @program_log = world.log_path && Trace::Log.new(world.log_path, world.trace_prefix)
113
+ @base_urls[environment.name] = world.base_url
114
+ roles = @scenarios.to_h { [_1, @world == "head" ? role_of(_1, environment) : "required"] }
115
+ runs = Hash.new { |h, k| h[k] = [] }
116
+ ran = lambda do |scenario, execution|
117
+ runs[scenario] << execution
118
+ executions << execution
119
+ @records&.puts JSON.generate(execution[:json])
41
120
  end
121
+ # Each control that broke a Then runs again, one round at a time,
122
+ # until it has broken the same claim at the same line --proof-runs
123
+ # times or a run disagrees.
124
+ due = -> { @scenarios.select { proving?(roles[_1], runs[_1]) } }
125
+ if @concurrency > 1
126
+ play_in_workers(environment, roles, world, due, ran, runs)
127
+ else
128
+ @process_fixtures = FixtureCache.new
129
+ @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}), secrets: -> { secrets })
130
+ play_one = lambda do |scenario|
131
+ @out.puts boundary(scenario.uri, scenario.line, scenario.name, roles[scenario])
132
+ ran.(scenario, play(scenario, environment, roles[scenario], world))
133
+ end
134
+ # The whole selection once, then again, so a failure that depends
135
+ # on what ran before it meets the same neighbours every round.
136
+ @repeat.times { @scenarios.each(&play_one) }
137
+ until (round = due.()).empty?
138
+ round.each do |scenario|
139
+ @out.puts proof_boundary(scenario.uri, scenario.line, scenario.name, environment.name, runs[scenario].size + 1)
140
+ ran.(scenario, play(scenario, environment, roles[scenario], world))
141
+ end
142
+ end
143
+ end
144
+ @scenarios.each { cells[_1] << cell(runs[_1], environment, roles[_1], _1) }
42
145
  ensure
43
146
  @browser&.close
44
147
  @process_fixtures&.teardown
45
148
  world&.stop
149
+ @world_entries << world_entry(environment, world, world_dir, (runs&.values || []).flatten) if world && @program.file?
150
+ @browser = @process_fixtures = @program_log = nil
46
151
  end
47
- finish(executions, cells)
152
+ [executions, cells]
48
153
  end
49
154
 
50
- private
155
+ # A stopped world as run.json names it. The lines of the program's log
156
+ # that came after their step's record was read go beside that record,
157
+ # and its run.json entry names them.
158
+ #: (Environment, World, String, Array[Hash[Symbol, untyped]]) -> Hash[Symbol, untyped]
159
+ def world_entry(environment, world, world_dir, executions)
160
+ entry = { name: environment.name, tree: @world, url: world.base_url, commands: world.commands, timings: world.timings,
161
+ log: world.log_path && File.join("worlds", File.basename(world_dir), "program.log"), error: nil }
162
+ return entry unless world.base_url
163
+ return entry.merge(program_log: nil) unless world.log_path
164
+
165
+ steps = executions.flat_map { _1[:json][:steps] || [] }.select { _1.dig(:observed, :program_log) }
166
+ traced = steps.to_h { |step| [step[:observed][:program_log][:trace_id], [step[:observed][:program_log][:lines], File.join(@dir, step[:record])]] }
167
+ found = Trace::Log.new(world.log_path, world.trace_prefix).late(traced)
168
+ steps.each do |step|
169
+ late = found[:late][step[:observed][:program_log][:trace_id]]
170
+ step[:program_log_late] = late if late
171
+ end
172
+ sum = ->(key) { steps.sum { _1[:observed][:program_log][key] } }
173
+ entry.merge(program_log: { stamped: sum.(:stamped), lines: sum.(:lines), late: found[:late].values.sum { _1[:lines] }, tagged: found[:tagged] })
174
+ end
175
+
176
+ # Under --concurrency the files go to worker processes in the run's
177
+ # order, round-robin, and each worker plays its own files --repeat
178
+ # times. A file whose Feature line is @nukadoko:serial runs after
179
+ # them, alone, and each round of proof runs is one worker of its own.
180
+ # The parent keeps the world each worker reaches, and takes each
181
+ # execution as it arrives.
182
+ #: (Environment, Hash[Scenario, String], World, ^() -> Array[Scenario], ^(Scenario, Hash[Symbol, untyped]) -> void, Hash[Scenario, Array[Hash[Symbol, untyped]]]) -> void
183
+ def play_in_workers(environment, roles, world, due, ran, runs)
184
+ files = @scenarios.group_by(&:uri).values
185
+ parallel, serial = files.partition { !_1.first.serial }
186
+ buckets = Array.new([@concurrency, parallel.size].min) { [] }
187
+ parallel.each_with_index { |file, i| buckets[i % buckets.size] << file } unless buckets.empty?
188
+ groups = buckets.map(&:flatten)
189
+ # The parent numbers a scenario's line when its execution arrives:
190
+ # the Nth to finish, since workers end in no fixed order.
191
+ line_for = lambda do |scenario, proof|
192
+ proof ? proof_boundary(scenario.uri, scenario.line, scenario.name, environment.name, runs[scenario].size + 1)
193
+ : boundary(scenario.uri, scenario.line, scenario.name, roles[scenario])
194
+ end
195
+ main = ->(scenario) { line_for.(scenario, false) }
196
+ unplayed = workers(groups.map { |group| @repeat.times.flat_map { group } }, environment, roles, world, ran, main)
197
+ serial.each { |file| unplayed += workers([@repeat.times.flat_map { file }], environment, roles, world, ran, main) }
198
+ until (round = due.()).empty?
199
+ break unless workers([round], environment, roles, world, ran, ->(scenario) { line_for.(scenario, true) }).empty?
200
+ end
201
+ return if unplayed.empty?
202
+
203
+ where = unplayed.uniq.sort.map { @environments.size > 1 ? "#{_1} (#{environment.name})" : _1 }
204
+ @incomplete << { severity: "failed", code: "run-incomplete",
205
+ message: "A worker exited without writing any record for: #{where.join(", ")}. This run is incomplete and cannot be treated as a pass" }
206
+ end
207
+
208
+ # Each list is one worker's scenarios in the order it plays them. A
209
+ # worker sends each line it prints and each execution down a pipe of
210
+ # its own, one Marshal frame at a time, so no line or record is ever
211
+ # spliced from two workers. Returns the files a worker that failed
212
+ # left without any execution.
213
+ #: (Array[Array[Scenario]], Environment, Hash[Scenario, String], World, ^(Scenario, Hash[Symbol, untyped]) -> void, ^(Scenario) -> String) -> Array[String]
214
+ def workers(lists, environment, roles, world, ran, line_for)
215
+ live = lists.each_with_index.map do |list, index|
216
+ reader, writer = IO.pipe
217
+ pid = fork do
218
+ reader.close
219
+ exit!(play_as_worker(index + 1, list, environment, roles, world, writer))
220
+ end
221
+ writer.close
222
+ worker = { pid: pid, reader: reader, list: list, played: Set.new } #: Hash[Symbol, untyped]
223
+ worker
224
+ end
225
+ by_key = @scenarios.to_h { [[_1.uri, _1.line], _1] }
226
+ until (open = live.reject { _1[:done] }).empty?
227
+ IO.select(open.map { _1[:reader] })&.first.to_a.each do |reader|
228
+ worker = open.find { _1[:reader] == reader } #: Hash[Symbol, untyped]
229
+ kind, *value = Marshal.load(reader)
230
+ if kind == :line then @out.puts value.first
231
+ else
232
+ scenario = by_key.fetch(value[0])
233
+ @out.puts line_for.(scenario)
234
+ value[2].each { @out.puts _1 }
235
+ worker[:played] << scenario.uri
236
+ ran.(scenario, value[1])
237
+ end
238
+ rescue EOFError
239
+ reader.close
240
+ ended = open.find { _1[:reader] == reader } #: Hash[Symbol, untyped]
241
+ ended[:done] = true
242
+ ended[:status] = Process.wait2(ended[:pid])[1]
243
+ end
244
+ end
245
+ live.reject { _1[:status].success? }.flat_map { |worker| worker[:list].map(&:uri).uniq - worker[:played].to_a }
246
+ end
247
+
248
+ #: (Integer, Array[Scenario], Environment, Hash[Scenario, String], World, IO) -> Integer
249
+ def play_as_worker(number, list, environment, roles, world, pipe)
250
+ @worker = number
251
+ @out = WorkerOut.new(pipe)
252
+ @records = nil
253
+ @process_fixtures = FixtureCache.new
254
+ @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}), secrets: -> { secrets })
255
+ list.each do |scenario|
256
+ execution = play(scenario, environment, roles[scenario], world)
257
+ Marshal.dump([:execution, [scenario.uri, scenario.line], execution, @out.take], pipe)
258
+ end
259
+ 0
260
+ rescue Exception => e # rubocop:disable Lint/RescueException
261
+ Marshal.dump([:line, "worker #{number} stopped: #{e.class}: #{e.message}"], pipe) rescue nil
262
+ 1
263
+ ensure
264
+ @browser&.close
265
+ @process_fixtures&.teardown
266
+ pipe.close
267
+ end
268
+
269
+ # A worker's progress: the line that a scenario starts goes to the
270
+ # parent at once, and the scenario's other lines go with its
271
+ # execution, so one scenario's lines are never split by another's.
272
+ class WorkerOut
273
+ #: (IO) -> void
274
+ def initialize(pipe)
275
+ @pipe = pipe
276
+ @held = []
277
+ end
278
+
279
+ #: (?untyped) -> void
280
+ def puts(text = "")
281
+ text = text.to_s
282
+ text.start_with?("scenario start ") ? Marshal.dump([:line, text], @pipe) : @held << text
283
+ end
284
+
285
+ #: () -> Array[String]
286
+ def take = @held.slice!(0..)
287
+ end
51
288
 
289
+ # A head control and a base cell stand where the behaviour is absent,
290
+ # so a Then failing there the same way in each proof run is proof.
291
+ #: (String, Array[Hash[Symbol, untyped]]) -> bool
52
292
  def proving?(role, runs)
53
- role == "control" && runs.size < Table::PROOF_RUNS && runs.all? { _1[:execution].first == :fail } && runs.map { _1[:execution] }.uniq.size == 1
293
+ absent = @world == "base" || (@world == "head" && role == "control")
294
+ absent && runs.size < Table.proof_runs && runs.all? { _1[:execution].first == :fail } && runs.map { _1[:execution] }.uniq.size == 1
54
295
  end
55
296
 
56
- def finish(executions, cells)
297
+ # A cell is what one scenario's executions in one environment came to;
298
+ # a cell whose first execution broke a claim names it and what it read.
299
+ # Its conditions are the ones the row's tags name, as the environment
300
+ # gives them.
301
+ #: (Array[Hash[Symbol, untyped]], Environment, String, Scenario) -> Hash[Symbol, untyped]
302
+ def cell(runs, environment, role, scenario)
303
+ executions = runs.map { _1[:execution] }
304
+ cell = Table.cell(executions)
305
+ entry = { world: @world, environment: environment.name, role: role, conditions: Table.conditions_of(scenario.tags, environment.conditions),
306
+ outcome: cell[:outcome], line: cell[:line], runs: cell[:runs] }.compact
307
+ if cell[:outcome] == "fail"
308
+ entry[:claim] = executions.first[2]
309
+ entry[:actuals] = runs.map { { value: _1[:actual] } }
310
+ end
311
+ entry
312
+ end
313
+
314
+ # run.json is the --json envelope as a file: the commit and worlds the
315
+ # run judged, the counts, each execution, and the verdict table.
316
+ # `tree_cells` holds each row's base and old cells, by its scenario,
317
+ # under `--base`; each row is judged with what changed since the base.
318
+ #: (Array[Hash[Symbol, untyped]], Hash[Scenario, Array[Hash[Symbol, untyped]]], ?Hash[Scenario, Array[Hash[Symbol, untyped]]]) -> Hash[Symbol, untyped]
319
+ def finish(executions, cells, tree_cells = {})
57
320
  rows = @scenarios.map do |scenario|
58
- row_cells = cells[scenario]
59
- { feature: scenario.uri, line: scenario.line, name: scenario.name, conditions: Table.condition_tags(scenario.tags),
60
- cells: row_cells, verdict: Table.verdict(row_cells) }
321
+ change = @base&.changes&.[](Criteria.key(scenario.uri, scenario.line))
322
+ row_cells = cells[scenario] + tree_cells.fetch(scenario, [])
323
+ verdict, reason = RunRecord.judge_row(row_cells, context_of(scenario, change, executions))
324
+ row = { feature: scenario.uri, line: scenario.line, name: scenario.name, change: change&.dig(:change) }
325
+ row[:renamed_from] = change[:renamed_from] if change&.dig(:renamed_from)
326
+ row[:retagged] = true if change&.dig(:retagged)
327
+ row.merge(conditions: Table.row_tags(scenario.tags), cells: row_cells, verdict: verdict, reason: reason)
328
+ end
329
+ rows.sort_by! { [_1[:feature], _1[:line]] }
330
+ rows.concat(removed_rows) if @base
331
+ scenarios = executions.map { _1[:json] }
332
+ worlds = %w[head base old].flat_map do |world|
333
+ environments = world == "old" ? (@base&.old_environments || @environments) : @environments
334
+ environments.map(&:name).select { |name| world == "head" || rows.any? { |row| row[:cells].any? { _1[:world] == world && _1[:environment] == name } } }
335
+ .map { { world: world, environment: _1 } }
61
336
  end
62
- write_summary(rows)
63
- @out.puts "summary #{File.join(".nukadoko/runs", @id, "summary.md")}"
64
- { run_id: @id, run_dir: File.join(".nukadoko/runs", @id), scenarios: executions.map { _1[:json] },
65
- table: { rows: rows }, passed: rows.none? { _1[:verdict] == "failed" } }
337
+ judged = @base ? judged_findings(rows) : []
338
+ # Judgments sit beside the verdicts, read after the table is built
339
+ # and never folded into a row's verdict. A file that cannot be read
340
+ # is a failed finding of its own, and its rows read as judged by
341
+ # nothing.
342
+ problems = [] #: Array[Hash[Symbol, untyped]]
343
+ entries = {} #: Hash[String, Array[Hash[Symbol, untyped]]]
344
+ entries_of = lambda do |feature|
345
+ entries[feature] ||= begin
346
+ read = JudgmentFile.read(@project, feature)
347
+ if read[:problem]
348
+ problems << { severity: "failed", code: "judgments-unread", file: JudgmentFile.of(feature),
349
+ message: "the judgments of #{feature} were not read: #{read[:problem]}, so its criteria read as judged by nothing",
350
+ fix: "repair #{JudgmentFile.of(feature)} by hand, or remove it and judge the criteria again with nuka judge" }
351
+ end
352
+ read[:entries] || []
353
+ end
354
+ end
355
+ rows = Judgments.with_judgments(rows, scenarios, entries_of)
356
+ # Under --base a reviewer reads which judgments the change added or
357
+ # replaced, as the summary lists the mapping files that changed.
358
+ warnings = [] #: Array[Hash[Symbol, untyped]]
359
+ changed = @base && JudgmentFile.changed(@project, @base.commit)
360
+ if @base && changed.nil?
361
+ warnings << { severity: "warning", code: "judgments-not-compared", message: "the judgment files were not compared with the base: git did not answer" }
362
+ end
363
+ judged += Judgments.findings(rows, @id) + problems
364
+ { run_id: @id, run_dir: File.join(".nukadoko/runs", @id), started_at: @started_at, finished_at: now, commit: @commit,
365
+ environments: @environments.map { environment_entry(_1) }, worlds: @world_entries, order: @order,
366
+ counts: RunRecord.counts(scenarios.reject { _1[:world] }), scenarios: scenarios,
367
+ table: { base: @base && { ref: @base.ref, commit: @base.commit }, mapping_changed: @base&.mapping&.dig(:changed),
368
+ mapping_changes: @base&.mapping_changes, **(changed ? { judgments_changed: changed } : {}),
369
+ worlds: worlds, rows: rows, left_out: @left_out, proof_runs: Table.proof_runs },
370
+ failures: warnings + executions.filter_map { _1[:failure] } + judged + @incomplete,
371
+ # A criterion whose Then asks for a judgment holds only once one
372
+ # cites what it read: the judgment column has a gate of its own.
373
+ passed: @incomplete.empty? && rows.none? { Summary::RED.include?(_1[:verdict]) } && !Judgments.open?(rows) && problems.empty?,
374
+ **(@walk ? { walk: @walk.record } : {}) }
66
375
  end
67
376
 
377
+ # What `--base` knows of one row: its change, whether it carries
378
+ # @held, whether the mapping changed, whether its tags or its name or
379
+ # file changed, and whether its passing executions judged no claim in
380
+ # Then position.
381
+ #: (Scenario, Hash[Symbol, untyped]?, Array[Hash[Symbol, untyped]]) -> Hash[Symbol, untyped]?
382
+ def context_of(scenario, change, executions)
383
+ return nil unless change
384
+
385
+ no_claim = Run.then_judged_by(scenario, executions)
386
+ { change: change[:change], held: scenario.tags.include?(Criteria::HELD), mapping_changed: @base.mapping[:changed],
387
+ retagged: change[:retagged] == true, renamed: !change[:renamed_from].nil?, then_judges_no_claim: no_claim }
388
+ end
389
+
390
+ # sources.json: the feature text this run parsed its scenarios from,
391
+ # so `nuka report` renders the scenarios as they ran, long after the
392
+ # files moved on. The project name rides along: it is part of an
393
+ # Allure result's full name, and a copied run directory has no
394
+ # package.json beside it.
395
+ #: () -> void
396
+ def write_sources
397
+ package = File.join(@project, "package.json")
398
+ name = begin
399
+ (JSON.parse(File.read(package))["name"] if File.file?(package))
400
+ rescue JSON::ParserError
401
+ nil
402
+ end
403
+ features = @scenarios.map(&:uri).uniq.filter_map do |uri|
404
+ file = File.join(@project, uri)
405
+ { path: uri, source: File.read(file, encoding: "UTF-8") } if File.file?(file)
406
+ end
407
+ document = { schema_version: 1, project: name.is_a?(String) ? name : nil, features: features }
408
+ File.write(File.join(@dir, "sources.json"), "#{JSON.pretty_generate(document)}\n")
409
+ end
410
+
411
+ # Why head's passing required executions of a row judged no claim in
412
+ # Then position, from the first that says: `nothing`, or `judgment`
413
+ # when its only claims there are judged-as claims.
414
+ #: (Scenario, Array[Hash[Symbol, untyped]]) -> untyped
415
+ def self.then_judged_by(scenario, executions)
416
+ executions.lazy.map { _1[:json] }.filter_map do |json|
417
+ json[:judged_by] if json[:feature] == scenario.uri && json[:line] == scenario.line && !json[:world] && json[:role] == "required" && json[:status] == "passed"
418
+ end.first
419
+ end
420
+
421
+ #: () -> Array[Hash[Symbol, untyped]]
422
+ def removed_rows
423
+ @base.removed.sort_by { [_1.feature, _1.line] }.map do |criterion|
424
+ { feature: criterion.feature, line: criterion.line, name: criterion.name, change: "removed",
425
+ conditions: Table.row_tags(criterion.tags), cells: [], verdict: "removed",
426
+ reason: "the base holds this criterion, and head no longer does", lines: criterion.lines }
427
+ end
428
+ end
429
+
430
+ # A finding for each unproven and moved row, which has no failed
431
+ # execution to carry one, with the command that judges it again
432
+ # against the commit the run compared with.
433
+ #: (Array[Hash[Symbol, untyped]]) -> Array[Hash[Symbol, untyped]]
434
+ def judged_findings(rows)
435
+ rows.filter_map do |row|
436
+ next unless %w[unproven moved].include?(row[:verdict])
437
+
438
+ command = ["nuka", "run", "#{row[:feature]}:#{row[:line]}", "--base", @base.commit, *@env_flags].map { Selection.shell_word(_1) }.join(" ")
439
+ { severity: "failed", code: row[:verdict] == "unproven" ? "criterion-unproven" : "criterion-moved", file: row[:feature], line: row[:line],
440
+ message: %(Scenario "#{row[:name]}" is #{row[:verdict]}: it #{row[:reason]}), do: command }
441
+ end
442
+ end
443
+
444
+ #: (Environment) -> Hash[Symbol, untyped]
445
+ def environment_entry(environment)
446
+ { name: environment.name, conditions: environment.conditions.empty? ? nil : environment.conditions,
447
+ target_version: nil, base_url: @base_urls[environment.name] }.compact.merge(target_version: nil, base_url: @base_urls[environment.name])
448
+ end
449
+
450
+ # The line before a scenario's execution, numbered across the run, in
451
+ # the TypeScript engine's words so a log reads the same from either.
452
+ #: (String, Integer, String, String) -> String
453
+ def boundary(uri, line, name, role)
454
+ @played += 1
455
+ "scenario #{@played}/#{@to_play} #{uri}:#{line} #{name}#{role == "control" ? " (control)" : ""}"
456
+ end
457
+
458
+ # The line before a control runs again for proof: which run of its cell
459
+ # this is, of how many --proof-runs asks.
460
+ #: (String, Integer, String, String, Integer) -> String
461
+ def proof_boundary(uri, line, name, environment, run)
462
+ "proof run #{run}/#{Table.proof_runs} #{uri}:#{line} #{name} (control in #{environment})"
463
+ end
464
+
465
+ # Why a step failed, one line each: its error's first line, each step
466
+ # it read from whose program exited nonzero, and where its record is.
467
+ #: (Hash[Symbol, untyped]) -> Array[String]
468
+ def step_failure(record)
469
+ lines = [Summary.first_error_line(record[:error].to_s)]
470
+ Summary.exited_producers(record[:used]).each { |step, code, output| lines << "used #{step} exit #{code} #{output}" }
471
+ lines << "record #{File.join(".nukadoko", "runs", @id, "steps", record[:step_record_id])}" if record[:step_record_id]
472
+ lines
473
+ end
474
+
475
+ # Where a scenario's run starts again: its line, and its environment
476
+ # unless that is the only one a run without --env would start.
477
+ # In a shuffled order what ran before a scenario is part of what it
478
+ # met, so the line names those scenarios, then it, with the order and
479
+ # the run's --env flags. Under --repeat no one part of the order ran
480
+ # before it, so the line is the run's own targets and flags.
481
+ #: (Scenario, Environment) -> String
482
+ def again(scenario, environment)
483
+ if @order[:kind] == "file"
484
+ env = @environments.map(&:name) == ["default"] ? "" : " --env #{environment.name}"
485
+ return "nuka run #{scenario.uri}:#{scenario.line}#{env}"
486
+ end
487
+
488
+ # Under --concurrency, what ran before it ran in other workers too.
489
+ words = if @repeat > 1 || @concurrency > 1
490
+ [*@rerun[:targets], *@rerun[:tags], *Order.flags(@order), *(["--repeat", @repeat.to_s] if @repeat > 1),
491
+ *(["--concurrency", @concurrency.to_s] if @concurrency > 1), *@env_flags]
492
+ else [*Order.replay_targets(@scenarios, @rerun[:whole_files], scenario), *Order.flags(@order), *@env_flags]
493
+ end
494
+ ["nuka", "run", *words].map { Selection.shell_word(_1) }.join(" ")
495
+ end
496
+
497
+ #: (Scenario, Environment, String, World) -> Hash[Symbol, untyped]
68
498
  def play(scenario, environment, role, world)
69
- @out.puts "scenario #{scenario.uri}:#{scenario.line} #{scenario.name}#{role == "control" ? " (control)" : ""}"
499
+ # The numbered line is the caller's: a worker's goes out with its
500
+ # execution, numbered by the parent.
501
+ @out.puts "scenario start worker #{@worker} #{scenario.uri}:#{scenario.line} #{scenario.name}" if @worker
502
+ started_at = now
70
503
  results = []
71
- stopped = nil
72
- @scratch = Scratch.new
504
+ stopped = nil #: Array[untyped]?
505
+ @scratch = Scratch.new(@project)
73
506
  @scenario_fixtures = FixtureCache.new
74
- records = scenario.steps.map do |line|
75
- record = stopped ? skipped(line) : play_step(line, results, world)
76
- stopped ||= [record[:outcome], line.line, record[:claim]] if record[:status] == "failed"
77
- @out.puts " #{record[:status]} #{line.text}"
78
- @out.puts " #{record[:error]}" if record[:error]
507
+ scenario_record_id = new_id("scn")
508
+ @step_file = lambda do |record|
509
+ RunRecord.step_file(record, environment: environment.name, world_name: @program.file? ? environment.name : nil, run_id: @id,
510
+ scenario_record_id: scenario_record_id, evidence_dir: File.join(".nukadoko", "runs", @id, "steps", record[:step_record_id]))
511
+ end
512
+ # Where a person stopped the walk, as run.json's `stopped` says it.
513
+ walk_stopped = nil #: Hash[Symbol, untyped]?
514
+ @walk&.begin({ run_id: @id, run_dir: File.join(".nukadoko", "runs", @id),
515
+ scenario: { feature: scenario.uri, line: scenario.line, name: scenario.name, environment: environment.name },
516
+ world: world.base_url ? { url: world.base_url } : nil })
517
+ records = scenario.steps.each_with_index.map do |line, index|
518
+ began = Process.clock_gettime(Process::CLOCK_MONOTONIC)
519
+ record = stopped || walk_stopped ? skipped(line) : play_step(line, results, world)
520
+ stopped ||= [record[:outcome], line.line, record[:claim], record[:broken_actual]] if record[:status] == "failed"
521
+ seconds = format("%.1f", Process.clock_gettime(Process::CLOCK_MONOTONIC) - began)
522
+ @out.puts " step #{index + 1}/#{scenario.steps.size} #{record[:status]} #{seconds}s #{line.text}"
523
+ step_failure(record).each { @out.puts " #{_1}" } if record[:status] == "failed"
524
+ # A step with a written record ran, so a walk pauses after it.
525
+ if @walk && record[:step_record_id] && record[:status] != "skipped"
526
+ remaining = stopped ? 0 : scenario.steps.size - index - 1
527
+ answer = pause(record, line, index + 1, scenario.steps.size, remaining)
528
+ walk_stopped = { after_step: index + 1, line: line.line } if answer == "stop" && remaining.positive?
529
+ end
79
530
  record
80
531
  end
81
- @browser.end_scenario
532
+ browser = @browser.scenario_browser
533
+ final = @browser.end_scenario(File.join(@dir, "scenarios", scenario_record_id))
82
534
  @scenario_fixtures.teardown
83
535
  @scratch.remove_all
84
- execution = stopped ? stopped.compact : [:pass]
85
- { execution: execution,
86
- json: { feature: scenario.uri, line: scenario.line, scenario: scenario.name, environment: environment.name, role: role,
87
- status: stopped ? "failed" : "passed",
88
- steps: scenario.steps.zip(records).map do |line, record|
89
- { line: line.line, text: line.text, step: record[:step], status: record[:status], record: record[:step_record_id] }.compact
90
- end } }
536
+ execution = if stopped then stopped[0, 3].to_a.compact
537
+ elsif walk_stopped then [:stopped, walk_stopped[:line]]
538
+ else [:pass]
539
+ end
540
+ failed = records.find { _1[:status] == "failed" }
541
+ status = if stopped then "failed"
542
+ elsif walk_stopped then "stopped"
543
+ else "passed"
544
+ end
545
+ json = { scenario_record_id: scenario_record_id, feature: scenario.uri, line: scenario.line, scenario: scenario.name,
546
+ status: status, **(walk_stopped && !stopped ? { stopped: walk_stopped } : {}),
547
+ environment: environment.name, started_at: started_at, finished_at: now, **(browser ? { browser: browser } : {}),
548
+ steps: scenario.steps.zip(records).map { |line, record| step_entry(line, record) }, hooks: [] } #: Hash[Symbol, untyped]
549
+ json[:evidence] = { dir: File.join("scenarios", scenario_record_id), screenshots: final } if final.any?
550
+ json[:do] = again(scenario, environment) if (failed || status == "stopped") && role != "control"
551
+ json[:claims] = RunRecord.claim_counts(records)
552
+ # A scenario in which no claim on a Then line was judged says so,
553
+ # since a pass there shows only that nothing raised. A Then whose
554
+ # only claims a reader judges compared nothing: its judgment is
555
+ # what decides it.
556
+ then_claims = scenario.steps.zip(records).select { |line, _| line_kind(line) == :then }.flat_map { _2[:claim_records] || [] }
557
+ unless then_claims.any? { !%w[unobserved for-judgment].include?(_1[:outcome]) }
558
+ json[:judged_by] = then_claims.any? { _1[:outcome] == "for-judgment" } ? "judgment" : "nothing"
559
+ end
560
+ json[:role] = role
561
+ failure = if failed && role != "control"
562
+ { severity: "failed", code: "scenario-failed", file: scenario.uri, line: scenario.line,
563
+ message: "#{scenario.name}: #{failed[:error]}", do: json[:do] }
564
+ elsif (where = walk_stopped) && status == "stopped" && role != "control"
565
+ at = where[:line] ? " (line #{where[:line]})" : ""
566
+ { severity: "failed", code: "walk-stopped", file: scenario.uri, line: scenario.line,
567
+ message: "#{scenario.name}: the walk was stopped after step #{where[:after_step]}#{at} with nuka step stop, so the steps after it did not run",
568
+ do: json[:do] }
569
+ end
570
+ { execution: execution, actual: stopped && stopped[3], json: json, failure: failure }
571
+ end
572
+
573
+ # The pause after the step that ran `number`th, under --step. Before
574
+ # the walk waits, the open page's traffic moves to the pause's own
575
+ # directory: a page that polls while the person reads is not the
576
+ # step's work, and the step's record is already written. After a
577
+ # failure nothing runs on `next` either, so nothing remains and a
578
+ # `stop` there stops nothing.
579
+ #: (Hash[Symbol, untyped], PickleStep, Integer, Integer, Integer) -> String?
580
+ def pause(record, line, number, of, remaining)
581
+ facts = { step: number, of: of, line: line.line, text: line.text, step_name: record[:step], status: record[:status] == "passed" ? "passed" : "failed",
582
+ step_record_id: record[:step_record_id], record: "steps/#{record[:step_record_id]}",
583
+ **(record[:error] ? { failure: { by: "step", message: record[:error] } } : {}), remaining: remaining }
584
+ @walk.pause_after(facts) { |dir, recorded_as| @browser.hold(dir, recorded_as) }
585
+ ensure
586
+ @browser&.release
587
+ end
588
+
589
+ # One step as run.json's scenarios[].steps[] holds it.
590
+ #: (PickleStep, Hash[Symbol, untyped]) -> Hash[Symbol, untyped]
591
+ def step_entry(line, record)
592
+ # A line no step matches is `undefined`, and one more than one step
593
+ # matches is `ambiguous`, as cucumber names them, so a messages
594
+ # stream says the same of it as the TypeScript engine's.
595
+ entry = { line: line.line, text: line.text, step: record[:step], status: record[:never_began] || record[:status],
596
+ step_record_id: record[:step_record_id], record: record[:step_record_id] && "steps/#{record[:step_record_id]}" }
597
+ return entry if record[:status] == "skipped"
598
+
599
+ entry[:mutates] = record[:mutates]
600
+ processes = record[:processes]
601
+ # run.json keeps the record's observed without file content, so it stays small.
602
+ entry[:observed] = { processes: processes&.any? ? processes : nil, http: record[:http_count]&.positive? ? record[:http_count] : nil,
603
+ files: record[:files]&.map { _1.except(:content) }, unmeasured: [],
604
+ **(record.key?(:program_log) ? { program_log: record[:program_log] } : {}) }
605
+ entry[:error] = { kind: record[:error_kind], message: record[:error] } if record[:error]
606
+ # Only a failed step names what it read: a reader then sees the value it broke on.
607
+ entry[:used] = record[:used] if record[:used]&.any? && record[:status] == "failed"
608
+ if record[:claim_records]
609
+ # A judgment cites a judged-as value by the digest of the whole value.
610
+ entry[:claims] = record[:claim_records].map do |claim|
611
+ claim[:outcome] == "for-judgment" && claim.key?(:actual) && !claim[:each] ? { **claim, value_digest: Judgments.value_digest(claim[:actual]) } : claim
612
+ end
613
+ entry[:observation] = record[:observation] || "observed"
614
+ entry.merge!(RunRecord.poll_fields(record).except(:readings), **RunRecord.page_fields(record, File.join("steps", record[:step_record_id].to_s)))
615
+ end
616
+ entry
91
617
  end
92
618
 
93
- def skipped(line) = { step: Engine.matches(@steps, line.text).first&.first&.step_name, status: "skipped" }
619
+ #: (PickleStep) -> Hash[Symbol, untyped]
620
+ def skipped(line)
621
+ { step: Engine.matches(@steps, line.text).first&.first&.step_name, status: "skipped", step_record_id: nil }
622
+ end
94
623
 
624
+ #: (PickleStep, Array[untyped], World) -> Hash[Symbol, untyped]
95
625
  def play_step(line, results, world)
96
- step, captures = Engine.matches(@steps, line.text).first
97
- return { status: "failed", outcome: :broke, error: %(no step matches "#{line.text}") } unless step
626
+ matched = Engine.matches(@steps, line.text)
627
+ step, captures = matched.first
628
+ unless step
629
+ return { status: "failed", outcome: :broke, step_record_id: nil, error_kind: "step_error", error: %(No step definition matches "#{line.text}"), never_began: "undefined" }
630
+ end
631
+ # Under --no-check nothing refused the line before it ran, and
632
+ # running the first match would pass a line the author meant for
633
+ # another step.
634
+ names = matched.map { _1.first.step_name }.uniq.sort
635
+ if names.size > 1
636
+ return { status: "failed", outcome: :broke, step_record_id: nil, error_kind: "step_error",
637
+ error: %("#{line.text}" matches more than one step: #{names.join(", ")}), never_began: "ambiguous" }
638
+ end
98
639
 
99
640
  id = new_id("step")
100
641
  dir = File.join(@dir, "steps", id)
642
+ record = { step_record_id: id, step: step.step_name, text: line.text, started_at: Time.now.utc.iso8601(3) }
643
+ origins = {}
644
+ execute(step, record, dir, world, then_line: line_kind(line) == :then, at_line: line.line, results: results, origins: origins) do
645
+ args = bind_args(step, captures, line, results, origins, record)
646
+ [args, (Pattern.new(step.pattern.to_s).texts(line.text) || {}).merge(attachment_texts(step, captures, line))]
647
+ end
648
+ end
649
+
650
+ public
651
+
652
+ # One step alone, as `nuka do` runs it: its args given on the command
653
+ # line or by earlier records (`origins` says which), in a world
654
+ # started for this one execution, its evidence in this run's
655
+ # directory, which is the record's own.
656
+ #: (singleton(Step), Hash[String, untyped], Hash[String, String], Hash[String, String], Environment) -> Hash[Symbol, untyped]
657
+ def do_step(step, args, origins, texts, environment)
658
+ FileUtils.mkdir_p(@dir)
659
+ read_env(environment)
660
+ world = @program.start(environment, @dir, @project)
661
+ @program_log = world.log_path && Trace::Log.new(world.log_path, world.trace_prefix)
662
+ @scratch = Scratch.new(@project)
663
+ @scenario_fixtures = FixtureCache.new
664
+ @process_fixtures = FixtureCache.new
665
+ @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}), secrets: -> { secrets })
666
+ record = { step_record_id: @id, step: step.step_name, started_at: now }
667
+ execute(step, record, @dir, world, then_line: true, at_line: nil, results: [], origins: origins) { [args, texts] }
668
+ ensure
669
+ @browser&.close
670
+ @scenario_fixtures&.teardown
671
+ @process_fixtures&.teardown
672
+ @scratch&.remove_all
673
+ world&.stop
674
+ end
675
+
676
+ # What `nuka do` writes its stdout and its record through.
677
+ #: (untyped) -> untyped
678
+ def redact(value) = secrets.redact(value)
679
+
680
+ private
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
+
695
+ # Runs one step whose args the block binds, and writes its record and
696
+ # HTTP log into `dir`.
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]
698
+ def execute(step, record, dir, world, then_line:, at_line:, results:, origins:)
101
699
  FileUtils.mkdir_p(dir)
102
700
  log = []
103
- record = { step_record_id: id, step: step.step_name, text: line.text, started_at: Time.now.utc.iso8601(3) }
104
701
  fixtures = {}
105
- finish = nil
702
+ finish = nil #: Proc?
106
703
  processes = []
704
+ scratch_dirs = @scratch&.dirs || []
705
+ scratch_before = @scratch&.snapshot || {}
706
+ # A world with a URL is one the step's requests can be traced into.
707
+ boundary = world.base_url && Trace::Boundary.new(Trace.new_id(world.trace_prefix), world.base_url)
107
708
  begin
108
- args = bind_args(step, captures, line, results)
109
- record[:args] = args
110
- problems = step.args.problems(args)
111
- raise TypeError, "args: #{problems.join("; ")}" if problems.any?
709
+ record[:mutates] = step.mutating?
710
+ args, texts = yield
711
+ record[:args] = stored(args)
712
+ problems = step.args.problems(args, strict: true)
713
+ if problems.any?
714
+ record[:error_kind] = "args_invalid"
715
+ raise TypeError, "args validation failed: #{problems.join("; ")}"
716
+ end
112
717
 
113
- fixtures, finish = build_fixtures(step, dir, log, world)
114
- Processes.collect(processes) { body(step, fixtures, args, line, record, results) }
718
+ @browser&.step = { step_record_id: record[:step_record_id], step: record[:step], line: at_line }
719
+ @browser&.begin_step
720
+ Trace.within(boundary) do
721
+ fixtures, finish = build_fixtures(step, dir, log, world, record)
722
+ HttpRecording.collect(log) do
723
+ Processes.collect(processes) { RedactedOutput.around(secrets) { body(step, fixtures, args, [then_line, at_line], record, results, origins, texts) } }
724
+ end
725
+ end
726
+ record[:page_view] = @browser.judged(dir, record[:step_record_id], aria_in_claims: step.claims.to_a.any? { !_1[:each] && _1[:compare] == "fits-aria-snapshot" }) if step.claims && fixtures[:page] && record[:observation] != "unobserved"
115
727
  record[:status] ||= "passed"
116
728
  rescue StandardError => e
117
- record.merge!(status: "failed", outcome: :broke, error: "#{e.class}: #{e.message}")
729
+ record.merge!(status: "failed", outcome: :broke, error: e.message)
730
+ record[:error_kind] ||= "step_error"
118
731
  ensure
732
+ @browser&.step = nil
119
733
  finish&.call
120
734
  log.concat(fixtures[:request].log) if fixtures[:request]
735
+ # A world at a URL has a log nukadoko does not read.
736
+ record[:program_log] = @program_log&.slice(dir, boundary) if boundary
121
737
  record[:finished_at] = Time.now.utc.iso8601(3)
738
+ # Each process's output is a file of the step's own, named by its number.
739
+ processes.each.with_index(1) do |process, n|
740
+ output = process.delete(:output) || {}
741
+ %i[stdout stderr stdin].each do |stream|
742
+ next if output[stream].to_s.empty?
743
+
744
+ File.write(File.join(dir, "process-#{n}.#{stream}.txt"), secrets.redact(output[stream]))
745
+ process[stream] = "process-#{n}.#{stream}.txt"
746
+ end
747
+ end
122
748
  record[:processes] = processes if processes&.any?
749
+ if @scratch
750
+ changes = @scratch.changes(scratch_before)
751
+ record[:files] = changes if changes.any?
752
+ made = @scratch.dirs - scratch_dirs
753
+ record[:scratch] = made if made.any?
754
+ end
123
755
  record[:calls] = fixtures[:call].calls if fixtures[:call]&.calls&.any?
124
- record[:observed] = { http: log.size, processes: processes&.size || 0 }
125
- File.write(File.join(dir, "http.jsonl"), log.map { JSON.generate(_1) }.join("\n"))
126
- File.write(File.join(dir, "record.json"), JSON.pretty_generate(record))
756
+ # A page's own traffic is in http.jsonl and the trace, not counted as the step's.
757
+ record[:http_count] = log.count { _1[:via] != "page" }
758
+ File.write(File.join(dir, "http.jsonl"), "#{log.map { JSON.generate(secrets.redact(_1)) }.join("\n")}\n") if log.any?
759
+ record[:http_file] = log.any?
760
+ if (traced = TraceActions.read(File.join(dir, "trace.zip")))
761
+ record[:trace] = "trace.zip"
762
+ record[:actions] = traced[:actions] if traced[:actions].any?
763
+ record[:actions_truncated] = traced[:truncated] if traced[:truncated]
764
+ end
765
+ measure(step, record, dir) if record[:claim_records]
766
+ File.write(File.join(dir, "record.json"), JSON.pretty_generate(secrets.redact(@step_file ? @step_file.(record) : record)))
127
767
  end
128
768
  record
129
769
  end
130
770
 
131
771
  # A Then step's claims are judged on what it observed, or on its args
132
772
  # when it reads nothing itself; any other step runs and returns.
133
- def body(step, fixtures, args, line, record, results)
773
+ # `step` is a step class whose observe or run its own file defines.
774
+ #: (untyped, Hash[Symbol, untyped], untyped, [bool, Integer?], Hash[Symbol, untyped], Array[untyped], Hash[String, String], Hash[String, String?]) -> void
775
+ def body(step, fixtures, args, position, record, results, origins, texts)
776
+ then_line, at_line = position
134
777
  if step.claims
135
778
  own = fixtures.slice(*step.fixtures)
136
- read = -> { step.method_defined?(:observe) ? step.new.observe(**own, args: step.inputs.load(args)) : args }
137
- observed = step.poll ? Poll.new(step.poll, step.claims, args).call(record, &read) : read.()
138
- judged = Claims.judge(step.claims, observed, args)
779
+ observes = step.method_defined?(:observe)
780
+ # A claim's actual that starts with a from key reads the value an
781
+ # earlier step returned, which wins over a key observe returns
782
+ # under the same name.
783
+ from_values = args.transform_keys(&:to_s).slice(*step.from.keys.map(&:to_s))
784
+ read = lambda do
785
+ next args unless observes
786
+
787
+ observed = step.new.observe(**step.keywords(own, step.inputs.load(args)))
788
+ observed = observed.is_a?(Hash) ? observed.transform_keys(&:to_s).merge(from_values) : observed
789
+ Claims.take_aria_snapshots(step.claims, observed)
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
796
+ # A reading with a page open is timed, so the record can say what the page had received by then.
797
+ read = (plain = read; -> { @browser.reading(&plain) }) if own[:page]
798
+ observed = begin
799
+ step.poll ? Poll.new(step.poll, step.claims, args, sides).call(record, &read) : read.()
800
+ rescue StandardError => e
801
+ raise unless observes && !step.poll
802
+
803
+ # observe failing is no claim breaking: nothing was read to judge.
804
+ record[:observation] = "unobserved"
805
+ record[:claim_records] = step.claims.reject { _1[:each] }.map { RunRecord.unobserved_claim(_1, origins, texts, patterns: [step.pattern].compact) }
806
+ record[:error_kind] = "unobserved"
807
+ raise e.class, "the step observed nothing, so no claim was judged: #{e.message}"
808
+ end
809
+ judged = Claims.judge(step.claims, observed, args, sides.(observed))
139
810
  record[:claims] = judged
140
- broken = judged.index { !_1[:holds] }
141
- record.merge!(status: "failed", outcome: line_kind(line) == :then ? :fail : :broke, claim: broken, error: "claim #{broken} broke") if broken
142
- else
143
- value = step.new.run(**fixtures.slice(*step.fixtures), args: step.inputs.load(args))
144
- problems = step.returns ? step.returns.problems(value) : []
145
- raise TypeError, "returns: #{problems.join("; ")}" if problems.any?
811
+ # The value each claim read before its view, for `measured`.
812
+ record[:raw_actuals] = step.claims.map do |declared|
813
+ next nil if declared[:each]
146
814
 
147
- if step.returns
148
- dropped = step.returns.dropped(value)
149
- record[:returns_dropped] = dropped if dropped.any?
150
- value = step.returns.strip(value)
815
+ # Under a view the raw value is the text the view read; else the value at `at`.
816
+ read = Claims.read(observed, declared[:actual])
817
+ next nil if declared[:compare] == "fits-aria-snapshot"
818
+
819
+ declared[:view] ? read : Claims.dig(read, declared[:at])
820
+ rescue StandardError
821
+ nil
822
+ end
823
+ patterns = [step.pattern].compact
824
+ record[:claim_records] = step.claims.zip(judged).map do |declared, result|
825
+ if declared[:each]
826
+ RunRecord.each_claim(declared, sides.(observed), origins, texts, patterns: patterns)
827
+ else
828
+ RunRecord.claim(declared, result, origins, texts, observed: observes && !from_values.key?(declared[:actual].to_s.split(".").first), patterns: patterns)
829
+ end
151
830
  end
152
- results << [step, value.transform_keys(&:to_s)]
831
+ broken = record[:claim_records].index { !%w[held for-judgment].include?(_1[:outcome]) }
832
+ return unless broken
833
+
834
+ message = RunRecord.broken_message(record[:claim_records])
835
+ first, *rest = message.split("\n", -1)
836
+ message = ["#{first}#{RunRecord.poll_end(step, record)}", *rest].join("\n")
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)
842
+ else
843
+ value, problems = step.returned(step.new.run(**step.keywords(fixtures.slice(*step.fixtures), step.inputs.load(args))))
844
+ if problems.any?
845
+ record[:error_kind] = "result_invalid"
846
+ raise TypeError, "returns validation failed: #{problems.join("; ")}"
847
+ end
848
+
849
+ record[:returns_dropped] = step.returns ? step.returns.drops(value) : []
850
+ value = step.returns.strip(value) if step.returns
851
+ results << [step, value.transform_keys(&:to_s), at_line, record[:step_record_id]]
153
852
  record[:result] = value
154
853
  end
155
854
  end
156
855
 
157
856
  # Captures first, then each `from` key from the nearest earlier step that
158
857
  # gave it, then a table or docstring for the one required key still open.
159
- def bind_args(step, captures, line, results)
858
+ # `origins` gets each from key's label, `from:<step>@<line>.<key>`, and
859
+ # `record[:used]` each earlier step a from key read, with its result.
860
+ # Each claim record's `measured`: the channel that holds the raw value
861
+ # it read, in the record of the step a `from` value came from, or in
862
+ # its own; and an expected value an earlier step gave, the same way.
863
+ #: (singleton(Step), Hash[Symbol, untyped], String) -> void
864
+ def measure(step, record, dir)
865
+ own = record[:step_record_id]
866
+ own_channels = Measured.channels(dir, { processes: record[:processes], files: record[:files] }, record[:http_count].to_i.positive? ? "http.jsonl" : nil)
867
+ cache = {}
868
+ channels_of = lambda do |id|
869
+ next own_channels if id == own
870
+
871
+ cache[id] ||= begin
872
+ found = [File.join(@dir, "steps", id), File.join(@project, ".nukadoko", "do", id)].find { File.exist?(File.join(_1, "record.json")) }
873
+ other = found && JSON.parse(File.read(File.join(found, "record.json")), symbolize_names: true)
874
+ other && found ? Measured.channels(found, other[:observed] || {}, other.dig(:evidence, :http)) : [{ channel: "record", unknown: true }]
875
+ end
876
+ end
877
+ from_of = ->(key) { (origin = (record[:args_origin] || {})[key.to_s.split(".").first]).is_a?(Hash) ? origin.dig(:from, :step_record_id) : nil }
878
+ (step.claims || []).zip(record[:claim_records], record[:raw_actuals] || []).each do |declared, claim, raw|
879
+ next if claim.nil? || claim[:outcome] == "unobserved" || declared[:each]
880
+ # A tree nukadoko took is a measurement of the page, not a value a channel carried.
881
+ next claim[:measured] = nil if declared[:compare] == "fits-aria-snapshot" || claim[:actual_from].to_s.start_with?(Judgments::ARIA_LABEL)
882
+
883
+ measured = Measured.channel_for(from_of.(declared[:actual]) || own, raw, channels_of)
884
+ claim[:measured] = measured
885
+ key = declared[:expected].is_a?(String) ? declared[:expected] : declared[:expected].is_a?(Hash) && declared[:expected][:from]
886
+ source = declared[:expected].is_a?(Hash) && declared[:expected].key?(:observe) ? own : key && from_of.(key)
887
+ next unless source && claim.key?(:expected)
888
+
889
+ # The expected side's channel comes before the actual's, as the TypeScript engine writes it.
890
+ claim.delete(:measured)
891
+ claim.merge!(expected_measured: Measured.channel_for(source, claim[:expected], channels_of, measured), measured: measured)
892
+ end
893
+ record.delete(:raw_actuals)
894
+ end
895
+
896
+ #: (singleton(Step), Hash[String, untyped], PickleStep, Array[untyped], Hash[String, String], Hash[Symbol, untyped]) -> Hash[String, untyped]
897
+ def bind_args(step, captures, line, results, origins, record)
160
898
  args = captures.dup
899
+ record[:args_origin] = captures.keys.to_h { [_1, "capture"] }
900
+ used = []
161
901
  step.from.each do |key, sources|
162
- cls, value = results.reverse_each.find { |c, _| sources.any? { _1.first == c } }
163
- raise ArgumentError, %(no earlier step in this scenario gave "#{key}") unless cls
902
+ cls, value, at_line, record_id = results.reverse_each.find { |c, _| sources.any? { _1.first == c } }
903
+ unless cls
904
+ record[:error_kind] = "binding_invalid"
905
+ raise ArgumentError, %(no earlier step in this scenario gave "#{key}")
906
+ end
164
907
 
165
- args[key] = value.fetch(sources.find { _1.first == cls }[1].to_s)
908
+ source_key = sources.find { _1.first == cls }[1].to_s
909
+ args[key] = value.fetch(source_key)
910
+ origins[key] = "from:#{cls.step_name}@#{at_line}.#{source_key}"
911
+ record[:args_origin][key] = { from: { step_record_id: record_id, step: cls.step_name, key: source_key } }
912
+ used << { step: cls.step_name, record: "steps/#{record_id}", result: value } unless used.any? { _1[:record] == "steps/#{record_id}" }
166
913
  end
914
+ record[:used] = used
167
915
  open = step.args.fields.map { _1.name.to_s } - args.keys
168
916
  attachment = line.table || line.doc_string
169
- args[open.first] = attachment if attachment && open.any?
170
- args
917
+ if attachment && open.any?
918
+ args[open.first] = attachment
919
+ record[:args_origin][open.first] = line.table ? "table" : "docstring"
920
+ end
921
+ # In the order the args schema declares, as the record shows them.
922
+ rank = step.args.fields.each_with_index.to_h { [_1.name.to_s, _2] }
923
+ record[:args_origin] = record[:args_origin].sort_by { |key, _| rank.fetch(key.to_s, rank.size) }.to_h
924
+ args.sort_by { |key, _| rank.fetch(key.to_s, rank.size) }.to_h
171
925
  end
172
926
 
927
+ # The docstring or table a line attaches is the sentence's own text
928
+ # for the one key it fills.
929
+ #: (singleton(Step), Hash[String, untyped], PickleStep) -> Hash[String, String]
930
+ def attachment_texts(step, captures, line)
931
+ open = step.args.fields.map { _1.name.to_s } - captures.keys - step.from.keys
932
+ return {} if open.empty?
933
+ return { open.first => line.doc_string } if line.doc_string
934
+ return { open.first => line.table.map { |row| "| #{row.join(" | ")} |" }.join("\n") } if line.table
935
+
936
+ {}
937
+ end
938
+
939
+ #: (PickleStep) -> Symbol
173
940
  def line_kind(line) = line.kind == "Outcome" ? :then : :other
174
941
 
175
942
  # A project fixture is built the first time a step of its scope names
176
943
  # it, directly or through another fixture, and kept until the scope ends.
944
+ #: (Symbol, World, Array[Symbol]) -> untyped
177
945
  def project_fixture(name, world, chain)
178
946
  fixture = Nukadoko.project_fixtures[name] or raise ArgumentError, "the Ruby engine has no fixture #{name} yet"
179
947
  raise ArgumentError, "fixtures depend on each other in a cycle: #{[*chain, name].join(" -> ")}" if chain.include?(name)
180
948
 
181
949
  cache = fixture.scope == :process ? @process_fixtures : @scenario_fixtures
182
- return cache[name] if cache.key?(name)
183
-
184
950
  deps = fixture.dependencies.to_h do |dep|
185
951
  case dep
186
952
  when :baseURL then [dep, world.base_url]
@@ -188,15 +954,60 @@ module Nukadoko
188
954
  else [dep, project_fixture(dep, world, [*chain, name])]
189
955
  end
190
956
  end
191
- cache.build(fixture, deps)
957
+ return cache[name].tap { note_fixture(name, fixture.scope, nil, nil) } if cache.key?(name)
958
+
959
+ at = now
960
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
961
+ cache.build(fixture, deps).tap { note_fixture(name, fixture.scope, Request.since(started), at) }
962
+ end
963
+
964
+ # Each project fixture a step's bag touched, once, as the step record
965
+ # lists it: built here with its setup time, or reused from its scope.
966
+ #: (Symbol, Symbol, Integer?, String?) -> void
967
+ def note_fixture(name, scope, setup_ms, at)
968
+ return if @fixture_usage.nil? || @fixture_usage.any? { _1[:name] == name.to_s }
969
+
970
+ @fixture_usage << { name: name.to_s, scope: scope.to_s, reused: setup_ms.nil?, setup_ms: setup_ms, at: at }.compact
192
971
  end
193
972
 
194
- def build_fixtures(step, dir, log, world)
973
+ # The secrets of the environment running now, which every record
974
+ # surface is written through.
975
+ #: () -> Secrets
976
+ def secrets = @secrets || Secrets.new
977
+
978
+ # What the env fixture holds: the env files, then the world's own env.
979
+ #: (World) -> Hash[String, String]
980
+ def step_env(world) = (@env_vars || {}).merge(world.env)
981
+
982
+ # Reads an environment's env files into the env fixture and the secret
983
+ # set, from the same read, so the two agree on what was loaded.
984
+ #: (Environment) -> void
985
+ def read_env(environment)
986
+ EnvCheck.validate!
987
+ config = Nukadoko.config_options.fetch(:secrets, {}) #: Hash[Symbol, untyped]
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]))
997
+ rescue EnvFile::Unreadable => e
998
+ raise Refusal.new("env-file-unreadable", e.message)
999
+ end
1000
+
1001
+ #: (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped]) -> [Hash[Symbol, untyped], (^() -> void)?]
1002
+ def build_fixtures(step, dir, log, world, record)
195
1003
  finish = nil
1004
+ @fixture_usage = []
196
1005
  fixtures = (step.bag - [:call]).to_h do |name|
197
1006
  case name
198
1007
  when :request then [name, Request.new(world.base_url)]
199
1008
  when :baseURL then [name, world.base_url]
1009
+ when :env then [name, step_env(world)]
1010
+ when :requireEnv then [name, ->(key) { step_env(world).fetch(key.to_s) { raise %(requireEnv("#{key}"): the world's env has no #{key}) } }]
200
1011
  when :scratch then [name, @scratch]
201
1012
  when :page
202
1013
  page, finish = @browser.page_for(dir, log)
@@ -205,20 +1016,16 @@ module Nukadoko
205
1016
  end
206
1017
  end
207
1018
  fixtures[:call] = Caller.new(step, fixtures) if step.fixtures.include?(:call)
1019
+ record[:fixtures] = @fixture_usage if @fixture_usage.any?
1020
+ @fixture_usage = nil
208
1021
  [fixtures, finish]
209
1022
  end
210
1023
 
211
- def write_summary(rows)
212
- verdicts = rows.map { _1[:verdict] }.tally.map { |v, n| "#{n} #{v}" }.join(", ")
213
- lines = ["# nukadoko run #{rows.none? { _1[:verdict] == "failed" } ? "passed" : "failed"}: #{rows.size} criteria, #{verdicts}", ""]
214
- rows.each do |r|
215
- cells = r[:cells].map { |c| "#{c[:environment]} #{c[:outcome]}#{c[:line] ? "@#{c[:line]}" : ""}#{c[:role] == "control" ? " (control)" : ""}" }
216
- lines << "- #{r[:verdict]} #{r[:feature]}:#{r[:line]} #{r[:name]} #{cells.join(", ")}"
217
- end
218
- File.write(File.join(@dir, "summary.md"), "#{lines.join("\n")}\n")
219
- end
220
-
1024
+ #: (String) -> String
221
1025
  def new_id(kind) = "#{kind}-#{Time.now.utc.strftime("%Y%m%d-%H%M%S")}-#{SecureRandom.alphanumeric(4).downcase}"
1026
+
1027
+ #: () -> String
1028
+ def now = Time.now.utc.iso8601(3)
222
1029
  end
223
1030
  end
224
1031
  end