nukadoko 0.3.0 → 0.5.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.
@@ -28,12 +28,25 @@ module Nukadoko
28
28
  class Request
29
29
  attr_reader :log #: Array[Hash[Symbol, untyped]]
30
30
 
31
- #: (String) -> void
31
+ # `base_url` is the world's URL, which a path joins onto; a project with
32
+ # no program has none. An absolute URL, http or https, goes where it
33
+ # names, so a step can call a third-party API and still have its
34
+ # requests recorded.
35
+ #: (String?) -> void
32
36
  def initialize(base_url)
33
- @base = URI(base_url)
37
+ @base = base_url && URI(base_url)
34
38
  @log = []
35
39
  end
36
40
 
41
+ #: (String) -> URI::Generic
42
+ def target(path)
43
+ named = URI(path.to_s)
44
+ return named if named.absolute?
45
+ raise ArgumentError, %(The request fixture needs an absolute URL for "#{path}": this world has no program, so there is no base URL to join a path onto) unless @base
46
+
47
+ URI.join(@base.to_s, path.to_s)
48
+ end
49
+
37
50
  BODY_TEXT = 16 * 1024
38
51
 
39
52
  #: (Float) -> Integer
@@ -57,7 +70,8 @@ module Nukadoko
57
70
  # `data:` is sent as JSON; `body:` is sent as it is, for a request
58
71
  # whose body is meant to be wrong.
59
72
  define_method(verb) do |path, data: nil, body: nil, headers: {}|
60
- uri = URI.join(@base, path)
73
+ # @type self: Request
74
+ uri = target(path)
61
75
  klass = Net::HTTP.const_get(verb.capitalize)
62
76
  req = klass.new(uri, headers)
63
77
  if data
@@ -73,7 +87,7 @@ module Nukadoko
73
87
  entry = { method: verb.upcase, url: uri.to_s, **(path.to_s == uri.to_s ? {} : { declared_url: path.to_s }) }
74
88
  stamp = traceparent ? { traceparent: traceparent, traceparent_sent_to: [Trace.origin(uri)] } : {}
75
89
  begin
76
- res = HttpRecording.unrecorded { Net::HTTP.start(uri.host.to_s, uri.port) { _1.request(req) } }
90
+ res = HttpRecording.unrecorded { Net::HTTP.start(uri.host.to_s, uri.port, use_ssl: uri.scheme == "https") { _1.request(req) } }
77
91
  rescue StandardError => e
78
92
  @log << entry.merge(status: 0, duration_ms: Request.since(started), via: "request", **stamp, **Request.body(:request_body, req.body),
79
93
  error: e.message.lines.first.to_s.chomp)
@@ -139,11 +153,22 @@ module Nukadoko
139
153
  false
140
154
  end
141
155
 
142
- #: (String, Array[Hash[Symbol, untyped]]) -> [untyped, ^() -> void]
143
- def page_for(step_dir, log)
156
+ #: () -> untyped
157
+ def launch
144
158
  require "playwright"
159
+ # playwright-ruby-client parses each driver message from a buffer in
160
+ # the default external encoding. Under US-ASCII (LANG unset) its reader
161
+ # thread dies on the first non-ASCII byte and the step waits forever.
162
+ # exe/nuka sets UTF-8, but a run started another way (a Rake task, a
163
+ # script that calls the CLI) reaches here without it.
164
+ Encoding.default_external = Encoding::UTF_8 unless @execution
145
165
  @execution ||= Playwright.create(playwright_cli_executable_path: ENV.fetch("PLAYWRIGHT_CLI", "npx playwright"))
146
166
  @browser ||= @execution.playwright.chromium.launch(**@launch_options)
167
+ end
168
+
169
+ #: (String, Array[Hash[Symbol, untyped]]) -> [untyped, ^() -> void]
170
+ def page_for(step_dir, log)
171
+ launch
147
172
  @context ||= @browser.new_context(baseURL: @base_url).tap do |context|
148
173
  context.tracing.start(screenshots: true, snapshots: true)
149
174
  watch_requests(context)
@@ -368,7 +393,7 @@ module Nukadoko
368
393
  # nil when it opened none.
369
394
  #: () -> Hash[Symbol, untyped]?
370
395
  def scenario_browser
371
- @context && @browser ? { type: "chromium", version: @browser.version } : nil
396
+ (@context || named.any?) && @browser ? { type: "chromium", version: @browser.version } : nil
372
397
  end
373
398
 
374
399
  # Closes the scenario's context, and returns the screenshot of its
@@ -382,12 +407,88 @@ module Nukadoko
382
407
  FileUtils.mkdir_p(dir)
383
408
  shots << { file: "final.png", at: Time.now.utc.iso8601(3) } if masked_shot(@page, File.join(dir, "final.png"), monotonic + VIEW_TIMEOUT_MS / 1000.0, bounded: false)
384
409
  end
410
+ named.each do |name, held|
411
+ if dir
412
+ FileUtils.mkdir_p(dir)
413
+ file = "final.#{name}.png"
414
+ shots << { file: file, at: Time.now.utc.iso8601(3), as: name } if masked_shot(held[:page], File.join(dir, file), monotonic + VIEW_TIMEOUT_MS / 1000.0, bounded: false)
415
+ end
416
+ held[:context].tracing.stop rescue nil
417
+ held[:context].close rescue nil
418
+ end
419
+ @named = {}
385
420
  @context&.tracing&.stop
386
421
  @context&.close
387
422
  @context = @page = nil
388
423
  shots
389
424
  end
390
425
 
426
+ CONTEXT_NAME = /\A[a-z0-9][a-z0-9-]{0,63}\z/
427
+
428
+ # The page of a browser context of its own, named `name`, so a second
429
+ # person in the scenario has cookies and storage of their own. The
430
+ # context opens on the first call for the name in the scenario, with
431
+ # `options` over the world's base URL, and a later call gets the same
432
+ # page. Each step that calls it gets a trace chunk, trace.<name>.zip,
433
+ # and the page's requests go to the step's log with `as`.
434
+ #: (String, Hash[untyped, untyped]?, String, Array[Hash[Symbol, untyped]]) -> untyped
435
+ def page_as(name, options, step_dir, log)
436
+ unless name.is_a?(String) && name.match?(CONTEXT_NAME)
437
+ raise InvalidContextNameError, "pageAs name #{name.inspect} is not valid. Use 1 to 64 lowercase letters, digits, and hyphens, " \
438
+ "starting with a letter or a digit: the name becomes part of evidence file names such as trace.<name>.zip."
439
+ end
440
+ asked = options&.to_h { |key, value| [key.to_sym, value] }&.compact
441
+ held = named[name]
442
+ if held
443
+ if asked && asked != held[:options]
444
+ raise ContextOptionsConflictError, "pageAs(#{name.inspect}) already opened that context in this scenario with other options. " \
445
+ "A context keeps the options it was created with: pass the same options, or none, on a later call."
446
+ end
447
+ else
448
+ launch
449
+ context = @browser.new_context(baseURL: @base_url, **(asked || {}))
450
+ context.tracing.start(screenshots: true, snapshots: true)
451
+ held = named[name] = { context: context, page: context.new_page, options: asked || {} }
452
+ end
453
+ unless step_named.key?(name)
454
+ held[:context].tracing.start_chunk
455
+ listener = ->(req) { log << { method: req.method, url: req.url, via: "page", as: name } }
456
+ held[:page].on("request", listener)
457
+ step_named[name] = [step_dir, listener]
458
+ end
459
+ held[:page]
460
+ end
461
+
462
+ # Ends the step's chunk of each named context it reached, and names
463
+ # the files, in the order the contexts opened.
464
+ #: () -> Array[Hash[Symbol, String]]
465
+ def finish_named
466
+ traces = [] #: Array[Hash[Symbol, String]]
467
+ named.each do |name, held|
468
+ step_dir, listener = step_named[name]
469
+ next unless step_dir
470
+
471
+ held[:page].off("request", listener)
472
+ file = "trace.#{name}.zip"
473
+ held[:context].tracing.stop_chunk(path: File.join(step_dir, file))
474
+ traces << { as: name, file: file }
475
+ rescue StandardError
476
+ nil
477
+ end
478
+ @step_named = {}
479
+ traces
480
+ end
481
+
482
+ private
483
+
484
+ #: () -> Hash[String, Hash[Symbol, untyped]]
485
+ def named = (@named ||= {})
486
+
487
+ #: () -> Hash[String, [String, untyped]]
488
+ def step_named = (@step_named ||= {})
489
+
490
+ public
491
+
391
492
  #: () -> void
392
493
  def close
393
494
  @browser&.close
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # The config's parameterTypes, read and handed to Pattern: each entry a
5
+ # name, a regexp, and an optional transformer. A shape the TypeScript
6
+ # engine's schema refuses is refused here with its words, so a project
7
+ # moves between the engines without a config that one of them takes and
8
+ # the other does not. Boundary: reading the entries; registering them and
9
+ # matching lines are Pattern's.
10
+ module Nukadoko
11
+ module Engine
12
+ module ParameterTypes
13
+ NAME = /\A[a-zA-Z0-9_-]+\z/
14
+ KEYS = %i[name regexp transformer].freeze
15
+
16
+ #: (untyped) -> void
17
+ def self.read(types)
18
+ types = [] if types.nil?
19
+ invalid("parameterTypes: Invalid input: expected array, received #{kind(types)}") unless types.is_a?(Array)
20
+ types.each_with_index do |type, index|
21
+ at = "parameterTypes.#{index}"
22
+ invalid("#{at}: Invalid input: expected object, received #{kind(type)}") unless type.is_a?(Hash)
23
+ extra = type.keys.map(&:to_sym) - KEYS
24
+ invalid("unknown key(s): #{extra.join(", ")}") if extra.any?
25
+ name = type[:name]
26
+ invalid("#{at}.name: Invalid input: expected string, received #{kind(name)}") unless name.is_a?(String)
27
+ invalid("#{at}.name: Invalid string: must match pattern /^[a-zA-Z0-9_-]+$/") unless name.match?(NAME)
28
+ invalid("#{at}.regexp: must be a Regexp or a string") unless type[:regexp].is_a?(Regexp) || type[:regexp].is_a?(String)
29
+ invalid("#{at}.transformer: must be a function") unless type[:transformer].nil? || type[:transformer].respond_to?(:call)
30
+ end
31
+ Pattern.configure(types)
32
+ end
33
+
34
+ # A value's kind in the words zod uses for it.
35
+ #: (untyped) -> String
36
+ def self.kind(value)
37
+ case value
38
+ when nil then "undefined"
39
+ when String then "string"
40
+ when Numeric then "number"
41
+ when true, false then "boolean"
42
+ when Array then "array"
43
+ when Hash then "object"
44
+ else value.class.name.to_s.downcase
45
+ end
46
+ end
47
+
48
+ #: (String) -> bot
49
+ def self.invalid(detail)
50
+ raise Refusal.new("config-invalid", "Invalid config at #{CONFIG}: #{detail}", fix: "Correct the fields the message names in #{CONFIG}.")
51
+ end
52
+ end
53
+ end
54
+ end
@@ -71,7 +71,53 @@ module Nukadoko
71
71
  end
72
72
 
73
73
  NAMED = /\{([A-Za-z_][\w-]*):([\w-]+)\}/
74
- REGISTRY = Registry.new
74
+ BUILT_IN = Registry.new.parameter_types.map(&:name).freeze #: Array[String]
75
+
76
+ # The registry every pattern of the loaded project reads: the built-in
77
+ # types, and the config's parameterTypes on top of them.
78
+ #: () -> Registry
79
+ def self.registry = @registry ||= Registry.new
80
+
81
+ # Why the config's parameterTypes could not be registered, in the
82
+ # TypeScript engine's words, or nil. While it is set no pattern
83
+ # matches a line, as no pattern binds there: nuka check reports it
84
+ # once, as parameter-type-invalid, and a run under --no-check stops.
85
+ #: () -> String?
86
+ def self.collision = @collision
87
+
88
+ # The names of the config's parameter types that have a transformer,
89
+ # whose capture a claim cannot compare with.
90
+ #: () -> Array[String]
91
+ def self.transformed = @transformed || []
92
+
93
+ # Registers the config's parameterTypes: each a name, a regexp, and an
94
+ # optional transformer, given the groups the regexp captured. A type
95
+ # with no transformer gives the text the regexp matched, or its first
96
+ # group, as the JavaScript package does.
97
+ #: (Array[Hash[Symbol, untyped]]) -> void
98
+ def self.configure(types)
99
+ @registry = Registry.new
100
+ @collision = nil
101
+ @transformed = types.select { _1[:transformer] }.map { _1[:name].to_s }
102
+ seen = [] #: Array[String]
103
+ types.each do |type|
104
+ name = type[:name].to_s
105
+ if BUILT_IN.include?(name)
106
+ @collision = %(Custom parameter type "#{name}" collides with one of cucumber-expressions' own built-in parameter types; ) +
107
+ "redefining what {#{name}} means would quietly change the meaning of every pattern that already uses it"
108
+ elsif seen.include?(name)
109
+ @collision = %(Custom parameter type "#{name}" is registered more than once in parameterTypes)
110
+ end
111
+ if @collision
112
+ @registry = Registry.new
113
+ return
114
+ end
115
+
116
+ seen << name
117
+ transformer = type[:transformer] || ->(*groups) { groups.first }
118
+ @registry.define_parameter_type(CE::ParameterType.new(name, type[:regexp], Object, transformer, true, false))
119
+ end
120
+ end
75
121
 
76
122
  attr_reader :source, :keys
77
123
 
@@ -79,11 +125,13 @@ module Nukadoko
79
125
  def initialize(source)
80
126
  @source = source
81
127
  @keys = source.scan(NAMED).map { Array(_1).first.to_s }
82
- @expression = CE::CucumberExpression.new(source.gsub(NAMED, '{\2}'), REGISTRY)
128
+ @expression = CE::CucumberExpression.new(source.gsub(NAMED, '{\2}'), Pattern.registry)
83
129
  end
84
130
 
85
131
  #: (String) -> Hash[String, untyped]?
86
132
  def match(text)
133
+ return nil if Pattern.collision
134
+
87
135
  found = @expression.match(text)
88
136
  found && keys.zip(found.map { _1.value(nil) }).to_h
89
137
  end
@@ -91,6 +139,8 @@ module Nukadoko
91
139
  # Each capture's text as the line wrote it, quotes included.
92
140
  #: (String) -> Hash[String, String]?
93
141
  def texts(text)
142
+ return nil if Pattern.collision
143
+
94
144
  found = @expression.match(text)
95
145
  found && keys.zip(found.map { _1.group.value }).to_h
96
146
  end
data/lib/nukadoko/run.rb CHANGED
@@ -718,20 +718,22 @@ module Nukadoko
718
718
  @browser&.step = { step_record_id: record[:step_record_id], step: record[:step], line: at_line }
719
719
  @browser&.begin_step
720
720
  Trace.within(boundary) do
721
- fixtures, finish = build_fixtures(step, dir, log, world, record)
721
+ fixtures, finish = build_fixtures(step, dir, log, world, record, results)
722
722
  HttpRecording.collect(log) do
723
723
  Processes.collect(processes) { RedactedOutput.around(secrets) { body(step, fixtures, args, [then_line, at_line], record, results, origins, texts) } }
724
724
  end
725
725
  end
726
- record[:page_view] = @browser.judged(dir, record[:step_record_id], aria_in_claims: step.claims.to_a.any? { !_1[:each] && _1[:compare] == "fits-aria-snapshot" }) if step.claims && fixtures[:page] && record[:observation] != "unobserved"
726
+ record[:page_view] = @browser.judged(dir, record[:step_record_id], aria_in_claims: step.claims.to_a.any? { !_1[:each] && _1[:compare] == "fits-aria-snapshot" }) if step.claims && (fixtures[:page] || fixtures[:context]) && record[:observation] != "unobserved"
727
727
  record[:status] ||= "passed"
728
728
  rescue StandardError => e
729
729
  record.merge!(status: "failed", outcome: :broke, error: e.message)
730
730
  record[:error_kind] ||= "step_error"
731
+ record[:error_at] = ErrorFrames.of(e, @project).map { redact(_1) } if record[:error_kind] == "step_error"
731
732
  ensure
732
733
  @browser&.step = nil
733
734
  finish&.call
734
- log.concat(fixtures[:request].log) if fixtures[:request]
735
+ log.concat(@request_log.log) if @request_log
736
+ @request_log = nil
735
737
  # A world at a URL has a log nukadoko does not read.
736
738
  record[:program_log] = @program_log&.slice(dir, boundary) if boundary
737
739
  record[:finished_at] = Time.now.utc.iso8601(3)
@@ -753,6 +755,17 @@ module Nukadoko
753
755
  record[:scratch] = made if made.any?
754
756
  end
755
757
  record[:calls] = fixtures[:call].calls if fixtures[:call]&.calls&.any?
758
+ # The step's own marks, waits, and files, as plain values for the record.
759
+ sections = record.delete(:section_log)&.entries
760
+ record[:sections] = sections if sections&.any?
761
+ polls = record.delete(:poll_log)&.entries
762
+ record[:polls] = polls if polls&.any?
763
+ if (evidence = record.delete(:evidence_log))
764
+ attachments, total = evidence.snapshot
765
+ record[:attachments] = attachments if attachments.any?
766
+ record[:attachments_total] = total if total
767
+ end
768
+ record.delete(:required_env) if record[:required_env] && record[:required_env].empty?
756
769
  # A page's own traffic is in http.jsonl and the trace, not counted as the step's.
757
770
  record[:http_count] = log.count { _1[:via] != "page" }
758
771
  File.write(File.join(dir, "http.jsonl"), "#{log.map { JSON.generate(secrets.redact(_1)) }.join("\n")}\n") if log.any?
@@ -768,6 +781,21 @@ module Nukadoko
768
781
  record
769
782
  end
770
783
 
784
+ # The args keys the line fills through a parameter type with a
785
+ # transformer, each with why a claim does not compare with it: code
786
+ # made the value, while the record would name the sentence. nuka check
787
+ # reports such a pattern; a run under --no-check agrees with it.
788
+ #: (untyped, Hash[String, String]) -> Hash[String, String]
789
+ def transformed_fills(step, origins)
790
+ pattern = step.pattern.to_s
791
+ pattern.scan(Pattern::NAMED).each_with_object({}) do |(key, type), found|
792
+ next unless Pattern.transformed.include?(type.to_s) && !origins.key?(key.to_s)
793
+
794
+ 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, ) +
795
+ "so code would decide what the claim compares, and the claim was not judged"
796
+ end
797
+ end
798
+
771
799
  # A Then step's claims are judged on what it observed, or on its args
772
800
  # when it reads nothing itself; any other step runs and returns.
773
801
  # `step` is a step class whose observe or run its own file defines.
@@ -791,10 +819,10 @@ module Nukadoko
791
819
  sides = lambda do |observed|
792
820
  ClaimSides::Inputs.new(observed: observed, args: args, observes: observes, from_keys: step.from.keys.map(&:to_s),
793
821
  labels: ->(key) { origins.fetch(key, "sentence:#{key}") },
794
- received: observes ? step.inputs.fields.map { _1.name.to_s } : [])
822
+ received: observes ? step.inputs.fields.map { _1.name.to_s } : [], transformed: transformed_fills(step, origins))
795
823
  end
796
824
  # A reading with a page open is timed, so the record can say what the page had received by then.
797
- read = (plain = read; -> { @browser.reading(&plain) }) if own[:page]
825
+ read = (plain = read; -> { @browser.reading(&plain) }) if own[:page] || own[:context]
798
826
  observed = begin
799
827
  step.poll ? Poll.new(step.poll, step.claims, args, sides).call(record, &read) : read.()
800
828
  rescue StandardError => e
@@ -900,6 +928,8 @@ module Nukadoko
900
928
  used = []
901
929
  step.from.each do |key, sources|
902
930
  cls, value, at_line, record_id = results.reverse_each.find { |c, _| sources.any? { _1.first == c } }
931
+ # An optional key stays absent when no producer ran, as zod leaves it.
932
+ next if !cls && step.args[key]&.absent_ok?
903
933
  unless cls
904
934
  record[:error_kind] = "binding_invalid"
905
935
  raise ArgumentError, %(no earlier step in this scenario gave "#{key}")
@@ -912,7 +942,7 @@ module Nukadoko
912
942
  used << { step: cls.step_name, record: "steps/#{record_id}", result: value } unless used.any? { _1[:record] == "steps/#{record_id}" }
913
943
  end
914
944
  record[:used] = used
915
- open = step.args.fields.map { _1.name.to_s } - args.keys
945
+ open = step.args.required_names - args.keys
916
946
  attachment = line.table || line.doc_string
917
947
  if attachment && open.any?
918
948
  args[open.first] = attachment
@@ -928,7 +958,7 @@ module Nukadoko
928
958
  # for the one key it fills.
929
959
  #: (singleton(Step), Hash[String, untyped], PickleStep) -> Hash[String, String]
930
960
  def attachment_texts(step, captures, line)
931
- open = step.args.fields.map { _1.name.to_s } - captures.keys - step.from.keys
961
+ open = step.args.required_names - captures.keys - step.from.keys
932
962
  return {} if open.empty?
933
963
  return { open.first => line.doc_string } if line.doc_string
934
964
  return { open.first => line.table.map { |row| "| #{row.join(" | ")} |" }.join("\n") } if line.table
@@ -941,17 +971,20 @@ module Nukadoko
941
971
 
942
972
  # A project fixture is built the first time a step of its scope names
943
973
  # it, directly or through another fixture, and kept until the scope ends.
944
- #: (Symbol, World, Array[Symbol]) -> untyped
945
- def project_fixture(name, world, chain)
974
+ #: (Symbol, World, Array[Symbol], ?(^(Symbol) -> untyped)?) -> untyped
975
+ def project_fixture(name, world, chain, builtin = nil)
946
976
  fixture = Nukadoko.project_fixtures[name] or raise ArgumentError, "the Ruby engine has no fixture #{name} yet"
947
977
  raise ArgumentError, "fixtures depend on each other in a cycle: #{[*chain, name].join(" -> ")}" if chain.include?(name)
948
978
 
949
979
  cache = fixture.scope == :process ? @process_fixtures : @scenario_fixtures
980
+ # A fixture that names itself wraps the builtin of that name, as a
981
+ # page override in the TypeScript config does, so it is no cycle.
950
982
  deps = fixture.dependencies.to_h do |dep|
951
- case dep
952
- when :baseURL then [dep, world.base_url]
953
- when :scratch then [dep, @scratch]
954
- else [dep, project_fixture(dep, world, [*chain, name])]
983
+ if BUILTINS.include?(dep) && (dep == name || !Nukadoko.project_fixtures.key?(dep))
984
+ raise ArgumentError, %(fixture "#{name}" names "#{dep}", which only a step's own fixtures can give) unless builtin
985
+
986
+ [dep, builtin.(dep)]
987
+ else [dep, project_fixture(dep, world, [*chain, name], builtin)]
955
988
  end
956
989
  end
957
990
  return cache[name].tap { note_fixture(name, fixture.scope, nil, nil) } if cache.key?(name)
@@ -998,29 +1031,102 @@ module Nukadoko
998
1031
  raise Refusal.new("env-file-unreadable", e.message)
999
1032
  end
1000
1033
 
1001
- #: (singleton(Step), String, Array[Hash[Symbol, untyped]], World, Hash[Symbol, untyped]) -> [Hash[Symbol, untyped], (^() -> void)?]
1002
- def build_fixtures(step, dir, log, world, record)
1003
- finish = nil
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
1036
+
1037
+ # The snake_case spelling of each builtin a Ruby step may name instead,
1038
+ # 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
1040
+
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)
1043
+ finishes = [] #: Array[^() -> void]
1004
1044
  @fixture_usage = []
1005
- fixtures = (step.bag - [:call]).to_h do |name|
1006
- case name
1007
- when :request then [name, Request.new(world.base_url)]
1008
- when :baseURL then [name, world.base_url]
1009
- when :env then [name, step_env(world)]
1010
- when :requireEnv then [name, ->(key) { step_env(world).fetch(key.to_s) { raise %(requireEnv("#{key}"): the world's env has no #{key}) } }]
1011
- when :scratch then [name, @scratch]
1012
- when :page
1013
- page, finish = @browser.page_for(dir, log)
1014
- [name, page]
1015
- else [name, project_fixture(name, world, [])]
1016
- end
1045
+ built = {} #: Hash[Symbol, untyped]
1046
+ builtin = lambda do |name|
1047
+ name = ALIASES.fetch(name, name)
1048
+ next built[name] if built.key?(name)
1049
+
1050
+ built[name] =
1051
+ 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)
1056
+ when :scratch then @scratch
1057
+ when :page
1058
+ page, finish = @browser.page_for(dir, log)
1059
+ finishes << finish
1060
+ page
1061
+ when :context then builtin.(:page).context
1062
+ when :pageAs
1063
+ finishes << lambda do
1064
+ traces = @browser.finish_named
1065
+ record[:named_traces] = traces if traces.any?
1066
+ end
1067
+ ->(as, options = nil) { @browser.page_as(as, options, dir, log) }
1068
+ when :section then (record[:section_log] = Sections.new)
1069
+ when :poll then (record[:poll_log] = Polls.new)
1070
+ when :evidence then (record[:evidence_log] = Evidence.new(dir))
1071
+ when :resultOf then result_of(step, results, record)
1072
+ end
1073
+ end
1074
+ # A project fixture of a builtin's name replaces it for the step.
1075
+ fixtures = {} #: Hash[Symbol, untyped]
1076
+ (step.bag - [:call]).each do |name|
1077
+ fixtures[name] = Nukadoko.project_fixtures.key?(name) || !BUILTINS.include?(name) ? project_fixture(name, world, [], builtin) : builtin.(name)
1017
1078
  end
1079
+ # Requests a wrapped request fixture sends are the builtin's, so the record keeps them.
1080
+ @request_log = built[:request]
1018
1081
  fixtures[:call] = Caller.new(step, fixtures) if step.fixtures.include?(:call)
1019
1082
  record[:fixtures] = @fixture_usage if @fixture_usage.any?
1020
1083
  @fixture_usage = nil
1084
+ finish = finishes.empty? ? nil : -> { finishes.reverse_each(&:call) }
1021
1085
  [fixtures, finish]
1022
1086
  end
1023
1087
 
1088
+ # requireEnv: the env fixture's value for a key, or a raise that names
1089
+ # only the key. An empty value counts as missing, since a step that
1090
+ # requires it is broken either way. Every name asked for is kept, in
1091
+ # 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)
1094
+ asked = record[:required_env] = [] #: Array[String]
1095
+ lambda do |key|
1096
+ key = key.to_s
1097
+ 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?
1100
+
1101
+ value
1102
+ end
1103
+ end
1104
+
1105
+ # resultOf: the result an earlier step of the scenario last gave when
1106
+ # it passed, or nil when it has not. A claim step takes an earlier
1107
+ # value through `from` alone, so its record names where the value
1108
+ # came from. A read that found a result names its step in `used`, as
1109
+ # a from key does.
1110
+ #: (singleton(Step), Array[untyped], Hash[Symbol, untyped]) -> ^(untyped) -> untyped
1111
+ def result_of(step, results, record)
1112
+ lambda do |source|
1113
+ unless source.is_a?(Class) && source < Step && @steps.include?(source)
1114
+ raise ArgumentError, "resultOf(#{source.inspect}): that is not a step this project registered, so no step record could hold its result"
1115
+ end
1116
+ if step.claims
1117
+ raise ArgumentError, %(Step "#{step.step_name}" declares claims, so it takes an earlier step's value through "from" alone, ) +
1118
+ %(which names where the value came from; resultOf(#{source.step_name}) is not available in a claim step.)
1119
+ end
1120
+
1121
+ _, value, _, record_id = results.reverse_each.find { |cls, *| cls == source }
1122
+ next nil unless value
1123
+
1124
+ used = (record[:used] ||= []) #: Array[Hash[Symbol, untyped]]
1125
+ used << { step: source.step_name, record: "steps/#{record_id}", result: value } unless used.any? { _1[:record] == "steps/#{record_id}" }
1126
+ (schema = source.returns) ? schema.load(value) : value
1127
+ end
1128
+ end
1129
+
1024
1130
  #: (String) -> String
1025
1131
  def new_id(kind) = "#{kind}-#{Time.now.utc.strftime("%Y%m%d-%H%M%S")}-#{SecureRandom.alphanumeric(4).downcase}"
1026
1132
 
@@ -25,7 +25,7 @@ module Nukadoko
25
25
  def step_file(record, environment:, world_name:, run_id:, scenario_record_id:, evidence_dir:)
26
26
  passed = record[:status] == "passed"
27
27
  outcome = if passed then { result: record[:result] || {}, returns_dropped: record[:returns_dropped] }.compact
28
- else { error: { message: record[:error], kind: record[:error_kind] } }
28
+ else { error: { message: record[:error], kind: record[:error_kind], **(record[:error_at]&.any? ? { at: record[:error_at] } : {}) } }
29
29
  end
30
30
  processes = record[:processes]
31
31
  used = (record[:used] || []).map do |entry|
@@ -35,12 +35,16 @@ module Nukadoko
35
35
  args: record[:args] || {}, **(record[:args_origin]&.any? ? { args_origin: record[:args_origin] } : {}),
36
36
  **outcome, status: record[:status], environment: environment, world_name: world_name,
37
37
  scenario_record_id: scenario_record_id, run_id: run_id, started_at: record[:started_at], finished_at: record[:finished_at],
38
- evidence: { dir: evidence_dir, screenshots: [], **(record[:scratch] ? { scratch: record[:scratch] } : {}),
39
- **(record[:http_file] ? { http: "http.jsonl" } : {}), **(record[:trace] ? { trace: record[:trace] } : {}) },
38
+ evidence: { dir: evidence_dir, screenshots: [], **(record[:attachments] ? { attachments: record[:attachments] } : {}),
39
+ **(record[:scratch] ? { scratch: record[:scratch] } : {}),
40
+ **(record[:http_file] ? { http: "http.jsonl" } : {}), **(record[:trace] ? { trace: record[:trace] } : {}),
41
+ **(record[:named_traces] ? { named_traces: record[:named_traces] } : {}) },
40
42
  observed: { processes: processes&.any? ? processes : nil, http: record[:http_count].to_i.positive? ? record[:http_count] : nil,
41
43
  files: record[:files], unmeasured: [], **(record.key?(:program_log) ? { program_log: record[:program_log] } : {}) },
42
- mutates: record[:mutates], **(used.any? ? { used: used } : {}), **(record[:calls] ? { calls: record[:calls] } : {}),
43
- **(record[:actions] ? { actions: record[:actions] } : {}), **(record[:actions_truncated] ? { truncated: { actions: record[:actions_truncated] } } : {}),
44
+ mutates: record[:mutates], **(used.any? ? { used: used } : {}), **(record[:sections] ? { sections: record[:sections] } : {}),
45
+ **(record[:calls] ? { calls: record[:calls] } : {}), **(record[:polls] ? { polls: record[:polls] } : {}),
46
+ **(record[:required_env] ? { required_env: record[:required_env] } : {}),
47
+ **(record[:actions] ? { actions: record[:actions] } : {}), **(record[:actions_truncated] || record[:attachments_total] ? { truncated: { actions: record[:actions_truncated], evidence: record[:attachments_total] }.compact } : {}),
44
48
  **(record[:fixtures] ? { fixtures: record[:fixtures] } : {}),
45
49
  **(record[:claim_records] ? { claims: record[:claim_records], observation: record[:observation] || "observed", **poll_fields(record), **page_fields(record) } : {}) }
46
50
  end
@@ -73,7 +73,7 @@ module Nukadoko
73
73
  repeated = captures.map(&:key).tally.select { _2 > 1 }.keys
74
74
  return refusal("Refusing to scaffold: the pattern captures #{repeated.map { %("#{_1}") }.join(", ")} more than once, and one args field holds one value") if repeated.any?
75
75
 
76
- types = Pattern::REGISTRY.parameter_types.map(&:name).reject(&:empty?).sort
76
+ types = Pattern.registry.parameter_types.map(&:name).reject(&:empty?).sort
77
77
  unknown = captures.map(&:type).uniq.find { !types.include?(_1) }
78
78
  if unknown
79
79
  return refusal(%(Refusing to scaffold: the pattern names type "#{unknown}", and this project registers none by that name; registered types: #{types.join(", ")}))
@@ -918,7 +918,7 @@ module Nukadoko
918
918
  # itself, with the readings it could not choose between.
919
919
  #: (String) -> Hash[Symbol, untyped]
920
920
  def self.infer(text)
921
- generated = generate(text, Pattern::REGISTRY)
921
+ generated = generate(text, Pattern.registry)
922
922
  first = generated.first
923
923
  same = generated.all? do |expression|
924
924
  expression.parameter_types.size == first.parameter_types.size &&