nukadoko 0.5.0 → 0.7.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 (203) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +553 -3
  3. data/README.ja.md +22 -6
  4. data/README.md +13 -7
  5. data/docs/ci.ja.md +542 -0
  6. data/docs/ci.md +635 -0
  7. data/docs/commands.ja.md +1524 -0
  8. data/docs/commands.md +1281 -0
  9. data/docs/engines.json +19 -0
  10. data/docs/execution-events.ja.md +336 -0
  11. data/docs/execution-events.md +423 -0
  12. data/docs/glossary.json +1348 -0
  13. data/docs/guide.ja.md +733 -0
  14. data/docs/guide.md +815 -0
  15. data/docs/intent.ja.md +133 -0
  16. data/docs/intent.md +156 -0
  17. data/docs/layout.ja.md +442 -0
  18. data/docs/layout.md +399 -0
  19. data/docs/releasing.ja.md +186 -0
  20. data/docs/releasing.md +237 -0
  21. data/docs/ruby/reference.ja.md +302 -0
  22. data/docs/ruby/reference.md +368 -0
  23. data/docs/spec.ja.md +8916 -0
  24. data/docs/spec.md +11250 -0
  25. data/docs/tutorial.ja.md +451 -0
  26. data/docs/tutorial.md +458 -0
  27. data/docs/typescript/adopting.ja.md +231 -0
  28. data/docs/typescript/adopting.md +251 -0
  29. data/docs/typescript/doors.ja.md +301 -0
  30. data/docs/typescript/doors.md +329 -0
  31. data/docs/typescript/migration-playwright-test.ja.md +189 -0
  32. data/docs/typescript/migration-playwright-test.md +212 -0
  33. data/docs/typescript/migration.ja.md +391 -0
  34. data/docs/typescript/migration.md +505 -0
  35. data/docs/typescript/reference.ja.md +176 -0
  36. data/docs/typescript/reference.md +197 -0
  37. data/docs/typescript/upgrading.ja.md +1774 -0
  38. data/docs/typescript/upgrading.md +2224 -0
  39. data/docs/web-app.ja.md +627 -0
  40. data/docs/web-app.md +659 -0
  41. data/docs/writing-scenarios.ja.md +544 -0
  42. data/docs/writing-scenarios.md +563 -0
  43. data/lib/nukadoko/base.rb +12 -5
  44. data/lib/nukadoko/changed_files.rb +95 -0
  45. data/lib/nukadoko/check.rb +459 -51
  46. data/lib/nukadoko/claim_drops.rb +271 -0
  47. data/lib/nukadoko/claim_line.rb +24 -4
  48. data/lib/nukadoko/claim_rules.rb +143 -1
  49. data/lib/nukadoko/claim_sides.rb +157 -9
  50. data/lib/nukadoko/cli.rb +403 -50
  51. data/lib/nukadoko/codes.json +246 -21
  52. data/lib/nukadoko/codes.rb +21 -4
  53. data/lib/nukadoko/command.rb +120 -13
  54. data/lib/nukadoko/command_help.rb +128 -0
  55. data/lib/nukadoko/compat.rb +469 -0
  56. data/lib/nukadoko/criteria.rb +1 -1
  57. data/lib/nukadoko/definition.rb +157 -7
  58. data/lib/nukadoko/error_frames.rb +6 -3
  59. data/lib/nukadoko/events/count.rb +146 -0
  60. data/lib/nukadoko/events/counted.rb +114 -0
  61. data/lib/nukadoko/events/format.rb +257 -0
  62. data/lib/nukadoko/events/lists.rb +154 -0
  63. data/lib/nukadoko/events/path.rb +285 -0
  64. data/lib/nukadoko/events/read.rb +284 -0
  65. data/lib/nukadoko/events/reader.rb +490 -0
  66. data/lib/nukadoko/events/selection.rb +252 -0
  67. data/lib/nukadoko/events/tally.rb +438 -0
  68. data/lib/nukadoko/features.rb +2 -2
  69. data/lib/nukadoko/fixtures.rb +160 -35
  70. data/lib/nukadoko/http_recording.rb +6 -2
  71. data/lib/nukadoko/intent.rb +364 -0
  72. data/lib/nukadoko/intent_file.rb +81 -0
  73. data/lib/nukadoko/intent_view.rb +190 -0
  74. data/lib/nukadoko/js_json.rb +2 -1
  75. data/lib/nukadoko/judge.rb +2 -2
  76. data/lib/nukadoko/judgment_file.rb +22 -1
  77. data/lib/nukadoko/judgments.rb +33 -3
  78. data/lib/nukadoko/measure_mcp.rb +202 -0
  79. data/lib/nukadoko/parts.rb +8 -2
  80. data/lib/nukadoko/path_view.rb +252 -0
  81. data/lib/nukadoko/place_rows.rb +161 -0
  82. data/lib/nukadoko/program.rb +1265 -51
  83. data/lib/nukadoko/program_log.rb +122 -0
  84. data/lib/nukadoko/program_shape.rb +385 -0
  85. data/lib/nukadoko/project_fixtures.rb +43 -10
  86. data/lib/nukadoko/project_program.rb +5 -4
  87. data/lib/nukadoko/repeated_prefix.rb +310 -0
  88. data/lib/nukadoko/report_run.rb +3 -3
  89. data/lib/nukadoko/run.rb +1156 -159
  90. data/lib/nukadoko/run_record.rb +70 -46
  91. data/lib/nukadoko/scaffold.rb +24 -6
  92. data/lib/nukadoko/schema.rb +15 -2
  93. data/lib/nukadoko/secrets.rb +55 -5
  94. data/lib/nukadoko/states.rb +478 -0
  95. data/lib/nukadoko/step.rb +71 -2
  96. data/lib/nukadoko/step_fixtures.rb +52 -3
  97. data/lib/nukadoko/summary.rb +803 -30
  98. data/lib/nukadoko/table.rb +4 -2
  99. data/lib/nukadoko/text_fit.rb +20 -7
  100. data/lib/nukadoko/trace.rb +152 -45
  101. data/lib/nukadoko/tree_passes.rb +95 -33
  102. data/lib/nukadoko/underneath.rb +311 -0
  103. data/lib/nukadoko/verdict.rb +18 -1
  104. data/lib/nukadoko/version.rb +1 -1
  105. data/lib/nukadoko/vocabulary.rb +166 -23
  106. data/lib/nukadoko/walk.rb +2 -2
  107. data/lib/nukadoko/walk_step.rb +1 -1
  108. data/lib/nukadoko.rb +23 -0
  109. data/llms.txt +42 -35
  110. data/sig/generated/nukadoko/base.rbs +4 -4
  111. data/sig/generated/nukadoko/changed_files.rbs +42 -0
  112. data/sig/generated/nukadoko/check.rbs +147 -10
  113. data/sig/generated/nukadoko/claim_drops.rbs +135 -0
  114. data/sig/generated/nukadoko/claim_line.rbs +11 -0
  115. data/sig/generated/nukadoko/claim_rules.rbs +49 -4
  116. data/sig/generated/nukadoko/claim_sides.rbs +63 -12
  117. data/sig/generated/nukadoko/cli.rbs +80 -7
  118. data/sig/generated/nukadoko/codes.rbs +19 -4
  119. data/sig/generated/nukadoko/command.rbs +68 -1
  120. data/sig/generated/nukadoko/command_help.rbs +18 -0
  121. data/sig/generated/nukadoko/compat.rbs +392 -0
  122. data/sig/generated/nukadoko/criteria.rbs +1 -1
  123. data/sig/generated/nukadoko/definition.rbs +50 -0
  124. data/sig/generated/nukadoko/error_frames.rbs +1 -1
  125. data/sig/generated/nukadoko/events/count.rbs +69 -0
  126. data/sig/generated/nukadoko/events/counted.rbs +70 -0
  127. data/sig/generated/nukadoko/events/format.rbs +163 -0
  128. data/sig/generated/nukadoko/events/lists.rbs +47 -0
  129. data/sig/generated/nukadoko/events/path.rbs +161 -0
  130. data/sig/generated/nukadoko/events/read.rbs +109 -0
  131. data/sig/generated/nukadoko/events/reader.rbs +226 -0
  132. data/sig/generated/nukadoko/events/selection.rbs +100 -0
  133. data/sig/generated/nukadoko/events/tally.rbs +227 -0
  134. data/sig/generated/nukadoko/features.rbs +6 -4
  135. data/sig/generated/nukadoko/fixtures.rbs +67 -11
  136. data/sig/generated/nukadoko/http_recording.rbs +1 -1
  137. data/sig/generated/nukadoko/intent.rbs +132 -0
  138. data/sig/generated/nukadoko/intent_file.rbs +46 -0
  139. data/sig/generated/nukadoko/intent_view.rbs +69 -0
  140. data/sig/generated/nukadoko/judgment_file.rbs +7 -1
  141. data/sig/generated/nukadoko/judgments.rbs +10 -0
  142. data/sig/generated/nukadoko/measure_mcp.rbs +104 -0
  143. data/sig/generated/nukadoko/parts.rbs +2 -2
  144. data/sig/generated/nukadoko/path_view.rbs +105 -0
  145. data/sig/generated/nukadoko/place_rows.rbs +43 -0
  146. data/sig/generated/nukadoko/program.rbs +627 -23
  147. data/sig/generated/nukadoko/program_log.rbs +67 -0
  148. data/sig/generated/nukadoko/program_shape.rbs +147 -0
  149. data/sig/generated/nukadoko/project_fixtures.rbs +16 -3
  150. data/sig/generated/nukadoko/project_program.rbs +2 -1
  151. data/sig/generated/nukadoko/repeated_prefix.rbs +172 -0
  152. data/sig/generated/nukadoko/report_run.rbs +1 -1
  153. data/sig/generated/nukadoko/run.rbs +286 -41
  154. data/sig/generated/nukadoko/run_record.rbs +20 -12
  155. data/sig/generated/nukadoko/scaffold.rbs +3 -0
  156. data/sig/generated/nukadoko/schema.rbs +5 -0
  157. data/sig/generated/nukadoko/secrets.rbs +26 -3
  158. data/sig/generated/nukadoko/states.rbs +214 -0
  159. data/sig/generated/nukadoko/step.rbs +58 -1
  160. data/sig/generated/nukadoko/step_fixtures.rbs +39 -0
  161. data/sig/generated/nukadoko/summary.rbs +256 -2
  162. data/sig/generated/nukadoko/table.rbs +3 -2
  163. data/sig/generated/nukadoko/trace.rbs +108 -33
  164. data/sig/generated/nukadoko/tree_passes.rbs +36 -8
  165. data/sig/generated/nukadoko/underneath.rbs +141 -0
  166. data/sig/generated/nukadoko/verdict.rbs +8 -0
  167. data/sig/generated/nukadoko/vocabulary.rbs +45 -6
  168. data/skills/nukadoko/SKILL.md +18 -18
  169. data/skills/nukadoko/references/checking-steps.md +16 -83
  170. data/skills/nukadoko/references/diagnosing.md +6 -6
  171. data/skills/nukadoko/references/done.md +22 -0
  172. data/skills/nukadoko/references/evidence.md +19 -6
  173. data/skills/nukadoko/references/exploring.md +22 -7
  174. data/skills/nukadoko/references/fixtures.md +12 -32
  175. data/skills/nukadoko/references/judgments.md +18 -0
  176. data/skills/nukadoko/references/maintenance.md +1 -1
  177. data/skills/nukadoko/references/merge-risk.md +1 -1
  178. data/skills/nukadoko/references/parts.md +46 -23
  179. data/skills/nukadoko/references/{perturbed-worlds.md → perturbed-systems.md} +30 -12
  180. data/skills/nukadoko/references/program.md +168 -169
  181. data/skills/nukadoko/references/reviewing.md +20 -20
  182. data/skills/nukadoko/references/ruby/checking-steps.md +106 -0
  183. data/skills/nukadoko/references/ruby/examples/cli.md +212 -0
  184. data/skills/nukadoko/references/ruby/fixtures.md +34 -0
  185. data/skills/nukadoko/references/ruby/program.md +112 -0
  186. data/skills/nukadoko/references/ruby/step-files.md +115 -0
  187. data/skills/nukadoko/references/running.md +34 -34
  188. data/skills/nukadoko/references/scenario-rules.md +7 -6
  189. data/skills/nukadoko/references/states.md +7 -1
  190. data/skills/nukadoko/references/step-files.md +41 -120
  191. data/skills/nukadoko/references/typescript/checking-steps.md +129 -0
  192. data/skills/nukadoko/references/{examples → typescript/examples}/cli.md +1 -1
  193. data/skills/nukadoko/references/{examples → typescript/examples}/http-api.md +6 -6
  194. data/skills/nukadoko/references/{examples → typescript/examples}/workflow.md +1 -1
  195. data/skills/nukadoko/references/typescript/fixtures.md +56 -0
  196. data/skills/nukadoko/references/typescript/program.md +111 -0
  197. data/skills/nukadoko/references/typescript/step-files.md +104 -0
  198. data/skills/nukadoko/references/verdicts.md +10 -10
  199. data/skills/nukadoko/references/writing-steps.md +67 -67
  200. data/skills/nukadoko/references/writing-the-feature.md +1 -1
  201. data/skills/nukadoko-verification/SKILL.md +13 -8
  202. metadata +103 -7
  203. data/skills/nukadoko/references/ruby.md +0 -80
data/lib/nukadoko/run.rb CHANGED
@@ -4,39 +4,50 @@
4
4
  require "securerandom"
5
5
  require "fileutils"
6
6
  require "time"
7
+ require "timeout"
7
8
 
8
- # One run: for each environment, start its world, play every scenario's steps
9
+ # One run: for each environment, start its system, play every scenario's steps
9
10
  # in order, and write a record per step. A scenario stops at its first step
10
11
  # that does not pass and skips the rest. A control that fails at a Then runs
11
12
  # again for proof. The table and the summary come last.
12
13
  module Nukadoko
13
14
  module Engine
14
15
  class Run
15
- # `world` is head for a run, or base or old for a tree's pass, which
16
+ # `system` is head for a run, or base or old for a tree's pass, which
16
17
  # writes into the head run's directory `dir`, and reads its env files
17
18
  # from `head`'s root, with head's secrets as well as its own. `base` is the
18
19
  # comparison a `--base` run judges its rows by. `scenarios` are in the
19
20
  # run's order, which every round of every pass keeps; `records`, when
20
21
  # given, gets each scenario's run.json entry as one line as it ends,
21
22
  # 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: [],
23
+ #: (String, Array[singleton(Step)], Array[Scenario], Hash[Symbol, untyped], ?environments: Array[Environment]?, ?left_out: Integer, ?out: untyped, ?system: 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
24
+ def initialize(project, steps, scenarios, program, environments: nil, left_out: 0, out: $stdout, system: "head", dir: nil, base: nil, env_flags: [],
24
25
  repeat: 1, concurrency: 1, order: Order::FILE, records: nil, rerun: nil, walk: nil, head: nil)
25
26
  @head = head
26
27
  @project = project
27
28
  @steps = steps
28
29
  @scenarios = scenarios
29
30
  @program = Program.new(program)
31
+ # A tree's pass builds nothing head's pass or an earlier pass of
32
+ # this run already built (Program#builds).
33
+ @head&.dig(:builds)&.each { |key, (system, failed)| @program.builds[key.to_s] = [system, failed] }
30
34
  @environments = environments || @program.environments
31
35
  @left_out = left_out
32
36
  @out = out
33
- @world = world
37
+ @system = system
34
38
  @base = base
35
39
  @env_flags = env_flags
36
40
  @repeat = repeat
37
41
  @concurrency = concurrency
38
42
  @incomplete = []
39
- @world_entries = []
43
+ @target_versions = {} #: Hash[String, String]
44
+ # Findings that are told and never fail the run.
45
+ @warnings = [] #: Array[Hash[Symbol, untyped]]
46
+ # A process fixture's teardown errors, which no scenario record holds.
47
+ @process_teardown = [] #: Array[Hash[Symbol, untyped]]
48
+ @judged_early = {} #: Hash[String, Hash[Symbol, untyped]]
49
+ @state_writes = {} #: Hash[String, untyped]
50
+ @system_entries = []
40
51
  @order = order
41
52
  @records = records
42
53
  @rerun = rerun || { targets: [], tags: [], whole_files: [] }
@@ -56,13 +67,16 @@ module Nukadoko
56
67
  @commit = RunRecord.commit(@project)
57
68
  # Said before any scenario, so a run a signal stops still names its seed.
58
69
  @out.puts "order #{Order.text(@order)}" unless @order[:kind] == "file"
70
+ read_intent
59
71
  executions, cells = pass
60
72
  tree_cells = {}
61
73
  if @base
62
74
  begin
63
- trees = TreePasses.new(@base, @scenarios, cells, @environments, @dir, @out, ->(scenario) { Run.then_judged_by(scenario, executions) }, head_root: @project)
75
+ trees = TreePasses.new(@base, @scenarios, cells, @environments, @dir, @out, ->(scenario) { Run.then_judged_by(scenario, executions) }, head_root: @project,
76
+ writes_events: ->(environment) { @program.writes_events?(environment) }, own_fields: own_fields, builds: @program.builds,
77
+ urls: service_url_keys)
64
78
  tree_cells = trees.call(executions)
65
- @world_entries.concat(trees.worlds)
79
+ @system_entries.concat(trees.systems)
66
80
  ensure
67
81
  @base.cleanup
68
82
  end
@@ -82,17 +96,93 @@ module Nukadoko
82
96
  end
83
97
  end
84
98
 
85
- # Each world this run started, as run.json's worlds holds it.
86
- attr_reader :world_entries #: Array[Hash[Symbol, untyped]]
99
+ # Each system this run started, as run.json's systems holds it.
100
+ attr_reader :system_entries #: Array[Hash[Symbol, untyped]]
101
+
102
+ # The builds this run's program ran or was handed, for the next tree
103
+ # pass (Program#builds).
104
+ #: () -> Hash[String, [String, String?]]
105
+ def builds = @program.builds
106
+
107
+ # The key of the URL each service of each of this pass's systems
108
+ # reached (Program.url_key), by environment and then by service: a
109
+ # base service of the tree whose url function answers with head's URL
110
+ # is unavailable (Program#start).
111
+ #: () -> Hash[String, Hash[String, String]]
112
+ def service_url_keys = @service_url_keys || {}
87
113
 
88
114
  #: (Scenario, Environment) -> String
89
115
  def role_of(scenario, environment) = Table.role(Table.condition_tags(scenario.tags), environment.conditions)
90
116
 
91
117
  private
92
118
 
119
+ # The intent the change declares (docs/intent.md), read before any
120
+ # system starts, since a step's path counts a writer's own kinds by
121
+ # the fields it names, and the base's system and head's must count
122
+ # them alike.
123
+ #: () -> void
124
+ def read_intent
125
+ return unless @base && @system == "head"
126
+
127
+ @change_intent = IntentFile.read(@project, @base.commit)
128
+ rescue IntentFile::GitFailed => e
129
+ @intent_unread = e.message
130
+ end
131
+
132
+ # The key of the URL each service of head's system of `environment`
133
+ # reached, which head's run sent with this tree's plan, by service.
134
+ # Empty in head's own pass, which is what the keys are read from.
135
+ #: (Environment) -> Hash[String, String]
136
+ def head_url_keys(environment)
137
+ ((@head&.dig(:urls) || {})[environment.name.to_sym] || {}).to_h { |service, key| [service.to_s, key.to_s] }
138
+ end
139
+
140
+ # The fields a path counts each writer's own kind by: the intent's,
141
+ # or, in a tree's pass, the ones head's run sent with it.
142
+ #: () -> Hash[String, Array[String]]
143
+ def own_fields
144
+ return (@head[:own_fields] || {}).to_h { |kind, fields| [kind.to_s, fields] } if @head
145
+
146
+ @change_intent ? Intent.own_fields(@change_intent[:intent]) : {}
147
+ end
148
+
149
+ # run.json's `paths` and `intent`, and the findings an intent adds:
150
+ # each row judged against the base pairs of the paths.
151
+ #: (Array[Hash[Symbol, untyped]], Hash[Symbol, untyped], Array[Hash[Symbol, untyped]]) -> [Array[Hash[Symbol, untyped]], Hash[Symbol, untyped]?, Array[Hash[Symbol, untyped]]]
152
+ def paths_and_intent(scenarios, table, environments)
153
+ compared = PathView.compare({ scenarios: scenarios, table: table, environments: environments, systems: @system_entries })
154
+ found = [] #: Array[Hash[Symbol, untyped]]
155
+ if @intent_unread
156
+ found << { severity: "failed", code: "intent-unread", message: "the change's intent was not read: #{@intent_unread}" }
157
+ end
158
+ change = @change_intent
159
+ return [compared, nil, found] unless change && @base
160
+
161
+ tags_of = ->(place) { @scenarios.find { _1.uri == place[:feature] && _1.line == place[:line] }&.tags || [] }
162
+ judged = IntentView.judge(change[:intent], compared, scenarios, table[:rows], tags_of)
163
+ intent = { **change[:record], problems: change[:intent][:problems],
164
+ rows: change[:intent][:rows].each_with_index.map do |row, index|
165
+ came = judged[:rows].fetch(index)
166
+ { row: row[:row], line: row[:line], **row[:cells], result: came[:result], as_intended: came[:as_intended], not_happening: came[:not_happening] }
167
+ end }
168
+ base = @base
169
+ rerun = ->(place) { ["nuka", "run", "#{place[:feature]}:#{place[:line]}", "--base", base.commit, *@env_flags].map { Selection.shell_word(_1) }.join(" ") }
170
+ [judged[:paths], intent, found + IntentView.findings(intent, judged[:paths], rerun)]
171
+ end
172
+
93
173
  #: () -> [Array[Hash[Symbol, untyped]], Hash[Scenario, Array[Hash[Symbol, untyped]]]]
94
174
  def pass
95
175
  @base_urls = {}
176
+ # The URL each service of each system reached, as another tree
177
+ # compares it (Program.url_key).
178
+ @service_url_keys = {} #: Hash[String, Hash[String, String]]
179
+ # What each of head's systems read of the program's lists, by
180
+ # environment, for run.json's flags and routes.
181
+ @listed_places = {} #: Hash[String, Hash[String, Array[Hash[Symbol, untyped]]]]
182
+ # The service that printed them, which is the primary: a flags list
183
+ # is one service's, so the sides it declares are rows of that service.
184
+ @listed_by = {} #: Hash[String, String]
185
+ @system_tables = {} #: Hash[String, Hash[Symbol, untyped]]
96
186
  executions = []
97
187
  cells = Hash.new { |h, k| h[k] = [] }
98
188
  # Each scenario line is numbered across every environment and
@@ -102,16 +192,54 @@ module Nukadoko
102
192
  @to_play = @scenarios.size * @repeat * @environments.size
103
193
  @environments.each do |environment|
104
194
  # One environment needs no line of its own: every scenario is in it.
105
- if @world != "head" then @out.puts "#{@world} #{environment.name}"
195
+ if @system != "head" then @out.puts "#{@system} #{environment.name}"
106
196
  elsif @environments.size > 1 then @out.puts "environment #{environment.name}"
107
197
  end
108
- world_dir = File.join(@dir, "worlds", @world == "head" ? environment.name : "#{environment.name}@#{@world}")
109
- FileUtils.mkdir_p(world_dir)
198
+ system_dir = File.join(@dir, "systems", @system == "head" ? environment.name : "#{environment.name}@#{@system}")
199
+ FileUtils.mkdir_p(system_dir)
110
200
  read_env(environment)
111
- world = @program.start(environment, world_dir, @project)
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"] }
201
+ @environment = environment
202
+ probe_version(environment)
203
+ roles = @scenarios.to_h { [_1, @system == "head" ? role_of(_1, environment) : "required"] }
204
+ begin
205
+ system = @program.start(environment, system_dir, @project, secrets: secrets, tree: @system, lists: true, progress: @out, head_root: head_root,
206
+ env_vars: @env_vars || {}, head_urls: head_url_keys(environment))
207
+ rescue Program::Unavailable => e
208
+ # A base with no URL of its own runs no cell, and nothing failed.
209
+ @scenarios.each { cells[_1] << cell([], environment, roles[_1], _1).merge(reason: "the #{@system} system has no URL to reach: #{e.message}") }
210
+ system = nil
211
+ next
212
+ rescue Program::StartFailed => e
213
+ # No scenario runs in a system whose program did not start: each
214
+ # cell is not run, saying why. Head's run fails outside them; a
215
+ # base that did not start is a warning, as nothing of head failed.
216
+ head = @system == "head"
217
+ # The system's {token} can be in a command and in what it printed.
218
+ shown = secrets.with(e.system.secrets)
219
+ (head ? @incomplete : @warnings) << { severity: head ? "failed" : "warning", code: "program-start-failed", message: shown.redact(e.message), fix: Codes.fix("program-start-failed") }
220
+ @system_entries << { name: environment.name, tree: @system, primary: e.system.primary, url: shown.redact(e.system.primary_service.base_url), error: shown.redact(e.cause_text),
221
+ timings: e.system.timings, services: e.system.services.map { shown.redact(service_entry(_1, system_dir)) } }
222
+ reason = head ? "the program did not start for its system" : "the program did not start for the #{@system} system"
223
+ @scenarios.each { cells[_1] << cell([], environment, roles[_1], _1).merge(reason: reason) }
224
+ system = nil
225
+ next
226
+ end
227
+ @secrets = secrets.with(system.secrets)
228
+ # What the system declared with stepsReach, for every step,
229
+ # fixture, and hook of this pass. A --concurrency worker is forked
230
+ # from this process, so it holds the same rule.
231
+ release_reach = Reach.declare(system.steps_reach, environment.name)
232
+ @program_logs = system.program_logs
233
+ @primary_logged = !@program_logs[system.primary].nil?
234
+ @events = events_reader(system)
235
+ @base_urls[environment.name] = redact(system.primary_service.base_url)
236
+ @service_url_keys[environment.name] = system.services.to_h { [_1.name, _1.base_url && Program.url_key(_1.base_url)] }.compact
237
+ @system_tables = system.services.to_h { [_1.name, _1.tables] }
238
+ if @system == "head"
239
+ @listed_places[environment.name] = system.primary_service.places
240
+ @listed_by[environment.name] = system.primary
241
+ end
242
+ warn_lists_unread(environment, system, system_dir)
115
243
  runs = Hash.new { |h, k| h[k] = [] }
116
244
  ran = lambda do |scenario, execution|
117
245
  runs[scenario] << execution
@@ -122,14 +250,19 @@ module Nukadoko
122
250
  # until it has broken the same claim at the same line --proof-runs
123
251
  # times or a run disagrees.
124
252
  due = -> { @scenarios.select { proving?(roles[_1], runs[_1]) } }
125
- if @concurrency > 1
126
- play_in_workers(environment, roles, world, due, ran, runs)
253
+ # BeforeAll brackets the pass with AfterAll, in this process, which
254
+ # each worker forks from; a BeforeAll that failed plays nothing.
255
+ all_hooks = @scenarios.any?
256
+ before_all_failed = all_hooks && !run_hooks(:before_all, environment)
257
+ if before_all_failed then nil
258
+ elsif @concurrency > 1
259
+ play_in_workers(environment, roles, system, due, ran, runs)
127
260
  else
128
261
  @process_fixtures = FixtureCache.new
129
- @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}), secrets: -> { secrets })
262
+ @browser = browser_of(system)
130
263
  play_one = lambda do |scenario|
131
264
  @out.puts boundary(scenario.uri, scenario.line, scenario.name, roles[scenario])
132
- ran.(scenario, play(scenario, environment, roles[scenario], world))
265
+ ran.(scenario, play(scenario, environment, roles[scenario], system))
133
266
  end
134
267
  # The whole selection once, then again, so a failure that depends
135
268
  # on what ran before it meets the same neighbours every round.
@@ -137,50 +270,297 @@ module Nukadoko
137
270
  until (round = due.()).empty?
138
271
  round.each do |scenario|
139
272
  @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))
273
+ ran.(scenario, play(scenario, environment, roles[scenario], system))
141
274
  end
142
275
  end
143
276
  end
144
- @scenarios.each { cells[_1] << cell(runs[_1], environment, roles[_1], _1) }
145
277
  ensure
278
+ run_hooks(:after_all, environment) if all_hooks
146
279
  @browser&.close
147
- @process_fixtures&.teardown
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
280
+ process_teardown_failed(@process_fixtures&.teardown(runs && !$! && runs.values.flatten.all? { _1[:json][:status] == "passed" } ? "passed" : "failed") || [])
281
+ system&.stop
282
+ @system_entries << system_entry(environment, system, system_dir, (runs&.values || []).flatten) if system && @program.file?
283
+ # Cells are folded once the system stopped, so a claim its stop judged
284
+ # otherwise turns its execution broke.
285
+ if system && runs && !$!
286
+ @scenarios.each do |scenario|
287
+ cells[scenario] << cell(runs[scenario], environment, roles[scenario], scenario).merge(before_all_failed ? { reason: "a BeforeAll hook failed" } : {})
288
+ end
289
+ end
290
+ system&.remove_events
291
+ release_reach&.call
292
+ @browser = @process_fixtures = @program_logs = @events = nil
293
+ @primary_logged = false
151
294
  end
152
295
  [executions, cells]
153
296
  end
154
297
 
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
298
+ # Runs each BeforeAll or AfterAll hook once, with no World, as the
299
+ # run's own: a failure is a finding of the run, naming the
300
+ # environment, and stops the BeforeAll hooks after it. False when one
301
+ # failed.
302
+ #: (Symbol, Environment) -> bool
303
+ def run_hooks(type, environment)
304
+ label = type == :before_all ? "BeforeAll" : "AfterAll"
305
+ ok = true
306
+ Compat.hooks_of(type).each do |hook|
307
+ hook.block.call
308
+ rescue StandardError => e
309
+ title = hook.name && !hook.name.empty? ? hook.name : label
310
+ message = e.is_a?(Compat::Pending) ? %(Hook "#{title}" called pending, which nukadoko does not interpret as pending or skipped (unlike cucumber-ruby). See docs/ruby/reference.md "Compat steps") : e.message
311
+ words = [*@rerun[:targets], *@rerun[:tags], *Order.flags(@order), *@env_flags]
312
+ @incomplete << { severity: "failed", code: "hook-failed", message: redact(%(#{title} failed in environment "#{environment.name}": #{message})),
313
+ do: ["nuka", "run", *words].map { Selection.shell_word(_1) }.join(" ") }
314
+ ok = false
315
+ break if type == :before_all
316
+ end
317
+ ok
318
+ end
319
+
320
+ # A list a started system did not read, as a warning: head's routes and
321
+ # flags, and the tables list of a system of any tree. A system of more
322
+ # than one service names the service.
323
+ #: (Environment, System, String) -> void
324
+ def warn_lists_unread(environment, system, system_dir)
325
+ named = @system == "head" ? environment.name : "#{environment.name} (#{@system})"
326
+ system.services.each do |service|
327
+ where = system.services.size > 1 ? "system #{named}, service #{service.name}" : "system #{named}"
328
+ service.listed.each do |kind, list|
329
+ next unless list[:error]
330
+
331
+ log = service.log_path ? "; see #{File.join(@dir, "systems", File.basename(system_dir), service.name, "program.log").delete_prefix("#{@project}/")}" : ""
332
+ @warnings << { severity: "warning", code: "program-list-unread", message: redact("#{where}: the #{kind} list was not read: #{list[:error]}#{log}"),
333
+ fix: Codes.fix("program-list-unread") }
334
+ end
335
+ end
336
+ end
337
+
338
+ # Under `nuka do`, a tables list the system did not read leaves the
339
+ # step's counts unjudged, and the warning says why, as a run's does.
340
+ #: (System) -> void
341
+ def warn_do_lists_unread(system)
342
+ system.services.each do |service|
343
+ where = system.services.size > 1 ? "system #{@environment&.name}, service #{service.name}" : "system #{@environment&.name}"
344
+ service.listed.each do |kind, list|
345
+ next unless list[:error]
346
+
347
+ log = service.log_path ? "; see #{service.log_path.to_s.delete_prefix("#{@project}/")}" : ""
348
+ message = redact("#{where}: the #{kind} list was not read: #{list[:error]}#{log}")
349
+ fix = Codes.fix("program-list-unread")
350
+ @out.puts ["warning", "program-list-unread", "-", message].join("\t"), *(" fix: #{fix}" if fix)
351
+ end
352
+ end
353
+ end
164
354
 
355
+ # A stopped system as run.json names it. The lines of each service's
356
+ # log that came after their step's record was read go beside that
357
+ # record, and its run.json entry names them by service: a request one
358
+ # service passed on to another carries the step's one trace.
359
+ #: (Environment, System, String, Array[Hash[Symbol, untyped]]) -> Hash[Symbol, untyped]
360
+ def system_entry(environment, system, system_dir, executions)
361
+ primary = system.primary_service
165
362
  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)
363
+ # Every service's events file is read in one pass, so a step's path
364
+ # and its counts hold what each of them reported of its one trace.
365
+ events = system_events(system, system_dir, executions)
366
+ services = system.services.map do |service|
367
+ entry = service_entry(service, system_dir)
368
+ if service.base_url && service.pid && service.log_path
369
+ own = ->(step) { step[:observed][:program_log][:services][service.name] }
370
+ traced = steps.to_h { |step| [step[:observed][:program_log][:trace_id], [own.(step)&.dig(:lines) || 0, File.join(@dir, step[:record])]] }
371
+ found = Trace::Log.new(service.log_path.to_s, system.trace_prefix, service.name).late(traced)
372
+ steps.each do |step|
373
+ late = found[:late][step[:observed][:program_log][:trace_id]]
374
+ (step[:program_log_late] ||= {})[service.name] = late if late
375
+ end
376
+ sum = ->(key) { steps.sum { own.(_1)&.dig(key) || 0 } }
377
+ entry = entry.merge(program_log: { stamped: sum.(:stamped), lines: sum.(:lines), late: found[:late].values.sum { _1[:lines] }, tagged: found[:tagged] })
378
+ end
379
+ events[service.name] ? entry.merge(events: events.fetch(service.name)) : entry
380
+ end
381
+ # Which test tenant, or whatever else setup made, this system ran
382
+ # against: the one fact that says what a failed run was looking at
383
+ # on a shared environment. Redacted like every other recorded
384
+ # value, so a {token} in it reads as its name.
385
+ { name: environment.name, tree: @system, primary: system.primary, url: redact(primary.base_url), error: nil, timings: system.timings,
386
+ **(system.setup_result.nil? ? {} : { setup_result: redact(system.setup_result) }), services: services }
387
+ end
388
+
389
+ # The reader of every service's events file of a system, or nil when
390
+ # no service of it writes one: a step's trace runs across the
391
+ # services, so one reader reads them all. A service with a URL whose
392
+ # events nukadoko does not read is named, so the steps that sent it a
393
+ # request say so (`service-unrecorded`).
394
+ #: (System) -> Events::Reader?
395
+ def events_reader(system)
396
+ services = system.services.select(&:base_url)
397
+ return nil if services.none? { _1.pid && _1.events_path }
398
+
399
+ Events::Reader.new(services.map { { service: _1.name, path: _1.pid && _1.events_path } }, system.trace_prefix, -> { secrets })
400
+ end
401
+
402
+ # The browser of a system's pass: its pages resolve against the
403
+ # primary, and a page's request to any stamped service carries the
404
+ # step's traceparent.
405
+ #: (System) -> Browser
406
+ def browser_of(system)
407
+ Browser.new(system.primary_service.base_url, Nukadoko.config_options.fetch(:browser, {}), secrets: -> { secrets },
408
+ stamped: system.trace_origins.select { _1[:stamped] }.map { _1[:url] })
409
+ end
410
+
411
+ # One service of a system as run.json names it, before its stop reads
412
+ # its log: a service at a URL has a log and events nukadoko does not
413
+ # read, so both are null.
414
+ #: (Service, String) -> Hash[Symbol, untyped]
415
+ def service_entry(service, system_dir)
416
+ code = service.code[:kind]
417
+ root = case code
418
+ when "tree" then { root: service.code[:path] }
419
+ # Named from head's project in every tree, where the program
420
+ # wrote it, with the commit it had when the system started.
421
+ when "checkout" then { root: Pathname(service.root).relative_path_from(Pathname(head_root)).to_s, commit: service.code[:commit], dirty: service.code[:dirty] }
422
+ else {}
423
+ end
424
+ entry = { name: service.name, code: code, **root, url: redact(service.base_url), commands: redact(service.commands), timings: service.timings,
425
+ log: service.log_path && File.join("systems", File.basename(system_dir), service.name, "program.log"), error: redact(service.error),
426
+ **(service.listed.empty? ? {} : { lists: redact(service.listed) }) }
427
+ return entry if service.base_url.nil? || service.pid
428
+
429
+ entry.merge(program_log: nil, events: nil)
430
+ end
431
+
432
+ # The stopped system's events as run.json names them, by service:
433
+ # each service's redacted copy beside its program.log, and each step's
434
+ # lines that came after its record beside that record, which each
435
+ # service's run.json entry names. Every service's file is read in one
436
+ # pass: a step's trace runs across them.
437
+ #: (System, String, Array[Hash[Symbol, untyped]]) -> Hash[String, Hash[Symbol, untyped]]
438
+ def system_events(system, system_dir, executions)
439
+ inlets = system.services.select { _1.pid && _1.events_path }
440
+ reader = events_reader(system)
441
+ return {} if inlets.empty? || reader.nil?
442
+
443
+ steps = executions.flat_map { _1[:json][:steps] || [] }.select { _1.dig(:observed, :events) }
444
+ traced = steps.to_h do |step|
445
+ slice = step[:observed][:events]
446
+ lines = (slice[:services] || {}).to_h { |service, own| [service.to_s, own&.dig(:lines) || 0] }
447
+ [slice[:trace_id], [lines, File.join(@dir, step[:record]), Events.inputs_of_slice(slice), Events.replaced_services(slice[:open] || [])]]
448
+ end #: Hash[String, Array[untyped]]
449
+ places, recounts = readings_to_recount(executions)
450
+ copies = inlets.to_h { [_1.name, File.join(system_dir, _1.name, Events::SYSTEM_FILE)] }
451
+ # Each service reads its own tables list: a db line is placed by the
452
+ # list of the service that wrote it.
453
+ tables = system.services.to_h { [_1.name, _1.tables] }
454
+ found = reader.collect(copies, traced, recounts: recounts, tables: tables, own_fields: own_fields)
455
+ steps.each do |step|
456
+ id = step[:observed][:events][:trace_id]
457
+ late = found[:late][id]
458
+ step[:events_late] = late if late
459
+ step[:path] = found[:paths][id] if found[:paths][id]
460
+ end
461
+ @state_writes.merge!(found[:state_writes])
462
+ places.zip(found[:recounted]).each { |(step, claim, read), recounted| after_system_stop(step, claim, read, recounted) }
463
+ executions.each { judged_too_early(_1) }
464
+ # An unhandled error on a step's path, which the stop just
465
+ # attached, can turn a pass broke too.
466
+ executions.each { _1[:execution] = demoted(_1[:execution], _1[:json]) }
467
+ inlets.to_h do |service|
468
+ own = found[:services].fetch(service.name)
469
+ [service.name,
470
+ { file: own[:copied] ? File.join("systems", File.basename(system_dir), service.name, Events::SYSTEM_FILE) : nil, lines: own[:lines], owned: own[:owned],
471
+ late: found[:late].values.sum { _1[service.name]&.dig(:lines) || 0 }, unowned: own[:unowned], unreadable: own[:unreadable],
472
+ undefined_kinds: own[:undefined_kinds] }]
473
+ end
474
+ end
475
+
476
+ # The claims of `executions` measured on a reading whose producer is
477
+ # a step of the same pass, each with the recount its system's stop
478
+ # makes. A reading of a finished record (`nuka do --use`) has its
479
+ # producer in another system, and a reading of nothing has none.
480
+ #: (Array[Hash[Symbol, untyped]]) -> [Array[[Hash[Symbol, untyped], Hash[Symbol, untyped], Hash[Symbol, untyped]]], Array[Hash[Symbol, untyped]]]
481
+ def readings_to_recount(executions)
482
+ steps = executions.flat_map { _1[:json][:steps] || [] }
483
+ producers = steps.filter_map { (slice = _1.dig(:observed, :events)) && [slice[:trace_id], slice] }.to_h
484
+ places = [] #: Array[[Hash[Symbol, untyped], Hash[Symbol, untyped], Hash[Symbol, untyped]]]
485
+ recounts = [] #: Array[Hash[Symbol, untyped]]
168
486
  steps.each do |step|
169
- late = found[:late][step[:observed][:program_log][:trace_id]]
170
- step[:program_log_late] = late if late
487
+ (step[:claims] || []).each do |claim|
488
+ channel = claim[:measured].is_a?(Hash) && claim[:measured][:step_record_id] == step[:step_record_id] ? claim[:measured][:channel].to_s : ""
489
+ next unless channel.start_with?("events_read.")
490
+
491
+ read = (step[:events_read] || {})[channel.delete_prefix("events_read.")]
492
+ slice = read && read[:trace_id] && producers[read[:trace_id]]
493
+ next unless slice
494
+
495
+ places << [step, claim, read]
496
+ recounts << { trace_id: slice[:trace_id], inputs: Events.inputs_of_slice(slice), selection: read[:count],
497
+ **(read[:service] ? { service: read[:service] } : {}), replaced: Events.replaced_services(read[:open]) }
498
+ end
171
499
  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] })
500
+ [places, recounts]
501
+ end
502
+
503
+ # A claim on a count, judged again over every line of the producer's
504
+ # trace once its system stopped: `after_system_stop` on the claim when
505
+ # a line arrived after it was judged. A claim the whole count would
506
+ # have judged otherwise was judged on lines still on their way.
507
+ #: (Hash[Symbol, untyped], Hash[Symbol, untyped], Hash[Symbol, untyped], Hash[Symbol, untyped]) -> void
508
+ def after_system_stop(_step, claim, read, recounted)
509
+ return if claim[:each] || claim[:outcome] == "unobserved"
510
+ return unless Events::Count::COMPARES.include?(claim[:compare]) && claim[:expected].is_a?(Numeric)
511
+
512
+ judged = read[:lines] + read[:unreadable]
513
+ all = recounted[:lines] + recounted[:unreadable]
514
+ return if all <= judged
515
+
516
+ # The reading's window closed when it read: the lines no step owns
517
+ # in it may still be the producer's, and the stop counts none.
518
+ maybe = recounted[:count][:maybe].merge("unowned" => recounted[:count][:maybe]["unowned"] + read[:maybe]["unowned"].to_i)
519
+ whole = recounted[:open].empty?
520
+ range = Events::Count.range_of(recounted[:count][:yes], maybe, whole)
521
+ judgment = Events::Count.judge({ range: range, whole: whole, open: recounted[:open], maybe: maybe }, claim[:compare], claim[:expected])
522
+ added = Events::Counted.describe(Events::Counted.added(read[:counted], recounted[:count][:counted]), true)
523
+ lines = ->(count) { count == 1 ? "1 line" : "#{count} lines" }
524
+ late = %(#{lines.(all - judged)} of the trace of step "#{read.dig(:of, :step) || "unknown"}" arrived after this claim was judged on #{lines.(judged)}) +
525
+ (added.empty? ? "" : ", and the stop counted #{added}")
526
+ reason = if judgment[:outcome] == :unjudged then "#{late}; #{judgment[:reason]}"
527
+ else "#{late}; over all #{lines.(all)}, the count is #{Events::Count.describe_range(range)}, so the claim #{judgment[:outcome] == :held ? "holds" : "breaks"}"
528
+ end
529
+ claim[:after_system_stop] = { lines: recounted[:lines], range: range, outcome: judgment[:outcome].to_s, reason: reason }
530
+ end
531
+
532
+ # An execution with a claim the system's stop judged otherwise was
533
+ # judged on lines still on their way: its cell is broke, and a
534
+ # claim-judged-early finding names the first such claim.
535
+ #: (Hash[Symbol, untyped]) -> void
536
+ def judged_too_early(execution)
537
+ json = execution[:json]
538
+ index = (json[:steps] || []).index { |step| (step[:claims] || []).any? { _1[:after_system_stop] && _1[:after_system_stop][:outcome] != _1[:outcome] } }
539
+ return unless index
540
+
541
+ step = json[:steps][index]
542
+ line = step[:line] || json[:line]
543
+ execution[:execution] = [:broke, line, "a claim at line #{line} was judged before every execution event it counts had arrived"]
544
+ claim = step[:claims].find { _1[:after_system_stop] && _1[:after_system_stop][:outcome] != _1[:outcome] }
545
+ # One per scenario and environment, since --repeat would say it again.
546
+ key = "#{json[:feature]}:#{json[:line]}:#{json[:environment]}"
547
+ scenario = @scenarios.find { _1.uri == json[:feature] && _1.line == json[:line] }
548
+ return if @system != "head" || @judged_early.key?(key) || scenario.nil? || @environment.nil?
549
+
550
+ @judged_early[key] = { severity: "failed", code: "claim-judged-early", file: json[:feature], line: line,
551
+ message: "#{label(json[:scenario], json[:environment])}: a claim at line #{line} #{claim[:outcome]} before every execution event it counts " \
552
+ "had arrived, so its cell is broke: #{claim[:after_system_stop][:reason]}",
553
+ do: again(scenario, @environment) }
174
554
  end
175
555
 
176
556
  # Under --concurrency the files go to worker processes in the run's
177
557
  # order, round-robin, and each worker plays its own files --repeat
178
558
  # times. A file whose Feature line is @nukadoko:serial runs after
179
559
  # 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
560
+ # The parent keeps the system each worker reaches, and takes each
181
561
  # 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)
562
+ #: (Environment, Hash[Scenario, String], System, ^() -> Array[Scenario], ^(Scenario, Hash[Symbol, untyped]) -> void, Hash[Scenario, Array[Hash[Symbol, untyped]]]) -> void
563
+ def play_in_workers(environment, roles, system, due, ran, runs)
184
564
  files = @scenarios.group_by(&:uri).values
185
565
  parallel, serial = files.partition { !_1.first.serial }
186
566
  buckets = Array.new([@concurrency, parallel.size].min) { [] }
@@ -193,10 +573,10 @@ module Nukadoko
193
573
  : boundary(scenario.uri, scenario.line, scenario.name, roles[scenario])
194
574
  end
195
575
  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) }
576
+ unplayed = workers(groups.map { |group| @repeat.times.flat_map { group } }, environment, roles, system, ran, main)
577
+ serial.each { |file| unplayed += workers([@repeat.times.flat_map { file }], environment, roles, system, ran, main) }
198
578
  until (round = due.()).empty?
199
- break unless workers([round], environment, roles, world, ran, ->(scenario) { line_for.(scenario, true) }).empty?
579
+ break unless workers([round], environment, roles, system, ran, ->(scenario) { line_for.(scenario, true) }).empty?
200
580
  end
201
581
  return if unplayed.empty?
202
582
 
@@ -205,18 +585,26 @@ module Nukadoko
205
585
  message: "A worker exited without writing any record for: #{where.join(", ")}. This run is incomplete and cannot be treated as a pass" }
206
586
  end
207
587
 
588
+ # A process fixture's teardown errors, from this process or a worker:
589
+ # printed as warnings, and kept for the envelope's findings.
590
+ #: (Array[{ fixture: String, message: String }]) -> void
591
+ def process_teardown_failed(errors)
592
+ FixtureCache.warnings(errors) { redact(_1) }.each { @out.puts _1 }
593
+ @process_teardown.concat(FixtureCache.findings(errors) { redact(_1) })
594
+ end
595
+
208
596
  # Each list is one worker's scenarios in the order it plays them. A
209
597
  # worker sends each line it prints and each execution down a pipe of
210
598
  # its own, one Marshal frame at a time, so no line or record is ever
211
599
  # spliced from two workers. Returns the files a worker that failed
212
600
  # 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)
601
+ #: (Array[Array[Scenario]], Environment, Hash[Scenario, String], System, ^(Scenario, Hash[Symbol, untyped]) -> void, ^(Scenario) -> String) -> Array[String]
602
+ def workers(lists, environment, roles, system, ran, line_for)
215
603
  live = lists.each_with_index.map do |list, index|
216
604
  reader, writer = IO.pipe
217
605
  pid = fork do
218
606
  reader.close
219
- exit!(play_as_worker(index + 1, list, environment, roles, world, writer))
607
+ exit!(play_as_worker(index + 1, list, environment, roles, system, writer))
220
608
  end
221
609
  writer.close
222
610
  worker = { pid: pid, reader: reader, list: list, played: Set.new } #: Hash[Symbol, untyped]
@@ -228,6 +616,7 @@ module Nukadoko
228
616
  worker = open.find { _1[:reader] == reader } #: Hash[Symbol, untyped]
229
617
  kind, *value = Marshal.load(reader)
230
618
  if kind == :line then @out.puts value.first
619
+ elsif kind == :teardown then process_teardown_failed(value.first)
231
620
  else
232
621
  scenario = by_key.fetch(value[0])
233
622
  @out.puts line_for.(scenario)
@@ -245,24 +634,29 @@ module Nukadoko
245
634
  live.reject { _1[:status].success? }.flat_map { |worker| worker[:list].map(&:uri).uniq - worker[:played].to_a }
246
635
  end
247
636
 
248
- #: (Integer, Array[Scenario], Environment, Hash[Scenario, String], World, IO) -> Integer
249
- def play_as_worker(number, list, environment, roles, world, pipe)
637
+ #: (Integer, Array[Scenario], Environment, Hash[Scenario, String], System, IO) -> Integer
638
+ def play_as_worker(number, list, environment, roles, system, pipe)
250
639
  @worker = number
251
640
  @out = WorkerOut.new(pipe)
252
641
  @records = nil
253
642
  @process_fixtures = FixtureCache.new
254
- @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}), secrets: -> { secrets })
643
+ @browser = browser_of(system)
644
+ passed = true
255
645
  list.each do |scenario|
256
- execution = play(scenario, environment, roles[scenario], world)
646
+ execution = play(scenario, environment, roles[scenario], system)
647
+ passed &&= execution[:json][:status] == "passed"
257
648
  Marshal.dump([:execution, [scenario.uri, scenario.line], execution, @out.take], pipe)
258
649
  end
259
650
  0
260
651
  rescue Exception => e # rubocop:disable Lint/RescueException
652
+ passed = false
261
653
  Marshal.dump([:line, "worker #{number} stopped: #{e.class}: #{e.message}"], pipe) rescue nil
262
654
  1
263
655
  ensure
264
656
  @browser&.close
265
- @process_fixtures&.teardown
657
+ # The parent reports these, so they reach the envelope's findings as
658
+ # a serial run's do, not only stderr.
659
+ Marshal.dump([:teardown, @process_fixtures&.teardown(passed ? "passed" : "failed") || []], pipe) rescue nil
266
660
  pipe.close
267
661
  end
268
662
 
@@ -290,7 +684,7 @@ module Nukadoko
290
684
  # so a Then failing there the same way in each proof run is proof.
291
685
  #: (String, Array[Hash[Symbol, untyped]]) -> bool
292
686
  def proving?(role, runs)
293
- absent = @world == "base" || (@world == "head" && role == "control")
687
+ absent = @system == "base" || (@system == "head" && role == "control")
294
688
  absent && runs.size < Table.proof_runs && runs.all? { _1[:execution].first == :fail } && runs.map { _1[:execution] }.uniq.size == 1
295
689
  end
296
690
 
@@ -302,8 +696,8 @@ module Nukadoko
302
696
  def cell(runs, environment, role, scenario)
303
697
  executions = runs.map { _1[:execution] }
304
698
  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
699
+ entry = { system: @system, environment: environment.name, role: role, conditions: Table.conditions_of(scenario.tags, environment.conditions),
700
+ outcome: cell[:outcome], line: cell[:line], runs: cell[:runs], reason: cell[:reason] }.compact
307
701
  if cell[:outcome] == "fail"
308
702
  entry[:claim] = executions.first[2]
309
703
  entry[:actuals] = runs.map { { value: _1[:actual] } }
@@ -311,7 +705,7 @@ module Nukadoko
311
705
  entry
312
706
  end
313
707
 
314
- # run.json is the --json envelope as a file: the commit and worlds the
708
+ # run.json is the --json envelope as a file: the commit and systems the
315
709
  # run judged, the counts, each execution, and the verdict table.
316
710
  # `tree_cells` holds each row's base and old cells, by its scenario,
317
711
  # under `--base`; each row is judged with what changed since the base.
@@ -324,17 +718,21 @@ module Nukadoko
324
718
  row = { feature: scenario.uri, line: scenario.line, name: scenario.name, change: change&.dig(:change) }
325
719
  row[:renamed_from] = change[:renamed_from] if change&.dig(:renamed_from)
326
720
  row[:retagged] = true if change&.dig(:retagged)
327
- row.merge(conditions: Table.row_tags(scenario.tags), cells: row_cells, verdict: verdict, reason: reason)
721
+ expects = Underneath.tags_of(scenario.tags)
722
+ row.merge(conditions: Table.row_tags(scenario.tags), **(expects.empty? ? {} : { expects: expects }), cells: row_cells, verdict: verdict, reason: reason)
328
723
  end
329
724
  rows.sort_by! { [_1[:feature], _1[:line]] }
330
725
  rows.concat(removed_rows) if @base
331
726
  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 } }
727
+ systems = %w[head base old].flat_map do |system|
728
+ environments = system == "old" ? (@base&.old_environments || @environments) : @environments
729
+ environments.map(&:name).select { |name| system == "head" || rows.any? { |row| row[:cells].any? { _1[:system] == system && _1[:environment] == name } } }
730
+ .map { { system: system, environment: _1 } }
336
731
  end
337
- judged = @base ? judged_findings(rows) : []
732
+ # An unproven or moved row has no failed execution to carry its
733
+ # finding, so it gets one of its own, listed before the findings
734
+ # set beside an execution's steps, as the TypeScript engine lists it.
735
+ judged_rows = @base ? judged_findings(rows) : []
338
736
  # Judgments sit beside the verdicts, read after the table is built
339
737
  # and never folded into a row's verdict. A file that cannot be read
340
738
  # is a failed finding of its own, and its rows read as judged by
@@ -360,20 +758,142 @@ module Nukadoko
360
758
  if @base && changed.nil?
361
759
  warnings << { severity: "warning", code: "judgments-not-compared", message: "the judgment files were not compared with the base: git did not answer" }
362
760
  end
363
- judged += Judgments.findings(rows, @id) + problems
761
+ # And per row, which judgment the change brought: a row that stands
762
+ # on a judgment the change made of its own output.
763
+ if (base = @base) && changed
764
+ at_base = {} #: Hash[String, Array[Hash[Symbol, untyped]]?]
765
+ rows = Judgments.with_base_judgments(rows, lambda do |feature|
766
+ at_base.fetch(feature) { at_base[feature] = JudgmentFile.at_commit(@project, base.commit, feature)&.dig(:entries) }
767
+ end)
768
+ end
769
+ judged = Judgments.findings(rows, @id) + problems
770
+ listed = lambda do |kind|
771
+ @environments.filter_map do |e|
772
+ entries = @listed_places.dig(e.name, kind) or next nil
773
+
774
+ { environment: e.name, **(@listed_by[e.name] ? { service: @listed_by[e.name] } : {}), kind.to_sym => entries }
775
+ end
776
+ end
777
+ flags = PlaceRows.flag_rows(scenarios, rows, listed.("flags"))
778
+ # With no routes list read, a run has no routes at all, never one
779
+ # that reads as nothing listed.
780
+ routes = listed.("routes").then { _1.empty? ? nil : PlaceRows.route_rows(scenarios, rows, _1) }
781
+ environments = @environments.map { environment_entry(_1) }
782
+ table = { base: @base && { ref: @base.ref, commit: @base.commit }, mapping_changed: @base&.mapping&.dig(:changed),
783
+ mapping_changes: @base&.mapping_changes, **(changed ? { judgments_changed: changed } : {}),
784
+ systems: systems, rows: rows, left_out: @left_out, proof_runs: Table.proof_runs }
785
+ paths, intent, intent_found = paths_and_intent(scenarios, table, environments)
364
786
  { 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,
787
+ environments: environments, systems: @system_entries, order: @order,
788
+ counts: RunRecord.counts(scenarios.reject { _1[:system] }, rows), scenarios: scenarios,
789
+ table: table,
790
+ **(flags.empty? ? {} : { flags: flags }),
791
+ **(routes.nil? ? {} : { routes: routes }),
792
+ **(paths.empty? ? {} : { paths: paths }),
793
+ **(intent.nil? ? {} : { intent: intent }),
794
+ failures: @warnings + warnings + executions.filter_map { _1[:failure] } + judged_rows + @judged_early.values + underneath_findings(scenarios) + undeclared_writes(scenarios) +
795
+ refused_commands(scenarios) + judged + intent_found + @incomplete +
796
+ # Last, as in the TypeScript engine. Read from the run's
797
+ # own scenario entries and the step records they cite,
798
+ # which are on disk by now, so the notes reach run.json
799
+ # in its one write. Head's executions only: a tree ran
800
+ # other code or other steps.
801
+ RepeatedPrefix.findings(@dir, scenarios.reject { _1[:system] }, @scenarios),
371
802
  # A criterion whose Then asks for a judgment holds only once one
372
803
  # 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 } : {}) }
804
+ # A change that declares its intent opts into one more gate: a
805
+ # difference it does not declare, or a row that did not happen.
806
+ passed: @incomplete.empty? && rows.none? { Summary::RED.include?(_1[:verdict]) } && !Judgments.open?(rows) && problems.empty? &&
807
+ intent_found.none? { _1[:severity] == "failed" },
808
+ **(@walk ? { walk: @walk.record } : {}),
809
+ # Printed as they happened; a --json envelope lists them instead.
810
+ teardown_warnings: scenarios.flat_map { FixtureCache.findings(_1[:teardown_errors] || []) { |text| text } } + @process_teardown }
375
811
  end
376
812
 
813
+ # The cells a failure underneath made broke, and each tag that
814
+ # accepts a failure that no longer happens.
815
+ #: (Array[Hash[Symbol, untyped]]) -> Array[Hash[Symbol, untyped]]
816
+ def underneath_findings(scenarios)
817
+ name = ->(scenario) { label(scenario[:scenario], scenario[:environment]) }
818
+ rerun = lambda do |scenario|
819
+ criterion = @scenarios.find { _1.uri == scenario[:feature] && _1.line == scenario[:line] }
820
+ environment = @environments.find { _1.name == scenario[:environment] }
821
+ criterion && environment ? again(criterion, environment) : nil
822
+ end
823
+ Underneath.unexpected_findings(scenarios, label: name, rerun: rerun) + Underneath.unseen_notes(scenarios, label: name)
824
+ end
825
+
826
+ # A step that declares mutates: false and whose trace holds a write
827
+ # the program committed to a table that holds state: one note per
828
+ # step line of each scenario and environment, the first execution's
829
+ # writes named, since the runs of --repeat would say it again. Only
830
+ # head's executions: another tree's declarations are not the change.
831
+ #: (Array[Hash[Symbol, untyped]]) -> Array[Hash[Symbol, untyped]]
832
+ def undeclared_writes(scenarios)
833
+ found = {} #: Hash[String, Hash[Symbol, untyped]]
834
+ scenarios.each do |scenario|
835
+ next if scenario[:system]
836
+
837
+ (scenario[:steps] || []).each_with_index do |step, index|
838
+ next unless step[:mutates] == false
839
+
840
+ writes = @state_writes[step.dig(:observed, :events, :trace_id)]
841
+ next if writes.nil? || writes.empty?
842
+
843
+ line = step[:line] || scenario[:line]
844
+ found["#{scenario[:feature]}:#{scenario[:line]}:#{scenario[:environment]}:#{index}"] ||= {
845
+ severity: "note", code: "undeclared-write", file: scenario[:feature], line: line,
846
+ message: "#{label(scenario[:scenario], scenario[:environment])}: the step at line #{line}, #{step[:step] || step[:text]}, declares mutates: false, " \
847
+ "and its trace holds writes the program committed to tables that hold state, #{Events::Counted.describe(writes)}",
848
+ fix: Codes.fix("undeclared-write")
849
+ }.compact
850
+ end
851
+ end
852
+ found.values
853
+ end
854
+
855
+ # A system that declares stepsReach: "url" refused a command: one
856
+ # finding per scenario and environment, naming every refused place of
857
+ # it, since a suite that reaches for the command line in several steps
858
+ # reads one line per scenario rather than one per call. It reads the
859
+ # step records, not the error a step raised, so a step that rescued
860
+ # the refusal and went on is reported too. Head's executions only: a
861
+ # row of another tree carries a finding of its own.
862
+ #: (Array[Hash[Symbol, untyped]]) -> Array[Hash[Symbol, untyped]]
863
+ def refused_commands(scenarios)
864
+ found = {} #: Hash[String, Hash[Symbol, untyped]]
865
+ scenarios.each do |scenario|
866
+ next if scenario[:system]
867
+
868
+ key = "#{scenario[:feature]}:#{scenario[:line]}:#{scenario[:environment]}"
869
+ next if found.key?(key)
870
+
871
+ places = (scenario[:steps] || []).filter_map do |step|
872
+ commands = (step.dig(:observed, :processes) || []).select { _1[:refused] }
873
+ next if commands.empty?
874
+
875
+ line = step[:line] || scenario[:line]
876
+ [line, %(the step at line #{line}, "#{step[:text] || step[:step]}" (#{commands.map { _1[:command]&.first }.join(", ")}))]
877
+ end
878
+ next if places.empty?
879
+
880
+ criterion = @scenarios.find { _1.uri == scenario[:feature] && _1.line == scenario[:line] }
881
+ environment = @environments.find { _1.name == scenario[:environment] }
882
+ found[key] = {
883
+ severity: "failed", code: "command-refused", file: scenario[:feature], line: places.first.first,
884
+ message: %(#{label(scenario[:scenario], scenario[:environment])}: environment "#{scenario[:environment]}" declares stepsReach: "url", ) +
885
+ "and Nukadoko.run_command was called, so nothing ran and the cell is broke: #{places.map(&:last).join("; ")}",
886
+ fix: Codes.fix("command-refused"),
887
+ do: criterion && environment ? again(criterion, environment) : nil
888
+ }.compact
889
+ end
890
+ found.values
891
+ end
892
+
893
+ # A scenario's name, and its environment in a run over several.
894
+ #: (String, String) -> String
895
+ def label(name, environment) = @environments.size > 1 ? "#{name} (#{environment})" : name
896
+
377
897
  # What `--base` knows of one row: its change, whether it carries
378
898
  # @held, whether the mapping changed, whether its tags or its name or
379
899
  # file changed, and whether its passing executions judged no claim in
@@ -414,7 +934,7 @@ module Nukadoko
414
934
  #: (Scenario, Array[Hash[Symbol, untyped]]) -> untyped
415
935
  def self.then_judged_by(scenario, executions)
416
936
  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"
937
+ json[:judged_by] if json[:feature] == scenario.uri && json[:line] == scenario.line && !json[:system] && json[:role] == "required" && json[:status] == "passed"
418
938
  end.first
419
939
  end
420
940
 
@@ -443,8 +963,26 @@ module Nukadoko
443
963
 
444
964
  #: (Environment) -> Hash[Symbol, untyped]
445
965
  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])
966
+ version = @target_versions[environment.name]
967
+ { name: environment.name, conditions: environment.conditions.empty? ? nil : environment.conditions }.compact
968
+ .merge(target_version: version && redact(version), base_url: @base_urls[environment.name])
969
+ end
970
+
971
+ # The environment's version function, under ten seconds: its answer
972
+ # goes into run.json and every record of the environment as
973
+ # target_version, and a probe that fails is a warning, never a reason
974
+ # the run fails.
975
+ #: (Environment) -> void
976
+ def probe_version(environment)
977
+ probe = @program.version(environment.name)
978
+ return unless probe
979
+
980
+ answer = Timeout.timeout(10, Timeout::Error, "version probe timed out after 10000ms") { probe.call }
981
+ raise TypeError, "version probe must resolve to a string, got #{answer.nil? ? "undefined" : answer.class.name.downcase}" unless answer.is_a?(String)
982
+
983
+ @target_versions[environment.name] = answer
984
+ rescue StandardError => e
985
+ @warnings << { severity: "warning", code: "version-probe-failed", message: redact(%(version probe for environment "#{environment.name}" failed: #{e.message})) }
448
986
  end
449
987
 
450
988
  # The line before a scenario's execution, numbered across the run, in
@@ -494,8 +1032,8 @@ module Nukadoko
494
1032
  ["nuka", "run", *words].map { Selection.shell_word(_1) }.join(" ")
495
1033
  end
496
1034
 
497
- #: (Scenario, Environment, String, World) -> Hash[Symbol, untyped]
498
- def play(scenario, environment, role, world)
1035
+ #: (Scenario, Environment, String, System) -> Hash[Symbol, untyped]
1036
+ def play(scenario, environment, role, system)
499
1037
  # The numbered line is the caller's: a worker's goes out with its
500
1038
  # execution, numbered by the parent.
501
1039
  @out.puts "scenario start worker #{@worker} #{scenario.uri}:#{scenario.line} #{scenario.name}" if @worker
@@ -503,21 +1041,54 @@ module Nukadoko
503
1041
  results = []
504
1042
  stopped = nil #: Array[untyped]?
505
1043
  @scratch = Scratch.new(@project)
1044
+ # Each step that passed in this scenario, its latest line, for a files key.
1045
+ ran = {} #: Hash[untyped, Hash[Symbol, untyped]]
1046
+ @files_source = ->(key, entry) { scenario_files_source(ran, key, entry) }
1047
+ @events_source = ->(key, entry) { scenario_events_source(ran, key, entry) }
1048
+ @events_producers = {}
1049
+ @ran = ran
506
1050
  @scenario_fixtures = FixtureCache.new
507
1051
  scenario_record_id = new_id("scn")
508
1052
  @step_file = lambda do |record|
509
- RunRecord.step_file(record, environment: environment.name, world_name: @program.file? ? environment.name : nil, run_id: @id,
1053
+ RunRecord.step_file(record, environment: environment.name, system_name: @program.file? ? environment.name : nil, run_id: @id, target_version: @target_versions[environment.name],
510
1054
  scenario_record_id: scenario_record_id, evidence_dir: File.join(".nukadoko", "runs", @id, "steps", record[:step_record_id]))
511
1055
  end
512
1056
  # Where a person stopped the walk, as run.json's `stopped` says it.
513
1057
  walk_stopped = nil #: Hash[Symbol, untyped]?
514
1058
  @walk&.begin({ run_id: @id, run_dir: File.join(".nukadoko", "runs", @id),
515
1059
  scenario: { feature: scenario.uri, line: scenario.line, name: scenario.name, environment: environment.name },
516
- world: world.base_url ? { url: world.base_url } : nil })
1060
+ system: system.primary_service.base_url ? { url: system.primary_service.base_url } : nil })
1061
+ # A line the steps before it can only reach without a state it
1062
+ # requires fails the scenario before any step runs, --no-check
1063
+ # included, as nuka check reports it: each such line carries its
1064
+ # message and every other line is skipped.
1065
+ refusals = States.refusals(@steps, scenario)
1066
+ # A scenario of a suite that came in through the compat door gets a
1067
+ # World of its own, which its hooks and compat steps share.
1068
+ hooks = [] #: Array[Hash[Symbol, untyped]]
1069
+ compat = (Compat::Scenario.new(scenario.name, scenario.tags, "#{scenario.uri}:#{scenario.line}") if Compat.steps.any? || Compat.hooks.any?)
1070
+ @compat_world = compat ? Compat.new_world : nil
1071
+ @compat_tags = scenario.tags
1072
+ hook_failed = compat && !compat_hooks(:before, hooks, [compat])
517
1073
  records = scenario.steps.each_with_index.map do |line, index|
518
1074
  began = Process.clock_gettime(Process::CLOCK_MONOTONIC)
519
- record = stopped || walk_stopped ? skipped(line) : play_step(line, results, world)
1075
+ record = if refusals.any?
1076
+ if (messages = refusals[index])
1077
+ { status: "failed", outcome: :broke, step_record_id: nil, step: Engine.matches(@steps, line.text).first&.first&.step_name, error: messages.join("; "), refused: true }
1078
+ else skipped(line)
1079
+ end
1080
+ elsif stopped || walk_stopped || hook_failed then skipped(line)
1081
+ else play_step(line, results, system)
1082
+ end
520
1083
  stopped ||= [record[:outcome], line.line, record[:claim], record[:broken_actual]] if record[:status] == "failed"
1084
+ # AfterStep runs after each step that began, and its failure
1085
+ # stops the scenario as the step's own would.
1086
+ if compat && record[:step_record_id] && record[:status] != "skipped"
1087
+ result = Compat::StepResult.new(status: record[:status].to_sym, exception: nil)
1088
+ unless compat_hooks(:after_step, hooks, [result, line], step_index: index)
1089
+ stopped ||= [:broke, scenario.line, "an AfterStep hook failed after the step at line #{line.line} passed"]
1090
+ end
1091
+ end
521
1092
  seconds = format("%.1f", Process.clock_gettime(Process::CLOCK_MONOTONIC) - began)
522
1093
  @out.puts " step #{index + 1}/#{scenario.steps.size} #{record[:status]} #{seconds}s #{line.text}"
523
1094
  step_failure(record).each { @out.puts " #{_1}" } if record[:status] == "failed"
@@ -529,25 +1100,41 @@ module Nukadoko
529
1100
  end
530
1101
  record
531
1102
  end
1103
+ if compat
1104
+ compat.status = stopped || hook_failed ? :failed : :passed
1105
+ unless compat_hooks(:after, hooks, [compat])
1106
+ stopped ||= [:broke, scenario.line, walk_stopped ? "an After hook failed after the walk was stopped" : "an After hook failed after its steps passed"] unless hook_failed
1107
+ end
1108
+ stopped ||= [:broke, scenario.line, "a Before hook failed before its steps ran"] if hook_failed
1109
+ end
1110
+ @compat_world = nil
532
1111
  browser = @browser.scenario_browser
533
1112
  final = @browser.end_scenario(File.join(@dir, "scenarios", scenario_record_id))
534
- @scenario_fixtures.teardown
1113
+ teardown_errors = @scenario_fixtures.teardown(stopped || walk_stopped ? "failed" : "passed")
1114
+ FixtureCache.warnings(teardown_errors) { redact(_1) }.each { @out.puts _1 }
535
1115
  @scratch.remove_all
536
1116
  execution = if stopped then stopped[0, 3].to_a.compact
537
1117
  elsif walk_stopped then [:stopped, walk_stopped[:line]]
538
1118
  else [:pass]
539
1119
  end
540
1120
  failed = records.find { _1[:status] == "failed" }
1121
+ # A hook that failed with every step passed or skipped is the
1122
+ # failure the scenario reports, by its message's first line.
1123
+ hook_failure = hooks.find { _1[:status] == "failed" }
1124
+ failed ||= { error: hook_failure[:error][:message].lines.first.to_s.chomp } if hook_failure
541
1125
  status = if stopped then "failed"
542
1126
  elsif walk_stopped then "stopped"
543
1127
  else "passed"
544
1128
  end
545
1129
  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]
1130
+ environment: environment.name, status: status, **(walk_stopped && !stopped ? { stopped: walk_stopped } : {}),
1131
+ started_at: started_at, finished_at: now, **(browser ? { browser: browser } : {}),
1132
+ steps: scenario.steps.zip(records).map { |line, record| step_entry(line, record) }, hooks: hooks } #: Hash[Symbol, untyped]
549
1133
  json[:evidence] = { dir: File.join("scenarios", scenario_record_id), screenshots: final } if final.any?
1134
+ json[:teardown_errors] = redact(teardown_errors) if teardown_errors.any?
550
1135
  json[:do] = again(scenario, environment) if (failed || status == "stopped") && role != "control"
1136
+ expects = Underneath.tags_of(scenario.tags)
1137
+ json[:expects] = expects if expects.any?
551
1138
  json[:claims] = RunRecord.claim_counts(records)
552
1139
  # A scenario in which no claim on a Then line was judged says so,
553
1140
  # since a pass there shows only that nothing raised. A Then whose
@@ -555,7 +1142,12 @@ module Nukadoko
555
1142
  # what decides it.
556
1143
  then_claims = scenario.steps.zip(records).select { |line, _| line_kind(line) == :then }.flat_map { _2[:claim_records] || [] }
557
1144
  unless then_claims.any? { !%w[unobserved for-judgment].include?(_1[:outcome]) }
558
- json[:judged_by] = then_claims.any? { _1[:outcome] == "for-judgment" } ? "judgment" : "nothing"
1145
+ # A compat step in Then position may have judged by raising.
1146
+ compat_then = scenario.steps.zip(records).any? { |line, record| line_kind(line) == :then && @steps.any? { _1.step_name == record[:step] && Vocabulary.compat?(_1) } }
1147
+ json[:judged_by] = if then_claims.any? { _1[:outcome] == "for-judgment" } then "judgment"
1148
+ elsif compat_then then "compat"
1149
+ else "nothing"
1150
+ end
559
1151
  end
560
1152
  json[:role] = role
561
1153
  failure = if failed && role != "control"
@@ -567,7 +1159,65 @@ module Nukadoko
567
1159
  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
1160
  do: json[:do] }
569
1161
  end
570
- { execution: execution, actual: stopped && stopped[3], json: json, failure: failure }
1162
+ { execution: refused_command(json) || demoted(execution, json), actual: stopped && stopped[3], json: json, failure: failure }
1163
+ end
1164
+
1165
+ # A system that declares stepsReach: "url" refused a command the
1166
+ # execution tried to run. Whatever the execution came to, nothing it
1167
+ # did reached the program the way the system says it must, and a step
1168
+ # that rescued the refusal would otherwise pass, so its cell is broke.
1169
+ #: (Hash[Symbol, untyped]) -> Array[untyped]?
1170
+ def refused_command(json)
1171
+ step = (json[:steps] || []).find { |entry| (entry.dig(:observed, :processes) || []).any? { _1[:refused] } }
1172
+ return nil unless step
1173
+
1174
+ line = step[:line] || json[:line]
1175
+ [:broke, line, %(the step at line #{line} was refused a command: the environment declares stepsReach: "url")]
1176
+ end
1177
+
1178
+ # What a pass comes to once a failure underneath it that no tag of its
1179
+ # scenario accepts is known: broke, at that failure's step. Claims
1180
+ # that held over a program that failed underneath them prove nothing
1181
+ # about the criterion.
1182
+ #: (Array[untyped], Hash[Symbol, untyped]) -> Array[untyped]
1183
+ def demoted(execution, json)
1184
+ return execution unless execution == [:pass]
1185
+
1186
+ failure = Underneath.demoting(json)
1187
+ failure ? [:broke, failure[:line], Underneath.reason(failure)] : execution
1188
+ end
1189
+
1190
+ # Runs a compat hook kind on the scenario's World, each that its tags
1191
+ # select, and adds an entry for each to `hooks`. Before stops at the
1192
+ # first that fails, since nothing is left to prepare into; After runs
1193
+ # in reverse order, as teardown unwinds setup. False when one failed.
1194
+ #: (Symbol, Array[Hash[Symbol, untyped]], Array[untyped], ?step_index: Integer?) -> bool
1195
+ def compat_hooks(type, hooks, given, step_index: nil)
1196
+ chosen = Compat.hooks_of(type)
1197
+ chosen = chosen.reverse if type == :after
1198
+ ok = true
1199
+ chosen.each do |hook|
1200
+ entry = { type: type.to_s, **(step_index ? { step_index: step_index } : {}), status: "passed" } #: Hash[Symbol, untyped]
1201
+ title = hook.name && !hook.name.empty? ? hook.name : { before: "Before", after: "After", after_step: "AfterStep hook (step #{step_index.to_i + 1})" }.fetch(type)
1202
+ begin
1203
+ next unless Compat.applies?(hook, @compat_tags)
1204
+
1205
+ Reach.at("in #{title}") { @compat_world.instance_exec(*given, &hook.block) }
1206
+ rescue Compat::Pending
1207
+ entry.merge!(status: "failed", error: { message: %(Hook "#{title}" called pending, which nukadoko does not interpret as pending or skipped (unlike cucumber-ruby). See docs/ruby/reference.md "Compat steps"), kind: "unsupported" })
1208
+ rescue Compat::Unsupported => e
1209
+ entry.merge!(status: "failed", error: { message: redact(e.message), kind: "unsupported" })
1210
+ rescue StandardError => e
1211
+ entry.merge!(status: "failed", error: { message: redact(e.message), kind: "step_error" })
1212
+ end
1213
+ entry[:name] = hook.name if hook.name && !hook.name.empty?
1214
+ hooks << entry
1215
+ next if entry[:status] == "passed"
1216
+
1217
+ ok = false
1218
+ break if type == :before
1219
+ end
1220
+ ok
571
1221
  end
572
1222
 
573
1223
  # The pause after the step that ran `number`th, under --step. Before
@@ -601,8 +1251,12 @@ module Nukadoko
601
1251
  # run.json keeps the record's observed without file content, so it stays small.
602
1252
  entry[:observed] = { processes: processes&.any? ? processes : nil, http: record[:http_count]&.positive? ? record[:http_count] : nil,
603
1253
  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]
1254
+ **(record[:mcp_count] ? { mcp: record[:mcp_count] } : {}),
1255
+ **(record.key?(:program_log) ? { program_log: record[:program_log] } : {}),
1256
+ **(record.key?(:events) ? { events: record[:events] } : {}) }
1257
+ # A refused line never began, so its error has no kind, as the
1258
+ # TypeScript engine writes it.
1259
+ entry[:error] = record[:refused] ? { kind: nil, message: record[:error] } : { kind: record[:error_kind], message: record[:error] }.compact if record[:error]
606
1260
  # Only a failed step names what it read: a reader then sees the value it broke on.
607
1261
  entry[:used] = record[:used] if record[:used]&.any? && record[:status] == "failed"
608
1262
  if record[:claim_records]
@@ -611,8 +1265,9 @@ module Nukadoko
611
1265
  claim[:outcome] == "for-judgment" && claim.key?(:actual) && !claim[:each] ? { **claim, value_digest: Judgments.value_digest(claim[:actual]) } : claim
612
1266
  end
613
1267
  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)))
1268
+ entry.merge!(RunRecord.poll_fields(record).except(:readings), **RunRecord.read_fields(record, File.join("steps", record[:step_record_id].to_s)))
615
1269
  end
1270
+ entry[:underneath] = record[:underneath] if record[:underneath]
616
1271
  entry
617
1272
  end
618
1273
 
@@ -621,8 +1276,8 @@ module Nukadoko
621
1276
  { step: Engine.matches(@steps, line.text).first&.first&.step_name, status: "skipped", step_record_id: nil }
622
1277
  end
623
1278
 
624
- #: (PickleStep, Array[untyped], World) -> Hash[Symbol, untyped]
625
- def play_step(line, results, world)
1279
+ #: (PickleStep, Array[untyped], System) -> Hash[Symbol, untyped]
1280
+ def play_step(line, results, system)
626
1281
  matched = Engine.matches(@steps, line.text)
627
1282
  step, captures = matched.first
628
1283
  unless step
@@ -637,40 +1292,226 @@ module Nukadoko
637
1292
  error: %("#{line.text}" matches more than one step: #{names.join(", ")}), never_began: "ambiguous" }
638
1293
  end
639
1294
 
1295
+ if (refused = read_only_refusal(step))
1296
+ return { status: "failed", outcome: :broke, step_record_id: nil, step: step.step_name, error: refused }
1297
+ end
1298
+
640
1299
  id = new_id("step")
641
1300
  dir = File.join(@dir, "steps", id)
642
1301
  record = { step_record_id: id, step: step.step_name, text: line.text, started_at: Time.now.utc.iso8601(3) }
643
1302
  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))]
1303
+ drops = {}
1304
+ execute(step, record, dir, system, then_line: line_kind(line) == :then, at_line: line.line, results: results, origins: origins, drops: drops) do
1305
+ # A compat step takes its matched values in order, then the line's
1306
+ # table or docstring, as cucumber-ruby passes them.
1307
+ compat = step #: untyped
1308
+ next [compat.values(captures, @compat_world) + [line.table ? Compat::DataTable.new(line.table) : line.doc_string].compact, {}] if Vocabulary.compat?(step)
1309
+
1310
+ args = bind_args(step, captures, line, results, origins, record, drops)
1311
+ [args, (step.patterns.lazy.filter_map { Pattern.new(_1).texts(line.text) }.first || {}).merge(attachment_texts(step, captures, line))]
1312
+ end
1313
+ @ran[step] = { step: step.step_name, line: line.line, record: record } if @ran && record[:status] == "passed"
1314
+ record
1315
+ end
1316
+
1317
+ # The step a files key reads the changed paths of: the one of its
1318
+ # `of` steps that passed on an earlier line, as nuka check reports a
1319
+ # line where none or two did (files-producer-missing,
1320
+ # files-producer-ambiguous); under --no-check the claim is unjudged.
1321
+ #: (Hash[untyped, Hash[Symbol, untyped]], String, Hash[untyped, untyped]) -> Hash[Symbol, untyped]
1322
+ def scenario_files_source(ran, key, entry)
1323
+ candidates = ChangedFiles.producers(entry)
1324
+ names = candidates.map(&:step_name)
1325
+ present = candidates.filter_map { ran[_1] }
1326
+ of = names.join(" or ")
1327
+ if present.empty?
1328
+ return { of: of, unchosen: "files.#{key}.of names #{names.map { %("#{_1}") }.join(" or ")}, and no earlier line in this scenario ran it, so there is no list of the files it changed" }
1329
+ end
1330
+ if present.size > 1
1331
+ return { of: of, unchosen: "files.#{key}.of names #{present.map { %("#{_1[:step]}") }.join(" and ")}, and each ran earlier in this scenario, so the step cannot choose whose files to read" }
1332
+ end
1333
+
1334
+ found = present.first
1335
+ { of: "#{found[:step]}@#{found[:line]}", record: { step_record_id: found[:record][:step_record_id], processes: found[:record][:processes] } }
1336
+ end
1337
+
1338
+ # Each files key of a claim step: the list read from its producer's
1339
+ # record, or why there is none.
1340
+ #: (untyped) -> Hash[String, Hash[Symbol, untyped]]
1341
+ def files_sides(step)
1342
+ step.files.to_h do |key, entry|
1343
+ source = @files_source ? @files_source.(key, entry) : { of: "files.#{key}.of", unchosen: "nukadoko was given no step whose files this key reads" }
1344
+ [key, ChangedFiles.side(entry, source)]
647
1345
  end
648
1346
  end
649
1347
 
1348
+ # The step an events key counts the execution events of, chosen as a
1349
+ # files key's producer is (events-producer-missing,
1350
+ # events-producer-ambiguous); under --no-check the claim is unjudged.
1351
+ #: (Hash[untyped, Hash[Symbol, untyped]], String, Hash[untyped, untyped]) -> Hash[Symbol, untyped]
1352
+ def scenario_events_source(ran, key, entry)
1353
+ names = ChangedFiles.producers(entry).map(&:step_name)
1354
+ present = ChangedFiles.producers(entry).filter_map { ran[_1] }
1355
+ of = names.join(" or ")
1356
+ return { of: of, producer: { source: "unread", of: nil, gap: "producer-not-run" } } if present.empty?
1357
+ if present.size > 1
1358
+ return { of: of, unchosen: "events.#{key}.of names #{present.map { %("#{_1[:step]}") }.join(" and ")}, and each ran earlier in this scenario, so the step cannot choose whose events to count" }
1359
+ end
1360
+
1361
+ found = present.first
1362
+ record = found[:record]
1363
+ # A step with no events trace is read by its record id, which names
1364
+ # no trace: the producer then says why there is nothing to read.
1365
+ producer = events_producer({ step_record_id: record[:step_record_id], step: found[:step], line: found[:line] }, record.dig(:events, :trace_id) || record[:step_record_id])
1366
+ { of: "#{found[:step]}@#{found[:line] || record[:step_record_id]}", producer: producer }
1367
+ end
1368
+
1369
+ # One producer per trace, so the keys that read it share one reading.
1370
+ #: (Hash[Symbol, untyped], String) -> Hash[Symbol, untyped]
1371
+ def events_producer(of, trace_id)
1372
+ @events_producers ||= {}
1373
+ @events_producers[trace_id] ||=
1374
+ if @events.nil?
1375
+ # A system nukadoko serves has a log; one whose program names no
1376
+ # {events} has no events file to read.
1377
+ { source: "unread", of: of, gap: @primary_logged ? "inlet-unnamed" : "system-unread" }
1378
+ elsif (start = @events.producer(trace_id))
1379
+ { source: "live", of: of, start: start, files: @events.systems }
1380
+ else { source: "unread", of: of, gap: "producer-not-run" }
1381
+ end
1382
+ end
1383
+
1384
+ # How long a claim step waits for the events it reads to be whole
1385
+ # when it names no timeout.
1386
+ EVENTS_WAIT_MS = 10_000
1387
+
1388
+ # Each events key of a claim step: the reading of its producer's
1389
+ # events, or why there is none. The step waits for the readings
1390
+ # before it observes, so the steps between the producer and the
1391
+ # claim run where they ran. `record[:events_read]` gets each reading.
1392
+ #: (untyped, Hash[untyped, untyped], Hash[Symbol, untyped], String) -> Hash[String, Hash[Symbol, untyped]]
1393
+ def events_sides(step, args, record, dir)
1394
+ return {} if step.events.empty?
1395
+
1396
+ values = args.is_a?(Hash) ? args.transform_keys(&:to_s) : {}
1397
+ plans = step.events.map do |key, entry|
1398
+ source = @events_source ? @events_source.(key, entry) : { of: "events.#{key}.of", producer: { source: "unread", of: nil, gap: "producer-not-run" } }
1399
+ count = Events::Selection.normalize(entry[:count] || entry["count"])
1400
+ resolved = Events::Selection.resolve(count, ->(name) { values[name] }, "events.#{key}.count")
1401
+ service = entry[:service] || entry["service"]
1402
+ where = service ? " in service #{service}" : ""
1403
+ { key: key, source: source, resolved: resolved, service: service,
1404
+ label: "events:#{source[:of]} count #{Events::Selection.describe(resolved[:selection] || count)}#{where}" }
1405
+ end
1406
+ wait = step.timeout || [EVENTS_WAIT_MS, Nukadoko.config_options.fetch(:stepTimeout, EVENTS_WAIT_MS)].min
1407
+ requests = plans.filter_map do |plan|
1408
+ next unless plan[:resolved][:selection] && plan[:source][:producer]
1409
+
1410
+ { key: plan[:key], producer: plan[:source][:producer], selection: plan[:resolved][:selection], **(plan[:service] ? { service: plan[:service] } : {}) }
1411
+ end
1412
+ read = {} #: Hash[String, Hash[Symbol, untyped]]
1413
+ failure = "nukadoko read no execution events for this key"
1414
+ begin
1415
+ read = Events.read(requests, Events.clock + (Float(wait) / 1000), dir, secrets, @system_tables) if requests.any?
1416
+ rescue StandardError => e
1417
+ failure = "nukadoko could not read the execution events: #{e.message}"
1418
+ end
1419
+ record[:events_read] = read if read.any?
1420
+ plans.to_h do |plan|
1421
+ label = plan[:label]
1422
+ next [plan[:key], { label: label, broken: plan[:resolved][:problems].join("; ") }] if plan[:resolved][:problems]
1423
+ next [plan[:key], { label: label, unjudged: plan[:source][:unchosen] }] if plan[:source][:unchosen]
1424
+
1425
+ found = read[plan[:key]]
1426
+ next [plan[:key], { label: label, unjudged: failure }] unless found
1427
+
1428
+ [plan[:key], { label: label, of: plan[:source][:of], reading: found.slice(:range, :whole, :open, :maybe), counted: found[:counted], **found.slice(:left_out) }]
1429
+ end
1430
+ end
1431
+
1432
+ # A step that declares it mutates does not run in a read-only
1433
+ # environment: the declaration is trusted, not checked against what
1434
+ # the step does.
1435
+ #: (untyped) -> String?
1436
+ def read_only_refusal(step)
1437
+ name = @environment&.name
1438
+ return nil unless name && step.mutating? && @program.policy(name) == "read-only"
1439
+
1440
+ %(Step "#{step.step_name}" mutates state but environment "#{name}" has policy "read-only")
1441
+ end
1442
+
650
1443
  public
651
1444
 
652
1445
  # 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
1446
+ # line or by earlier records (`origins` says which), in a system
654
1447
  # started for this one execution, its evidence in this run's
655
1448
  # 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)
1449
+ #: (singleton(Step), Hash[String, untyped], Hash[String, String], Hash[String, String], Environment, ?(^(String, untyped) -> Hash[Symbol, untyped])?, ?(^(String, untyped) -> Hash[Symbol, untyped])?, ?Hash[String, Hash[Symbol, untyped]]) -> Hash[Symbol, untyped]
1450
+ def do_step(step, args, origins, texts, environment, files_source = nil, events_source = nil, drops = {})
1451
+ @files_source = files_source
1452
+ @events_source = events_source
1453
+ @events_producers = {}
1454
+ @ran = nil
658
1455
  FileUtils.mkdir_p(@dir)
659
1456
  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)
1457
+ @environment = environment
1458
+ probe_version(environment)
1459
+ # The system's own files go in a directory beside the record's.
1460
+ system_dir = File.join(@dir, "system")
1461
+ FileUtils.mkdir_p(system_dir)
1462
+ # Its tables list is read only for a step that counts execution events.
1463
+ system = @program.start(environment, system_dir, @project, secrets: secrets, tables: step.events.any?, progress: $stderr, env_vars: @env_vars || {})
1464
+ # One step of a system is held to its rule as a whole pass is.
1465
+ release_reach = Reach.declare(system.steps_reach, environment.name)
1466
+ @system_tables = system.services.to_h { [_1.name, _1.tables] }
1467
+ warn_do_lists_unread(system)
1468
+ @secrets = secrets.with(system.secrets)
1469
+ @program_logs = system.program_logs
1470
+ @primary_logged = !@program_logs[system.primary].nil?
1471
+ @events = events_reader(system)
662
1472
  @scratch = Scratch.new(@project)
663
1473
  @scenario_fixtures = FixtureCache.new
664
1474
  @process_fixtures = FixtureCache.new
665
- @browser = Browser.new(world.base_url, Nukadoko.config_options.fetch(:browser, {}), secrets: -> { secrets })
1475
+ @browser = browser_of(system)
666
1476
  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] }
1477
+ version = @target_versions[environment.name]
1478
+ execute(step, record, @dir, system, then_line: true, at_line: nil, results: [], origins: origins, drops: drops) { [args, texts] }
1479
+ record[:target_version] = version if version
1480
+ record
668
1481
  ensure
1482
+ # The step's own lines still on their way land beside its record
1483
+ # when the system stops, where a later --use reads them, so the stop
1484
+ # waits for them first: no later step's timing can change here.
1485
+ own = record&.dig(:events)
1486
+ Events.settle(@events, @events.producer(own[:trace_id]), Events.clock + (EVENTS_WAIT_MS / 1000.0)) if @events && own && !own[:whole]
669
1487
  @browser&.close
670
- @scenario_fixtures&.teardown
671
- @process_fixtures&.teardown
1488
+ outcome = record&.dig(:status) == "passed" ? "passed" : "failed"
1489
+ errors = [*@scenario_fixtures&.teardown(outcome), *@process_fixtures&.teardown(outcome)]
1490
+ FixtureCache.warnings(errors) { redact(_1) }.each { $stderr.puts _1 }
672
1491
  @scratch&.remove_all
673
- world&.stop
1492
+ system&.stop
1493
+ # The record is written after this stop, so it names its own late
1494
+ # lines: the step's lines of each service's log that came after its
1495
+ # slice read, which a note on stderr then names.
1496
+ if (log_slice = record&.dig(:program_log))
1497
+ (@program_logs || {}).each do |name, log|
1498
+ next unless log
1499
+
1500
+ found = log.late({ log_slice[:trace_id] => [log_slice[:services][name]&.dig(:lines) || 0, @dir] })
1501
+ late = found[:late][log_slice[:trace_id]]
1502
+ (record[:program_log_late] ||= {})[name] = late if late
1503
+ end
1504
+ end
1505
+ if system && record&.dig(:events) && (reader = events_reader(system))
1506
+ inlets = system.services.select { _1.pid && _1.events_path }
1507
+ copies = inlets.to_h { [_1.name, File.join(@dir, "system", _1.name, Events::SYSTEM_FILE)] }
1508
+ lines = (record[:events][:services] || {}).to_h { |service, own| [service.to_s, own&.dig(:lines) || 0] }
1509
+ found = reader.collect(copies, { record[:events][:trace_id] => [lines, @dir] })
1510
+ late = found[:late].values.first
1511
+ record[:events_late] = late if late
1512
+ end
1513
+ system&.remove_events
1514
+ release_reach&.call
674
1515
  end
675
1516
 
676
1517
  # What `nuka do` writes its stdout and its record through.
@@ -692,24 +1533,50 @@ module Nukadoko
692
1533
  end
693
1534
  end
694
1535
 
1536
+ # stepTimeout's default: long enough for any step that is working, short
1537
+ # enough that one that never returns does not hold the run all day.
1538
+ DEFAULT_STEP_TIMEOUT_MS = 1_200_000
1539
+
1540
+ # A step past its deadline fails as timed out, naming the knob that set it.
1541
+ class StepTimeout < StandardError; end
1542
+
1543
+ # Runs the step's body under its own timeout, or the config's
1544
+ # stepTimeout. Ruby's Timeout stops the body where it is, which the
1545
+ # TypeScript engine cannot do; either way the step is failed and the
1546
+ # scenario moves on.
1547
+ #: (singleton(Step), Hash[Symbol, untyped]) { (Numeric) -> untyped } -> untyped
1548
+ def within_deadline(step, record, &)
1549
+ ms = step.timeout || Nukadoko.config_options.fetch(:stepTimeout, DEFAULT_STEP_TIMEOUT_MS)
1550
+ where = step.timeout ? "the step's own timeout" : "stepTimeout in nukadoko.config.rb; raise it, or give this step its own timeout"
1551
+ Timeout.timeout(ms / 1000.0, StepTimeout, %(Step "#{step.step_name}" timed out after #{ms}ms (#{where})), &)
1552
+ rescue StepTimeout
1553
+ record[:error_kind] = "timeout"
1554
+ raise
1555
+ end
1556
+
695
1557
  # Runs one step whose args the block binds, and writes its record and
696
1558
  # 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:)
1559
+ #: (singleton(Step), Hash[Symbol, untyped], String, System, then_line: bool, at_line: Integer?, results: Array[untyped], origins: Hash[String, String], ?drops: Hash[String, Hash[Symbol, untyped]]) { () -> [Hash[String, untyped], Hash[String, String]] } -> Hash[Symbol, untyped]
1560
+ def execute(step, record, dir, system, then_line:, at_line:, results:, origins:, drops: {})
699
1561
  FileUtils.mkdir_p(dir)
700
1562
  log = []
1563
+ mcp_log = [] #: Array[Hash[Symbol, untyped]]
701
1564
  fixtures = {}
702
1565
  finish = nil #: Proc?
703
1566
  processes = []
704
1567
  scratch_dirs = @scratch&.dirs || []
705
1568
  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)
1569
+ # A system with a service a request gets a traceparent at is one the
1570
+ # step's requests can be traced into.
1571
+ traced = system.trace_origins
1572
+ boundary = traced.any? { _1[:stamped] } ? Trace::Boundary.new(Trace.new_id(system.trace_prefix), traced) : nil
708
1573
  begin
709
- record[:mutates] = step.mutating?
1574
+ compat = Vocabulary.compat?(step)
1575
+ # A compat step declares nothing about what it changes.
1576
+ record[:mutates] = compat ? nil : step.mutating?
710
1577
  args, texts = yield
711
- record[:args] = stored(args)
712
- problems = step.args.problems(args, strict: true)
1578
+ record[:args] = stored(compat ? args.map { _1.is_a?(Compat::DataTable) ? _1.raw : _1 } : args)
1579
+ problems = compat ? [] : step.args.problems(args, strict: true)
713
1580
  if problems.any?
714
1581
  record[:error_kind] = "args_invalid"
715
1582
  raise TypeError, "args validation failed: #{problems.join("; ")}"
@@ -717,10 +1584,29 @@ module Nukadoko
717
1584
 
718
1585
  @browser&.step = { step_record_id: record[:step_record_id], step: record[:step], line: at_line }
719
1586
  @browser&.begin_step
1587
+ began = true
720
1588
  Trace.within(boundary) do
721
- fixtures, finish = build_fixtures(step, dir, log, world, record, results)
1589
+ fixtures, finish = build_fixtures(step, dir, log, system, record, results)
1590
+ if compat
1591
+ open = @compat_open
1592
+ Compat.opener = ->(kind) { open.(kind).tap { @request_log = @compat_built[:request] } }
1593
+ Compat.evidence = lambda do |kind, values|
1594
+ evidence = (record[:evidence_log] ||= Evidence.new(dir))
1595
+ if kind == :log then evidence.attach("log.txt", values.join("\n"))
1596
+ else
1597
+ data, _media_type, filename = values
1598
+ evidence.attach(filename || "attachment", data.to_s)
1599
+ end
1600
+ end
1601
+ end
722
1602
  HttpRecording.collect(log) do
723
- Processes.collect(processes) { RedactedOutput.around(secrets) { body(step, fixtures, args, [then_line, at_line], record, results, origins, texts) } }
1603
+ McpCalls.collect(mcp_log) do
1604
+ Processes.collect(processes) do
1605
+ Reach.at(%(in step "#{step.step_name}")) do
1606
+ RedactedOutput.around(secrets) { within_deadline(step, record) { body(step, fixtures, args, [then_line, at_line], record, results, origins, drops, texts, dir) } }
1607
+ end
1608
+ end
1609
+ end
724
1610
  end
725
1611
  end
726
1612
  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] || fixtures[:context]) && record[:observation] != "unobserved"
@@ -731,11 +1617,28 @@ module Nukadoko
731
1617
  record[:error_at] = ErrorFrames.of(e, @project).map { redact(_1) } if record[:error_kind] == "step_error"
732
1618
  ensure
733
1619
  @browser&.step = nil
1620
+ Compat.opener = Compat.evidence = nil
734
1621
  finish&.call
1622
+ if began && (browser = @browser)
1623
+ page_events = browser.page_events
1624
+ record[:page_events] = page_events if page_events
1625
+ omitted = browser.http_omitted
1626
+ record[:http_omitted] = omitted if omitted
1627
+ end
735
1628
  log.concat(@request_log.log) if @request_log
736
1629
  @request_log = nil
737
- # A world at a URL has a log nukadoko does not read.
738
- record[:program_log] = @program_log&.slice(dir, boundary) if boundary
1630
+ if boundary
1631
+ # Every slice waits at once, so a step that stamped a request
1632
+ # waits for the slowest, not for each in turn: a line one
1633
+ # service writes for a request another passed on can come after
1634
+ # the first one's lines.
1635
+ events = @events && Thread.new { @events.slice(dir, boundary, processes) }
1636
+ # A service at a URL has a log nukadoko does not read: null.
1637
+ logs = (@program_logs || {}).transform_values { |log| log && Thread.new { log.slice(dir, boundary) } }
1638
+ record[:program_log] = { trace_id: boundary.trace_id, stamped: boundary.stamped, services: logs.transform_values { _1&.value } } unless logs.empty?
1639
+ record[:events] = events.value if events
1640
+ record[:events] = nil if !events && !system.primary_service.pid
1641
+ end
739
1642
  record[:finished_at] = Time.now.utc.iso8601(3)
740
1643
  # Each process's output is a file of the step's own, named by its number.
741
1644
  processes.each.with_index(1) do |process, n|
@@ -768,8 +1671,12 @@ module Nukadoko
768
1671
  record.delete(:required_env) if record[:required_env] && record[:required_env].empty?
769
1672
  # A page's own traffic is in http.jsonl and the trace, not counted as the step's.
770
1673
  record[:http_count] = log.count { _1[:via] != "page" }
1674
+ underneath = Underneath.of_record(record[:page_events], log, nil, record[:http_omitted])
1675
+ record[:underneath] = underneath if underneath
771
1676
  File.write(File.join(dir, "http.jsonl"), "#{log.map { JSON.generate(secrets.redact(_1)) }.join("\n")}\n") if log.any?
772
1677
  record[:http_file] = log.any?
1678
+ File.write(File.join(dir, McpCalls::FILE), mcp_log.map { "#{JSON.generate(secrets.redact(_1))}\n" }.join) if mcp_log.any?
1679
+ record[:mcp_count] = mcp_log.size if mcp_log.any?
773
1680
  if (traced = TraceActions.read(File.join(dir, "trace.zip")))
774
1681
  record[:trace] = "trace.zip"
775
1682
  record[:actions] = traced[:actions] if traced[:actions].any?
@@ -787,8 +1694,7 @@ module Nukadoko
787
1694
  # reports such a pattern; a run under --no-check agrees with it.
788
1695
  #: (untyped, Hash[String, String]) -> Hash[String, String]
789
1696
  def transformed_fills(step, origins)
790
- pattern = step.pattern.to_s
791
- pattern.scan(Pattern::NAMED).each_with_object({}) do |(key, type), found|
1697
+ step.patterns.flat_map { |pattern| pattern.scan(Pattern::NAMED).map { [pattern, *_1] } }.each_with_object({}) do |(pattern, key, type), found|
792
1698
  next unless Pattern.transformed.include?(type.to_s) && !origins.key?(key.to_s)
793
1699
 
794
1700
  found[key.to_s] = %(the pattern "#{pattern}" fills args.#{key} with the parameter type {#{type}}, whose transformer rewrites the line's text before the claim reads it, ) +
@@ -799,16 +1705,38 @@ module Nukadoko
799
1705
  # A Then step's claims are judged on what it observed, or on its args
800
1706
  # when it reads nothing itself; any other step runs and returns.
801
1707
  # `step` is a step class whose observe or run its own file defines.
802
- #: (untyped, Hash[Symbol, untyped], untyped, [bool, Integer?], Hash[Symbol, untyped], Array[untyped], Hash[String, String], Hash[String, String?]) -> void
803
- def body(step, fixtures, args, position, record, results, origins, texts)
1708
+ #: (untyped, Hash[Symbol, untyped], untyped, [bool, Integer?], Hash[Symbol, untyped], Array[untyped], Hash[String, String], Hash[String, Hash[Symbol, untyped]], Hash[String, String?], String) -> void
1709
+ def body(step, fixtures, args, position, record, results, origins, drops, texts, dir)
804
1710
  then_line, at_line = position
805
- if step.claims
1711
+ if Vocabulary.compat?(step)
1712
+ block = step.registration.block
1713
+ # cucumber-ruby refuses a block whose parameters the match does
1714
+ # not fill, rather than leaving one nil.
1715
+ if block.arity >= 0 && block.arity != args.size
1716
+ raise ArgumentError, "Your block takes #{block.arity} argument#{"s" unless block.arity == 1}, but the step \"#{record[:text]}\" passes #{args.size}"
1717
+ end
1718
+
1719
+ begin
1720
+ @compat_world.instance_exec(*args, &block)
1721
+ rescue Compat::Pending
1722
+ record[:error_kind] = "unsupported"
1723
+ raise Compat::Unsupported, %(Step "#{step.step_name}" called pending, which nukadoko does not interpret as pending or skipped (unlike cucumber-ruby). See docs/ruby/reference.md "Compat steps")
1724
+ rescue Compat::Unsupported
1725
+ record[:error_kind] = "unsupported"
1726
+ raise
1727
+ end
1728
+ record[:result] = nil
1729
+ elsif step.claims
806
1730
  own = fixtures.slice(*step.fixtures)
807
1731
  observes = step.method_defined?(:observe)
808
1732
  # A claim's actual that starts with a from key reads the value an
809
1733
  # earlier step returned, which wins over a key observe returns
810
1734
  # under the same name.
811
1735
  from_values = args.transform_keys(&:to_s).slice(*step.from.keys.map(&:to_s))
1736
+ files = files_sides(step)
1737
+ files.each { |key, side| origins[key] = side[:label] }
1738
+ events = events_sides(step, args, record, dir)
1739
+ events.each { |key, side| origins[key] = side[:label] }
812
1740
  read = lambda do
813
1741
  next args unless observes
814
1742
 
@@ -819,7 +1747,8 @@ module Nukadoko
819
1747
  sides = lambda do |observed|
820
1748
  ClaimSides::Inputs.new(observed: observed, args: args, observes: observes, from_keys: step.from.keys.map(&:to_s),
821
1749
  labels: ->(key) { origins.fetch(key, "sentence:#{key}") },
822
- received: observes ? step.inputs.fields.map { _1.name.to_s } : [], transformed: transformed_fills(step, origins))
1750
+ received: observes ? step.inputs.fields.map { _1.name.to_s } : [], transformed: transformed_fills(step, origins), files: files, events: events,
1751
+ from_drops: drops)
823
1752
  end
824
1753
  # A reading with a page open is timed, so the record can say what the page had received by then.
825
1754
  read = (plain = read; -> { @browser.reading(&plain) }) if own[:page] || own[:context]
@@ -830,15 +1759,19 @@ module Nukadoko
830
1759
 
831
1760
  # observe failing is no claim breaking: nothing was read to judge.
832
1761
  record[:observation] = "unobserved"
833
- record[:claim_records] = step.claims.reject { _1[:each] }.map { RunRecord.unobserved_claim(_1, origins, texts, patterns: [step.pattern].compact) }
1762
+ record[:claim_records] = step.claims.reject { _1[:each] }.map { RunRecord.unobserved_claim(_1, origins, texts, patterns: step.patterns) }
834
1763
  record[:error_kind] = "unobserved"
835
1764
  raise e.class, "the step observed nothing, so no claim was judged: #{e.message}"
836
1765
  end
837
1766
  judged = Claims.judge(step.claims, observed, args, sides.(observed))
838
1767
  record[:claims] = judged
1768
+ # A files claim's list was measured in its producer's record.
1769
+ record[:files_measured] = step.claims.zip(judged).map { |declared, result| files[declared[:actual].to_s]&.[](:measured) if !declared[:each] && result[:files_read] }
1770
+ # An events claim's count was measured in this step's events_read.
1771
+ record[:events_measured] = step.claims.zip(judged).map { |declared, result| declared[:actual].to_s if !declared[:each] && result[:events_read] }
839
1772
  # The value each claim read before its view, for `measured`.
840
1773
  record[:raw_actuals] = step.claims.map do |declared|
841
- next nil if declared[:each]
1774
+ next nil if declared[:each] || files.key?(declared[:actual].to_s) || events.key?(declared[:actual].to_s)
842
1775
 
843
1776
  # Under a view the raw value is the text the view read; else the value at `at`.
844
1777
  read = Claims.read(observed, declared[:actual])
@@ -848,12 +1781,12 @@ module Nukadoko
848
1781
  rescue StandardError
849
1782
  nil
850
1783
  end
851
- patterns = [step.pattern].compact
1784
+ patterns = step.patterns
852
1785
  record[:claim_records] = step.claims.zip(judged).map do |declared, result|
853
1786
  if declared[:each]
854
1787
  RunRecord.each_claim(declared, sides.(observed), origins, texts, patterns: patterns)
855
1788
  else
856
- RunRecord.claim(declared, result, origins, texts, observed: observes && !from_values.key?(declared[:actual].to_s.split(".").first), patterns: patterns)
1789
+ RunRecord.claim(declared, result, origins, texts, observed: observes && !from_values.key?(declared[:actual].to_s.split(".").first) && !files.key?(declared[:actual].to_s) && !events.key?(declared[:actual].to_s), patterns: patterns)
857
1790
  end
858
1791
  end
859
1792
  broken = record[:claim_records].index { !%w[held for-judgment].include?(_1[:outcome]) }
@@ -876,7 +1809,7 @@ module Nukadoko
876
1809
 
877
1810
  record[:returns_dropped] = step.returns ? step.returns.drops(value) : []
878
1811
  value = step.returns.strip(value) if step.returns
879
- results << [step, value.transform_keys(&:to_s), at_line, record[:step_record_id]]
1812
+ results << [step, value.transform_keys(&:to_s), at_line, record[:step_record_id], record[:returns_dropped]]
880
1813
  record[:result] = value
881
1814
  end
882
1815
  end
@@ -903,12 +1836,22 @@ module Nukadoko
903
1836
  end
904
1837
  end
905
1838
  from_of = ->(key) { (origin = (record[:args_origin] || {})[key.to_s.split(".").first]).is_a?(Hash) ? origin.dig(:from, :step_record_id) : nil }
906
- (step.claims || []).zip(record[:claim_records], record[:raw_actuals] || []).each do |declared, claim, raw|
1839
+ files_measured = record.delete(:files_measured) || []
1840
+ events_measured = record.delete(:events_measured) || []
1841
+ (step.claims || []).zip(record[:claim_records], record[:raw_actuals] || []).each_with_index do |(declared, claim, raw), index|
907
1842
  next if claim.nil? || claim[:outcome] == "unobserved" || declared[:each]
908
1843
  # A tree nukadoko took is a measurement of the page, not a value a channel carried.
909
1844
  next claim[:measured] = nil if declared[:compare] == "fits-aria-snapshot" || claim[:actual_from].to_s.start_with?(Judgments::ARIA_LABEL)
910
1845
 
911
- measured = Measured.channel_for(from_of.(declared[:actual]) || own, raw, channels_of)
1846
+ # A list of paths was read from its producer's record, so that
1847
+ # record's channel is where it was measured, and no expected
1848
+ # value is told apart from it.
1849
+ files = step.files.key?(declared[:actual].to_s)
1850
+ events = step.events.key?(declared[:actual].to_s)
1851
+ measured = if files then files_measured[index]
1852
+ elsif events then (key = events_measured[index]) && { step_record_id: own, channel: "events_read.#{key}" }
1853
+ else Measured.channel_for(from_of.(declared[:actual]) || own, raw, channels_of)
1854
+ end
912
1855
  claim[:measured] = measured
913
1856
  key = declared[:expected].is_a?(String) ? declared[:expected] : declared[:expected].is_a?(Hash) && declared[:expected][:from]
914
1857
  source = declared[:expected].is_a?(Hash) && declared[:expected].key?(:observe) ? own : key && from_of.(key)
@@ -916,18 +1859,18 @@ module Nukadoko
916
1859
 
917
1860
  # The expected side's channel comes before the actual's, as the TypeScript engine writes it.
918
1861
  claim.delete(:measured)
919
- claim.merge!(expected_measured: Measured.channel_for(source, claim[:expected], channels_of, measured), measured: measured)
1862
+ claim.merge!(expected_measured: Measured.channel_for(source, claim[:expected], channels_of, files || events ? nil : measured), measured: measured)
920
1863
  end
921
1864
  record.delete(:raw_actuals)
922
1865
  end
923
1866
 
924
- #: (singleton(Step), Hash[String, untyped], PickleStep, Array[untyped], Hash[String, String], Hash[Symbol, untyped]) -> Hash[String, untyped]
925
- def bind_args(step, captures, line, results, origins, record)
1867
+ #: (singleton(Step), Hash[String, untyped], PickleStep, Array[untyped], Hash[String, String], Hash[Symbol, untyped], Hash[String, Hash[Symbol, untyped]]) -> Hash[String, untyped]
1868
+ def bind_args(step, captures, line, results, origins, record, from_drops)
926
1869
  args = captures.dup
927
1870
  record[:args_origin] = captures.keys.to_h { [_1, "capture"] }
928
1871
  used = []
929
1872
  step.from.each do |key, sources|
930
- cls, value, at_line, record_id = results.reverse_each.find { |c, _| sources.any? { _1.first == c } }
1873
+ cls, value, at_line, record_id, dropped = results.reverse_each.find { |c, _| sources.any? { _1.first == c } }
931
1874
  # An optional key stays absent when no producer ran, as zod leaves it.
932
1875
  next if !cls && step.args[key]&.absent_ok?
933
1876
  unless cls
@@ -939,6 +1882,7 @@ module Nukadoko
939
1882
  args[key] = value.fetch(source_key)
940
1883
  origins[key] = "from:#{cls.step_name}@#{at_line}.#{source_key}"
941
1884
  record[:args_origin][key] = { from: { step_record_id: record_id, step: cls.step_name, key: source_key } }
1885
+ from_drops[key.to_s] = { step: cls.step_name, key: source_key, dropped: dropped }
942
1886
  used << { step: cls.step_name, record: "steps/#{record_id}", result: value } unless used.any? { _1[:record] == "steps/#{record_id}" }
943
1887
  end
944
1888
  record[:used] = used
@@ -971,8 +1915,8 @@ module Nukadoko
971
1915
 
972
1916
  # A project fixture is built the first time a step of its scope names
973
1917
  # it, directly or through another fixture, and kept until the scope ends.
974
- #: (Symbol, World, Array[Symbol], ?(^(Symbol) -> untyped)?) -> untyped
975
- def project_fixture(name, world, chain, builtin = nil)
1918
+ #: (Symbol, System, Array[Symbol], ?(^(Symbol) -> untyped)?) -> untyped
1919
+ def project_fixture(name, system, chain, builtin = nil)
976
1920
  fixture = Nukadoko.project_fixtures[name] or raise ArgumentError, "the Ruby engine has no fixture #{name} yet"
977
1921
  raise ArgumentError, "fixtures depend on each other in a cycle: #{[*chain, name].join(" -> ")}" if chain.include?(name)
978
1922
 
@@ -984,14 +1928,16 @@ module Nukadoko
984
1928
  raise ArgumentError, %(fixture "#{name}" names "#{dep}", which only a step's own fixtures can give) unless builtin
985
1929
 
986
1930
  [dep, builtin.(dep)]
987
- else [dep, project_fixture(dep, world, [*chain, name], builtin)]
1931
+ else [dep, project_fixture(dep, system, [*chain, name], builtin)]
988
1932
  end
989
1933
  end
990
1934
  return cache[name].tap { note_fixture(name, fixture.scope, nil, nil) } if cache.key?(name)
991
1935
 
992
1936
  at = now
993
1937
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
994
- cache.build(fixture, deps).tap { note_fixture(name, fixture.scope, Request.since(started), at) }
1938
+ # A refusal in the fixture's own body names the fixture, not the
1939
+ # step that asked for it: that is where the edit goes.
1940
+ Reach.at(%(in fixture "#{name}")) { cache.build(fixture, deps) }.tap { note_fixture(name, fixture.scope, Request.since(started), at) }
995
1941
  end
996
1942
 
997
1943
  # Each project fixture a step's bag touched, once, as the step record
@@ -1008,9 +1954,55 @@ module Nukadoko
1008
1954
  #: () -> Secrets
1009
1955
  def secrets = @secrets || Secrets.new
1010
1956
 
1011
- # What the env fixture holds: the env files, then the world's own env.
1012
- #: (World) -> Hash[String, String]
1013
- def step_env(world) = (@env_vars || {}).merge(world.env)
1957
+ # What the env fixture holds: the env files, then the system's own env,
1958
+ # minus a variable that names the events file, which only the program
1959
+ # may write. The system's `setup` reads the same thing.
1960
+ #: (System) -> Hash[String, String]
1961
+ def step_env(system) = (@env_vars || {}).merge(Program.step_env(system.primary_service))
1962
+
1963
+ # The `setup_result` fixture of `system`: what the system's setup gave
1964
+ # back, read from the system the pass was handed, so a worker reads the
1965
+ # same value the parent made. Its keys are strings, as every value the
1966
+ # project hands the engine is, because the value crosses to a worker
1967
+ # as JSON. Nothing made a value for it is a mistake in the step or the
1968
+ # program, not an empty value: a step that reads it needs a tenant.
1969
+ #: (System) -> untyped
1970
+ def setup_result_of(system)
1971
+ value = system.setup_result
1972
+ raise SetupResultMissing, setup_result_missing_message if value.nil?
1973
+
1974
+ value
1975
+ end
1976
+
1977
+ # Names which of the two mistakes it is: a run with no program at all
1978
+ # cannot have a setup, and one with a program may have no setup or a
1979
+ # setup that returned nothing.
1980
+ #: () -> String
1981
+ def setup_result_missing_message
1982
+ return "setup_result: this run has no program, so no setup made a value for it" unless @program.file?
1983
+
1984
+ "setup_result: nothing made a value for it in this system: the program declares no setup, or its setup returned nothing. " \
1985
+ "Write setup in the program in nukadoko.config.rb and return what the steps read, such as { tenant: tenant }."
1986
+ end
1987
+
1988
+ # The `services` fixture of `system`: none without a program file, as
1989
+ # in the TypeScript engine, and each service's env leaves out a
1990
+ # variable that names its events file, which only the program may
1991
+ # write.
1992
+ #: (System) -> Services
1993
+ def services_of(system)
1994
+ return Services.new({}) unless @program.file?
1995
+
1996
+ Services.new(system.services.to_h do |service|
1997
+ env = Program.step_env(service)
1998
+ [service.name, Program::Address.new(url: service.base_url, port: service.port, root: service.root, dir: service.dir, env: env.freeze)]
1999
+ end)
2000
+ end
2001
+
2002
+ # Head's project root: a tree's pass reads a service's root and names
2003
+ # a checkout from there, as head's pass does.
2004
+ #: () -> String
2005
+ def head_root = @head ? @head[:root].to_s : @project
1014
2006
 
1015
2007
  # Reads an environment's env files into the env fixture and the secret
1016
2008
  # set, from the same read, so the two agree on what was loaded.
@@ -1031,28 +2023,30 @@ module Nukadoko
1031
2023
  raise Refusal.new("env-file-unreadable", e.message)
1032
2024
  end
1033
2025
 
1034
- BUILTINS = %i[request baseURL env requireEnv scratch page context pageAs section poll evidence resultOf
1035
- base_url require_env page_as result_of].freeze
2026
+ BUILTINS = %i[request baseURL env requireEnv scratch page context pageAs section poll evidence resultOf services setupResult
2027
+ base_url require_env page_as result_of setup_result].freeze
1036
2028
 
1037
2029
  # The snake_case spelling of each builtin a Ruby step may name instead,
1038
2030
  # so a body passes RuboCop's naming cops. Both reach the same fixture.
1039
- ALIASES = { base_url: :baseURL, require_env: :requireEnv, page_as: :pageAs, result_of: :resultOf }.freeze
2031
+ ALIASES = { base_url: :baseURL, require_env: :requireEnv, page_as: :pageAs, result_of: :resultOf, setup_result: :setupResult }.freeze
1040
2032
 
1041
- #: (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped], Array[untyped]) -> [Hash[Symbol, untyped], (^() -> void)?]
1042
- def build_fixtures(step, dir, log, world, record, results)
2033
+ #: (singleton(Step), String, Array[Hash[Symbol, untyped]], System, Hash[Symbol, untyped], Array[untyped]) -> [Hash[Symbol, untyped], (^() -> void)?]
2034
+ def build_fixtures(step, dir, log, system, record, results)
1043
2035
  finishes = [] #: Array[^() -> void]
1044
2036
  @fixture_usage = []
1045
- built = {} #: Hash[Symbol, untyped]
2037
+ built = @compat_built = {} #: Hash[Symbol, untyped]
1046
2038
  builtin = lambda do |name|
1047
2039
  name = ALIASES.fetch(name, name)
1048
2040
  next built[name] if built.key?(name)
1049
2041
 
1050
2042
  built[name] =
1051
2043
  case name
1052
- when :request then Request.new(world.base_url)
1053
- when :baseURL then world.base_url
1054
- when :env then step_env(world)
1055
- when :requireEnv then require_env(world, record)
2044
+ when :request then Request.new(system.primary_service.base_url)
2045
+ when :baseURL then system.primary_service.base_url
2046
+ when :services then services_of(system)
2047
+ when :setupResult then setup_result_of(system)
2048
+ when :env then step_env(system)
2049
+ when :requireEnv then require_env(system, record)
1056
2050
  when :scratch then @scratch
1057
2051
  when :page
1058
2052
  page, finish = @browser.page_for(dir, log)
@@ -1074,14 +2068,17 @@ module Nukadoko
1074
2068
  # A project fixture of a builtin's name replaces it for the step.
1075
2069
  fixtures = {} #: Hash[Symbol, untyped]
1076
2070
  (step.bag - [:call]).each do |name|
1077
- fixtures[name] = Nukadoko.project_fixtures.key?(name) || !BUILTINS.include?(name) ? project_fixture(name, world, [], builtin) : builtin.(name)
2071
+ fixtures[name] = Nukadoko.project_fixtures.key?(name) || !BUILTINS.include?(name) ? project_fixture(name, system, [], builtin) : builtin.(name)
1078
2072
  end
2073
+ # A compat step opens the page or the request when its glue asks.
2074
+ @compat_open = builtin
1079
2075
  # Requests a wrapped request fixture sends are the builtin's, so the record keeps them.
1080
2076
  @request_log = built[:request]
1081
- fixtures[:call] = Caller.new(step, fixtures) if step.fixtures.include?(:call)
2077
+ fixtures[:call] = Caller.new(step, fixtures, refuse: ->(part) { read_only_refusal(part) }) if step.fixtures.include?(:call)
1082
2078
  record[:fixtures] = @fixture_usage if @fixture_usage.any?
1083
2079
  @fixture_usage = nil
1084
- finish = finishes.empty? ? nil : -> { finishes.reverse_each(&:call) }
2080
+ # Read when the step ends, so a page a compat step opened later is finished too.
2081
+ finish = -> { finishes.reverse_each(&:call) }
1085
2082
  [fixtures, finish]
1086
2083
  end
1087
2084
 
@@ -1089,14 +2086,14 @@ module Nukadoko
1089
2086
  # only the key. An empty value counts as missing, since a step that
1090
2087
  # requires it is broken either way. Every name asked for is kept, in
1091
2088
  # the order asked, whether the read found a value or not.
1092
- #: (World, Hash[Symbol, untyped]) -> ^(String | Symbol) -> String
1093
- def require_env(world, record)
2089
+ #: (System, Hash[Symbol, untyped]) -> ^(String | Symbol) -> String
2090
+ def require_env(system, record)
1094
2091
  asked = record[:required_env] = [] #: Array[String]
1095
2092
  lambda do |key|
1096
2093
  key = key.to_s
1097
2094
  asked << key unless asked.include?(key)
1098
- value = step_env(world)[key]
1099
- raise %(requireEnv("#{key}") found no value: set "#{key}" in one of the environment's env files, or in the world's env) if value.nil? || value.empty?
2095
+ value = step_env(system)[key]
2096
+ raise %(requireEnv("#{key}") found no value: set "#{key}" in one of the environment's env files, or in the system's env) if value.nil? || value.empty?
1100
2097
 
1101
2098
  value
1102
2099
  end