From 4b9a8a5741895fa27fc13cb0b0647e4daeff36b8 Mon Sep 17 00:00:00 2001 From: Vasu Jaganath Date: Thu, 12 Nov 2026 15:25:24 -0500 Subject: [PATCH 1/7] test(nextflow): runs as example workflows The run cases are seven example directories that state every output, run under Nextflow and cwltool, and stops that name their step and why. --- .../data/nextflow/command_line/copy_into.cwl | 22 + .../data/nextflow/command_line/source.txt | 1 + .../data/nextflow/command_line/workflow.wic | 8 + tests/core/data/nextflow/runs.yaml | 585 ------------------ .../data/nextflow/runs/commands/cat_file.cwl | 13 + .../data/nextflow/runs/commands/copy_file.cwl | 14 + .../nextflow/runs/commands/count_bytes.cwl | 12 + .../data/nextflow/runs/commands/expected.yaml | 20 + .../data/nextflow/runs/commands/greeting.txt | 1 + .../nextflow/runs/commands/print_bindings.cwl | 20 + .../data/nextflow/runs/commands/produce.cwl | 14 + .../nextflow/runs/commands/shell_redirect.cwl | 16 + .../nextflow/runs/commands/three_commands.cwl | 27 + .../nextflow/runs/commands/touch_file.cwl | 12 + .../data/nextflow/runs/commands/workflow.wic | 50 ++ .../runs/conditions_and_scatter/cat_pair.cwl | 16 + .../runs/conditions_and_scatter/copy_note.cwl | 15 + .../runs/conditions_and_scatter/echo_item.cwl | 13 + .../runs/conditions_and_scatter/expected.yaml | 46 ++ .../runs/conditions_and_scatter/job.yml | 3 + .../conditions_and_scatter/never_runs.cwl | 15 + .../conditions_and_scatter/numbers_if.cwl | 19 + .../numbers_if_prev_last.cwl | 19 + .../runs/conditions_and_scatter/pair.cwl | 18 + .../pair_after_sleeping.cwl | 17 + .../runs/conditions_and_scatter/ref.txt | 1 + .../runs/conditions_and_scatter/say_ok.cwl | 15 + .../conditions_and_scatter/touch_done.cwl | 10 + .../runs/conditions_and_scatter/workflow.wic | 109 ++++ .../conditions_and_scatter/write_note.cwl | 14 + .../core/data/nextflow/runs/nested/child.wic | 13 + .../data/nextflow/runs/nested/copy_file.cwl | 14 + .../data/nextflow/runs/nested/count_lines.cwl | 12 + .../data/nextflow/runs/nested/echo_each.cwl | 13 + .../data/nextflow/runs/nested/expected.yaml | 13 + .../data/nextflow/runs/nested/grandchild.wic | 7 + .../data/nextflow/runs/nested/sibling.wic | 6 + .../data/nextflow/runs/nested/touch_n.cwl | 10 + .../data/nextflow/runs/nested/workflow.wic | 14 + .../nextflow/runs/nested/write_source.cwl | 13 + .../nextflow/runs/outputs/backtick_named.cwl | 11 + .../nextflow/runs/outputs/brace_named.cwl | 9 + .../nextflow/runs/outputs/dollar_named.cwl | 9 + .../data/nextflow/runs/outputs/expected.yaml | 11 + .../nextflow/runs/outputs/first_of_braces.cwl | 15 + .../data/nextflow/runs/outputs/maybe_log.cwl | 12 + .../nextflow/runs/outputs/maybe_named.cwl | 12 + .../nextflow/runs/outputs/touch_names.cwl | 12 + .../data/nextflow/runs/outputs/workflow.wic | 27 + .../nextflow/runs/resources/expected.yaml | 5 + .../data/nextflow/runs/resources/make_dir.cwl | 20 + .../nextflow/runs/resources/nextflow.config | 1 + .../data/nextflow/runs/resources/workflow.nf | 83 +++ .../data/nextflow/runs/resources/workflow.wic | 5 + .../runs/staging/capture_own_entry.cwl | 17 + .../runs/staging/capture_renamed_entry.cwl | 15 + .../runs/staging/copy_named_after_source.cwl | 14 + .../data/nextflow/runs/staging/expected.yaml | 11 + .../data/nextflow/runs/staging/plugin.cwl | 20 + .../nextflow/runs/staging/stage_and_read.cwl | 17 + .../runs/staging/stage_own_basename.cwl | 17 + .../data/nextflow/runs/staging/workflow.wic | 24 + .../nextflow/runs/staging/write_source.cwl | 13 + .../nextflow/runs/step_inputs/cat_files.cwl | 13 + .../nextflow/runs/step_inputs/expected.yaml | 21 + .../data/nextflow/runs/step_inputs/job.yml | 3 + .../data/nextflow/runs/step_inputs/say_if.cwl | 17 + .../nextflow/runs/step_inputs/say_word.cwl | 13 + .../nextflow/runs/step_inputs/say_words.cwl | 13 + .../nextflow/runs/step_inputs/workflow.wic | 82 +++ .../nextflow/runs/step_inputs/write_name.cwl | 13 + .../pick_first_of_none/expected.yaml | 5 + .../pick_first_of_none/workflow.wic | 8 + .../pick_only_of_none/expected.yaml | 5 + .../pick_only_of_none/workflow.wic | 8 + .../pick_only_of_two/expected.yaml | 5 + .../before_a_task/pick_only_of_two/job.yml | 2 + .../pick_only_of_two/workflow.wic | 8 + .../when_is_not_finite/expected.yaml | 6 + .../when_is_not_finite/touch_c.cwl | 10 + .../when_is_not_finite/workflow.wic | 6 + .../expected.yaml | 5 + .../list_both.cwl | 19 + .../one/data/one.txt | 1 + .../two/data/two.txt | 1 + .../workflow.wic | 6 + .../optional_output_two_matches/expected.yaml | 4 + .../optional_output_two_matches/maybe_log.cwl | 12 + .../optional_output_two_matches/workflow.wic | 4 + .../required_output_no_match/expected.yaml | 4 + .../required_output_no_match/workflow.wic | 4 + .../write_nothing.cwl | 14 + .../expected.yaml | 4 + .../touch_names.cwl | 12 + .../workflow.wic | 4 + .../two_entries_share_a_name/expected.yaml | 4 + .../two_entries_share_a_name/list_both.cwl | 20 + .../two_entries_share_a_name/one/data/one.txt | 1 + .../two_entries_share_a_name/two/data/two.txt | 1 + .../two_entries_share_a_name/workflow.wic | 4 + tests/core/nextflow/test_capabilities.py | 137 ---- tests/core/nextflow/test_composition.py | 273 -------- tests/core/nextflow/test_dotproduct.py | 106 ---- .../core/nextflow/test_nested_crossproduct.py | 98 --- tests/core/nextflow/test_phase3_cells.py | 4 +- .../nextflow/test_reference_differential.py | 28 +- tests/core/nextflow/test_renderer.py | 258 -------- tests/core/nextflow/test_runtime.py | 207 ++++--- tests/core/nextflow/test_shipped_append.py | 31 - tests/core/nextflow/test_step_inputs.py | 4 +- tests/core/nextflow/testkit.py | 28 + tests/core/test_ci_coverage.py | 11 +- 112 files changed, 1588 insertions(+), 1599 deletions(-) create mode 100644 tests/core/data/nextflow/command_line/copy_into.cwl create mode 100644 tests/core/data/nextflow/command_line/source.txt create mode 100644 tests/core/data/nextflow/command_line/workflow.wic delete mode 100644 tests/core/data/nextflow/runs.yaml create mode 100644 tests/core/data/nextflow/runs/commands/cat_file.cwl create mode 100644 tests/core/data/nextflow/runs/commands/copy_file.cwl create mode 100644 tests/core/data/nextflow/runs/commands/count_bytes.cwl create mode 100644 tests/core/data/nextflow/runs/commands/expected.yaml create mode 100644 tests/core/data/nextflow/runs/commands/greeting.txt create mode 100644 tests/core/data/nextflow/runs/commands/print_bindings.cwl create mode 100644 tests/core/data/nextflow/runs/commands/produce.cwl create mode 100644 tests/core/data/nextflow/runs/commands/shell_redirect.cwl create mode 100644 tests/core/data/nextflow/runs/commands/three_commands.cwl create mode 100644 tests/core/data/nextflow/runs/commands/touch_file.cwl create mode 100644 tests/core/data/nextflow/runs/commands/workflow.wic create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/cat_pair.cwl create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/copy_note.cwl create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/echo_item.cwl create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/expected.yaml create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/job.yml create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/never_runs.cwl create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if.cwl create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if_prev_last.cwl create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/pair.cwl create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/pair_after_sleeping.cwl create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/ref.txt create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/say_ok.cwl create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/touch_done.cwl create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/workflow.wic create mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/write_note.cwl create mode 100644 tests/core/data/nextflow/runs/nested/child.wic create mode 100644 tests/core/data/nextflow/runs/nested/copy_file.cwl create mode 100644 tests/core/data/nextflow/runs/nested/count_lines.cwl create mode 100644 tests/core/data/nextflow/runs/nested/echo_each.cwl create mode 100644 tests/core/data/nextflow/runs/nested/expected.yaml create mode 100644 tests/core/data/nextflow/runs/nested/grandchild.wic create mode 100644 tests/core/data/nextflow/runs/nested/sibling.wic create mode 100644 tests/core/data/nextflow/runs/nested/touch_n.cwl create mode 100644 tests/core/data/nextflow/runs/nested/workflow.wic create mode 100644 tests/core/data/nextflow/runs/nested/write_source.cwl create mode 100644 tests/core/data/nextflow/runs/outputs/backtick_named.cwl create mode 100644 tests/core/data/nextflow/runs/outputs/brace_named.cwl create mode 100644 tests/core/data/nextflow/runs/outputs/dollar_named.cwl create mode 100644 tests/core/data/nextflow/runs/outputs/expected.yaml create mode 100644 tests/core/data/nextflow/runs/outputs/first_of_braces.cwl create mode 100644 tests/core/data/nextflow/runs/outputs/maybe_log.cwl create mode 100644 tests/core/data/nextflow/runs/outputs/maybe_named.cwl create mode 100644 tests/core/data/nextflow/runs/outputs/touch_names.cwl create mode 100644 tests/core/data/nextflow/runs/outputs/workflow.wic create mode 100644 tests/core/data/nextflow/runs/resources/expected.yaml create mode 100644 tests/core/data/nextflow/runs/resources/make_dir.cwl create mode 100644 tests/core/data/nextflow/runs/resources/nextflow.config create mode 100644 tests/core/data/nextflow/runs/resources/workflow.nf create mode 100644 tests/core/data/nextflow/runs/resources/workflow.wic create mode 100644 tests/core/data/nextflow/runs/staging/capture_own_entry.cwl create mode 100644 tests/core/data/nextflow/runs/staging/capture_renamed_entry.cwl create mode 100644 tests/core/data/nextflow/runs/staging/copy_named_after_source.cwl create mode 100644 tests/core/data/nextflow/runs/staging/expected.yaml create mode 100644 tests/core/data/nextflow/runs/staging/plugin.cwl create mode 100644 tests/core/data/nextflow/runs/staging/stage_and_read.cwl create mode 100644 tests/core/data/nextflow/runs/staging/stage_own_basename.cwl create mode 100644 tests/core/data/nextflow/runs/staging/workflow.wic create mode 100644 tests/core/data/nextflow/runs/staging/write_source.cwl create mode 100644 tests/core/data/nextflow/runs/step_inputs/cat_files.cwl create mode 100644 tests/core/data/nextflow/runs/step_inputs/expected.yaml create mode 100644 tests/core/data/nextflow/runs/step_inputs/job.yml create mode 100644 tests/core/data/nextflow/runs/step_inputs/say_if.cwl create mode 100644 tests/core/data/nextflow/runs/step_inputs/say_word.cwl create mode 100644 tests/core/data/nextflow/runs/step_inputs/say_words.cwl create mode 100644 tests/core/data/nextflow/runs/step_inputs/workflow.wic create mode 100644 tests/core/data/nextflow/runs/step_inputs/write_name.cwl create mode 100644 tests/core/data/nextflow/stops/before_a_task/pick_first_of_none/expected.yaml create mode 100644 tests/core/data/nextflow/stops/before_a_task/pick_first_of_none/workflow.wic create mode 100644 tests/core/data/nextflow/stops/before_a_task/pick_only_of_none/expected.yaml create mode 100644 tests/core/data/nextflow/stops/before_a_task/pick_only_of_none/workflow.wic create mode 100644 tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/expected.yaml create mode 100644 tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/job.yml create mode 100644 tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/workflow.wic create mode 100644 tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/expected.yaml create mode 100644 tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/touch_c.cwl create mode 100644 tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/workflow.wic create mode 100644 tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/expected.yaml create mode 100644 tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/list_both.cwl create mode 100644 tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/one/data/one.txt create mode 100644 tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/two/data/two.txt create mode 100644 tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/workflow.wic create mode 100644 tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/expected.yaml create mode 100644 tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/maybe_log.cwl create mode 100644 tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/workflow.wic create mode 100644 tests/core/data/nextflow/stops/in_a_task/required_output_no_match/expected.yaml create mode 100644 tests/core/data/nextflow/stops/in_a_task/required_output_no_match/workflow.wic create mode 100644 tests/core/data/nextflow/stops/in_a_task/required_output_no_match/write_nothing.cwl create mode 100644 tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/expected.yaml create mode 100644 tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/touch_names.cwl create mode 100644 tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/workflow.wic create mode 100644 tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/expected.yaml create mode 100644 tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/list_both.cwl create mode 100644 tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/one/data/one.txt create mode 100644 tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/two/data/two.txt create mode 100644 tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/workflow.wic delete mode 100644 tests/core/nextflow/test_composition.py delete mode 100644 tests/core/nextflow/test_dotproduct.py delete mode 100644 tests/core/nextflow/test_nested_crossproduct.py delete mode 100644 tests/core/nextflow/test_renderer.py delete mode 100644 tests/core/nextflow/test_shipped_append.py diff --git a/tests/core/data/nextflow/command_line/copy_into.cwl b/tests/core/data/nextflow/command_line/copy_into.cwl new file mode 100644 index 000000000..c55272e5a --- /dev/null +++ b/tests/core/data/nextflow/command_line/copy_into.cwl @@ -0,0 +1,22 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Copy `source` into the directory it is told to write into, which it stages writable and gives back. +baseCommand: cp +requirements: + InitialWorkDirRequirement: + listing: + - entry: $(inputs.outDir) + writable: true +inputs: + outDir: + type: Directory + source: + type: File +outputs: + outDir: + type: Directory + outputBinding: + glob: $(inputs.outDir.basename) +arguments: +- $(inputs.source) +- $(inputs.outDir.basename)/copied.txt diff --git a/tests/core/data/nextflow/command_line/source.txt b/tests/core/data/nextflow/command_line/source.txt new file mode 100644 index 000000000..b522eb7b1 --- /dev/null +++ b/tests/core/data/nextflow/command_line/source.txt @@ -0,0 +1 @@ +copied text diff --git a/tests/core/data/nextflow/command_line/workflow.wic b/tests/core/data/nextflow/command_line/workflow.wic new file mode 100644 index 000000000..1896bd41e --- /dev/null +++ b/tests/core/data/nextflow/command_line/workflow.wic @@ -0,0 +1,8 @@ +# Run from the command line in another directory: the two relative paths are read beside this file. +steps: + copy_into: + in: + outDir: !ii made # made beside this file and left empty: the tool writes into its own copy + source: !ii source.txt + out: + - outDir: !& made diff --git a/tests/core/data/nextflow/runs.yaml b/tests/core/data/nextflow/runs.yaml deleted file mode 100644 index 2c7395d03..000000000 --- a/tests/core/data/nextflow/runs.yaml +++ /dev/null @@ -1,585 +0,0 @@ -- id: adapter_then_cp_and_wc - why: One workflow mixing an imported adapter with tools written beside it runs, the adapter's stdout read by both. - tools: - copy_file: {baseCommand: cp, arguments: [{position: 2, valueFrom: copy.txt}], inputs: {source: {type: File, - inputBinding: {position: 1}}}, outputs: {result: {type: File, outputBinding: {glob: copy.txt}}}} - count_bytes: {baseCommand: [wc, -c], inputs: {source: {type: File, inputBinding: {position: 1}}}, - stdout: count.txt, outputs: {result: {type: File, outputBinding: {glob: count.txt}}}} - steps: | - - {id: emit, run: echo, in: {message: !ii 'mixed construction, one backend'}, out: [stdout: !& emitted]} - - id: copy_file - in: {source: !* emitted} - - id: count_bytes - in: {source: !* emitted} - outputs: {emit~stdout: {class: File, basename: stdout, contents: "mixed construction, one backend\n"}, - copy_file~result: {class: File, basename: copy.txt, contents: "mixed construction, one backend\n"}, - count_bytes~result: {class: File, basename: count.txt, contents: {re: '^\s*32 '}}} -- id: basename_derived_output - why: An output name derived from a staged input's basename names the copy the command made. - tools: - write_source: &tool_write_source {baseCommand: echo, inputs: {message: {type: string, inputBinding: {position: 1}}}, - stdout: lines.txt, outputs: {result: {type: File, outputBinding: {glob: lines.txt}}}} - copy_named_after_source: {baseCommand: cp, inputs: {source: {type: File, inputBinding: {position: 1}}}, - arguments: [{position: 2, valueFrom: $(inputs.source.basename).copy}], outputs: {result: {type: File, - outputBinding: {glob: $(inputs.source.basename).copy}}}} - steps: | - - id: write_source - in: {message: !ii basename derived} - - id: copy_named_after_source - outputs: {write_source~result: {class: File, basename: lines.txt, contents: "basename derived\n"}, - copy_named_after_source~result: {class: File, basename: lines.txt.copy, contents: "basename derived\n"}} -- id: brace_glob_literal - why: 'A CWL glob has no brace expansion: `a{b,c}.txt` names one file, not the decoy `ab.txt`.' - tools: {produce: {baseCommand: [sh, -c, 'echo literal > ''a{b,c}.txt''; echo decoy > ab.txt'], - outputs: {result: {type: File, outputBinding: {glob: 'a{b,c}.txt'}}}}} - outputs: {produce~result: {class: File, basename: 'a{b,c}.txt', contents: "literal\n"}} -- id: broadcast_from_conditional_step - why: A step reading a conditional step's output has a queue of one element, which every task of a scattered step - reads whole; the conditional step runs, and the string it made is its output. - tools: - gate: {baseCommand: [echo, 'yes'], inputs: {n: int}, stdout: said.txt, outputs: {said: {type: string, - outputBinding: {glob: said.txt, loadContents: true, outputEval: '$(self[0].contents)'}}}} - write_note: {baseCommand: echo, inputs: {text: {type: string, inputBinding: {position: 1}}, after: 'string?'}, - stdout: note.txt, outputs: {note: {type: File, outputBinding: {glob: note.txt}}}} - copy_note: {baseCommand: cp, arguments: [{position: 2, valueFrom: $(inputs.name).txt}], inputs: {note: {type: File, - inputBinding: {position: 1}}, name: string}, outputs: {copy: {type: File, outputBinding: {glob: $(inputs.name).txt}}}} - steps: | - - id: gate - in: {n: !ii 1} - out: [said: !& gated] - when: $(inputs.n > 0) - - id: write_note - in: {text: !ii shared, after: !* gated} - out: [note: !& noted] - - id: copy_note - scatter: [name] - scatterMethod: dotproduct - in: {note: !* noted, name: !ii [a, b, c]} - outputs: {gate~said: "yes\n", write_note~note: {class: File, basename: note.txt, contents: "shared\n"}, - copy_note~copy: [{class: File, basename: a.txt, contents: "shared\n"}, {class: File, basename: b.txt, - contents: "shared\n"}, {class: File, basename: c.txt, contents: "shared\n"}]} -- id: cuda_requirement_runs - why: The local executor accepts the accelerator directive and runs the task; the CUDA fields change nothing about - the Directory it makes. - tools: {gpu_tool: {$namespaces: {cwltool: 'http://commonwl.org/cwltool#'}, hints: [{class: 'cwltool:CUDARequirement', - cudaVersionMin: '11.4', cudaDeviceCountMin: 2, cudaComputeCapability: ['7.0', '8.0']}], baseCommand: [mkdir, made], - outputs: {result: {type: Directory, outputBinding: {glob: made}}}}} - outputs: {gpu_tool~result: {class: Directory, basename: made, link: false, contents: {}}} -- id: default_is_the_value_with_no_source - why: A step-input default is the value of an input with no source, and takes the place of a null one, from an absent - workflow input or a skipped step, but not of a given value. - tools: - skipped: &tool_maybe {baseCommand: printf, inputs: {text: {type: string, inputBinding: {position: 1}}, go: boolean}, - stdout: said.txt, outputs: {said: &said_text {type: string, outputBinding: {glob: said.txt, loadContents: true, - outputEval: '$(self[0].contents)'}}}} - unsourced: &tool_say_word {baseCommand: echo, inputs: {words: {type: string, inputBinding: {position: 1}}}, - stdout: out.txt, outputs: {line: {type: File, outputBinding: {glob: out.txt}}}} - missing: *tool_say_word - present: *tool_say_word - after_skip: *tool_say_word - inputs: {unset: 'string?', given: 'string?'} - params: {unset: null, given: g} - steps: | - - id: skipped - in: {text: !ii never, go: !ii false} - out: [said: !& skipped_said] - when: $(inputs.go) - - id: unsourced - in: {words: !cwl {default: d1}} - - id: missing - in: {words: !cwl {source: unset, default: d2}} - - id: present - in: {words: !cwl {source: given, default: d3}} - - id: after_skip - in: {words: !cwl {source: !* skipped_said, default: d4}} - outputs: {skipped~said: null, unsourced~line: {class: File, basename: out.txt, contents: "d1\n"}, - missing~line: {class: File, basename: out.txt, contents: "d2\n"}, - present~line: {class: File, basename: out.txt, contents: "g\n"}, - after_skip~line: {class: File, basename: out.txt, contents: "d4\n"}} -- id: entry_name_collision-entry-and-staged-input - why: &why_entry_name_collision cp and ln would make the entry inside the directory holding its name, so the task - stops, saying so. - tools: {mix: {requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.a), writable: true}]}}, - baseCommand: ls, inputs: {a: {type: Directory}, b: {type: Directory, inputBinding: {position: 1}}}, - stdout: listing.txt, outputs: {listing: {type: File, outputBinding: {glob: listing.txt}}}}} - steps: &steps_entry_name_collision | - - id: mix - in: {a: !ii one/data, b: !ii two/data} - files: &files_entry_name_collision {one/data/one.txt: one, two/data/two.txt: two} - fails: 'InitialWorkDirRequirement entry already exists in the task directory: data' -- id: entry_name_collision-two-entries - why: *why_entry_name_collision - tools: {mix: {requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.a), writable: true}, - $(inputs.b)]}}, baseCommand: ls, inputs: {a: {type: Directory}, b: {type: Directory, inputBinding: {position: 1}}}, - stdout: listing.txt, outputs: {listing: {type: File, outputBinding: {glob: listing.txt}}}}} - steps: *steps_entry_name_collision - files: *files_entry_name_collision - fails: 'InitialWorkDirRequirement entry already exists in the task directory: data' -- id: fanout_with_resources - why: One output feeds two steps, each of which cats it whole, under a process that requests cpus and memory. - tools: - produce: {requirements: {ResourceRequirement: {coresMin: 2, ramMin: 64}}, baseCommand: [printf, '%s', fanout], - stdout: data.txt, outputs: {result: {type: File, outputBinding: {glob: data.txt}}}} - consume_a: {baseCommand: cat, inputs: {source: {type: File, inputBinding: {position: 1}}}, stdout: a.txt, - outputs: {result: {type: File, outputBinding: {glob: a.txt}}}} - consume_b: {baseCommand: cat, inputs: {source: {type: File, inputBinding: {position: 1}}}, stdout: b.txt, - outputs: {result: {type: File, outputBinding: {glob: b.txt}}}} - steps: | - - id: produce - out: [result: !& data] - - id: consume_a - in: {source: !* data} - - id: consume_b - in: {source: !* data} - rendered: {contains: [cpus 2, memory "64 MB"]} - outputs: {produce~result: {class: File, basename: data.txt, contents: fanout}, consume_a~result: {class: File, - basename: a.txt, contents: fanout}, consume_b~result: {class: File, basename: b.txt, contents: fanout}} -- id: four_step_adapters - why: The checked-in echo adapters print their message, and echo_3 its three joined into one word, each to its stdout. - steps: | - - {id: emit_single_1, run: echo, in: {message: !ii Sophios reaches Nextflow}} - - {id: emit_triplet_1, run: echo_3, in: {message1: !ii spaces remain, message2: !ii one, message3: !ii argument}} - - {id: emit_single_2, run: echo, in: {message: !ii a literal costs $5}} - - {id: emit_triplet_2, run: echo_3, in: {message1: !ii literal, message2: !ii '&&', - message3: !ii text is not shell syntax}} - outputs: {emit_single_1~stdout: {class: File, basename: stdout, contents: "Sophios reaches Nextflow\n"}, - emit_triplet_1~stdout: {class: File, basename: stdout, contents: "spaces remain one argument\n"}, - emit_single_2~stdout: {class: File, basename: stdout, contents: "a literal costs $5\n"}, - emit_triplet_2~stdout: {class: File, basename: stdout, contents: "literal && text is not shell syntax\n"}} -- id: gathered_rescatter_broadcast_file - why: A workflow input is one value, passed to every job of a scattered step, in the order CWL scatters. - tools: - echo_item: {baseCommand: echo, inputs: {item: {type: string, inputBinding: {position: 1}}}, stdout: a.txt, - outputs: {out: {type: File, outputBinding: {glob: a.txt}}}} - cat_pair: {baseCommand: cat, inputs: {f: {type: File, inputBinding: {position: 1}}, r: {type: File, - inputBinding: {position: 2}}}, stdout: b.txt, outputs: {out: {type: File, outputBinding: {glob: b.txt}}}} - steps: | - - id: echo_item - scatter: [item] - scatterMethod: dotproduct - in: {item: !ii ['1', '2', '3']} - out: [out: !& items] - - id: cat_pair - scatter: [f] - scatterMethod: dotproduct - in: {f: !* items, r: !ii ref.txt} - files: {ref.txt: "REF\n"} - outputs: {echo_item~out: [{class: File, basename: a.txt, contents: "1\n"}, {class: File, basename: a.txt, - contents: "2\n"}, {class: File, basename: a.txt, contents: "3\n"}], cat_pair~out: [{class: File, basename: b.txt, - contents: "1\nREF\n"}, {class: File, basename: b.txt, contents: "2\nREF\n"}, {class: File, basename: b.txt, - contents: "3\nREF\n"}]} -- id: gated_chain-queue-first - why: &why_gated_chain A three-operand `when` over an upstream output, a parameter and an absent optional runs when - all hold, whichever input its process declares first, and with an array input the command sees whole; a skipped - upstream or a false parameter skips it. - tools: &tools_gated_chain_first - up: &tool_up {baseCommand: echo, arguments: [{position: 1, valueFrom: ok}], inputs: {go: boolean}, stdout: out.txt, - outputs: {result: &text_result {type: string, outputBinding: {glob: out.txt, loadContents: true, - outputEval: '$(self[0].contents)'}}}} - gated: {baseCommand: echo, stdout: out.txt, outputs: {result: *text_result}, inputs: {prev: 'string?', flag: boolean, - xs: {type: 'int[]', inputBinding: {position: 1}}, maybe: 'int?'}} - inputs: &inputs_gated_chain {go: boolean, flag: boolean, maybe: 'int?', xs: 'int[]'} - params: ¶ms_gated_chain {go: true, flag: true, xs: [1, 2, 3]} - steps: &steps_gated_chain | - - id: up - in: {go: !cwl {source: go}} - out: [result: !& upped] - when: $(inputs.go) - - id: gated - in: - prev: !* upped - flag: !cwl {source: flag} - xs: !cwl {source: xs} - maybe: !cwl {source: maybe} - when: $(inputs.prev !== null && inputs.flag && inputs.maybe === null) - outputs: {up~result: "ok\n", gated~result: "1 2 3\n"} -- id: gated_chain-queue-last - why: *why_gated_chain - tools: - up: *tool_up - gated: {baseCommand: echo, stdout: out.txt, outputs: {result: *text_result}, inputs: {flag: boolean, - xs: {type: 'int[]', inputBinding: {position: 1}}, maybe: 'int?', prev: 'string?'}} - inputs: *inputs_gated_chain - params: *params_gated_chain - steps: *steps_gated_chain - outputs: {up~result: "ok\n", gated~result: "1 2 3\n"} -- id: gated_chain-skipped-upstream - why: *why_gated_chain - tools: *tools_gated_chain_first - inputs: *inputs_gated_chain - params: {go: false, flag: true, xs: [1, 2, 3]} - steps: *steps_gated_chain - outputs: {up~result: null, gated~result: null} -- id: gated_chain-false-parameter - why: *why_gated_chain - tools: *tools_gated_chain_first - inputs: *inputs_gated_chain - params: {go: true, flag: false, xs: [1, 2, 3]} - steps: *steps_gated_chain - outputs: {up~result: "ok\n", gated~result: null} -- id: golden_path - why: touch makes an empty file, inferred into cp, which copies it. - tools: - touch_file: {baseCommand: touch, inputs: {filename: {type: string, inputBinding: {position: 1}}}, - outputs: {result: {type: File, outputBinding: {glob: $(inputs.filename)}}}} - copy_file: &tool_copy_file {baseCommand: cp, arguments: [{position: 2, valueFrom: copy.txt}], - inputs: {source: {type: File, inputBinding: {position: 1}}}, outputs: {result: {type: File, - outputBinding: {glob: copy.txt}}}} - steps: | - - id: touch_file - in: {filename: !ii message.txt} - - id: copy_file - outputs: {touch_file~result: {class: File, basename: message.txt, contents: ''}, copy_file~result: {class: File, - basename: copy.txt, contents: ''}} -- id: iwdr_own_basename - why: The bare $(inputs.) listing makes the entry, which the command reads. - tools: - write_source: *tool_write_source - stage_own_basename: {requirements: {InitialWorkDirRequirement: {listing: [$(inputs.source)]}}, baseCommand: cat, - inputs: {source: {type: File, inputBinding: {position: 1}}}, stdout: out.txt, outputs: {result: {type: File, - outputBinding: {glob: out.txt}}}} - steps: | - - id: write_source - in: {message: !ii own basename staging} - - id: stage_own_basename - outputs: {write_source~result: {class: File, basename: lines.txt, contents: "own basename staging\n"}, - stage_own_basename~result: {class: File, basename: out.txt, contents: "own basename staging\n"}} -- id: iwdr_rename - why: A literal entryname stages the file under the name the command hard-codes. - tools: - write_source: {baseCommand: echo, inputs: {message: {type: string, inputBinding: {position: 1}}}, - stdout: original_name.txt, outputs: {result: {type: File, outputBinding: {glob: original_name.txt}}}} - stage_and_read: {requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), - entryname: renamed_by_iwdr.txt}]}}, baseCommand: cat, arguments: [renamed_by_iwdr.txt], - inputs: {source: {type: File}}, stdout: out.txt, outputs: {result: {type: File, outputBinding: {glob: out.txt}}}} - steps: | - - id: write_source - in: {message: !ii iwdr staged content} - - id: stage_and_read - outputs: {write_source~result: {class: File, basename: original_name.txt, contents: "iwdr staged content\n"}, - stage_and_read~result: {class: File, basename: out.txt, contents: "iwdr staged content\n"}} -- id: link_merge_joins_the_sources_in_order - why: A step input of several sources joins them in order, flattened over a scattered step's Files and a lone one's, - or nested over scalar Files, and a lone merge_nested source is an array of one. - tools: - write_each: &tool_write_name {baseCommand: echo, inputs: {name: {type: string, inputBinding: {position: 1}}}, - stdout: out.txt, outputs: {file: {type: File, outputBinding: {glob: out.txt}}}} - write_one: *tool_write_name - write_two: *tool_write_name - cat_flat: &tool_cat {baseCommand: cat, inputs: {files: {type: 'File[]', inputBinding: {position: 1}}}, - stdout: all.txt, outputs: {line: {type: File, outputBinding: {glob: all.txt}}}} - cat_nested: *tool_cat - cat_single: *tool_cat - say_nested: &tool_say {baseCommand: echo, inputs: {words: {type: 'string[]', inputBinding: {position: 1}}}, - stdout: out.txt, outputs: {line: {type: File, outputBinding: {glob: out.txt}}}} - say_single: *tool_say - inputs: {x: {type: string}, y: {type: string}} - params: {x: x, y: y z} - steps: | - - id: write_each - scatter: [name] - scatterMethod: dotproduct - in: {name: !ii [a, b]} - out: [file: !& each] - - id: write_one - in: {name: !ii c} - out: [file: !& one] - - id: write_two - in: {name: !ii d} - out: [file: !& two] - - id: cat_flat - in: - files: !cwl {source: [!* each, !* one], linkMerge: merge_flattened} - - id: cat_nested - in: - files: !cwl {source: [!* two, !* one]} - - id: cat_single - in: - files: !cwl {source: [!* one], linkMerge: merge_nested} - - id: say_nested - in: - words: !cwl {source: [x, y]} - - id: say_single - in: - words: !cwl {source: [x], linkMerge: merge_nested} - outputs: {write_each~file: [{class: File, basename: out.txt, contents: "a\n"}, {class: File, basename: out.txt, - contents: "b\n"}], write_one~file: {class: File, basename: out.txt, contents: "c\n"}, write_two~file: {class: File, - basename: out.txt, contents: "d\n"}, cat_flat~line: {class: File, basename: all.txt, contents: "a\nb\nc\n"}, - cat_nested~line: {class: File, basename: all.txt, contents: "d\nc\n"}, cat_single~line: {class: File, - basename: all.txt, contents: "c\n"}, say_nested~line: {class: File, basename: out.txt, contents: "x y z\n"}, - say_single~line: {class: File, basename: out.txt, contents: "x\n"}} -- id: literal_dollar_and_backtick_globs - why: A `$` before no `(` or `{` is text, and a backtick beside a reference is text, so each glob names the file made. - A plain input reference can carry a pattern, so globbing stays on. - tools: - literal: {baseCommand: [touch, out$name.txt], outputs: {result: {type: File, outputBinding: {glob: out$name.txt}}}} - mixed: {baseCommand: touch, inputs: {name: {type: string}}, arguments: ['`$(inputs.name).txt'], - outputs: {result: {type: File, outputBinding: {glob: '`$(inputs.name).txt'}}}} - steps: | - - id: literal - - id: mixed - in: {name: !ii report} - rendered: {contains: ['path ''out$name.txt'', emit: result', 'path "`${name}.txt", arity: ''1'', emit: result']} - outputs: {literal~result: {class: File, basename: out$name.txt, contents: ''}, mixed~result: {class: File, - basename: '`report.txt', contents: ''}} -- id: nested_workflow - why: A one-level subworkflow runs the copy its inlined form declares, of the message written outside it. - tools: - write_source: {baseCommand: echo, inputs: {message: {type: string, inputBinding: {position: 1}}}, - stdout: message.txt, outputs: {result: {type: File, outputBinding: {glob: message.txt}}}} - copy_file: *tool_copy_file - steps: | - - id: write_source - in: {message: !ii nested composition} - out: [result: !& written] - - id: child.wic - in: {source: !* written} - children: - child: | - inputs: {source: {type: File}} - steps: - - id: copy_file - in: {source: source} - outputs: {write_source~result: {class: File, basename: message.txt, contents: "nested composition\n"}, - child~copy_file~result: {class: File, basename: copy.txt, contents: "nested composition\n"}} -- id: optional_output-absent - why: &why_optional_output A File? output is null for no match and the file for one; more fail the run, as in CWL. - tools: {maybe: {baseCommand: 'true', outputs: {o: {type: 'File?', outputBinding: {glob: maybe.txt}}}}} - outputs: {maybe~o: null} -- id: optional_output-pattern-none - why: *why_optional_output - tools: {maybe: {baseCommand: [touch, unmatched.txt], outputs: {o: {type: 'File?', outputBinding: {glob: '*.log'}}}}} - outputs: {maybe~o: null} -- id: optional_output-pattern-one - why: *why_optional_output - tools: {maybe: {baseCommand: [touch, unmatched.txt, a.log], outputs: {o: {type: 'File?', - outputBinding: {glob: '*.log'}}}}} - outputs: {maybe~o: {class: File, basename: a.log, contents: ''}} -- id: optional_output-pattern-two - why: *why_optional_output - tools: {maybe: {baseCommand: [touch, unmatched.txt, a.log, b.log], outputs: {o: {type: 'File?', - outputBinding: {glob: '*.log'}}}}} - fails: matched 2 files; it takes at most one -- id: optional_output-present - why: *why_optional_output - tools: {maybe: {baseCommand: [touch, maybe.txt], outputs: {o: {type: 'File?', outputBinding: {glob: maybe.txt}}}}} - outputs: {maybe~o: {class: File, basename: maybe.txt, contents: ''}} -- id: pattern_glob_matches_iwdr_entry - why: A pattern glob, or a glob of the input's own basename, captures the entry the task made, as a CWL glob does. - tools: - write_source: {baseCommand: echo, inputs: {message: {type: string, inputBinding: {position: 1}}}, stdout: lines.txt, - outputs: {result: {type: File, outputBinding: {glob: lines.txt}}}} - own: {requirements: {InitialWorkDirRequirement: {listing: [$(inputs.source)]}}, baseCommand: 'true', - inputs: {source: File}, outputs: {wild: {type: File, outputBinding: {glob: lines*}}, same: {type: File, - outputBinding: {glob: $(inputs.source.basename)}}}} - renamed: {requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), - entryname: renamed.txt}]}}, baseCommand: 'true', inputs: {source: File}, outputs: {wild: {type: File, - outputBinding: {glob: renamed*}}}} - steps: | - - id: write_source - in: {message: !ii entry content} - out: [result: !& written] - - id: own - in: {source: !* written} - - id: renamed - in: {source: !* written} - outputs: {write_source~result: {class: File, basename: lines.txt, contents: "entry content\n", link: false}, - own~wild: {class: File, basename: lines.txt, contents: "entry content\n", link: true}, - own~same: {class: File, basename: lines.txt, contents: "entry content\n", link: true}, - renamed~wild: {class: File, basename: renamed.txt, contents: "entry content\n", link: true}} -- id: pick_value_picks_from_the_joined_sources - why: first_non_null, the_only_non_null and all_non_null pick among a joined list of workflow inputs and conditional - steps' outputs, skipping the null of an absent input and of a skipped step. - tools: - skipped: *tool_maybe - ran: *tool_maybe - first: *tool_say_word - only: *tool_say_word - every: {baseCommand: echo, inputs: {words: {type: 'string[]', inputBinding: {position: 1}}}, stdout: out.txt, - outputs: {line: {type: File, outputBinding: {glob: out.txt}}}} - inputs: {unset: 'string?', given: 'string?'} - params: {unset: null, given: x} - steps: | - - id: skipped - in: {text: !ii never, go: !ii false} - out: [said: !& skipped_said] - when: $(inputs.go) - - id: ran - in: {text: !ii only, go: !ii true} - out: [said: !& ran_said] - when: $(inputs.go) - - id: first - in: {words: !cwl {source: [unset, !* skipped_said, given], pickValue: first_non_null}} - - id: only - in: {words: !cwl {source: [!* skipped_said, !* ran_said], pickValue: the_only_non_null}} - - id: every - in: {words: !cwl {source: [given, !* skipped_said, !* ran_said, unset], pickValue: all_non_null}} - outputs: {skipped~said: null, ran~said: only, first~line: {class: File, basename: out.txt, contents: "x\n"}, - only~line: {class: File, basename: out.txt, contents: "only\n"}, - every~line: {class: File, basename: out.txt, contents: "x only\n"}} -- id: pick_value_finding_no_one_value-first_non_null-of-none - why: &why_pick_none A pickValue that finds no one value stops the run before the step runs, naming the count it found. - tools: {pick: *tool_say_word} - inputs: {a: 'string?', b: 'string?'} - params: {a: null, b: null} - steps: | - - id: pick - in: {words: !cwl {source: [a, b], pickValue: first_non_null}} - never: [out.txt] - fails: 'Sophios step input pick.words: first_non_null finds 0 values that are not null' -- id: pick_value_finding_no_one_value-the_only_non_null-of-none - why: *why_pick_none - tools: {pick: *tool_say_word} - inputs: {a: 'string?', b: 'string?'} - params: {a: null, b: null} - steps: | - - id: pick - in: {words: !cwl {source: [a, b], pickValue: the_only_non_null}} - never: [out.txt] - fails: 'Sophios step input pick.words: the_only_non_null finds 0 values that are not null' -- id: pick_value_finding_no_one_value-the_only_non_null-of-two - why: *why_pick_none - tools: {pick: *tool_say_word} - inputs: {a: 'string?', b: 'string?'} - params: {a: x, b: y} - steps: | - - id: pick - in: {words: !cwl {source: [a, b], pickValue: the_only_non_null}} - never: [out.txt] - fails: 'Sophios step input pick.words: the_only_non_null finds 2 values that are not null' -- id: shipped_append_appends_the_message_as_written - why: 'The shipped `append.cwl` appends one line holding exactly the message, whose shell syntax and backslashes are - text: a separator, a run of spaces, a quote, a substitution, a glob; the file it was given keeps its contents.' - steps: | - - id: append - in: {file: !ii greeting.txt, str: !ii "Hello; it's $(echo substituted) * a\\tb\\nc 100%s"} - files: {greeting.txt: "first line\n"} - outputs: {append~file: {class: File, basename: greeting.txt, - contents: "first line\nHello; it's $(echo substituted) * a\\tb\\nc 100%s\n"}} -- id: shell_redirect_literal - why: An approved shellQuote false literal reaches the shell as real redirect syntax; printf writes its one quoted - word. - tools: {shell_redirect: {requirements: {ShellCommandRequirement: {}}, baseCommand: printf, arguments: [{position: 1, - valueFrom: '%s'}, {position: 2, valueFrom: payload; not a separate command}, {position: 3, valueFrom: '>>', - shellQuote: false}, {position: 4, valueFrom: redirected.txt}], outputs: {result: {type: File, - outputBinding: {glob: redirected.txt}}}}} - outputs: {shell_redirect~result: {class: File, basename: redirected.txt, contents: payload; not a separate command}} -- id: single_capture_literal_braces - why: A CWL glob has no brace expansion, so the one capture is the file named with braces. - tools: {write_one: {baseCommand: echo, inputs: {message: {type: string, inputBinding: {position: 1}}}, - stdout: 'out{1,2}.txt', outputs: {result: {type: File, outputBinding: {glob: 'out{1,2}.txt', - outputEval: '$(self[0])'}}}}} - steps: | - - id: write_one - in: {message: !ii one match only} - outputs: {write_one~result: {class: File, basename: 'out{1,2}.txt', contents: "one match only\n"}} -- id: single_capture_missing_fails - why: Zero matches of a declared single output fail the run, naming the glob, never an empty channel. - tools: {write_nothing: {baseCommand: 'true', inputs: {message: {type: string, inputBinding: {position: 1}}}, - outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0])'}}}}} - steps: | - - id: write_nothing - in: {message: !ii nothing is written} - fails: out.txt -- id: skipped_step_feeds_an_optional_input - why: A skipped step makes no task and a null output, and a step with an optional input reading it still runs. - tools: - produce: {baseCommand: [echo, produced], inputs: {n: int}, stdout: out.txt, outputs: {text: {type: string, - outputBinding: {glob: out.txt, loadContents: true, outputEval: '$(self[0].contents)'}}}} - consume: {baseCommand: [touch, done.txt], inputs: {maybe: 'string?'}, outputs: {done: {type: File, - outputBinding: {glob: done.txt}}}} - steps: | - - id: produce - in: {n: !ii 0} - out: [text: !& produced] - when: $(inputs.n > 0) - - id: consume - in: {maybe: !* produced} - outputs: {produce~text: null, consume~done: {class: File, basename: done.txt, contents: ''}} - never: [out.txt] -- id: stdout_of_every_shell_command - why: CWL redirects stdout for the whole shell command, not its last part, so both echoes land in out.txt. - tools: {two_commands: {requirements: {ShellCommandRequirement: {}}, baseCommand: echo, arguments: [{position: 1, - valueFrom: first}, {position: 2, valueFrom: ;, shellQuote: false}, {position: 3, valueFrom: echo}, {position: 4, - valueFrom: second}], stdout: out.txt, outputs: {result: {type: File, outputBinding: {glob: out.txt}}}}} - outputs: {two_commands~result: {class: File, basename: out.txt, contents: "first\nsecond\n"}} -- id: when_in_an_inlined_child - why: The inlined inner step keeps its condition and is skipped; the outer step still runs. - tools: {touch_n: {baseCommand: [touch, n.txt], inputs: {n: int}, outputs: {out: {type: File, - outputBinding: {glob: n.txt}}}}} - steps: | - - id: child.wic - - id: touch_n - in: {n: !ii 3} - children: - child: | - steps: - - id: touch_n - in: {n: !ii 3} - when: $(inputs.n > 5) - outputs: {child~touch_n~out: null, touch_n~out: {class: File, basename: n.txt, contents: ''}} -- id: when_non_finite_fails - why: A non-finite subexpression of a condition fails the run, naming the step, the expression and the subexpression. - tools: {c0: {baseCommand: [touch, c0.txt], inputs: {i: int}, outputs: {out: {type: File, - outputBinding: {glob: c0.txt}}}}} - steps: | - - id: c0 - in: {i: !ii 7} - when: $(inputs.i / (inputs.i - 7) > 0) - never: [c0.txt] - fails: 'Sophios expression c0 when ((inputs.i / (inputs.i - 7)) > 0): (inputs.i / (inputs.i - 7)) is Infinity' -- id: when_per_scatter_combination - why: The condition sees each invocation's scattered elements and the broadcast value; the gather keeps null where it - skips, whatever order the tasks finish in. - tools: {pair: {baseCommand: [sh, -c, 'sleep "$2"; printf %s-%s "$1" "$2"', pair], inputs: {item: {type: string, - inputBinding: {position: 1}}, tag: {type: string, inputBinding: {position: 2}}, skipped: string}, stdout: out.txt, - outputs: {line: {type: File, outputBinding: {glob: out.txt}}}}} - steps: | - - id: pair - scatter: [item, tag] - scatterMethod: dotproduct - in: {item: !ii [a, b, c], tag: !ii ['2', '1', '0'], skipped: !ii '1'} - when: $(inputs.tag !== inputs.skipped) - outputs: {pair~line: [{class: File, basename: out.txt, contents: a-2}, null, {class: File, basename: out.txt, - contents: c-0}]} -- id: when_per_scatter_invocation - why: The condition runs per invocation, and the gather keeps null at the skipped position. - tools: {pair: {baseCommand: printf, arguments: [{position: 0, valueFrom: '%s-%s'}], inputs: {a: {type: string, - inputBinding: {position: 1}}, b: {type: string, inputBinding: {position: 2}}}, stdout: out.txt, outputs: {line: { - type: File, outputBinding: {glob: out.txt}}}}} - steps: | - - id: pair - scatter: [a, b] - scatterMethod: dotproduct - in: {a: !ii [a, b, c], b: !ii [x, y, z]} - when: $(inputs.a !== 'b') - outputs: {pair~line: [{class: File, basename: out.txt, contents: a-x}, null, {class: File, basename: out.txt, - contents: c-z}]} -- id: wildcard_output-one - why: A scalar File output whose glob matches one file is that file; the tool declares its input in `T[]` shorthand. - tools: &tools_wildcard_output {make: {baseCommand: touch, inputs: {names: {type: 'string[]', - inputBinding: {position: 1}}}, outputs: {result: {type: File, outputBinding: {glob: '*.txt'}}}}} - steps: | - - id: make - in: {names: !ii [a.txt]} - outputs: {make~result: {class: File, basename: a.txt, contents: ''}} -- id: wildcard_output-several - why: A scalar File output whose glob matches several files fails the run, as cwltool does. - tools: *tools_wildcard_output - steps: | - - id: make - in: {names: !ii [a.txt, b.txt]} - fails: true -- id: writable_out_dir_entry - why: 'The image-workflows plugin shape: a writable entry is a copy the tool writes into, which its own-basename glob - captures, and the input it was copied from is left as it was.' - tools: {plugin: {requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.outDir), writable: true}]}}, - baseCommand: [sh, -c, printf written > "$2/result.txt", plugin], inputs: {outDir: {type: Directory, - inputBinding: {position: 1, prefix: --outDir}}}, outputs: {outDir: {type: Directory, - outputBinding: {glob: $(inputs.outDir.basename)}}}}} - steps: | - - id: plugin - in: {outDir: !ii plugin_out} - files: {plugin_out/keep.txt: "kept\n"} - outputs: {plugin~outDir: {class: Directory, basename: plugin_out, link: false, contents: {keep.txt: "kept\n", - result.txt: written}}} diff --git a/tests/core/data/nextflow/runs/commands/cat_file.cwl b/tests/core/data/nextflow/runs/commands/cat_file.cwl new file mode 100644 index 000000000..deb866cda --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/cat_file.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print the source to read.txt. +baseCommand: cat +inputs: + source: + type: File + inputBinding: {position: 1} +stdout: read.txt +outputs: + result: + type: File + outputBinding: {glob: read.txt} diff --git a/tests/core/data/nextflow/runs/commands/copy_file.cwl b/tests/core/data/nextflow/runs/commands/copy_file.cwl new file mode 100644 index 000000000..f3a2e8da8 --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/copy_file.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Copy the source to copy.txt. +baseCommand: cp +inputs: + source: + type: File + inputBinding: {position: 1} +arguments: +- {position: 2, valueFrom: copy.txt} +outputs: + result: + type: File + outputBinding: {glob: copy.txt} diff --git a/tests/core/data/nextflow/runs/commands/count_bytes.cwl b/tests/core/data/nextflow/runs/commands/count_bytes.cwl new file mode 100644 index 000000000..3a28da9fb --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/count_bytes.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Count the bytes of the source into count.txt. +baseCommand: [wc, -c] +inputs: + source: File +stdin: $(inputs.source.path) +stdout: count.txt +outputs: + result: + type: File + outputBinding: {glob: count.txt} diff --git a/tests/core/data/nextflow/runs/commands/expected.yaml b/tests/core/data/nextflow/runs/commands/expected.yaml new file mode 100644 index 000000000..1722632b0 --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/expected.yaml @@ -0,0 +1,20 @@ +# Every output of workflow.wic, by step and port, in the order of its steps. +outputs: + touch_file~result: {class: File, basename: message.txt, contents: ""} + copy_file~result: {class: File, basename: copy.txt, contents: ""} + emit~stdout: {class: File, basename: stdout, contents: "mixed construction, one backend\n"} + copy_emitted~result: {class: File, basename: copy.txt, contents: "mixed construction, one backend\n"} + count_bytes~result: {class: File, basename: count.txt, contents: "32\n"} + three_words~stdout: {class: File, basename: stdout, contents: "spaces remain one argument\n"} + a_dollar~stdout: {class: File, basename: stdout, contents: "a literal costs $5\n"} + an_ampersand~stdout: {class: File, basename: stdout, contents: "literal && text is not shell syntax\n"} + append~file: {class: File, basename: greeting.txt, + contents: "first line\nHello; it's $(echo substituted) * a\\tb\\nc 100%s\n"} + shell_redirect~result: {class: File, basename: redirected.txt, contents: "payload; not a separate command"} + three_commands~result: {class: File, basename: out.txt, contents: "first\nsecond\n"} + three_commands~errors: {class: File, basename: err.txt, contents: "third\n"} + print_bindings~result: {class: File, basename: bindings.txt, + contents: "hello there\n-v\n--ratio\n0.5\n1.25\n--tag\na b\n--label=x\n2.5\n"} + produce~result: {class: File, basename: data.txt, contents: fanout} + read_once~result: {class: File, basename: read.txt, contents: fanout} + read_again~result: {class: File, basename: read.txt, contents: fanout} diff --git a/tests/core/data/nextflow/runs/commands/greeting.txt b/tests/core/data/nextflow/runs/commands/greeting.txt new file mode 100644 index 000000000..08fe2720d --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/greeting.txt @@ -0,0 +1 @@ +first line diff --git a/tests/core/data/nextflow/runs/commands/print_bindings.cwl b/tests/core/data/nextflow/runs/commands/print_bindings.cwl new file mode 100644 index 000000000..5941e932a --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/print_bindings.cwl @@ -0,0 +1,20 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print the variable GREETING, then each argument the bindings make, one per line, into bindings.txt. +requirements: + EnvVarRequirement: + envDef: {GREETING: hello there} +baseCommand: [sh, -c, 'printf "%s\n" "$GREETING" "$@"', sh] +inputs: + verbose: {type: boolean, inputBinding: {position: 1, prefix: -v}} + quiet: {type: boolean, inputBinding: {position: 2, prefix: -q}} + ratios: {type: 'float[]', inputBinding: {position: 3, prefix: --ratio}} + tag: {type: 'string?', inputBinding: {position: 4, prefix: --tag}} + label: {type: 'string?', inputBinding: {position: 5, prefix: --label=, separate: false}} + unset: {type: 'string?', inputBinding: {position: 6, prefix: --unset}} + scale: {type: float, inputBinding: {position: 7}} +stdout: bindings.txt +outputs: + result: + type: File + outputBinding: {glob: bindings.txt} diff --git a/tests/core/data/nextflow/runs/commands/produce.cwl b/tests/core/data/nextflow/runs/commands/produce.cwl new file mode 100644 index 000000000..e9ea12c07 --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/produce.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write the word fanout, with no newline, to data.txt, asking for 2 cores and 64 MiB. +requirements: + ResourceRequirement: + coresMin: 2 + ramMin: 64 +baseCommand: [printf, '%s', fanout] +inputs: {} +stdout: data.txt +outputs: + result: + type: File + outputBinding: {glob: data.txt} diff --git a/tests/core/data/nextflow/runs/commands/shell_redirect.cwl b/tests/core/data/nextflow/runs/commands/shell_redirect.cwl new file mode 100644 index 000000000..0969a92ea --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/shell_redirect.cwl @@ -0,0 +1,16 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print one word holding a semicolon, appended to redirected.txt by the shell. +requirements: + ShellCommandRequirement: {} +baseCommand: printf +arguments: +- {position: 1, valueFrom: '%s'} +- {position: 2, valueFrom: payload; not a separate command} +- {position: 3, valueFrom: '>>', shellQuote: false} +- {position: 4, valueFrom: redirected.txt} +inputs: {} +outputs: + result: + type: File + outputBinding: {glob: redirected.txt} diff --git a/tests/core/data/nextflow/runs/commands/three_commands.cwl b/tests/core/data/nextflow/runs/commands/three_commands.cwl new file mode 100644 index 000000000..68741444a --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/three_commands.cwl @@ -0,0 +1,27 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Run three echo commands in one shell command line; out.txt takes the output of the first two, err.txt the third's. +requirements: + ShellCommandRequirement: {} +baseCommand: echo +arguments: +- {position: 1, valueFrom: first} +- {position: 2, valueFrom: ;, shellQuote: false} +- {position: 3, valueFrom: echo} +- {position: 4, valueFrom: second} +- {position: 5, valueFrom: ;, shellQuote: false} +- {position: 6, valueFrom: echo} +- {position: 7, valueFrom: third} +- {position: 8, valueFrom: '>&2', shellQuote: false} +- {position: 9, valueFrom: ;, shellQuote: false} +- {position: 10, valueFrom: 'true'} +inputs: {} +stdout: out.txt +stderr: err.txt +outputs: + result: + type: File + outputBinding: {glob: out.txt} + errors: + type: File + outputBinding: {glob: err.txt} diff --git a/tests/core/data/nextflow/runs/commands/touch_file.cwl b/tests/core/data/nextflow/runs/commands/touch_file.cwl new file mode 100644 index 000000000..dc75d6a76 --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/touch_file.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make an empty file of the name given. +baseCommand: touch +inputs: + filename: + type: string + inputBinding: {position: 1} +outputs: + result: + type: File + outputBinding: {glob: $(inputs.filename)} diff --git a/tests/core/data/nextflow/runs/commands/workflow.wic b/tests/core/data/nextflow/runs/commands/workflow.wic new file mode 100644 index 000000000..5481c1ce3 --- /dev/null +++ b/tests/core/data/nextflow/runs/commands/workflow.wic @@ -0,0 +1,50 @@ +# Commands: what reaches a tool's command line, and where its output goes. The tools echo, echo_3 and append are the +# ones Sophios ships in cwl_adapters; the others are beside this file. +steps: +# No edge is written between these two: touch_file's File is inferred into copy_file. +- id: touch_file + in: {filename: !ii message.txt} +- id: copy_file + +# A shipped tool's output read by two tools written here. +- id: emit + run: echo + in: {message: !ii 'mixed construction, one backend'} + out: [stdout: !& emitted] +- id: copy_emitted + run: copy_file + in: {source: !* emitted} +- id: count_bytes + in: {source: !* emitted} + +# Text is given to the command as written: spaces stay in one argument, and shell syntax is not run. +- id: three_words + run: echo_3 + in: {message1: !ii spaces remain, message2: !ii one, message3: !ii argument} +- id: a_dollar + run: echo + in: {message: !ii a literal costs $5} +- id: an_ampersand + run: echo_3 + in: {message1: !ii literal, message2: !ii '&&', message3: !ii text is not shell syntax} +- id: append # one line is added to its own copy of greeting.txt, which is left as it was + in: {file: !ii greeting.txt, str: !ii "Hello; it's $(echo substituted) * a\\tb\\nc 100%s"} + +# shellQuote: false is the one way to write shell syntax, and stdout and stderr take the whole command's output. +- id: shell_redirect # redirected.txt holds the one quoted word +- id: three_commands # out.txt holds the first two lines, err.txt the third + +# Bindings: a true flag is its prefix and a false one nothing; an array takes its prefix once; an optional input is +# its prefix and value, apart or joined, or nothing when it has none; a float is printed as written. +- id: print_bindings + in: {verbose: !ii true, quiet: !ii false, ratios: !ii [0.5, 1.25], tag: !ii a b, label: !ii x, scale: !ii 2.5} + +# One output read by two steps, from a tool that asks for 2 cores and 64 MiB. +- id: produce + out: [result: !& data] +- id: read_once + run: cat_file + in: {source: !* data} +- id: read_again + run: cat_file + in: {source: !* data} diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/cat_pair.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/cat_pair.cwl new file mode 100644 index 000000000..17889c59b --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/cat_pair.cwl @@ -0,0 +1,16 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Concatenate two files, `f` then `r`, into b.txt. +baseCommand: cat +inputs: + f: + type: File + inputBinding: {position: 1} + r: + type: File + inputBinding: {position: 2} +stdout: b.txt +outputs: + out: + type: File + outputBinding: {glob: b.txt} diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/copy_note.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/copy_note.cwl new file mode 100644 index 000000000..0eea82f6d --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/copy_note.cwl @@ -0,0 +1,15 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Copy the note to .txt. +baseCommand: cp +inputs: + note: + type: File + inputBinding: {position: 1} + name: string +arguments: +- {position: 2, valueFrom: $(inputs.name).txt} +outputs: + copy: + type: File + outputBinding: {glob: $(inputs.name).txt} diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/echo_item.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/echo_item.cwl new file mode 100644 index 000000000..f9f87ffed --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/echo_item.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write one item to a.txt. +baseCommand: echo +inputs: + item: + type: string + inputBinding: {position: 1} +stdout: a.txt +outputs: + out: + type: File + outputBinding: {glob: a.txt} diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/expected.yaml b/tests/core/data/nextflow/runs/conditions_and_scatter/expected.yaml new file mode 100644 index 000000000..315ae2169 --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/expected.yaml @@ -0,0 +1,46 @@ +# Every output of workflow.wic, by step and port, in the order of its steps. +outputs: + up~result: "ok\n" + up_skipped~result: null + counted~result: "ok\n" + uncounted~result: null + carried~result: "ok\n" + gated~result: "1 2 3\n" + gated_prev_last~result: "1 2 3\n" + gated_after_skip~result: null + gated_flag_false~result: null + after_skip~done: {class: File, basename: done.txt, contents: ""} + write_note~note: {class: File, basename: note.txt, contents: "shared\n"} + copy_note~copy: + - {class: File, basename: a.txt, contents: "shared\n"} + - {class: File, basename: b.txt, contents: "shared\n"} + - {class: File, basename: c.txt, contents: "shared\n"} + echo_item~out: + - {class: File, basename: a.txt, contents: "1\n"} + - {class: File, basename: a.txt, contents: "2\n"} + - {class: File, basename: a.txt, contents: "3\n"} + cat_pair~out: + - {class: File, basename: b.txt, contents: "1\nREF\n"} + - {class: File, basename: b.txt, contents: "2\nREF\n"} + - {class: File, basename: b.txt, contents: "3\nREF\n"} + cat_pair_flat~out: + - {class: File, basename: b.txt, contents: "1\nREF\n"} + - {class: File, basename: b.txt, contents: "2\nREF\n"} + - {class: File, basename: b.txt, contents: "3\nREF\n"} + cat_pair_nested~out: + - {class: File, basename: b.txt, contents: "1\nREF\n"} + - {class: File, basename: b.txt, contents: "2\nREF\n"} + - {class: File, basename: b.txt, contents: "3\nREF\n"} + pair_nested~line: + - - {class: File, basename: out.txt, contents: a-x} + - {class: File, basename: out.txt, contents: a-y} + - - {class: File, basename: out.txt, contents: b-x} + - {class: File, basename: out.txt, contents: b-y} + pair_unless_b~line: + - {class: File, basename: out.txt, contents: "a-x"} + - null + - {class: File, basename: out.txt, contents: "c-z"} + pair_unless_skipped~line: + - {class: File, basename: out.txt, contents: "a-0.2"} + - null + - {class: File, basename: out.txt, contents: "c-0"} diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/job.yml b/tests/core/data/nextflow/runs/conditions_and_scatter/job.yml new file mode 100644 index 000000000..74ef44cca --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/job.yml @@ -0,0 +1,3 @@ +go: true +no_go: false +xs: [1, 2, 3] diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/never_runs.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/never_runs.cwl new file mode 100644 index 000000000..32519e75d --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/never_runs.cwl @@ -0,0 +1,15 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Fail. A step running this is one its condition must skip, so a run that starts it does not complete. +baseCommand: [sh, -c, 'echo "a skipped step was started" >&2; exit 1'] +inputs: + go: boolean + n: int +stdout: out.txt +outputs: + result: + type: string + outputBinding: + glob: out.txt + loadContents: true + outputEval: $(self[0].contents) diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if.cwl new file mode 100644 index 000000000..e75b8161f --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if.cwl @@ -0,0 +1,19 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print the numbers on one line; `prev`, `flag` and `maybe` are read only by the condition of the step. +baseCommand: echo +inputs: + prev: string? + flag: boolean + xs: + type: int[] + inputBinding: {position: 1} + maybe: int? +stdout: out.txt +outputs: + result: + type: string + outputBinding: + glob: out.txt + loadContents: true + outputEval: $(self[0].contents) diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if_prev_last.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if_prev_last.cwl new file mode 100644 index 000000000..d548cbcd0 --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if_prev_last.cwl @@ -0,0 +1,19 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: numbers_if, declaring `prev`, the input an upstream step gives, after the others. +baseCommand: echo +inputs: + flag: boolean + xs: + type: int[] + inputBinding: {position: 1} + maybe: int? + prev: string? +stdout: out.txt +outputs: + result: + type: string + outputBinding: + glob: out.txt + loadContents: true + outputEval: $(self[0].contents) diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/pair.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/pair.cwl new file mode 100644 index 000000000..7919186ec --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/pair.cwl @@ -0,0 +1,18 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print first-second, with no newline, to out.txt. +baseCommand: printf +arguments: +- {position: 0, valueFrom: '%s-%s'} +inputs: + first: + type: string + inputBinding: {position: 1} + second: + type: string + inputBinding: {position: 2} +stdout: out.txt +outputs: + line: + type: File + outputBinding: {glob: out.txt} diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/pair_after_sleeping.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/pair_after_sleeping.cwl new file mode 100644 index 000000000..c70ef40a4 --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/pair_after_sleeping.cwl @@ -0,0 +1,17 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Sleep `seconds`, then print first-seconds to out.txt; `skipped` is read only by the condition of the step. +baseCommand: [sh, -c, 'sleep "$2"; printf %s-%s "$1" "$2"', pair] +inputs: + first: + type: string + inputBinding: {position: 1} + seconds: + type: string + inputBinding: {position: 2} + skipped: string +stdout: out.txt +outputs: + line: + type: File + outputBinding: {glob: out.txt} diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/ref.txt b/tests/core/data/nextflow/runs/conditions_and_scatter/ref.txt new file mode 100644 index 000000000..2963d6ade --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/ref.txt @@ -0,0 +1 @@ +REF diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/say_ok.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/say_ok.cwl new file mode 100644 index 000000000..4c637c2bf --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/say_ok.cwl @@ -0,0 +1,15 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print ok; `go` and `n` are read only by the condition of the step. +baseCommand: [echo, ok] +inputs: + go: boolean + n: int +stdout: out.txt +outputs: + result: + type: string + outputBinding: + glob: out.txt + loadContents: true + outputEval: $(self[0].contents) diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/touch_done.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/touch_done.cwl new file mode 100644 index 000000000..b6d660c45 --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/touch_done.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make done.txt, whatever `maybe` is, null included. +baseCommand: [touch, done.txt] +inputs: + maybe: string? +outputs: + done: + type: File + outputBinding: {glob: done.txt} diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/workflow.wic b/tests/core/data/nextflow/runs/conditions_and_scatter/workflow.wic new file mode 100644 index 000000000..83560a778 --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/workflow.wic @@ -0,0 +1,109 @@ +# Conditions and scatter: which steps run, what a skipped step leaves behind, and what each scatter job reads. +# A step that must be skipped runs never_runs, which fails the run if it is ever started. +inputs: + go: boolean # the job gives true + no_go: boolean # the job gives false + maybe: int? # no value is given for it + xs: int[] # the job gives [1, 2, 3] + +steps: +# A condition on a workflow input, and one on a number written here. +- id: up # ok + run: say_ok + in: {go: go, n: !ii 1} + out: [result: !& up_said] + when: $(inputs.go) +- id: up_skipped # null + run: never_runs + in: {go: no_go, n: !ii 1} + out: [result: !& up_skipped_said] + when: $(inputs.go) +- id: counted # ok + run: say_ok + in: {go: go, n: !ii 1} + out: [result: !& counted_said] + when: $(inputs.n > 0) +- id: uncounted # null + run: never_runs + in: {go: go, n: !ii 0} + out: [result: !& uncounted_said] + when: $(inputs.n > 0) +# A condition may read an input the step gives and its tool does not declare. +- id: carried # ok + run: say_ok + in: {go: no_go, n: !ii 1, enabled: !cwl {source: go}} + when: $(inputs.enabled) + +# Three operands: an upstream output, a workflow input and an optional input nobody gave. +- id: gated # 1 2 3: all three hold + run: numbers_if + in: {prev: !* up_said, flag: go, xs: xs, maybe: maybe} + when: $(inputs.prev !== null && inputs.flag && inputs.maybe === null) +- id: gated_prev_last # 1 2 3: the tool declares the upstream input last + run: numbers_if_prev_last + in: {prev: !* up_said, flag: go, xs: xs, maybe: maybe} + when: $(inputs.prev !== null && inputs.flag && inputs.maybe === null) +- id: gated_after_skip # null: the upstream step was skipped + run: numbers_if + in: {prev: !* up_skipped_said, flag: go, xs: xs, maybe: maybe} + when: $(inputs.prev !== null && inputs.flag && inputs.maybe === null) +- id: gated_flag_false # null: the workflow input is false + run: numbers_if + in: {prev: !* up_said, flag: no_go, xs: xs, maybe: maybe} + when: $(inputs.prev !== null && inputs.flag && inputs.maybe === null) + +# A skipped step leaves null, and a step that reads it into an optional input still runs. +- id: after_skip # done.txt + run: touch_done + in: {maybe: !* uncounted_said} + +# One value from a conditional step reaches every job of a scattered step. +- id: write_note # shared + in: {text: !ii shared, after: !* counted_said} + out: [note: !& noted] +- id: copy_note # a.txt, b.txt, c.txt, each holding "shared" + scatter: [name] + scatterMethod: dotproduct + in: {note: !* noted, name: !ii [a, b, c]} + +# A gathered array is scattered again, beside one File every job reads; over one input the three methods agree. +- id: echo_item # 1, 2, 3 + scatter: [item] + scatterMethod: dotproduct + in: {item: !ii ['1', '2', '3']} + out: [out: !& items] +- id: cat_pair # 1 REF, 2 REF, 3 REF + scatter: [f] + scatterMethod: dotproduct + in: {f: !* items, r: !ii ref.txt} +- id: cat_pair_flat # the same three + run: cat_pair + scatter: [f] + scatterMethod: flat_crossproduct + in: {f: !* items, r: !ii ref.txt} +- id: cat_pair_nested # the same three, in one array + run: cat_pair + scatter: [f] + scatterMethod: nested_crossproduct + in: {f: !* items, r: !ii ref.txt} + +# A nested crossproduct over two inputs: one array per element of the first. +- id: pair_nested # [a-x, a-y], [b-x, b-y] + run: pair + scatter: [first, second] + scatterMethod: nested_crossproduct + in: {first: !ii [a, b], second: !ii [x, y]} + +# A condition is decided for each scatter job; the gathered array keeps null where a job was skipped. +- id: pair_unless_b # a-x, null, c-z + run: pair + scatter: [first, second] + scatterMethod: dotproduct + in: {first: !ii [a, b, c], second: !ii [x, y, z]} + when: $(inputs.first !== 'b') +- id: pair_unless_skipped # a-0.2, null, c-0: the first job sleeps longest and finishes last + run: pair_after_sleeping + scatter: [first, seconds] + scatterMethod: dotproduct + in: {first: !ii [a, b, c], seconds: !ii ['0.2', '0.1', '0'], skipped: !ii '0.1'} + when: $(inputs.seconds !== inputs.skipped) diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/write_note.cwl b/tests/core/data/nextflow/runs/conditions_and_scatter/write_note.cwl new file mode 100644 index 000000000..644c37e68 --- /dev/null +++ b/tests/core/data/nextflow/runs/conditions_and_scatter/write_note.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write the text to note.txt; `after` only orders this step behind the one that made it. +baseCommand: echo +inputs: + text: + type: string + inputBinding: {position: 1} + after: string? +stdout: note.txt +outputs: + note: + type: File + outputBinding: {glob: note.txt} diff --git a/tests/core/data/nextflow/runs/nested/child.wic b/tests/core/data/nextflow/runs/nested/child.wic new file mode 100644 index 000000000..60da34ba7 --- /dev/null +++ b/tests/core/data/nextflow/runs/nested/child.wic @@ -0,0 +1,13 @@ +# One level down: a step reading the input, a scatter, and a call one level further. +inputs: + source: {type: File} +outputs: + copy: {type: File, outputSource: copy_file/result} +steps: +- id: copy_file + in: {source: source} +- id: echo_each # a scatter inside a child: a, b + scatter: [item] + scatterMethod: dotproduct + in: {item: !ii [a, b]} +- id: grandchild.wic diff --git a/tests/core/data/nextflow/runs/nested/copy_file.cwl b/tests/core/data/nextflow/runs/nested/copy_file.cwl new file mode 100644 index 000000000..f3a2e8da8 --- /dev/null +++ b/tests/core/data/nextflow/runs/nested/copy_file.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Copy the source to copy.txt. +baseCommand: cp +inputs: + source: + type: File + inputBinding: {position: 1} +arguments: +- {position: 2, valueFrom: copy.txt} +outputs: + result: + type: File + outputBinding: {glob: copy.txt} diff --git a/tests/core/data/nextflow/runs/nested/count_lines.cwl b/tests/core/data/nextflow/runs/nested/count_lines.cwl new file mode 100644 index 000000000..1d13f7596 --- /dev/null +++ b/tests/core/data/nextflow/runs/nested/count_lines.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Count the lines of the source, read from standard input, into count.txt. +baseCommand: [wc, -l] +inputs: + source: File +stdin: $(inputs.source.path) +stdout: count.txt +outputs: + count: + type: File + outputBinding: {glob: count.txt} diff --git a/tests/core/data/nextflow/runs/nested/echo_each.cwl b/tests/core/data/nextflow/runs/nested/echo_each.cwl new file mode 100644 index 000000000..bbbe6e394 --- /dev/null +++ b/tests/core/data/nextflow/runs/nested/echo_each.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write one item to out.txt. +baseCommand: echo +inputs: + item: + type: string + inputBinding: {position: 1} +stdout: out.txt +outputs: + result: + type: File + outputBinding: {glob: out.txt} diff --git a/tests/core/data/nextflow/runs/nested/expected.yaml b/tests/core/data/nextflow/runs/nested/expected.yaml new file mode 100644 index 000000000..c1e0dce0e --- /dev/null +++ b/tests/core/data/nextflow/runs/nested/expected.yaml @@ -0,0 +1,13 @@ +# Every output of workflow.wic, by step and port, in the order of its steps. +outputs: + write_source~result: {class: File, basename: message.txt, contents: "nested composition\n"} + child~copy: {class: File, basename: copy.txt, contents: "nested composition\n"} + child~copy_file~result: {class: File, basename: copy.txt, contents: "nested composition\n"} + child~echo_each~result: + - {class: File, basename: out.txt, contents: "a\n"} + - {class: File, basename: out.txt, contents: "b\n"} + child~grandchild~touch_n~out: null + child~grandchild~write_source~result: {class: File, basename: message.txt, contents: "two levels down\n"} + count_lines~count: {class: File, basename: count.txt, contents: "1\n"} + sibling~copy_file~result: {class: File, basename: copy.txt, contents: "nested composition\n"} + touch_n~out: {class: File, basename: n.txt, contents: ""} diff --git a/tests/core/data/nextflow/runs/nested/grandchild.wic b/tests/core/data/nextflow/runs/nested/grandchild.wic new file mode 100644 index 000000000..610337536 --- /dev/null +++ b/tests/core/data/nextflow/runs/nested/grandchild.wic @@ -0,0 +1,7 @@ +# Two levels down: the condition stays with its step, which is skipped. +steps: +- id: touch_n # null: 3 is not above 5 + in: {n: !ii 3} + when: $(inputs.n > 5) +- id: write_source + in: {message: !ii two levels down} diff --git a/tests/core/data/nextflow/runs/nested/sibling.wic b/tests/core/data/nextflow/runs/nested/sibling.wic new file mode 100644 index 000000000..86c0be892 --- /dev/null +++ b/tests/core/data/nextflow/runs/nested/sibling.wic @@ -0,0 +1,6 @@ +# A second child running the tool child.wic runs. +inputs: + source: {type: File} +steps: +- id: copy_file + in: {source: source} diff --git a/tests/core/data/nextflow/runs/nested/touch_n.cwl b/tests/core/data/nextflow/runs/nested/touch_n.cwl new file mode 100644 index 000000000..b7c43de41 --- /dev/null +++ b/tests/core/data/nextflow/runs/nested/touch_n.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make n.txt; `n` is read only by the condition of the step. +baseCommand: [touch, n.txt] +inputs: + n: int +outputs: + out: + type: File + outputBinding: {glob: n.txt} diff --git a/tests/core/data/nextflow/runs/nested/workflow.wic b/tests/core/data/nextflow/runs/nested/workflow.wic new file mode 100644 index 000000000..7930ab072 --- /dev/null +++ b/tests/core/data/nextflow/runs/nested/workflow.wic @@ -0,0 +1,14 @@ +# Nesting: a child workflow is called as a step, and its steps run as if they were written here. +steps: +- id: write_source + in: {message: !ii nested composition} + out: [result: !& written] +- id: child.wic # copies the message, scatters, and calls grandchild.wic + in: {source: !* written} + out: [copy: !& copied] +- id: count_lines # an outer step reads what the child made: 1 + in: {source: !* copied} +- id: sibling.wic # a second call copies the same message; its steps do not collide with the first call's + in: {source: !* written} +- id: touch_n # runs here, although grandchild.wic skips the same tool + in: {n: !ii 3} diff --git a/tests/core/data/nextflow/runs/nested/write_source.cwl b/tests/core/data/nextflow/runs/nested/write_source.cwl new file mode 100644 index 000000000..34e2bd85c --- /dev/null +++ b/tests/core/data/nextflow/runs/nested/write_source.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write the message, and a newline, to message.txt. +baseCommand: echo +inputs: + message: + type: string + inputBinding: {position: 1} +stdout: message.txt +outputs: + result: + type: File + outputBinding: {glob: message.txt} diff --git a/tests/core/data/nextflow/runs/outputs/backtick_named.cwl b/tests/core/data/nextflow/runs/outputs/backtick_named.cwl new file mode 100644 index 000000000..30dc55a0a --- /dev/null +++ b/tests/core/data/nextflow/runs/outputs/backtick_named.cwl @@ -0,0 +1,11 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make a file named by a backtick and then the input. +baseCommand: touch +arguments: ['`$(inputs.name).txt'] +inputs: + name: string +outputs: + result: + type: File + outputBinding: {glob: '`$(inputs.name).txt'} diff --git a/tests/core/data/nextflow/runs/outputs/brace_named.cwl b/tests/core/data/nextflow/runs/outputs/brace_named.cwl new file mode 100644 index 000000000..c0b1804e5 --- /dev/null +++ b/tests/core/data/nextflow/runs/outputs/brace_named.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write a file whose name holds braces, and ab.txt, which a brace expansion would match instead. +baseCommand: [sh, -c, "echo literal > 'a{b,c}.txt'; echo decoy > ab.txt"] +inputs: {} +outputs: + result: + type: File + outputBinding: {glob: 'a{b,c}.txt'} diff --git a/tests/core/data/nextflow/runs/outputs/dollar_named.cwl b/tests/core/data/nextflow/runs/outputs/dollar_named.cwl new file mode 100644 index 000000000..1afa159fb --- /dev/null +++ b/tests/core/data/nextflow/runs/outputs/dollar_named.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make a file whose name holds a dollar that starts no reference. +baseCommand: [touch, out$name.txt] +inputs: {} +outputs: + result: + type: File + outputBinding: {glob: out$name.txt} diff --git a/tests/core/data/nextflow/runs/outputs/expected.yaml b/tests/core/data/nextflow/runs/outputs/expected.yaml new file mode 100644 index 000000000..da7619c12 --- /dev/null +++ b/tests/core/data/nextflow/runs/outputs/expected.yaml @@ -0,0 +1,11 @@ +# Every output of workflow.wic, by step and port, in the order of its steps. +outputs: + brace_named~result: {class: File, basename: "a{b,c}.txt", contents: "literal\n"} + dollar_named~result: {class: File, basename: "out$name.txt", contents: ""} + backtick_named~result: {class: File, basename: "`report.txt", contents: ""} + first_of_braces~result: {class: File, basename: "out{1,2}.txt", contents: "one match only\n"} + named_absent~o: null + named_present~o: {class: File, basename: maybe.txt, contents: ""} + pattern_none~o: null + pattern_one~o: {class: File, basename: a.log, contents: ""} + touch_names~result: {class: File, basename: a.txt, contents: ""} diff --git a/tests/core/data/nextflow/runs/outputs/first_of_braces.cwl b/tests/core/data/nextflow/runs/outputs/first_of_braces.cwl new file mode 100644 index 000000000..fe63e7bb1 --- /dev/null +++ b/tests/core/data/nextflow/runs/outputs/first_of_braces.cwl @@ -0,0 +1,15 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write the message to a file whose name holds braces, and give the first match of that name. +baseCommand: echo +inputs: + message: + type: string + inputBinding: {position: 1} +stdout: 'out{1,2}.txt' +outputs: + result: + type: File + outputBinding: + glob: 'out{1,2}.txt' + outputEval: $(self[0]) diff --git a/tests/core/data/nextflow/runs/outputs/maybe_log.cwl b/tests/core/data/nextflow/runs/outputs/maybe_log.cwl new file mode 100644 index 000000000..cad8719cf --- /dev/null +++ b/tests/core/data/nextflow/runs/outputs/maybe_log.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make each file named; give the one .log file if there is one. +baseCommand: touch +inputs: + names: + type: string[] + inputBinding: {position: 1} +outputs: + o: + type: File? + outputBinding: {glob: '*.log'} diff --git a/tests/core/data/nextflow/runs/outputs/maybe_named.cwl b/tests/core/data/nextflow/runs/outputs/maybe_named.cwl new file mode 100644 index 000000000..1cad4a5a6 --- /dev/null +++ b/tests/core/data/nextflow/runs/outputs/maybe_named.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make each file named; give maybe.txt if it is among them. +baseCommand: touch +inputs: + names: + type: string[] + inputBinding: {position: 1} +outputs: + o: + type: File? + outputBinding: {glob: maybe.txt} diff --git a/tests/core/data/nextflow/runs/outputs/touch_names.cwl b/tests/core/data/nextflow/runs/outputs/touch_names.cwl new file mode 100644 index 000000000..498ebbaa4 --- /dev/null +++ b/tests/core/data/nextflow/runs/outputs/touch_names.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make each file named; give the one .txt file. +baseCommand: touch +inputs: + names: + type: string[] + inputBinding: {position: 1} +outputs: + result: + type: File + outputBinding: {glob: '*.txt'} diff --git a/tests/core/data/nextflow/runs/outputs/workflow.wic b/tests/core/data/nextflow/runs/outputs/workflow.wic new file mode 100644 index 000000000..8f4150738 --- /dev/null +++ b/tests/core/data/nextflow/runs/outputs/workflow.wic @@ -0,0 +1,27 @@ +# Outputs: which file a glob names, and what an optional or a single File output is for none, one or several matches. +steps: +# A glob is matched as CWL matches it: braces, a lone dollar and a backtick are ordinary characters. +- id: brace_named # a{b,c}.txt, not the decoy ab.txt +- id: dollar_named # out$name.txt +- id: backtick_named # `report.txt + in: {name: !ii report} +- id: first_of_braces # out{1,2}.txt: $(self[0]) of a glob that can match only one file + in: {message: !ii one match only} + +# File? is null for no match and the file for one, whether the glob is a name or a pattern. +- id: named_absent # null + run: maybe_named + in: {names: !ii [other.txt]} +- id: named_present # maybe.txt + run: maybe_named + in: {names: !ii [maybe.txt]} +- id: pattern_none # null + run: maybe_log + in: {names: !ii [unmatched.txt]} +- id: pattern_one # a.log + run: maybe_log + in: {names: !ii [unmatched.txt, a.log]} + +# A File output whose pattern matches one file is that file. +- id: touch_names # a.txt + in: {names: !ii [a.txt]} diff --git a/tests/core/data/nextflow/runs/resources/expected.yaml b/tests/core/data/nextflow/runs/resources/expected.yaml new file mode 100644 index 000000000..e22cf4318 --- /dev/null +++ b/tests/core/data/nextflow/runs/resources/expected.yaml @@ -0,0 +1,5 @@ +why: cwltool runs the tool only on a machine with the two devices, so there is no reference run. Nextflow's local + executor takes the three requests and runs the task; none of them changes the Directory it makes. +reference: none +outputs: + make_dir~result: {class: Directory, basename: made, contents: {}} diff --git a/tests/core/data/nextflow/runs/resources/make_dir.cwl b/tests/core/data/nextflow/runs/resources/make_dir.cwl new file mode 100644 index 000000000..723dc1abc --- /dev/null +++ b/tests/core/data/nextflow/runs/resources/make_dir.cwl @@ -0,0 +1,20 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make the directory `made`, asking for 2 cores, 64 MiB and two CUDA devices. +$namespaces: + cwltool: http://commonwl.org/cwltool# +requirements: + ResourceRequirement: + coresMin: 2 + ramMin: 64 +hints: +- class: cwltool:CUDARequirement + cudaVersionMin: '11.4' + cudaDeviceCountMin: 2 + cudaComputeCapability: ['7.0', '8.0'] +baseCommand: [mkdir, made] +inputs: {} +outputs: + result: + type: Directory + outputBinding: {glob: made} diff --git a/tests/core/data/nextflow/runs/resources/nextflow.config b/tests/core/data/nextflow/runs/resources/nextflow.config new file mode 100644 index 000000000..0a5fd46b9 --- /dev/null +++ b/tests/core/data/nextflow/runs/resources/nextflow.config @@ -0,0 +1 @@ +docker.enabled = false diff --git a/tests/core/data/nextflow/runs/resources/workflow.nf b/tests/core/data/nextflow/runs/resources/workflow.nf new file mode 100644 index 000000000..709a6a970 --- /dev/null +++ b/tests/core/data/nextflow/runs/resources/workflow.nf @@ -0,0 +1,83 @@ +nextflow.enable.dsl=2 + +def __sophios_shell_quote_9f72e(value) { + return "'" + value.toString().replace("'", "'\"'\"'") + "'" +} + +def __sophios_input_9f72e(String name, value, String type) { + def item = type.replace('[]', '').replace('?', '') + if( type.contains('[]') ) { + if( value instanceof List ) + return value.collect { element -> __sophios_input_9f72e(name, element, item) } + } + else { + def text = value instanceof String + def path = value instanceof Map && value.getOrDefault('class', item) == item ? value.path : value + if( type.endsWith('?') && value == [] && !(item in ['File', 'Directory']) ) + return value + if( item == 'boolean' && value instanceof Boolean || item == 'int' && value instanceof Integer || + item == 'float' && (value instanceof Integer || value instanceof Long || + value instanceof Double && Double.isFinite(value)) || + item == 'string' && text ) + return value + if( item == 'boolean' && value in ['true', 'false'] ) + return value == 'true' + if( item == 'int' && text && value ==~ /[+-]?[0-9]+/ && + value.toBigInteger() == value.toBigInteger().intValue() ) + return value.toInteger() + if( item == 'float' && (text && value ==~ /[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?/ || + value instanceof BigDecimal) && Double.isFinite(value.toDouble()) ) + return value.toDouble() + if( item in ['File', 'Directory'] && path instanceof String && path != '' ) { + if( item == 'File' ? file(path, glob: false).isFile() : file(path, glob: false).isDirectory() ) + return path + throw new IllegalArgumentException("Sophios workflow input '" + name + "' must be " + type + "; no " + + item + " exists at '" + path + "'") + } + } + throw new IllegalArgumentException("Sophios workflow input '" + name + "' must be " + type + ", not " + + value.inspect()) +} + +def __sophios_output_9f72e(value, int depth) { + if( depth > 0 ) + return value.collect { item -> __sophios_output_9f72e(item, depth - 1) } + if( value instanceof java.nio.file.Path ) + return ['class': java.nio.file.Files.isDirectory(value) ? 'Directory' : 'File', 'path': value.toString()] + return value == [] ? null : value +} + +process make_dir { + cpus 2 + memory "64 MB" + accelerator 2 + ext cudaVersionMin: '11.4', cudaComputeCapability: ['7.0', '8.0'], Directory: ['result'] + + output: + path 'made', emit: result + + script: + """ +${__sophios_shell_quote_9f72e('mkdir')} ${__sophios_shell_quote_9f72e('made')} + """ + + stub: + """ + echo 'Sophios-generated Nextflow does not support dry runs (-stub-run)' >&2 + exit 1 + """ +} + +workflow _workflow { + main: + make_dir() + emit: + make_dir_result = make_dir.out.result +} + +workflow { + if( !nextflow.NF.isSyntaxParserV2() ) + error 'Sophios-generated Nextflow needs the v2 script parser: unset NXF_SYNTAX_PARSER or set it to v2' + _workflow() + _workflow.out.make_dir_result.toList().subscribe { items -> println('sophios-output ' + groovy.json.JsonOutput.toJson(['make_dir_result', __sophios_output_9f72e(items[0], 0)])) } +} diff --git a/tests/core/data/nextflow/runs/resources/workflow.wic b/tests/core/data/nextflow/runs/resources/workflow.wic new file mode 100644 index 000000000..74ae0dca6 --- /dev/null +++ b/tests/core/data/nextflow/runs/resources/workflow.wic @@ -0,0 +1,5 @@ +# Resources: the tool asks for 2 cores, 64 MiB and two CUDA devices. A run does not show what a process asked for, +# so the pipeline written for this workflow is kept beside it, as workflow.nf and nextflow.config. cwltool runs the +# tool only on a machine that has the devices, so expected.yaml states what the step makes, with no reference run. +steps: +- id: make_dir diff --git a/tests/core/data/nextflow/runs/staging/capture_own_entry.cwl b/tests/core/data/nextflow/runs/staging/capture_own_entry.cwl new file mode 100644 index 000000000..a944ca25c --- /dev/null +++ b/tests/core/data/nextflow/runs/staging/capture_own_entry.cwl @@ -0,0 +1,17 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Stage the source under its own basename and do nothing; both globs match the entry. +requirements: + InitialWorkDirRequirement: + listing: + - $(inputs.source) +baseCommand: 'true' +inputs: + source: File +outputs: + wild: + type: File + outputBinding: {glob: lines*} + same: + type: File + outputBinding: {glob: $(inputs.source.basename)} diff --git a/tests/core/data/nextflow/runs/staging/capture_renamed_entry.cwl b/tests/core/data/nextflow/runs/staging/capture_renamed_entry.cwl new file mode 100644 index 000000000..d722922a9 --- /dev/null +++ b/tests/core/data/nextflow/runs/staging/capture_renamed_entry.cwl @@ -0,0 +1,15 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Stage the source as renamed.txt and do nothing; the pattern matches the entry. +requirements: + InitialWorkDirRequirement: + listing: + - entry: $(inputs.source) + entryname: renamed.txt +baseCommand: 'true' +inputs: + source: File +outputs: + wild: + type: File + outputBinding: {glob: renamed*} diff --git a/tests/core/data/nextflow/runs/staging/copy_named_after_source.cwl b/tests/core/data/nextflow/runs/staging/copy_named_after_source.cwl new file mode 100644 index 000000000..c4d0fe66e --- /dev/null +++ b/tests/core/data/nextflow/runs/staging/copy_named_after_source.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Copy the source to .copy. +baseCommand: cp +inputs: + source: + type: File + inputBinding: {position: 1} +arguments: +- {position: 2, valueFrom: $(inputs.source.basename).copy} +outputs: + result: + type: File + outputBinding: {glob: $(inputs.source.basename).copy} diff --git a/tests/core/data/nextflow/runs/staging/expected.yaml b/tests/core/data/nextflow/runs/staging/expected.yaml new file mode 100644 index 000000000..b4ecf5cd2 --- /dev/null +++ b/tests/core/data/nextflow/runs/staging/expected.yaml @@ -0,0 +1,11 @@ +# Every output of workflow.wic, by step and port, in the order of its steps. +outputs: + write_source~result: {class: File, basename: lines.txt, contents: "staged content\n"} + copy_named_after_source~result: {class: File, basename: lines.txt.copy, contents: "staged content\n"} + stage_own_basename~result: {class: File, basename: out.txt, contents: "staged content\n"} + stage_and_read~result: {class: File, basename: out.txt, contents: "staged content\n"} + capture_own_entry~same: {class: File, basename: lines.txt, contents: "staged content\n"} + capture_own_entry~wild: {class: File, basename: lines.txt, contents: "staged content\n"} + copy_captured~result: {class: File, basename: lines.txt.copy, contents: "staged content\n"} + capture_renamed_entry~wild: {class: File, basename: renamed.txt, contents: "staged content\n"} + plugin~outDir: {class: Directory, basename: plugin_out, contents: {result.txt: written}} diff --git a/tests/core/data/nextflow/runs/staging/plugin.cwl b/tests/core/data/nextflow/runs/staging/plugin.cwl new file mode 100644 index 000000000..0b990fbbb --- /dev/null +++ b/tests/core/data/nextflow/runs/staging/plugin.cwl @@ -0,0 +1,20 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: >- + The shape of an image-workflows plugin: it is given the directory to write into, stages it writable, writes + result.txt there and gives the directory back. +requirements: + InlineJavascriptRequirement: {} + InitialWorkDirRequirement: + listing: + - entry: $(inputs.outDir) + writable: true +baseCommand: [sh, -c, 'printf written > "$2/result.txt"', plugin] +inputs: + outDir: + type: Directory + inputBinding: {position: 1, prefix: --outDir} +outputs: + outDir: + type: Directory + outputBinding: {glob: $(inputs.outDir.basename)} diff --git a/tests/core/data/nextflow/runs/staging/stage_and_read.cwl b/tests/core/data/nextflow/runs/staging/stage_and_read.cwl new file mode 100644 index 000000000..2d210c62b --- /dev/null +++ b/tests/core/data/nextflow/runs/staging/stage_and_read.cwl @@ -0,0 +1,17 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Stage the source as renamed_by_iwdr.txt, the name the command reads, and print it to out.txt. +requirements: + InitialWorkDirRequirement: + listing: + - entry: $(inputs.source) + entryname: renamed_by_iwdr.txt +baseCommand: cat +arguments: [renamed_by_iwdr.txt] +inputs: + source: File +stdout: out.txt +outputs: + result: + type: File + outputBinding: {glob: out.txt} diff --git a/tests/core/data/nextflow/runs/staging/stage_own_basename.cwl b/tests/core/data/nextflow/runs/staging/stage_own_basename.cwl new file mode 100644 index 000000000..9ca84f795 --- /dev/null +++ b/tests/core/data/nextflow/runs/staging/stage_own_basename.cwl @@ -0,0 +1,17 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Stage the source under its own basename, and print it to out.txt. +requirements: + InitialWorkDirRequirement: + listing: + - $(inputs.source) +baseCommand: cat +inputs: + source: + type: File + inputBinding: {position: 1} +stdout: out.txt +outputs: + result: + type: File + outputBinding: {glob: out.txt} diff --git a/tests/core/data/nextflow/runs/staging/workflow.wic b/tests/core/data/nextflow/runs/staging/workflow.wic new file mode 100644 index 000000000..59ebfb4f3 --- /dev/null +++ b/tests/core/data/nextflow/runs/staging/workflow.wic @@ -0,0 +1,24 @@ +# Staging: what InitialWorkDirRequirement puts in a step's working directory, and what a glob then finds there. +# Every tool reads or captures the one file write_source makes, lines.txt. +steps: +- id: write_source + in: {message: !ii staged content} + out: [result: !& written] + +- id: copy_named_after_source # lines.txt.copy: an output named after the input's basename + in: {source: !* written} +- id: stage_own_basename # the bare entry $(inputs.source) is lines.txt, which the command reads + in: {source: !* written} +- id: stage_and_read # entryname gives the entry the name the command hard-codes + in: {source: !* written} +- id: capture_own_entry # a pattern, and the input's own basename, each capture the entry: lines.txt twice + in: {source: !* written} + out: [same: !& captured] +- id: copy_captured # a later step reads the captured entry: lines.txt.copy + run: copy_named_after_source + in: {source: !* captured} +- id: capture_renamed_entry # a pattern captures the entry under its entryname: renamed.txt + in: {source: !* written} + +- id: plugin # a writable Directory entry is the tool's own copy, captured by its basename + in: {outDir: !ii plugin_out} diff --git a/tests/core/data/nextflow/runs/staging/write_source.cwl b/tests/core/data/nextflow/runs/staging/write_source.cwl new file mode 100644 index 000000000..01a66c68c --- /dev/null +++ b/tests/core/data/nextflow/runs/staging/write_source.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write the message, and a newline, to lines.txt. +baseCommand: echo +inputs: + message: + type: string + inputBinding: {position: 1} +stdout: lines.txt +outputs: + result: + type: File + outputBinding: {glob: lines.txt} diff --git a/tests/core/data/nextflow/runs/step_inputs/cat_files.cwl b/tests/core/data/nextflow/runs/step_inputs/cat_files.cwl new file mode 100644 index 000000000..68ac026aa --- /dev/null +++ b/tests/core/data/nextflow/runs/step_inputs/cat_files.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Concatenate the files, in the order given, into all.txt. +baseCommand: cat +inputs: + files: + type: File[] + inputBinding: {position: 1} +stdout: all.txt +outputs: + line: + type: File + outputBinding: {glob: all.txt} diff --git a/tests/core/data/nextflow/runs/step_inputs/expected.yaml b/tests/core/data/nextflow/runs/step_inputs/expected.yaml new file mode 100644 index 000000000..e74820ae7 --- /dev/null +++ b/tests/core/data/nextflow/runs/step_inputs/expected.yaml @@ -0,0 +1,21 @@ +# Every output of workflow.wic, by step and port, in the order of its steps. +outputs: + write_each~file: + - {class: File, basename: out.txt, contents: "a\n"} + - {class: File, basename: out.txt, contents: "b\n"} + write_one~file: {class: File, basename: out.txt, contents: "c\n"} + write_two~file: {class: File, basename: out.txt, contents: "d\n"} + skipped~said: null + ran~said: only + cat_flat~line: {class: File, basename: all.txt, contents: "a\nb\nc\n"} + cat_nested~line: {class: File, basename: all.txt, contents: "d\nc\n"} + cat_single~line: {class: File, basename: all.txt, contents: "c\n"} + say_nested~line: {class: File, basename: out.txt, contents: "x y z\n"} + say_single~line: {class: File, basename: out.txt, contents: "x\n"} + default_unsourced~line: {class: File, basename: out.txt, contents: "d1\n"} + default_for_absent~line: {class: File, basename: out.txt, contents: "d2\n"} + default_not_taken~line: {class: File, basename: out.txt, contents: "g\n"} + default_after_skip~line: {class: File, basename: out.txt, contents: "d4\n"} + pick_first~line: {class: File, basename: out.txt, contents: "g\n"} + pick_only~line: {class: File, basename: out.txt, contents: "only\n"} + pick_all~line: {class: File, basename: out.txt, contents: "g only\n"} diff --git a/tests/core/data/nextflow/runs/step_inputs/job.yml b/tests/core/data/nextflow/runs/step_inputs/job.yml new file mode 100644 index 000000000..92ab069f7 --- /dev/null +++ b/tests/core/data/nextflow/runs/step_inputs/job.yml @@ -0,0 +1,3 @@ +x: x +y: y z +given: g diff --git a/tests/core/data/nextflow/runs/step_inputs/say_if.cwl b/tests/core/data/nextflow/runs/step_inputs/say_if.cwl new file mode 100644 index 000000000..f3a6b002b --- /dev/null +++ b/tests/core/data/nextflow/runs/step_inputs/say_if.cwl @@ -0,0 +1,17 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print the text with no newline; its step runs only when `go` is true, so its output may be null. +baseCommand: printf +inputs: + text: + type: string + inputBinding: {position: 1} + go: boolean +stdout: said.txt +outputs: + said: + type: string + outputBinding: + glob: said.txt + loadContents: true + outputEval: $(self[0].contents) diff --git a/tests/core/data/nextflow/runs/step_inputs/say_word.cwl b/tests/core/data/nextflow/runs/step_inputs/say_word.cwl new file mode 100644 index 000000000..6e25effe7 --- /dev/null +++ b/tests/core/data/nextflow/runs/step_inputs/say_word.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print one word on one line of out.txt. +baseCommand: echo +inputs: + words: + type: string + inputBinding: {position: 1} +stdout: out.txt +outputs: + line: + type: File + outputBinding: {glob: out.txt} diff --git a/tests/core/data/nextflow/runs/step_inputs/say_words.cwl b/tests/core/data/nextflow/runs/step_inputs/say_words.cwl new file mode 100644 index 000000000..7c9d2a32b --- /dev/null +++ b/tests/core/data/nextflow/runs/step_inputs/say_words.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print the words on one line of out.txt. +baseCommand: echo +inputs: + words: + type: string[] + inputBinding: {position: 1} +stdout: out.txt +outputs: + line: + type: File + outputBinding: {glob: out.txt} diff --git a/tests/core/data/nextflow/runs/step_inputs/workflow.wic b/tests/core/data/nextflow/runs/step_inputs/workflow.wic new file mode 100644 index 000000000..c5efb5dd7 --- /dev/null +++ b/tests/core/data/nextflow/runs/step_inputs/workflow.wic @@ -0,0 +1,82 @@ +# Step inputs: what a step reads when an input has several sources, a default, or a choice among them. +# Every step prints what it read, so the outputs expected.yaml states are the semantics, under any runner. +inputs: + x: string + y: string + unset: string? # no value is given for it + given: string? # the job gives "g" + +steps: +# Sources: two files from a scattered step, one from each of two lone steps. +- id: write_each + run: write_name + scatter: [name] + scatterMethod: dotproduct + in: {name: !ii [a, b]} + out: [file: !& each] +- id: write_one + run: write_name + in: {name: !ii c} + out: [file: !& one] +- id: write_two + run: write_name + in: {name: !ii d} + out: [file: !& two] +# A step that is skipped, and one that runs: their outputs are null and "only". +- id: skipped + run: say_if + in: {text: !ii never, go: !ii false} + out: [said: !& skipped_said] + when: $(inputs.go) +- id: ran + run: say_if + in: {text: !ii only, go: !ii true} + out: [said: !& ran_said] + when: $(inputs.go) + +# linkMerge: several sources join in order. +- id: cat_flat # a b c: the scattered step's files flattened with a lone one + run: cat_files + in: + files: !cwl {source: [!* each, !* one], linkMerge: merge_flattened} +- id: cat_nested # d c: scalar files nested into one array, the default merge + run: cat_files + in: + files: !cwl {source: [!* two, !* one]} +- id: cat_single # c: one merge_nested source is an array of one + run: cat_files + in: + files: !cwl {source: [!* one], linkMerge: merge_nested} +- id: say_nested # x y z: workflow inputs join the same way + run: say_words + in: + words: !cwl {source: [x, y]} +- id: say_single # x: and one of them, merge_nested, is an array of one + run: say_words + in: + words: !cwl {source: [x], linkMerge: merge_nested} + +# default: the value of an input with no source, or with a null one; never of a given value. +- id: default_unsourced # d1 + run: say_word + in: {words: !cwl {default: d1}} +- id: default_for_absent # d2 + run: say_word + in: {words: !cwl {source: unset, default: d2}} +- id: default_not_taken # g + run: say_word + in: {words: !cwl {source: given, default: d3}} +- id: default_after_skip # d4 + run: say_word + in: {words: !cwl {source: !* skipped_said, default: d4}} + +# pickValue: choose among the joined sources, skipping nulls. +- id: pick_first # g: the first of the two that are not null + run: say_word + in: {words: !cwl {source: [unset, !* skipped_said, given, x], pickValue: first_non_null}} +- id: pick_only # only + run: say_word + in: {words: !cwl {source: [!* skipped_said, !* ran_said], pickValue: the_only_non_null}} +- id: pick_all # g only + run: say_words + in: {words: !cwl {source: [given, !* skipped_said, !* ran_said, unset], pickValue: all_non_null}} diff --git a/tests/core/data/nextflow/runs/step_inputs/write_name.cwl b/tests/core/data/nextflow/runs/step_inputs/write_name.cwl new file mode 100644 index 000000000..4f721f41f --- /dev/null +++ b/tests/core/data/nextflow/runs/step_inputs/write_name.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write one name, and a newline, to out.txt. +baseCommand: echo +inputs: + name: + type: string + inputBinding: {position: 1} +stdout: out.txt +outputs: + file: + type: File + outputBinding: {glob: out.txt} diff --git a/tests/core/data/nextflow/stops/before_a_task/pick_first_of_none/expected.yaml b/tests/core/data/nextflow/stops/before_a_task/pick_first_of_none/expected.yaml new file mode 100644 index 000000000..31f82ef44 --- /dev/null +++ b/tests/core/data/nextflow/stops/before_a_task/pick_first_of_none/expected.yaml @@ -0,0 +1,5 @@ +why: first_non_null of two absent inputs has nothing to pick, so the step cannot be given a value. +step: pick +says: 'first_non_null finds 0 values that are not null' +unwritten: stdout +cwltool: fails diff --git a/tests/core/data/nextflow/stops/before_a_task/pick_first_of_none/workflow.wic b/tests/core/data/nextflow/stops/before_a_task/pick_first_of_none/workflow.wic new file mode 100644 index 000000000..3e6f7757e --- /dev/null +++ b/tests/core/data/nextflow/stops/before_a_task/pick_first_of_none/workflow.wic @@ -0,0 +1,8 @@ +# first_non_null needs one source that is not null, and the job gives neither. +inputs: + a: string? + b: string? +steps: +- id: pick + run: echo + in: {message: !cwl {source: [a, b], pickValue: first_non_null}} diff --git a/tests/core/data/nextflow/stops/before_a_task/pick_only_of_none/expected.yaml b/tests/core/data/nextflow/stops/before_a_task/pick_only_of_none/expected.yaml new file mode 100644 index 000000000..1ff039f11 --- /dev/null +++ b/tests/core/data/nextflow/stops/before_a_task/pick_only_of_none/expected.yaml @@ -0,0 +1,5 @@ +why: the_only_non_null of two absent inputs has nothing to pick, so the step cannot be given a value. +step: pick +says: 'the_only_non_null finds 0 values that are not null' +unwritten: stdout +cwltool: fails diff --git a/tests/core/data/nextflow/stops/before_a_task/pick_only_of_none/workflow.wic b/tests/core/data/nextflow/stops/before_a_task/pick_only_of_none/workflow.wic new file mode 100644 index 000000000..0940485c4 --- /dev/null +++ b/tests/core/data/nextflow/stops/before_a_task/pick_only_of_none/workflow.wic @@ -0,0 +1,8 @@ +# the_only_non_null needs exactly one source that is not null, and the job gives neither. +inputs: + a: string? + b: string? +steps: +- id: pick + run: echo + in: {message: !cwl {source: [a, b], pickValue: the_only_non_null}} diff --git a/tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/expected.yaml b/tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/expected.yaml new file mode 100644 index 000000000..1540de51f --- /dev/null +++ b/tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/expected.yaml @@ -0,0 +1,5 @@ +why: the_only_non_null of two given inputs has two to pick from, so the step cannot be given one value. +step: pick +says: 'the_only_non_null finds 2 values that are not null' +unwritten: stdout +cwltool: fails diff --git a/tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/job.yml b/tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/job.yml new file mode 100644 index 000000000..bf07f4cd0 --- /dev/null +++ b/tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/job.yml @@ -0,0 +1,2 @@ +a: x +b: y diff --git a/tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/workflow.wic b/tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/workflow.wic new file mode 100644 index 000000000..17b6164a6 --- /dev/null +++ b/tests/core/data/nextflow/stops/before_a_task/pick_only_of_two/workflow.wic @@ -0,0 +1,8 @@ +# the_only_non_null needs exactly one source that is not null, and the job gives both. +inputs: + a: string? + b: string? +steps: +- id: pick + run: echo + in: {message: !cwl {source: [a, b], pickValue: the_only_non_null}} diff --git a/tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/expected.yaml b/tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/expected.yaml new file mode 100644 index 000000000..f05e434ec --- /dev/null +++ b/tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/expected.yaml @@ -0,0 +1,6 @@ +why: A subexpression of a condition that is not finite stops the run before the step, on Sophios's own rule; + JavaScript, and so cwltool, goes on. +step: touch_c +says: 'is Infinity' +unwritten: c.txt +cwltool: runs diff --git a/tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/touch_c.cwl b/tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/touch_c.cwl new file mode 100644 index 000000000..de3c71ff3 --- /dev/null +++ b/tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/touch_c.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make c.txt; `i` is read only by the condition of the step. +baseCommand: [touch, c.txt] +inputs: + i: int +outputs: + out: + type: File + outputBinding: {glob: c.txt} diff --git a/tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/workflow.wic b/tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/workflow.wic new file mode 100644 index 000000000..cce48a101 --- /dev/null +++ b/tests/core/data/nextflow/stops/before_a_task/when_is_not_finite/workflow.wic @@ -0,0 +1,6 @@ +# 7 / (7 - 7) is Infinity in JavaScript, and Infinity > 0 is true: cwltool runs the step. +# Sophios stops instead: a condition that divides by zero is taken for a mistake. +steps: +- id: touch_c + in: {i: !ii 7} + when: $(inputs.i / (inputs.i - 7) > 0) diff --git a/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/expected.yaml b/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/expected.yaml new file mode 100644 index 000000000..6627a92f2 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/expected.yaml @@ -0,0 +1,5 @@ +why: A writable entry and an input Nextflow stages beside it cannot both be called data, so the task stops; the + limit is the Nextflow target's own, and cwltool runs the step. +step: list_both +says: 'InitialWorkDirRequirement entry already exists in the task directory: data' +cwltool: runs diff --git a/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/list_both.cwl b/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/list_both.cwl new file mode 100644 index 000000000..e7ab13549 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/list_both.cwl @@ -0,0 +1,19 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: List the directory `b`, with `a` staged as a writable entry of the working directory. +requirements: + InitialWorkDirRequirement: + listing: + - entry: $(inputs.a) + writable: true +baseCommand: ls +inputs: + a: Directory + b: + type: Directory + inputBinding: {position: 1} +stdout: listing.txt +outputs: + listing: + type: File + outputBinding: {glob: listing.txt} diff --git a/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/one/data/one.txt b/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/one/data/one.txt new file mode 100644 index 000000000..43dd47ea6 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/one/data/one.txt @@ -0,0 +1 @@ +one \ No newline at end of file diff --git a/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/two/data/two.txt b/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/two/data/two.txt new file mode 100644 index 000000000..64c5e5885 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/two/data/two.txt @@ -0,0 +1 @@ +two \ No newline at end of file diff --git a/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/workflow.wic b/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/workflow.wic new file mode 100644 index 000000000..d51467935 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/entry_and_staged_input_share_a_name/workflow.wic @@ -0,0 +1,6 @@ +# Two directories called data, from different places: `a` is an entry of the working directory, `b` an input of the +# command line. cwltool keeps `b` elsewhere and lists it. A Nextflow task stages both in its one directory, so +# Sophios stops the task instead of putting one inside the other. +steps: +- id: list_both + in: {a: !ii one/data, b: !ii two/data} diff --git a/tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/expected.yaml b/tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/expected.yaml new file mode 100644 index 000000000..8ecc6aae7 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/expected.yaml @@ -0,0 +1,4 @@ +why: An optional File output is null or one file; two matches are neither. +step: maybe_log +says: 'matched 2 files; it takes at most one' +cwltool: fails diff --git a/tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/maybe_log.cwl b/tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/maybe_log.cwl new file mode 100644 index 000000000..cad8719cf --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/maybe_log.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make each file named; give the one .log file if there is one. +baseCommand: touch +inputs: + names: + type: string[] + inputBinding: {position: 1} +outputs: + o: + type: File? + outputBinding: {glob: '*.log'} diff --git a/tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/workflow.wic b/tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/workflow.wic new file mode 100644 index 000000000..1245d3333 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/optional_output_two_matches/workflow.wic @@ -0,0 +1,4 @@ +# A File? output takes no match or one: here its pattern matches two files. +steps: +- id: maybe_log + in: {names: !ii [unmatched.txt, a.log, b.log]} diff --git a/tests/core/data/nextflow/stops/in_a_task/required_output_no_match/expected.yaml b/tests/core/data/nextflow/stops/in_a_task/required_output_no_match/expected.yaml new file mode 100644 index 000000000..7792de952 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/required_output_no_match/expected.yaml @@ -0,0 +1,4 @@ +why: A required File output with no match is no value, never an empty result. +step: write_nothing +says: 'Missing output file(s) `out.txt`' +cwltool: fails diff --git a/tests/core/data/nextflow/stops/in_a_task/required_output_no_match/workflow.wic b/tests/core/data/nextflow/stops/in_a_task/required_output_no_match/workflow.wic new file mode 100644 index 000000000..348a84698 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/required_output_no_match/workflow.wic @@ -0,0 +1,4 @@ +# The tool declares out.txt, the first match of its glob, and writes nothing. +steps: +- id: write_nothing + in: {message: !ii nothing is written} diff --git a/tests/core/data/nextflow/stops/in_a_task/required_output_no_match/write_nothing.cwl b/tests/core/data/nextflow/stops/in_a_task/required_output_no_match/write_nothing.cwl new file mode 100644 index 000000000..e744a3576 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/required_output_no_match/write_nothing.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Do nothing, although out.txt is declared. +baseCommand: 'true' +inputs: + message: + type: string + inputBinding: {position: 1} +outputs: + result: + type: File + outputBinding: + glob: out.txt + outputEval: $(self[0]) diff --git a/tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/expected.yaml b/tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/expected.yaml new file mode 100644 index 000000000..57c62f0f0 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/expected.yaml @@ -0,0 +1,4 @@ +why: A File output is one file; two matches are not one. +step: touch_names +says: 'Incorrect number of output files' +cwltool: fails diff --git a/tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/touch_names.cwl b/tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/touch_names.cwl new file mode 100644 index 000000000..498ebbaa4 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/touch_names.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make each file named; give the one .txt file. +baseCommand: touch +inputs: + names: + type: string[] + inputBinding: {position: 1} +outputs: + result: + type: File + outputBinding: {glob: '*.txt'} diff --git a/tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/workflow.wic b/tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/workflow.wic new file mode 100644 index 000000000..01273aca6 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/single_output_several_matches/workflow.wic @@ -0,0 +1,4 @@ +# A File output takes one match: here its pattern matches two files. +steps: +- id: touch_names + in: {names: !ii [a.txt, b.txt]} diff --git a/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/expected.yaml b/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/expected.yaml new file mode 100644 index 000000000..b3cd44d4b --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/expected.yaml @@ -0,0 +1,4 @@ +why: Two entries cannot both be called data in one directory. +step: list_both +says: 'InitialWorkDirRequirement entry already exists in the task directory: data' +cwltool: fails diff --git a/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/list_both.cwl b/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/list_both.cwl new file mode 100644 index 000000000..e4bcf156f --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/list_both.cwl @@ -0,0 +1,20 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: List the directory `b`, with `a` and `b` both staged as entries of the working directory. +requirements: + InitialWorkDirRequirement: + listing: + - entry: $(inputs.a) + writable: true + - $(inputs.b) +baseCommand: ls +inputs: + a: Directory + b: + type: Directory + inputBinding: {position: 1} +stdout: listing.txt +outputs: + listing: + type: File + outputBinding: {glob: listing.txt} diff --git a/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/one/data/one.txt b/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/one/data/one.txt new file mode 100644 index 000000000..43dd47ea6 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/one/data/one.txt @@ -0,0 +1 @@ +one \ No newline at end of file diff --git a/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/two/data/two.txt b/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/two/data/two.txt new file mode 100644 index 000000000..64c5e5885 --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/two/data/two.txt @@ -0,0 +1 @@ +two \ No newline at end of file diff --git a/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/workflow.wic b/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/workflow.wic new file mode 100644 index 000000000..c4e60da2a --- /dev/null +++ b/tests/core/data/nextflow/stops/in_a_task/two_entries_share_a_name/workflow.wic @@ -0,0 +1,4 @@ +# Two directories called data, from different places, are both entries of one working directory. +steps: +- id: list_both + in: {a: !ii one/data, b: !ii two/data} diff --git a/tests/core/nextflow/test_capabilities.py b/tests/core/nextflow/test_capabilities.py index 1606687d6..176fc4aca 100644 --- a/tests/core/nextflow/test_capabilities.py +++ b/tests/core/nextflow/test_capabilities.py @@ -4,15 +4,12 @@ import copy from collections.abc import Callable -from dataclasses import replace from pathlib import Path import re from typing import Any, cast import pytest -from sophios import compiler -from sophios.api.python import _workflow_runtime as workflow_runtime from sophios.api.python._workflow_runtime import compile_workflow_result from sophios.api.python.tool_builder import ( CommandLineTool, @@ -23,14 +20,9 @@ cwl, ) from sophios.api.python.workflow import CompiledWorkflow, Step, StepInput, Workflow -from sophios.cli import default_compilation_settings from sophios.input_output_nf import render_nextflow from sophios.ir.artifacts import CompilationResult -from sophios.ir.frontdoor import SourceBundle -from sophios.ir.resolve import RegistrySnapshot from sophios.ir.resolved import NotLowered -from sophios.lang import Diagnostics, EdgeDef, EdgeRef, OutputBinding, ParseResult -from sophios.nf_types import NfProcessConnection, NfWorkflowInputConnection from sophios.utils_nf import NEXTFLOW from sophios.wic_types import Yaml @@ -107,93 +99,12 @@ def _write_step() -> Step: return write -def _copy_child(name: str, source: Any) -> Workflow: - inner = Step(_copy_tool(), step_name="inner_copy") - child = Workflow([inner], name) - inner.inputs.source = child.inputs.source - child.outputs.result = inner.outputs.result - child.inputs.source = source - return child - - -def _nested_result(*, siblings: int = 1) -> CompilationResult: - write = _write_step() - children = [_copy_child(f"child_{index}", write.outputs.result) for index in range(siblings)] - steps: list[Step | Workflow] = [write, *children] - return compile_workflow_result(Workflow(steps, "root")) - - -def _deep_nested_result() -> CompilationResult: - write = _write_step() - inner = Step(_copy_tool(), step_name="inner_copy") - leaf = Workflow([inner], "leaf") - inner.inputs.source = leaf.inputs.source - middle = Workflow([leaf], "middle") - leaf.inputs.source = middle.inputs.source - middle.inputs.source = write.outputs.result - return compile_workflow_result(Workflow([write, middle], "root")) - - -def _nested_downstream_result() -> CompilationResult: - """Compile a child-output edge the Python surface deliberately cannot author yet.""" - write = _write_step() - child = _copy_child("child", write.outputs.result) - consume = Step(_copy_tool("consumed.txt"), step_name="consume") - consume.inputs.source = "placeholder.txt" - root = Workflow([write, child, consume], "root") - document = workflow_runtime.workflow_document(root) - steps = list(document.steps) - steps[1] = replace(steps[1], outputs=(OutputBinding("result", EdgeDef("childout")),)) - steps[2] = replace(steps[2], inputs=(("source", EdgeRef("childout")),)) - compiler_options = default_compilation_settings() - tools = workflow_runtime._merged_known_tools(root) - bundle = SourceBundle( - ParseResult(replace(document, steps=tuple(steps)), Diagnostics()), - "root", - RegistrySnapshot.from_tools(tools, workflows={ - ("global", child.process_name): ParseResult( - workflow_runtime.workflow_document(child), Diagnostics() - ), - }), - ) - return compiler.compile_source(bundle, compiler_options, quiet=True) - - -def _nested_artifacts(result: CompilationResult) -> list[Any]: - return [artifact for artifact in result.artifact.children if artifact.graph is not None] - - @pytest.mark.fast def test_an_empty_resolved_subworkflow_projects_to_no_processes() -> None: result = compile_workflow_result(Workflow([Workflow([], "child")], "root")) assert lowered(result).processes == () -@pytest.mark.fast -def test_two_resolved_subworkflow_instances_do_not_collide() -> None: - workflow = lowered(_nested_result(siblings=2)) - child_names = [process.name for process in workflow.processes if "inner_copy" in process.name] - assert len(child_names) == 2 - assert len(set(child_names)) == 2 - - -@pytest.mark.fast -def test_a_resolved_subworkflow_output_reaches_a_downstream_outer_step() -> None: - workflow = lowered(_nested_downstream_result()) - connection = next( - edge - for edge in workflow.connections - if isinstance(edge, NfProcessConnection) and edge.to_process.endswith("consume") - ) - assert connection.from_process.endswith("inner_copy") - - -@pytest.mark.fast -def test_resolved_nesting_deeper_than_one_level_projects_recursively() -> None: - workflow = lowered(_deep_nested_result()) - assert [process.name for process in workflow.processes] == ["write", "middle_leaf_inner_copy"] - - def _echo(name: str = "echo") -> Step: return adapter_step("echo", name, message="Hello") @@ -272,54 +183,6 @@ def test_a_refused_input_made_from_a_written_value_is_refused_where_the_value_wa "for the Nextflow target: 'Any' (step 'pick')" in [str(line) for line in raised.value.diagnostics] -@pytest.mark.fast -def test_inner_input_source_is_taken_from_the_resolved_graph( - real_nested_result: CompilationResult, -) -> None: - result = copy.deepcopy(real_nested_result) - nested = _nested_artifacts(result)[0] - nested.cwl["steps"][0]["in"]["source"] = "ABSENT/result" - workflow = lowered(result) - assert any( - isinstance(edge, NfProcessConnection) and edge.from_process.endswith("write") - for edge in workflow.connections - ) - - -@pytest.mark.fast -@pytest.mark.parametrize("requirement", ["SubworkflowFeatureRequirement", "MultipleInputFeatureRequirement"]) -def test_accepts_an_inert_nested_workflow_feature_requirement(requirement: str) -> None: - write = {"id": "write", "baseCommand": ["echo", "hi"], "stdout": "message.txt", - "outputs": {"result": {"type": "File", "outputBinding": {"glob": "message.txt"}}}} - child = {"requirements": {requirement: {}}, "steps": [{"id": "write"}]} - workflow, _notes = lowered_case({"workflow": {"steps": [{"id": "child.wic", "subtree": child}]}, "tools": [write]}) - assert [process.name for process in workflow.processes] == ["child_write"] - - -@pytest.mark.fast -def test_a_scattered_step_inside_a_subworkflow_uses_the_outer_scatter_contract() -> None: - echo_tool = ( - CommandLineTool( - "echo_item", - Inputs(item=Input(cwl.string, position=1)), - Outputs(result=Output(cwl.file, glob="out.txt")), - ) - .base_command("echo") - .stdout("out.txt") - ) - echo = Step(echo_tool, step_name="echo_item") - echo.inputs.item = ["a", "b"] - echo.scatter_on(echo.inputs.item) - child = Workflow([echo], "child") - workflow = lowered( - compile_workflow_result(Workflow([child], "root")) - ) - assert any( - isinstance(edge, NfWorkflowInputConnection) and edge.adapter == "dotproduct" - for edge in workflow.connections - ) - - @pytest.mark.fast @pytest.mark.parametrize("case", cases( "nextflow/rejected", "tool", "out", "job", "workflow", "tools", "error", "findings", "codes")) diff --git a/tests/core/nextflow/test_composition.py b/tests/core/nextflow/test_composition.py deleted file mode 100644 index d6f35bb68..000000000 --- a/tests/core/nextflow/test_composition.py +++ /dev/null @@ -1,273 +0,0 @@ -"""Collection and conditional composition over indexed scatters (design §6, Topology).""" - -# pylint: disable=missing-function-docstring - -from typing import Any - -import pytest - -from sophios.input_output_nf import render_nextflow -from sophios.lang.subset import parse -from sophios.nf_types import ( - ExecutableNextflowWorkflow, - NfPort, - NfProcess, - NfProcessConnection, - NfWorkflowInputConnection, - NfWorkflowOutputConnection, -) - -from .testkit import command, lowered_case, output_port, step, tool - -STRINGS = {"type": "array", "items": "string"} -FILES = {"type": "array", "items": "File"} -FILE_OUT = {"type": "File", "outputBinding": {"glob": "out.txt"}} - - -def _tools() -> list[dict[str, Any]]: - pair = tool( - "PAIR", - inputs={ - "a": {"type": "string", "inputBinding": {"position": 1}}, - "b": {"type": "string", "inputBinding": {"position": 2}}, - "n": {"type": "int"}, - }, - arguments=[{"position": 3, "valueFrom": "$(inputs.n)0"}], - baseCommand="echo", - stdout="out.txt", - outputs={"out": FILE_OUT}, - ) - join = tool( - "JOIN", - inputs={ - "f": {"type": "File", "inputBinding": {"position": 1}}, - "g": {"type": "File", "inputBinding": {"position": 2}}, - }, - baseCommand="cat", - # Not out.txt: Nextflow stages inputs in the task directory, so an - # output named like a staged input would truncate it first. - stdout="joined.txt", - outputs={"out": {"type": "File", "outputBinding": {"glob": "joined.txt"}}}, - ) - concat = tool( - "CONCAT", - inputs={"files": {"type": FILES, "inputBinding": {"position": 1}}}, - baseCommand="cat", - stdout="all.txt", - outputs={"all": {"type": "File", "outputBinding": {"glob": "all.txt"}}}, - ) - return [pair, join, concat] - - -def _use_tool(file_ports: tuple[str, ...] = ("files",)) -> dict[str, Any]: - arrays = { - name: {"type": FILES, "inputBinding": {"position": position}} - for position, name in enumerate(file_ports, 1) - } - return tool( - "USE", - inputs={"x": {"type": "string"}, "y": {"type": "string"}, **arrays}, - baseCommand="cat", - stdout="used.txt", - outputs={"used": {"type": "File", "outputBinding": {"glob": "used.txt"}}}, - ) - - -def _pair_then_use(method: str, params: dict[str, Any]) -> ExecutableNextflowWorkflow: - """PAIR's gathered outputs feed the unscattered ``files`` port of the scattered USE.""" - steps = [ - step("PAIR", **{ - "in": {"a": "as", "b": "bs", "n": "n"}, "out": [{"out": {"wic_anchor": "pair_out"}}], - "scatter": ["a", "b"], "scatterMethod": "dotproduct", - }), - step("USE", **{ - "in": {"x": "xs", "y": "ys", "files": {"wic_alias": "pair_out"}}, "out": ["used"], - "scatter": ["x", "y"], "scatterMethod": method, - }), - ] - workflow = { - "steps": steps, - "inputs": { - "as": {"type": STRINGS}, "bs": {"type": STRINGS}, "n": {"type": "int"}, - "xs": {"type": STRINGS}, "ys": {"type": STRINGS}, - }, - "outputs": {"used": {"type": FILES, "outputSource": "USE/used"}}, - } - return lowered_case({"workflow": workflow, "tools": [_tools()[0], _use_tool()], "job": params})[0] - - -_PAIR_THEN_USE_PARAMS = {"as": ["a", "b", "c"], "bs": ["x", "y", "z"], "n": 2, "xs": ["p", "q"], "ys": ["r", "s"]} - - -def _two_gathered_arrays_into_use(second: str, method: str = "dotproduct") -> ExecutableNextflowWorkflow: - """USE scatters x and y and takes two gathered File arrays: ``files`` gathers PAIR, ``more`` gathers ``second`` - (PAIR or PAIR2).""" - pair = _tools()[0] - tools = [pair] - producers = [("PAIR", "as", "bs")] - if second == "PAIR2": - tools.append({**pair, "id": "PAIR2"}) - producers.append(("PAIR2", "bs", "as")) - tools.append(_use_tool(("files", "more"))) - steps = [ - step(name, **{ - "in": {"a": a, "b": b, "n": "n"}, "out": [{"out": {"wic_anchor": f"{name}_out"}}], - "scatter": ["a", "b"], "scatterMethod": "dotproduct", - }) - for name, a, b in producers - ] - steps.append(step("USE", **{ - "in": {"x": "xs", "y": "ys", "files": {"wic_alias": "PAIR_out"}, "more": {"wic_alias": f"{second}_out"}}, - "out": ["used"], "scatter": ["x", "y"], "scatterMethod": method, - })) - used = {"type": "array", "items": FILES} if method == "nested_crossproduct" else FILES - workflow = { - "steps": steps, - "inputs": { - "as": {"type": STRINGS}, "bs": {"type": STRINGS}, "n": {"type": "int"}, - "xs": {"type": STRINGS}, "ys": {"type": STRINGS}, - }, - "outputs": {"used": {"type": used, "outputSource": "USE/used"}}, - } - return lowered_case({"workflow": workflow, "tools": tools, "job": _PAIR_THEN_USE_PARAMS})[0] - - -@pytest.mark.fast -@pytest.mark.parametrize("method", ["dotproduct", "flat_crossproduct"]) -def test_a_gathered_array_on_a_scattered_steps_unscattered_port_stages_in_numbered_directories(method: str) -> None: - rendered = render_nextflow(_pair_then_use(method, _PAIR_THEN_USE_PARAMS)) - assert ( - "tuple val(__sophios_scatter_index_9f72e), val(x), val(y)\n" - " path files, arity: '0..*', stageAs: 'gather_files_*/*'\n" - ) in rendered - - -@pytest.mark.fast -@pytest.mark.parametrize("second", ["PAIR", "PAIR2"]) -def test_two_gathered_arrays_on_a_scattered_step_stage_under_separate_prefixes(second: str) -> None: - rendered = render_nextflow(_two_gathered_arrays_into_use(second)) - assert ( - " path files, arity: '0..*', stageAs: 'gather_files_*/*'\n" - " path more, arity: '0..*', stageAs: 'gather_more_*/*'\n" - ) in rendered - - -@pytest.mark.fast -def test_two_gathered_arrays_on_an_unscattered_step_stage_under_separate_prefixes() -> None: - pair = NfProcess( - "PAIR", - [NfPort("a", "val"), NfPort("b", "val")], - [output_port("f", "out.txt"), output_port("h", "h.txt")], - command("true"), - ) - following = NfProcess( - "NEXT", - [NfPort("x", "path", is_array=True), NfPort("y", "path", is_array=True)], - [output_port("g", "g.txt")], - command("true"), - ) - workflow = ExecutableNextflowWorkflow( - "wf", - [pair, following], - [ - NfWorkflowInputConnection("avals", "PAIR", "a", "dotproduct"), - NfWorkflowInputConnection("bvals", "PAIR", "b", "dotproduct"), - NfProcessConnection("PAIR", "f", "NEXT", "x", "gather"), - NfProcessConnection("PAIR", "h", "NEXT", "y", "gather"), - NfWorkflowOutputConnection("NEXT", "g", "result"), - ], - {"avals": ["x"], "bvals": ["y"]}, {"avals": "string[]", "bvals": "string[]"}, - ) - rendered = render_nextflow(workflow) - assert ( - " path x, arity: '0..*', stageAs: 'gather_x_*/*'\n" - " path y, arity: '0..*', stageAs: 'gather_y_*/*'\n" - ) in rendered - - -@pytest.mark.fast -def test_a_condition_on_a_broadcast_port_branches_the_indexed_scatter_and_indexes_the_skip() -> None: - process = NfProcess( - "PAIR", - [NfPort("a", "val"), NfPort("b", "val"), NfPort("c", "val")], - [output_port("f", "out.txt")], - command("true"), - condition=parse("$(inputs.c == 'go')"), - ) - workflow = ExecutableNextflowWorkflow( - "wf", - [process], - [ - NfWorkflowInputConnection("avals", "PAIR", "a", "dotproduct"), - NfWorkflowInputConnection("bvals", "PAIR", "b", "dotproduct"), - NfWorkflowInputConnection("c", "PAIR", "c"), - NfWorkflowOutputConnection("PAIR", "f", "result"), - ], - {"avals": ["x"], "bvals": ["y"], "c": "go"}, {"avals": "string[]", "bvals": "string[]", "c": "string"}, - ) - rendered = render_nextflow(workflow) - # One closure parameter per tuple element: index, two scattered, one broadcast. - assert "ch_PAIR_scatter.combine(c.map { [it] }).branch { __i, __w0, __w1, __b0 ->" in rendered - assert "run: (__b0 == 'go')" in rendered - assert ( - "PAIR(ch_PAIR_branch.run.map { __i, __w0, __w1, __b0 -> tuple(__i, __w0, __w1) }, " - "ch_PAIR_branch.run.map { __i, __w0, __w1, __b0 -> __b0 })" - ) in rendered - assert "ch_PAIR_branch.skip.map { __i, __w0, __w1, __b0 -> tuple(__i, []) }" in rendered - assert "tuple val(__sophios_scatter_index_9f72e), val(a), val(b)\n val c\n" in rendered - - -@pytest.mark.fast -def test_one_output_of_a_scattered_step_gathers_into_a_step_while_another_reaches_the_workflow() -> None: - pair = NfProcess( - "PAIR", - [NfPort("a", "val"), NfPort("b", "val")], - [output_port("f", "out.txt"), output_port("h", "h.txt")], - command("true"), - ) - following = NfProcess("NEXT", [NfPort("x", "path", is_array=True)], [output_port("g", "g.txt")], command("true")) - workflow = ExecutableNextflowWorkflow( - "wf", - [pair, following], - [ - NfWorkflowInputConnection("avals", "PAIR", "a", "dotproduct"), - NfWorkflowInputConnection("bvals", "PAIR", "b", "dotproduct"), - NfProcessConnection("PAIR", "h", "NEXT", "x", "gather"), - NfWorkflowOutputConnection("PAIR", "f", "pairs"), - NfWorkflowOutputConnection("NEXT", "g", "result"), - ], - {"avals": ["x"], "bvals": ["y"]}, {"avals": "string[]", "bvals": "string[]"}, - ) - rendered = render_nextflow(workflow) - assert "NEXT(PAIR.out.h.toSortedList { it[0] }.map { it.collect { row -> row[1] } })" in rendered - assert "pairs = PAIR.out.f.toSortedList { it[0] }.flatMap { it.collect { row -> row[1] } }" in rendered - assert "path x, arity: '0..*', stageAs: 'gather_x_*/*'" in rendered - - -@pytest.mark.fast -def test_a_gathered_array_feeds_a_single_input_scatter_staged_in_numbered_directories() -> None: - steps = [ - step("PAIR", **{ - "in": {"a": "as", "b": "bs", "n": "n"}, "out": [{"out": {"wic_anchor": "pair_out"}}], - "scatter": ["a", "b"], "scatterMethod": "dotproduct", - }), - step("USE", **{"in": {"x": "xs", "y": "y", "files": {"wic_alias": "pair_out"}}, "out": ["used"], - "scatter": ["x"]}), - ] - workflow = { - "steps": steps, - "inputs": { - "as": {"type": STRINGS}, "bs": {"type": STRINGS}, "n": {"type": "int"}, - "xs": {"type": STRINGS}, "y": {"type": "string"}, - }, - "outputs": {"used": {"type": FILES, "outputSource": "USE/used"}}, - } - params = {"as": ["a"], "bs": ["x"], "n": 2, "xs": ["p"], "y": "r"} - rendered = render_nextflow( - lowered_case({"workflow": workflow, "tools": [_tools()[0], _use_tool()], "job": params})[0] - ) - assert ( - "tuple val(__sophios_scatter_index_9f72e), val(x)\n" - " val y\n" - " path files, arity: '0..*', stageAs: 'gather_files_*/*'\n" - ) in rendered diff --git a/tests/core/nextflow/test_dotproduct.py b/tests/core/nextflow/test_dotproduct.py deleted file mode 100644 index af3cb46d8..000000000 --- a/tests/core/nextflow/test_dotproduct.py +++ /dev/null @@ -1,106 +0,0 @@ -"""Multi-input dotproduct scatter: index-paired invocations, index-ordered gather (design §6, Topology).""" - -# pylint: disable=missing-function-docstring - -import pytest - -from sophios.input_output_nf import render_nextflow -from sophios.nf_types import ( - ExecutableNextflowWorkflow, - NfArrayBinding, - NfCommand, - NfConnection, - NfInputReference, - NfPort, - NfProcess, - NfShellLiteral, - NfWorkflowInputConnection, - NfWorkflowOutputConnection, -) - -from .testkit import ref, template - - -def _text_port(name: str, glob: str = "out.txt") -> NfPort: - """A val output port whose captured text is the globbed file's decoded content.""" - return NfPort(name, "val", name, template(glob), capture="text") - - -def _sleep_then_pair(*port_names: str) -> NfCommand: - """sleep ; printf the hyphen-joined ports, to out.txt; the sleep reorders task completion.""" - parts: list[str | NfInputReference] = [ref(port_names[0])] - for name in port_names[1:]: - parts += ["-", ref(name)] - joined = template(*parts) - return NfCommand( - ( - template("sleep"), - template(ref(port_names[-1])), - NfShellLiteral(";"), - template("printf"), - template("%s"), - joined, - ), - stdout=template("out.txt"), - ) - - -@pytest.mark.fast -def test_mismatched_lengths_name_each_scattered_input_and_its_length() -> None: - """S3: the rendered idiom fails the run naming each scattered input and its - length, never truncating silently (design §6, Topology).""" - process = NfProcess( - "PAIR", - [NfPort("item", "val"), NfPort("tag", "val")], - [_text_port("line")], - _sleep_then_pair("item", "tag"), - ) - workflow = ExecutableNextflowWorkflow( - "PIPELINE", - [process], - [ - NfWorkflowInputConnection("items", "PAIR", "item", "dotproduct"), - NfWorkflowInputConnection("tags", "PAIR", "tag", "dotproduct"), - NfWorkflowOutputConnection("PAIR", "line", "result"), - ], - {"items": ["a"], "tags": ["b"]}, {"items": "string[]", "tags": "string[]"}, - ) - - rendered = render_nextflow(workflow) - - assert ( - "PAIR: dotproduct scatter inputs have mismatched lengths: " - "items=${__d0.size()}, tags=${__d1.size()}" in rendered - ) - - -def _scatter_with_file_array(method: str, sources: list[str]) -> ExecutableNextflowWorkflow: - """Two scattered inputs and a File array that stays outside the scattered tuple.""" - process = NfProcess( - "PAIR", - [NfPort("item", "val"), NfPort("tag", "val"), NfPort("sources", "path", is_array=True)], - [_text_port("line", "combined.txt")], - NfCommand( - (template("echo"), template(ref("item")), template(ref("tag")), NfArrayBinding("sources")), - stdout=template("combined.txt"), - ), - ) - connections: list[NfConnection] = [ - NfWorkflowInputConnection("items", "PAIR", "item", method), - NfWorkflowInputConnection("tags", "PAIR", "tag", method), - NfWorkflowInputConnection("sources", "PAIR", "sources"), - NfWorkflowOutputConnection("PAIR", "line", "result"), - ] - params = {"items": ["a", "b"], "tags": ["x", "y"], "sources": sources} - types = {"items": "string[]", "tags": "string[]", "sources": "File[]"} - return ExecutableNextflowWorkflow("PIPELINE", [process], connections, params, types) - - -@pytest.mark.fast -@pytest.mark.parametrize("method", ["dotproduct", "flat_crossproduct", "nested_crossproduct"]) -def test_an_unscattered_file_array_declares_the_list_arity_beside_the_scattered_tuple(method: str) -> None: - rendered = render_nextflow(_scatter_with_file_array(method, ["source_0.txt"])) - assert ( - "tuple val(__sophios_scatter_index_9f72e), val(item), val(tag)\n" - " path sources, arity: '0..*', stageAs: 'gather_sources_*/*'\n" - ) in rendered diff --git a/tests/core/nextflow/test_nested_crossproduct.py b/tests/core/nextflow/test_nested_crossproduct.py deleted file mode 100644 index 821cd4011..000000000 --- a/tests/core/nextflow/test_nested_crossproduct.py +++ /dev/null @@ -1,98 +0,0 @@ -"""Multi-input nested_crossproduct scatter: one array dimension per scattered input (design §6, Topology).""" - -# pylint: disable=missing-function-docstring - -import pytest - -from sophios.input_output_nf import render_nextflow -from sophios.nf_types import NF_NEST_HELPER, ExecutableNextflowWorkflow - -from .test_composition import FILES, STRINGS, _tools -from .testkit import lowered_case, step - - -@pytest.mark.fast -def test_a_nested_result_feeding_a_later_step_is_rejected_by_name() -> None: - steps = [ - step("PAIR", **{ - "in": {"a": "as", "b": "bs", "n": "n"}, "out": [{"out": {"wic_anchor": "pair_out"}}], - "scatter": ["a", "b"], "scatterMethod": "nested_crossproduct", - }), - step("CONCAT", **{"in": {"files": {"wic_alias": "pair_out"}}, "out": ["all"]}), - ] - workflow = { - "steps": steps, - "inputs": {"as": {"type": STRINGS}, "bs": {"type": STRINGS}, "n": {"type": "int"}}, - "outputs": {"all": {"type": "File", "outputSource": "CONCAT/all"}}, - } - pair, _join, concat = _tools() - # A two-input nested result is a File[][], which a File[] port cannot take (wic023). - tools = [pair, {**concat, "inputs": {"files": {"type": {"type": "array", "items": FILES}, "inputBinding": { - "position": 1}}}}] - message = "'PAIR/out' is a nested_crossproduct result, which reaches workflow outputs only" - with pytest.raises(ValueError, match=message): - lowered_case({"workflow": workflow, "tools": tools, "job": {"as": ["a"], "bs": ["b"], "n": 1}}) - - -def _single_input_join(**method: str) -> ExecutableNextflowWorkflow: - """JOIN scatters over PAIR's gathered output alone, and CONCAT gathers JOIN's.""" - steps = [ - step("PAIR", **{ - "in": {"a": "xs", "b": "ys", "n": "n"}, "out": [{"out": {"wic_anchor": "pair_out"}}], - "scatter": ["a", "b"], "scatterMethod": "dotproduct", - }), - step("JOIN", **{"in": {"f": {"wic_alias": "pair_out"}, "g": "g"}, "out": [{"out": {"wic_anchor": "join_out"}}], - "scatter": ["f"], **method}), - step("CONCAT", **{"in": {"files": {"wic_alias": "join_out"}}, "out": ["all"]}), - ] - workflow = { - "steps": steps, - "inputs": {"xs": {"type": STRINGS}, "ys": {"type": STRINGS}, "n": {"type": "int"}, "g": {"type": "File"}}, - "outputs": {"all": {"type": "File", "outputSource": "CONCAT/all"}}, - } - params = {"xs": ["a"], "ys": ["b"], "n": 1, "g": "/tmp/g"} - return lowered_case({"workflow": workflow, "tools": _tools(), "job": params})[0] - - -@pytest.mark.fast -@pytest.mark.parametrize("method", ["dotproduct", "flat_crossproduct", "nested_crossproduct"]) -def test_a_single_input_scatter_over_a_gathered_source_lowers_alike_under_each_method(method: str) -> None: - """At one scattered input the three methods coincide, as over a workflow input (design §6, Topology).""" - assert _single_input_join(scatterMethod=method).connections == _single_input_join().connections - - -def _gathered_into_nested_join(second: str) -> ExecutableNextflowWorkflow: - """JOIN nests over PAIR's gathered outputs ``f`` and ``second``: PAIR's again or the ``gs`` input.""" - steps = [ - step("PAIR", **{ - "in": {"a": "as", "b": "bs", "n": "n"}, "out": [{"out": {"wic_anchor": "pair_out"}}], - "scatter": ["a", "b"], "scatterMethod": "dotproduct", - }), - step("JOIN", **{ - "in": {"f": {"wic_alias": "pair_out"}, "g": {"wic_alias": "pair_out"} if second == "PAIR/out" else second}, - "out": ["out"], "scatter": ["f", "g"], "scatterMethod": "nested_crossproduct", - }), - ] - inputs = {"as": {"type": STRINGS}, "bs": {"type": STRINGS}, "n": {"type": "int"}} - params: dict[str, object] = {"as": ["a", "b"], "bs": ["x", "y"], "n": 1} - if second == "gs": - inputs["gs"] = {"type": FILES} - params["gs"] = ["/tmp/g1", "/tmp/g2", "/tmp/g3"] - workflow = { - "steps": steps, - "inputs": inputs, - "outputs": {"all": {"type": {"type": "array", "items": FILES}, "outputSource": "JOIN/out"}}, - } - tools = [tool for tool in _tools() if tool["id"] != "CONCAT"] - return lowered_case({"workflow": workflow, "tools": tools, "job": params})[0] - - -@pytest.mark.fast -@pytest.mark.parametrize("second", ["PAIR/out", "gs"], ids=["all_gathered", "one_gathered"]) -def test_a_nested_step_over_gathered_arrays_regroups_its_output_by_the_recorded_shape(second: str) -> None: - rendered = render_nextflow(_gathered_into_nested_join(second)) - assert f"def {NF_NEST_HELPER}(List flat, List shape) {{" in rendered - assert ( - "all = _JOIN.out.out.toSortedList { it[0] }.map { [it.collect { row -> row[1] }] }" - f".combine(ch__JOIN_shape).flatMap {{ flat, shape -> {NF_NEST_HELPER}(flat, shape) }}" - ) in rendered diff --git a/tests/core/nextflow/test_phase3_cells.py b/tests/core/nextflow/test_phase3_cells.py index 92a2ccf19..8af3221c0 100644 --- a/tests/core/nextflow/test_phase3_cells.py +++ b/tests/core/nextflow/test_phase3_cells.py @@ -1,6 +1,6 @@ """The Phase 3 acceptance cells (design §6) as builders. A1-A9, W1-W7 are decided in test_subset_differential.py, -S1-S14 in test_runtime.py's scatter property, W8-W11 and A11 in the cases of nextflow/runs.yaml; A10 has no runtime -test (rejected).""" +S1-S14 in test_runtime.py's scatter property, W8-W11 and A11 in the example workflows of +tests/core/data/nextflow/runs and stops; A10 has no runtime test (rejected).""" # pylint: disable=missing-function-docstring diff --git a/tests/core/nextflow/test_reference_differential.py b/tests/core/nextflow/test_reference_differential.py index 9a14a1151..1280dbb73 100644 --- a/tests/core/nextflow/test_reference_differential.py +++ b/tests/core/nextflow/test_reference_differential.py @@ -10,6 +10,7 @@ import json from pathlib import Path from typing import Any, cast +from urllib.parse import unquote, urlsplit import pytest @@ -130,11 +131,16 @@ def _tree(path: Path) -> Any: def _observed(value: Any) -> Any: - """An output's class, basename and contents; never its path.""" + """An output as a runner-independent observer sees it: a File's or Directory's class, basename and contents, + never its path; null and a string, number or boolean as they are.""" if isinstance(value, list): return [_observed(item) for item in value] - path = Path(value["path"]) - return {"class": value["class"], "basename": path.name, "contents": _tree(path)} + if not isinstance(value, dict): + return value + # cwltool gives a Directory it left where its step made it a location and no path, and an entry it captured the + # path of the file the entry links to: the name is the object's. + path = Path(value["path"] if "path" in value else unquote(urlsplit(value["location"]).path)) + return {"class": value["class"], "basename": value.get("basename", path.name), "contents": _tree(path)} def _snapshot(values: dict[str, Any]) -> dict[str, Any]: @@ -148,17 +154,25 @@ def _run_nextflow(workflow: Workflow, directory: Path) -> dict[str, Any]: return dict(recorded_outputs(result.stdout)) -def _run_cwltool(main: Callable[..., int], workflow: Workflow, directory: Path) -> dict[str, Any]: +def _cwltool(main: Callable[..., int], workflow: Workflow, directory: Path) -> tuple[int, str, str]: + """cwltool's exit code, output object and messages for the CWL `workflow` compiles to, written in `directory`. + Each output stays where its step left it: moved into one directory, two steps' out.txt could not both keep + the name.""" compiled = workflow.compile() document, job = compiled.write_cwl(directory), compiled.write_job_inputs(directory) stdout, stderr = io.StringIO(), io.StringIO() code = main( - ["--quiet", "--outdir", str(directory / "out"), "--tmpdir-prefix", f"{directory}/tmp/", + ["--quiet", "--leave-outputs", "--leave-tmpdir", "--tmpdir-prefix", f"{directory}/tmp/", "--tmp-outdir-prefix", f"{directory}/tmp_out/", str(document), str(job)], stdout=stdout, stderr=stderr, ) - assert code == 0, stderr.getvalue() - return cast(dict[str, Any], json.loads(stdout.getvalue())) + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_cwltool(main: Callable[..., int], workflow: Workflow, directory: Path) -> dict[str, Any]: + code, outputs, messages = _cwltool(main, workflow, directory) + assert code == 0, messages + return cast(dict[str, Any], json.loads(outputs)) @pytest.mark.nextflow diff --git a/tests/core/nextflow/test_renderer.py b/tests/core/nextflow/test_renderer.py deleted file mode 100644 index b645b3119..000000000 --- a/tests/core/nextflow/test_renderer.py +++ /dev/null @@ -1,258 +0,0 @@ -"""Pure deterministic rendering of validated executable IR into artifacts.""" - -# pylint: disable=missing-function-docstring - -from collections.abc import Callable -from functools import partial -from pathlib import Path -from typing import Any - -import pytest - -from sophios.input_output_nf import ( - NF_LOAD_CONTENTS_FUNCTION, - NF_PARSER_CHECK, - NF_STUB_LINES, - render_nextflow, - write_nextflow_artifacts, -) -from sophios.api.python._workflow_runtime import compile_workflow_result -from sophios.api.python.workflow import Workflow -from sophios.ir.artifacts import CompilationResult -from sophios.nf_types import ( - ExecutableNextflowWorkflow, - NF_LOAD_CONTENTS_HELPER, - NF_LOAD_CONTENTS_LIMIT, - NfArrayBinding, - NfBasenameReference, - NfCommand, - NfEntry, - NfFlag, - NfLiteral, - NfPort, - NfProcess, - NfResources, - NfShellLiteral, - NfTemplate, - NfWorkflowInputConnection, -) - -from .test_phase3_cells import _scatter_step -from .testkit import command, flag_workflow, lowered, output_port, ref, runtime_workflow, template - - -@pytest.mark.serial -@pytest.mark.parametrize("build", [runtime_workflow, flag_workflow]) -def test_writes_four_deterministic_artifacts(build: Callable[[], ExecutableNextflowWorkflow], tmp_path: Path) -> None: - workflow = build() - before = workflow.to_json() - paths = write_nextflow_artifacts(workflow, tmp_path) - first = {path.name: path.read_bytes() for path in paths} - assert list(first) == ["nextflow_workflow.json", "workflow.nf", "nextflow.config", "nextflow_params.json"] - write_nextflow_artifacts(workflow, tmp_path) - assert {path.name: path.read_bytes() for path in paths} == first - assert workflow.to_json() == before - - -#: The entry workflow's record of `runtime_workflow()`'s one output, an unscattered file. -RESULT_RECORD = (" PIPELINE.out.result.toList().subscribe { items -> println('sophios-output ' + " - "groovy.json.JsonOutput.toJson(['result', __sophios_output_9f72e(items[0], 0)])) }\n") - - -@pytest.mark.fast -def test_every_process_ends_with_the_stub_that_refuses_a_dry_run() -> None: - rendered = render_nextflow(runtime_workflow()) - stub = "".join(f"\n {line}" for line in NF_STUB_LINES) - assert rendered.count(f' """\n{stub}\n}}') == rendered.count("process ") == 2 - - -@pytest.mark.fast -def test_an_output_record_has_one_array_level_per_scattered_dimension( - real_scattered_result: CompilationResult, -) -> None: - """An unscattered output records its one value, a scatter its list, a nested crossproduct one level per input.""" - nested = _scatter_step("NEST", "nested_crossproduct", {"a": ["a"], "b": ["x"]}) - shapes = { - "unscattered": render_nextflow(runtime_workflow()), - "scattered": render_nextflow(lowered(real_scattered_result)), - "nested": render_nextflow(lowered(compile_workflow_result(Workflow([nested], "nest")))), - } - values = {shape: [line.split("__sophios_output_9f72e(", 1)[1].split(")", 1)[0] - for line in rendered.splitlines() if "subscribe { items" in line] - for shape, rendered in shapes.items()} - assert values == {"unscattered": ["items[0], 0"], "scattered": ["items, 1"], "nested": ["items, 2"]} - - -@pytest.mark.serial -def test_renders_real_compiled_source_with_typed_glob( - real_supported_result: CompilationResult, -) -> None: - rendered = render_nextflow(lowered(real_supported_result)) - assert "path \"${filename}\", arity: '1', emit: result" in rendered - assert "copy(touch.out.result)" in rendered - - -def _fed(*processes: NfProcess, adapter: str | None = None, **params: tuple[Any, str]) -> ExecutableNextflowWorkflow: - """Each input of `processes` fed through `adapter` by the param `params` gives it as (value, declared type), or - by the one param when there is one.""" - names = list(params) - return ExecutableNextflowWorkflow("WF", processes, [ - NfWorkflowInputConnection(port.name if port.name in params else names[0], process.name, port.name, adapter) - for process in processes for port in process.inputs], - {name: value for name, (value, _) in params.items()}, - {name: declared for name, (_, declared) in params.items()}) - - -def _staged() -> ExecutableNextflowWorkflow: - return _fed(NfProcess("STAGE", [ - NfPort("source", "path", entry=NfEntry("renamed.txt")), - NfPort("outDir", "path", path_kind="directory", entry=NfEntry(copy=True)), NfPort("other", "path")], - [NfPort("result", "path", "result", NfTemplate((NfBasenameReference("outDir"),)), "directory")], - command("cat", "renamed.txt", "--outDir", template(ref("outDir")))), - source=("input.txt", "File"), outDir=("out", "Directory"), other=("input2.txt", "File")) - - -def _unread() -> ExecutableNextflowWorkflow: - workflow = runtime_workflow() - return ExecutableNextflowWorkflow(workflow.name, workflow.processes, workflow.connections, - {**workflow.params, "unread": 1}, {**workflow.param_types, "unread": "int"}) - - -def _text_capture_workflow() -> ExecutableNextflowWorkflow: - return ExecutableNextflowWorkflow("wf", [NfProcess("READ", [], [NfPort("text", "val", "text", template("out.txt"), - capture="text")], - command("printf", "hello", stdout="out.txt"))], [], {}) - - -def _alone(*outputs: NfPort, tokens: tuple[Any, ...] = (template("true"),)) -> ExecutableNextflowWorkflow: - return ExecutableNextflowWorkflow("WF", [NfProcess("TASK", [], outputs, NfCommand(tokens))], [], {}) - - -_Q = "__sophios_shell_quote_9f72e" -_ENTRY = "(outDir.toString() - '.sophios_entry_outDir/')" -_EXISTS = "InitialWorkDirRequirement entry already exists in the task directory:" -_RENAMED, _OWN = f"${{{_Q}('renamed.txt')}}", f"${{{_Q}({_ENTRY})}}" -_BASENAME_COPY = NfTemplate((NfBasenameReference("source"), NfLiteral(".copy"))) -_ENTRY_CALL = "Channel.value(__sophios_input_9f72e('message', params.message, 'string'))" -_NAMES = NfPort("names", "val", is_array=True) - -#: Each IR idiom, built when its row runs, the fixed Nextflow text it renders as, and text it never renders. -IDIOMS: dict[str, tuple[Callable[[], ExecutableNextflowWorkflow], list[str], list[str]]] = { - # Artifacts for models that predate the text capture stay byte-identical: no load-contents helper. - "named-workflow-and-entry-wrapper": (runtime_workflow, [ - "workflow PIPELINE {", "take:\n message", "COPY(PRODUCE.out.result)", "result = COPY.out.copy", - f"workflow {{\n{NF_PARSER_CHECK} PIPELINE({_ENTRY_CALL})\n{RESULT_RECORD}}}"], [NF_LOAD_CONTENTS_HELPER]), - "an-unread-param-checked-before-the-call": (_unread, [ - f"workflow {{\n{NF_PARSER_CHECK} __sophios_input_9f72e('unread', params.unread, 'int')\n" - f" PIPELINE({_ENTRY_CALL})\n{RESULT_RECORD}}}\n"], []), - "process-metadata": (partial(_fed, NfProcess( - "TASK", [NfPort("source", "path")], [output_port("report", "report.txt")], command("touch", "report.txt"), - container="ubuntu:24.04", resources=NfResources(2, 1024)), source=("input.txt", "File")), - ["container 'ubuntu:24.04'", "cpus 2", 'memory "1024 MB"', "path 'report.txt', emit: report"], []), - # design §6, Inputs and channels: a hidden staging name, then a symlink or a copy under the CWL name. A basename - # reference to the entry is the last part of its staged path: the path's `.name` would be the whole of it. - "each-entry-staged-hidden-and-made-by-the-task": (_staged, [ - " path source, stageAs: '.sophios_entry_source/*'\n path outDir, stageAs: '.sophios_entry_outDir/*'\n" - " path other\n", " path \"${outDir.toString().tokenize('/').last()}\", glob: false, emit: result\n", - f"if [ -e {_RENAMED} ] || [ -L {_RENAMED} ]; then echo '{_EXISTS}' {_RENAMED} >&2; exit 1; fi\n" - f"ln -s -- ${{{_Q}(source.toString())}} {_RENAMED}\n" - f"if [ -e {_OWN} ] || [ -L {_OWN} ]; then echo '{_EXISTS}' {_OWN} >&2; exit 1; fi\n" - f"cp -RL -- ${{{_Q}(outDir.toString())}} {_OWN}\n" - f"${{{_Q}('cat')}} ${{{_Q}('renamed.txt')}} ${{{_Q}('--outDir')}} ${{{_Q}({_ENTRY})}}\n"], []), - "a-scattered-entry-staged-hidden-in-its-tuple": (partial(_fed, NfProcess( - "STAGE", [NfPort("source", "path", entry=NfEntry(copy=True))], - [NfPort("result", "path", "result", NfTemplate((NfBasenameReference("source"),)))], - command("touch", template(ref("source")))), adapter="dotproduct", sources=(["a.txt", "b.txt"], "File[]")), [ - " tuple val(__sophios_scatter_index_9f72e), path(source, stageAs: '.sophios_entry_source/*')\n", - f"\ncp -RL -- ${{{_Q}(source.toString())}} "], []), - "a-boolean-flag-as-a-conditional-argv-word": (partial(_fed, NfProcess( - "SORT", [NfPort("reverse", "val")], [output_port("result", "sorted.txt")], - NfCommand((template("sort"), NfFlag("reverse", "-r")), stdout=template("sorted.txt"))), - reverse=(True, "boolean")), - [f"${{reverse ? {_Q}('-r') : ''}}"], []), - # A command whose first token can render nothing would start with a space; the `(` starts at column 0. - "a-command-led-by-a-flag-opens-its-parentheses-at-column-0": (partial(_fed, NfProcess( - "SORT", [NfPort("reverse", "val")], [output_port("result", "sorted.txt")], - NfCommand((NfFlag("reverse", "-r"), template("sort")), stdout=template("sorted.txt"))), - reverse=(True, "boolean")), - [f" \"\"\"\n(\n${{reverse ? {_Q}('-r') : ''}} ${{{_Q}('sort')}}\n) > ${{{_Q}('sorted.txt')}}\n \"\"\""], - []), - "an-array-binding-with-a-prefix": (partial(_fed, NfProcess( - "NAMES", [_NAMES], [], NfCommand((template("echo"), NfArrayBinding("names", "--name")))), - names=(["alice", "bob"], "string[]")), - [f"${{names.isEmpty() ? '' : ([{_Q}('--name')] + names.collect{{ {_Q}(it.toString()) }}).join(' ')}}"], []), - "an-array-binding-without-a-prefix": (partial(_fed, NfProcess( - "NAMES", [_NAMES], [], NfCommand((template("echo"), NfArrayBinding("names")))), names=(["alice"], "string[]")), - [f"${{names.isEmpty() ? '' : names.collect{{ {_Q}(it.toString()) }}.join(' ')}}"], []), - "a-shell-literal-as-raw-unquoted-text": (partial(_alone, tokens=( - template("printf"), template("hi"), NfShellLiteral(">>"), template("out.txt"))), - [f" \"\"\"\n(\n${{{_Q}('printf')}} ${{{_Q}('hi')}} >> ${{{_Q}('out.txt')}}\n)\n \"\"\""], - [f"{_Q}('>>')"]), - # The script block is a GString, so a literal $ must not trigger interpolation. - "a-shell-literal-escapes-gstring-interpolation": (partial(_alone, tokens=( - template("true"), NfShellLiteral("$HOME >> out.txt"))), [r"\$HOME >> out.txt"], []), - "an-array-of-paths-staged-per-element": (partial(_fed, NfProcess( - "CAT", [NfPort("sources", "path", is_array=True)], [], NfCommand((template("cat"), NfArrayBinding("sources")))), - sources=(["a.txt", "b.txt"], "File[]")), ["Channel.value(__sophios_input_9f72e('sources', params.sources, " - "'File[]').collect { entry -> file(entry, glob: false) })"], []), - # A path input holding one file reaches the script as a bare Path, so the arity is what lets the array binding - # call list operations on it; the numbered directories keep same-named files apart. - "an-array-of-paths-with-a-list-arity-and-of-vals-without": (partial(_fed, NfProcess( - "CAT", [NfPort("sources", "path", is_array=True), _NAMES], [], - NfCommand((template("cat"), NfArrayBinding("sources"), NfArrayBinding("names")))), - sources=(["a.txt"], "File[]"), names=(["alice"], "string[]")), - [" path sources, arity: '0..*', stageAs: 'gather_sources_*/*'\n", " val names\n"], []), - "basename-segments-in-commands-and-globs": (partial(_fed, NfProcess( - "COPY", [NfPort("source", "path")], [NfPort("result", "path", "result", _BASENAME_COPY)], - command("cp", _BASENAME_COPY)), source=("lines.txt", "File")), - ["source.toString().tokenize('/').last().toString() + '.copy'", - "path \"${source.toString().tokenize('/').last()}.copy\", glob: false, emit: result"], []), - # An author-written name carries no runtime data, so its pattern meaning is whatever the author wrote. - "an-all-literal-output-name-keeps-globbing-on": (partial(_alone, NfPort("result", "path", "result", - template("out*.txt"))), - ["path 'out*.txt', arity: '1', emit: result"], []), - # The reference makes the name runtime-assembled, but the author asked for a pattern in their own literal part. - "an-assembled-name-with-an-author-written-metacharacter": (partial(_fed, NfProcess( - "COPY", [NfPort("source", "path")], [NfPort("result", "path", "result", NfTemplate( - (NfBasenameReference("source"), NfLiteral("*.txt"))))], command("true")), source=("lines.txt", "File")), - ["path \"${source.toString().tokenize('/').last()}*.txt\", arity: '1', emit: result"], []), - # A plain reference carries arbitrary data, and glob: $(inputs.pattern) with "*.txt" must still match. - "a-pattern-valued-input-glob-keeps-globbing-on": (partial(_fed, NfProcess( - "MATCH", [NfPort("pattern", "val")], [NfPort("matched", "path", "matched", template(ref("pattern")))], - command("true")), pattern=("*.txt", "string")), ["path \"${pattern}\", arity: '1', emit: matched"], []), - **{f"a-scattered-{qualifier}-parameter-carries-its-whole-array": (partial(_fed, NfProcess( - "SCATTER", [NfPort("item", qualifier)], [output_port("result", "out.txt")], command("echo", "x")), - adapter="dotproduct", items=(["a", "b"], declared)), [construction], []) - for qualifier, declared, construction in ( - ("val", "string[]", "Channel.value(__sophios_input_9f72e('items', params.items, 'string[]'))"), - ("path", "File[]", "Channel.value(__sophios_input_9f72e('items', params.items, 'File[]')" - ".collect { entry -> file(entry, glob: false) })"))}, - "an-unadapted-workflow-input-without-an-operator": (partial(_fed, NfProcess( - "TASK", [NfPort("item", "val")], [output_port("result", "out.txt")], command("echo", "x")), - items=("a", "string")), [" TASK(items)"], []), - # The author's cardinality declaration is stated, not silently dropped. - "a-capture-marker-as-a-single-valued-path-output": (lambda: ExecutableNextflowWorkflow("wf", [ - NfProcess(name, [], [NfPort("result", "path", "result", template("out.txt"), capture=capture)], - command("touch", "out.txt")) for name, capture in (("DECLARED", "single"), ("UNDECLARED", None))], - [], {}), [" path 'out.txt', glob: false, arity: '1', emit: result\n", - " path 'out.txt', emit: result\n"], []), - **{f"a-capture-marker-disables-{glob}": (partial(_alone, NfPort("result", "path", "result", template(glob), - capture="single")), - ["glob: false, arity: '1', emit: result"], []) - for glob in ("out{1,2}.txt", r"out\literal.txt")}, - # The mapping's own two halves: the byte limit and strict UTF-8 decoding. - "a-text-capture-as-a-value-output-over-the-generated-helper": (_text_capture_workflow, [ - f" val({NF_LOAD_CONTENTS_HELPER}(task.workDir.resolve('out.txt'))), emit: text\n", NF_LOAD_CONTENTS_FUNCTION, - f"bytes.length > {NF_LOAD_CONTENTS_LIMIT}", "UTF_8.newDecoder()"], []), -} - - -@pytest.mark.fast -@pytest.mark.parametrize(("build", "present", "absent"), IDIOMS.values(), ids=IDIOMS) -def test_each_idiom_renders_as_its_fixed_text(build: Callable[[], ExecutableNextflowWorkflow], present: list[str], - absent: list[str]) -> None: - """design §6, the idiom table: an IR idiom renders as one fixed Nextflow text, and the load-contents helper only - where a text capture uses it, so models that predate it render byte-identically.""" - rendered = render_nextflow(build()) - assert [text for text in present if text not in rendered] == [] - assert [text for text in absent if text in rendered] == [] diff --git a/tests/core/nextflow/test_runtime.py b/tests/core/nextflow/test_runtime.py index 8a021cf80..47ac89458 100644 --- a/tests/core/nextflow/test_runtime.py +++ b/tests/core/nextflow/test_runtime.py @@ -10,29 +10,27 @@ import os from pathlib import Path import shlex +import shutil import subprocess from typing import Any, NamedTuple from hypothesis import example, given, strategies as st import pytest +import yaml from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl -from sophios.api.python._workflow_runtime import compile_workflow_result from sophios.api.python.workflow import Step, StepInput, Workflow from sophios.backends import recorded_outputs -from sophios.input_output_nf import write_nextflow_artifacts from sophios.nf_symbols import NEXTFLOW_SCRIPT_NAMES -from sophios.plugins import get_tools_cwl -from sophios.compiler import resolved_view -from sophios.utils_nf import nextflow_names +from sophios.run_status import RunState, RunStatus from ..budgets import budget -from ..cases import cases, match -from ..helpers import ADAPTERS, python_process, search_config, write_tree +from ..cases import DATA, case_dirs +from ..helpers import python_process, search_config from .test_executable_ir import NAMES from .test_public_api import supported_workflow -from .test_reference_differential import _observed, _run_cwltool, _run_nextflow, _tree -from .testkit import assert_succeeded, execute_nextflow, lowered +from .test_reference_differential import _cwltool, _observed, _run_cwltool, _run_nextflow, _tree +from .testkit import assert_succeeded, example_workflow, examples, execute_nextflow @pytest.mark.nextflow @@ -161,62 +159,108 @@ def test_two_workflows_started_from_one_base_path_each_run_their_own_pipeline(tm assert (base / f"nextflow_{name}" / ".nextflow.log").is_file() -def _seen(value: Any) -> Any: - """A recorded output as test_reference_differential observes one, null and a string, number or boolean as it is, - a path also as whether it is a symlink (`link`).""" - if not isinstance(value, (dict, list)): - return value - if isinstance(value, list): - return [_seen(item) for item in value] - return {**_observed(value), "link": Path(value["path"]).is_symlink()} +def _example(folder: Path, directory: Path, monkeypatch: pytest.MonkeyPatch) -> Workflow: + """The workflow of the example `folder`, read from its copy at `directory` (`example_workflow`), which is made the + working directory. Nextflow is kept from asking the network for a newer release.""" + workflow = example_workflow(folder, directory) + monkeypatch.chdir(directory) + monkeypatch.setenv("NXF_OFFLINE", "true") + return workflow + + +def _files(directory: Path) -> dict[str, Any]: + """What `directory` holds, each file as its text.""" + return {path.name: _tree(path) for path in directory.iterdir()} -def _case_files(case: dict[str, Any]) -> dict[str, str]: - """A case's files: each tool a CommandLineTool but for what it leaves out, a workflow of one step per tool unless - it gives its `steps`, after its `inputs` (name: type), each child workflow, and its other files.""" - tools = case.get("tools", {}) - return { - **{f"{stem}.cwl": json.dumps({"cwlVersion": "v1.2", "class": "CommandLineTool", "inputs": {}, "outputs": {}, - **tool}) for stem, tool in tools.items()}, - "workflow.wic": (f"inputs: {json.dumps(case['inputs'])}\n" if "inputs" in case else "") + "steps:\n" + ( - case.get("steps") or "".join(f"- id: {stem}\n" for stem in tools)), - **{f"{stem}.wic": text for stem, text in case.get("children", {}).items()}, - **case.get("files", {}), - } +def _kept(directory: Path, before: dict[str, Any]) -> bool: + """Whether a run left every file `directory` held `before` it as it was.""" + return {name: found for name, found in _files(directory).items() if name in before} == before @pytest.mark.nextflow @pytest.mark.serial -@pytest.mark.parametrize("case", cases("nextflow/runs.yaml", "tools", "inputs", "params", "steps", "children", "files", - "outputs", "fails", "never", "rendered")) -def test_a_workflow_runs_as_its_case_says( - case: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """A case's workflow, its tools written beside it or among cwl_adapters, runs to each of its `outputs`, a workflow - output by its Sophios name, observed as its class, basename and contents, or `fails` showing the text given, no - output unlisted, and a `rendered` match of the script written; the files beside it are left as they were - (tests/core/cases.py reads each form); an output's `link` is whether it is a symlink, and no task made a file - named in `never`; `params` are the values of its workflow inputs.""" - write_tree(tmp_path, _case_files(case)) - monkeypatch.chdir(tmp_path) - inputs = {path.name: _tree(path) for path in tmp_path.iterdir() if path.suffix not in (".wic", ".cwl")} - tools = get_tools_cwl({"search_paths_cwl": {"global": [str(tmp_path), str(ADAPTERS)]}}) - children = {"global": {path.stem: path for path in tmp_path.glob("*.wic") if path.name != "workflow.wic"}} - compiled = compile_workflow_result(Workflow.from_wic(tmp_path / "workflow.wic", tool_registry=tools, - workflow_paths=children), tool_registry=tools) - write_nextflow_artifacts(lowered(compiled, case.get("params", {})), tmp_path) - if "rendered" in case: - assert match(case["rendered"], (tmp_path / "workflow.nf").read_text(encoding="utf-8")) - result = execute_nextflow(tmp_path) - output = f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}" - if "fails" in case: - assert result.returncode != 0 and (case["fails"] is True or case["fails"] in output), output - else: - assert result.returncode == 0, output - names = nextflow_names(resolved_view(compiled))["outputs"] - observed = {names[key]: _seen(value) for key, value in _recorded(result.stdout).items()} - assert match(case["outputs"], observed) and observed.keys() == case["outputs"].keys() - assert not [name for name in case.get("never", []) if list((tmp_path / "work").rglob(name))] - assert {path.name: _tree(path) for path in tmp_path.iterdir() if path.name in inputs} == inputs +@pytest.mark.needs_cwltool +@pytest.mark.parametrize("folder", examples("runs")) +def test_an_example_workflow_runs_under_nextflow_as_under_cwltool( + folder: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Each directory of tests/core/data/nextflow/runs is a workflow to read and to run: `workflow.wic`, the tools + and child workflows it names, `job.yml` for its inputs, and `expected.yaml` stating every output by class, + basename and contents. Run as Nextflow it gives exactly those outputs, and so does cwltool, the reference runner, + for the CWL the same workflow compiles to: the statement is CWL's answer, not Sophios's. The two runners agreeing + is not enough, since a compiler that reversed a list of sources would reverse it for both. Both leave the files + beside the workflow as they were. An example with no `reference` run here is run as Nextflow only. A + `workflow.nf` and `nextflow.config` are the pipeline written, for what no run shows.""" + import cwltool.main # pylint: disable=import-outside-toplevel + + stated = yaml.safe_load((folder / "expected.yaml").read_text(encoding="utf-8")) + for runner in ("nextflow", "cwltool")[:1 if stated.get("reference") == "none" else 2]: + directory = tmp_path / runner + workflow = _example(folder, directory, monkeypatch) + before = _files(directory) + if runner == "nextflow": + ran = workflow.run(target="nextflow", basepath=str(directory / "out")) + assert ran is not None and isinstance(ran.outputs, dict) + outputs = ran.outputs + else: + outputs = _run_cwltool(cwltool.main.main, workflow, directory) + assert {name: _observed(value) for name, value in outputs.items()} == stated["outputs"], runner + assert _kept(directory, before), f"{runner} changed a file beside the workflow" + pipeline = tmp_path / "nextflow" / "out" / "nextflow_workflow" + for written in ("workflow.nf", "nextflow.config"): + if (folder / written).exists(): + assert (pipeline / written).read_text(encoding="utf-8") == (folder / written).read_text(encoding="utf-8") + + +def _stopped(folder: Path, expected: dict[str, Any], tmp_path: Path, + monkeypatch: pytest.MonkeyPatch) -> tuple[RunStatus, Path]: + """An example the Nextflow target runs and cannot finish: the run fails, an error line of its log or the error the + run raised names the step `expected` names, the run's log or Nextflow's says why as `expected` says, and the files + beside the workflow are left as they were. cwltool `fails` on the same workflow too, or `runs` it, as `expected` + says: where it runs, the stop is a rule of Sophios's own. Returns the run's status and its work directory.""" + import cwltool.main # pylint: disable=import-outside-toplevel + + directory = tmp_path / "nextflow" + workflow = _example(folder, directory, monkeypatch) + before = _files(directory) + handle = workflow.start(target="nextflow", basepath=str(directory / "out")) + status = handle.wait() + assert status.state is RunState.FAILED, handle.logs() + logs, pipeline = handle.logs(), directory / "out" / "nextflow_workflow" + raised = [line for line in logs.splitlines() if "ERROR" in line or expected["says"] in line] + assert any(expected["step"] in line for line in raised), logs + assert expected["says"] in logs + (pipeline / ".nextflow.log").read_text(encoding="utf-8"), logs + assert _kept(directory, before) + reference = _example(folder, tmp_path / "cwltool", monkeypatch) + code, _, messages = _cwltool(cwltool.main.main, reference, tmp_path / "cwltool") + assert ("fails" if code else "runs") == expected["cwltool"], messages + return status, pipeline / "work" + + +@pytest.mark.nextflow +@pytest.mark.serial +@pytest.mark.needs_cwltool +@pytest.mark.parametrize("folder, expected", + case_dirs("nextflow/stops/before_a_task", "step", "says", "unwritten", "cwltool")) +def test_a_run_stops_before_a_step_whose_inputs_it_cannot_decide( + folder: Path, expected: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A pickValue that finds no one value, and a `when` holding a subexpression that is not finite, stop the run + naming the step and why (`_stopped`) before any task of it is started: no task failed, and none wrote the step's + file.""" + status, work = _stopped(folder, expected, tmp_path, monkeypatch) + assert not status.steps and not list(work.rglob(expected["unwritten"])) + + +@pytest.mark.nextflow +@pytest.mark.serial +@pytest.mark.needs_cwltool +@pytest.mark.parametrize("folder, expected", case_dirs("nextflow/stops/in_a_task", "step", "says", "cwltool")) +def test_a_run_stops_at_a_task_that_leaves_no_one_answer( + folder: Path, expected: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Two files for an output that takes one, none for an output that needs one, and two entries of one name in a + working directory stop the run naming the step and why (`_stopped`): no output is picked, and no entry is put + inside another.""" + _stopped(folder, expected, tmp_path, monkeypatch) _TEXT = st.text(st.characters(codec="utf-8", exclude_characters="\x00")) @@ -764,49 +808,22 @@ def test_a_captured_text_is_the_files_utf8_up_to_the_cwl_limit( assert _recorded(result.stdout)["captured"] == text -#: A tool that copies its source into an output-target Directory, which it captures. -_COPY_INTO = """cwlVersion: v1.2 -class: CommandLineTool -baseCommand: cp -requirements: - InitialWorkDirRequirement: - listing: - - entry: $(inputs.outDir) - writable: true -inputs: - outDir: - type: Directory - source: - type: File -outputs: - outDir: - type: Directory - outputBinding: - glob: $(inputs.outDir.basename) -arguments: -- $(inputs.source) -- $(inputs.outDir.basename)/copied.txt -""" - - @pytest.mark.nextflow @pytest.mark.serial def test_the_command_line_runs_the_nextflow_target_with_paths_read_beside_the_workflow(tmp_path: Path) -> None: - """Started from elsewhere, the run reads a relative path beside the `.wic` file, makes the output directory - named there, which the tool's writable copy leaves empty, and writes the output object under the Sophios - name of the output.""" - write_tree(tmp_path, { - "copy_into.cwl": _COPY_INTO, "source.txt": "copied text\n", - "w.wic": "steps:\n copy_into:\n in:\n outDir: !ii made\n source: !ii source.txt\n" - " out:\n - outDir: !& made\n"}) + """tests/core/data/nextflow/command_line is a workflow naming a file and an output directory by relative paths. + Started from elsewhere, the run reads both beside the `.wic` file, makes the output directory there, which the + tool's writable copy leaves empty, and writes the output object under the Sophios name of the output.""" + home = tmp_path / "beside" + shutil.copytree(DATA / "nextflow" / "command_line", home) elsewhere = tmp_path / "elsewhere" elsewhere.mkdir() - result = _sophios_cli(tmp_path, tmp_path / "w.wic", tmp_path, "--target", "nextflow", "--run_local", "--basepath", + result = _sophios_cli(home, home / "workflow.wic", home, "--target", "nextflow", "--run_local", "--basepath", "out", cwd=elsewhere, timeout=180) assert_succeeded(result) - assert not (tmp_path / "autogenerated").exists() - assert (tmp_path / "made").is_dir() and not any((tmp_path / "made").iterdir()) - outputs = json.loads((elsewhere / "out" / "output_w.json").read_text(encoding="utf-8")) + assert not (home / "autogenerated").exists() + assert (home / "made").is_dir() and not any((home / "made").iterdir()) + outputs = json.loads((elsewhere / "out" / "output_workflow.json").read_text(encoding="utf-8")) made = outputs["copy_into~outDir"] assert (made["class"], made["basename"]) == ("Directory", "made") assert (Path(made["path"]) / "copied.txt").read_text(encoding="utf-8") == "copied text\n" diff --git a/tests/core/nextflow/test_shipped_append.py b/tests/core/nextflow/test_shipped_append.py deleted file mode 100644 index a967b24c0..000000000 --- a/tests/core/nextflow/test_shipped_append.py +++ /dev/null @@ -1,31 +0,0 @@ -"""The shipped `append.cwl` appends the message as written under cwltool; the Nextflow half is a `runs.yaml` case.""" - -from pathlib import Path - -import pytest - -from sophios.api.python.workflow import Workflow - -from ..helpers import adapter_step -from .test_reference_differential import _run_cwltool - -#: What an unquoting shell would act on: a separator, a run of spaces, a quote, a substitution, a glob. -MESSAGE = "Hello; it's $(echo substituted) * a\\tb\\nc 100%s" - - -@pytest.mark.needs_cwltool -def test_the_shipped_append_tool_appends_the_message_as_written_under_cwltool(tmp_path: Path) -> None: - """One line holding exactly the message is appended, and the given file keeps its one line.""" - import cwltool.main # pylint: disable=import-outside-toplevel - - given = tmp_path / "inputs" / "greeting.txt" - given.parent.mkdir() - given.write_text("first line\n", encoding="utf-8") - append = adapter_step("append", file=given, str=MESSAGE) - workflow = Workflow([append], "append_as_written") - workflow.outputs.appended = append.outputs.file - - appended = Path(_run_cwltool(cwltool.main.main, workflow, tmp_path / "run")["appended"]["path"]) - - assert (appended.name, appended.read_text(encoding="utf-8")) == ("greeting.txt", f"first line\n{MESSAGE}\n") - assert given.read_text(encoding="utf-8") == "first line\n" diff --git a/tests/core/nextflow/test_step_inputs.py b/tests/core/nextflow/test_step_inputs.py index 986b53baa..2c252b957 100644 --- a/tests/core/nextflow/test_step_inputs.py +++ b/tests/core/nextflow/test_step_inputs.py @@ -1,5 +1,5 @@ -"""Step-input default, linkMerge and pickValue lowering (design §6, Topology); their runs are cases in -tests/core/data/nextflow/runs.yaml.""" +"""Step-input default, linkMerge and pickValue lowering (design §6, Topology); their runs are the example +tests/core/data/nextflow/runs/step_inputs and the pickValue stops beside it.""" # pylint: disable=missing-function-docstring diff --git a/tests/core/nextflow/testkit.py b/tests/core/nextflow/testkit.py index afd756916..e0680ebc6 100644 --- a/tests/core/nextflow/testkit.py +++ b/tests/core/nextflow/testkit.py @@ -3,10 +3,16 @@ from collections.abc import Sequence import copy import os +import shutil import subprocess from pathlib import Path from typing import Any +import pytest +import yaml + +from sophios.api.python.workflow import Workflow + from sophios.cli import default_compilation_settings from sophios.compiler import compile_source, resolved_view from sophios.input_output_nf import write_nextflow_artifacts @@ -26,10 +32,13 @@ NfWorkflowInputConnection, NfWorkflowOutputConnection, ) +from sophios.plugins import get_tools_cwl from sophios.utils_cwl import desugar_into_canonical_normal_form from sophios.utils_nf import NEXTFLOW from sophios.wic_types import StepId, Tool, Yaml +from ..cases import DATA +from ..helpers import ADAPTERS from ..hermetic import bundle from ..synthetic_tools import SYNTHETIC_NS @@ -264,3 +273,22 @@ def run_observed( emit: (directory / f"{emit}.sink").read_text(encoding="utf-8").split("\x01") for emit in names if (directory / f"{emit}.sink").exists() } + + +def examples(group: str) -> list[Any]: + """Each example directory of tests/core/data/nextflow/, by its name.""" + return [pytest.param(path, id=path.name) for path in sorted((DATA / "nextflow" / group).iterdir()) if path.is_dir()] + + +def example_workflow(folder: Path, directory: Path) -> Workflow: + """A copy of the example `folder` at `directory`, and the workflow its `workflow.wic` is: read with the tools and + child workflows beside it and the tools Sophios ships, its inputs given the values of `job.yml`. A relative path in + it is read against the working directory, which the caller makes `directory`.""" + shutil.copytree(folder, directory) + tools = get_tools_cwl({"search_paths_cwl": {"global": [str(directory), str(ADAPTERS)]}}) + children = {"global": {path.stem: path for path in directory.glob("*.wic") if path.name != "workflow.wic"}} + workflow = Workflow.from_wic(directory / "workflow.wic", tool_registry=tools, workflow_paths=children) + job = directory / "job.yml" + for name, value in (yaml.safe_load(job.read_text(encoding="utf-8")) if job.exists() else {}).items(): + setattr(workflow.inputs, name, value) + return workflow diff --git a/tests/core/test_ci_coverage.py b/tests/core/test_ci_coverage.py index ba72a314d..85db6d553 100644 --- a/tests/core/test_ci_coverage.py +++ b/tests/core/test_ci_coverage.py @@ -417,11 +417,12 @@ def _tests_importing(module: str, path: Path) -> set[str]: # One cwltool run of a one-step tool that fails, in about two seconds. That the Nextflow target refuses the # glob is checked on every leg by test_capabilities.py; only cwltool shows CWL refuses it too. 'tests/core/nextflow/test_reference_differential.py::test_neither_runner_takes_an_entrys_object_as_a_glob', - # One append step run under cwltool, in about two seconds. Lint And Test's Linux Nextflow step collects it, so the - # Windows leg gives up nothing it ran; the tool's compiled form is checked on every leg by - # test_example_scripts.py's ground truth and the cookbook pairs. - 'tests/core/nextflow/test_shipped_append.py::' - 'test_the_shipped_append_tool_appends_the_message_as_written_under_cwltool', + # Seven example workflows run under Nextflow, six of them under cwltool too, and nine that stop, in about + # forty-five seconds together. Lint And Test's Linux Nextflow step collects them, so the Windows leg gives up + # nothing it ran. + 'tests/core/nextflow/test_runtime.py::test_an_example_workflow_runs_under_nextflow_as_under_cwltool', + 'tests/core/nextflow/test_runtime.py::test_a_run_stops_before_a_step_whose_inputs_it_cannot_decide', + 'tests/core/nextflow/test_runtime.py::test_a_run_stops_at_a_task_that_leaves_no_one_answer', # Four batches of up to twelve small workflows, each run under Nextflow and under cwltool, in about ten # seconds; and one batch of four, whose tools run in containers, in about ten more. Lint And Test's Linux # Nextflow step collects them, so the Windows leg gives up nothing it ran; what each lowers to is checked on From 85f759859e8305777a033fe4a516099bd02cea97 Mon Sep 17 00:00:00 2001 From: Vasu Jaganath Date: Thu, 12 Nov 2026 15:25:30 -0500 Subject: [PATCH 2/7] test(nextflow): tables become properties Refusal tables are seven families of .wic roots refused by code, step and subject; import cases are the example pipelines; IR, support and lowering tables become loops over stated answers and properties. --- design_docs/one-target-table-design.md | 8 +- tests/core/data/nextflow/cli/raw.cwl | 11 + tests/core/data/nextflow/cli/refused.wic | 6 + .../core/data/nextflow/lowered/commands.yaml | 129 --- .../core/data/nextflow/lowered/inherited.yaml | 23 - tests/core/data/nextflow/lowered/staging.yaml | 125 --- .../core/data/nextflow/lowered/workflow.yaml | 182 ---- .../boundary/a_made_input_with_no_value.wic | 4 + .../a_parameter_named_like_a_tool_default.wic | 8 + .../refused/boundary/an_explicit_null.wic | 7 + .../refused/boundary/an_explicit_null.yml | 1 + .../nextflow/refused/boundary/classless.cwl | 8 + .../refused/boundary/colliding_ports.cwl | 8 + .../nextflow/refused/boundary/defaulted.cwl | 7 + .../nextflow/refused/boundary/expected.yaml | 55 ++ .../nextflow/refused/boundary/resources.cwl | 16 + .../refused/boundary/runtime_glob.cwl | 7 + .../data/nextflow/refused/boundary/say.cwl | 7 + .../boundary/steps_that_normalize_alike.wic | 11 + .../refused/boundary/wide_numbers.cwl | 13 + .../nextflow/refused/boundary/workflow.wic | 35 + .../core/data/nextflow/refused/calls/copy.cwl | 9 + .../data/nextflow/refused/calls/copy_all.cwl | 9 + .../nextflow/refused/calls/copy_source.wic | 8 + .../data/nextflow/refused/calls/defaulted.wic | 6 + .../data/nextflow/refused/calls/expected.yaml | 39 + .../nextflow/refused/calls/long_input.wic | 6 + .../nextflow/refused/calls/long_output.wic | 5 + .../data/nextflow/refused/calls/make_long.cwl | 8 + .../data/nextflow/refused/calls/ports.wic | 8 + .../data/nextflow/refused/calls/relay.wic | 7 + .../nextflow/refused/calls/relay_inside.wic | 12 + .../data/nextflow/refused/calls/relays.wic | 18 + .../data/nextflow/refused/calls/take_long.cwl | 7 + .../nextflow/refused/calls/with_hints.wic | 8 + .../refused/calls/with_requirements.wic | 8 + .../data/nextflow/refused/calls/workflow.wic | 50 ++ .../data/nextflow/refused/calls/write.cwl | 8 + .../data/nextflow/refused/calls/write_all.cwl | 7 + .../a_shell_inherited_beside_a_container.wic | 6 + .../refused/commands/absent_values.cwl | 22 + .../commands/argument_position_true.cwl | 7 + .../commands/arguments_as_a_string.cwl | 8 + .../refused/commands/array_separate_false.cwl | 7 + .../refused/commands/array_value_from.cwl | 7 + .../refused/commands/blank_prefix.cwl | 7 + .../nextflow/refused/commands/computed.cwl | 18 + .../refused/commands/computed_binding.cwl | 8 + .../nextflow/refused/commands/containers.cwl | 10 + .../refused/commands/dollar_javascript.cwl | 8 + .../refused/commands/dollar_property.cwl | 8 + .../refused/commands/dollar_runtime.cwl | 8 + .../nextflow/refused/commands/dollar_self.cwl | 8 + .../data/nextflow/refused/commands/double.cwl | 10 + .../refused/commands/empty_in_a_container.cwl | 9 + .../refused/commands/empty_prefix.cwl | 7 + .../nextflow/refused/commands/env_list.cwl | 21 + .../nextflow/refused/commands/env_map.cwl | 9 + .../nextflow/refused/commands/expected.yaml | 97 +++ .../data/nextflow/refused/commands/flags.cwl | 17 + .../data/nextflow/refused/commands/lists.cwl | 7 + .../nextflow/refused/commands/make_lists.cwl | 8 + .../nextflow/refused/commands/maybe_text.cwl | 9 + .../nextflow/refused/commands/on_the_host.cwl | 8 + .../commands/optional_boolean_value_from.cwl | 8 + .../nextflow/refused/commands/per_item.cwl | 7 + .../refused/commands/prefixed_shell_input.cwl | 9 + .../commands/requirements_as_a_name.cwl | 8 + .../commands/runtime_beside_an_optional.cwl | 8 + .../commands/separate_false_boolean.cwl | 7 + .../commands/separate_false_string.cwl | 7 + .../commands/separate_null_boolean.cwl | 7 + .../refused/commands/separate_null_string.cwl | 7 + .../nextflow/refused/commands/tool_fields.cwl | 10 + .../nextflow/refused/commands/unquoted.cwl | 18 + .../commands/unquoted_without_shell.cwl | 8 + .../refused/commands/values_read_as_paths.cwl | 13 + .../nextflow/refused/commands/workflow.wic | 77 ++ .../core/data/nextflow/refused/commands/x.txt | 1 + .../refused/conditions_and_step_inputs/a.txt | 1 + .../a_when_on_a_step_with_no_inputs.wic | 5 + .../an_absent_optional_file.wic | 7 + .../conditions_and_step_inputs/count.cwl | 9 + .../count_default.cwl | 8 + .../conditions_and_step_inputs/expected.yaml | 38 + .../conditions_and_step_inputs/make_files.cwl | 10 + .../conditions_and_step_inputs/say.cwl | 7 + .../conditions_and_step_inputs/say_all.cwl | 7 + .../say_maybe_twice.cwl | 8 + .../conditions_and_step_inputs/show.cwl | 7 + .../conditions_and_step_inputs/show_maybe.cwl | 7 + .../conditions_and_step_inputs/touch_done.cwl | 6 + .../conditions_and_step_inputs/workflow.wic | 118 +++ .../a_step_reads_an_optional_output.wic | 6 + .../an_output_from_a_port_its_step_lacks.wic | 6 + ...n_output_from_a_step_that_is_not_there.wic | 6 + .../outputs/an_output_named_inside_a_call.wic | 6 + .../outputs/an_output_without_a_source.wic | 6 + .../nextflow/refused/outputs/captures.cwl | 58 ++ .../data/nextflow/refused/outputs/evals.cwl | 94 ++ .../nextflow/refused/outputs/expected.yaml | 60 ++ .../data/nextflow/refused/outputs/inner.wic | 6 + .../nextflow/refused/outputs/many_files.cwl | 9 + .../nextflow/refused/outputs/maybe_file.cwl | 9 + .../refused/outputs/named_by_an_array.cwl | 12 + .../nextflow/refused/outputs/read_maybe.cwl | 13 + .../nextflow/refused/outputs/read_text.cwl | 13 + .../nextflow/refused/outputs/say_text.cwl | 13 + .../nextflow/refused/outputs/workflow.wic | 18 + .../nextflow/refused/scatter/expected.yaml | 27 + .../nextflow/refused/scatter/make_files.cwl | 7 + .../data/nextflow/refused/scatter/pair.cwl | 10 + .../requirements_of_the_wrong_shape.wic | 7 + .../data/nextflow/refused/scatter/say.cwl | 7 + .../data/nextflow/refused/scatter/say_all.cwl | 7 + .../data/nextflow/refused/scatter/show.cwl | 7 + .../nextflow/refused/scatter/show_nested.cwl | 7 + .../nextflow/refused/scatter/workflow.wic | 64 ++ .../refused/scatter/workflow_requirements.wic | 9 + .../refused/staging/directory_fields.cwl | 8 + .../data/nextflow/refused/staging/emit.cwl | 8 + .../refused/staging/emit_a_directory.cwl | 7 + .../refused/staging/emit_into_a_directory.cwl | 8 + .../data/nextflow/refused/staging/entries.cwl | 32 + .../refused/staging/entry_of_a_number.cwl | 12 + .../nextflow/refused/staging/expected.yaml | 60 ++ .../refused/staging/glob_at_a_staged_file.cwl | 8 + .../glob_inside_a_staged_directory.cwl | 8 + .../core/data/nextflow/refused/staging/in.txt | 1 + .../data/nextflow/refused/staging/in/keep.txt | 0 .../refused/staging/linked_by_basename.cwl | 10 + .../nextflow/refused/staging/list_into_it.cwl | 9 + .../refused/staging/list_of_globs.cwl | 8 + .../refused/staging/listing_not_a_list.cwl | 8 + .../refused/staging/object_streams.cwl | 14 + .../nextflow/refused/staging/references.cwl | 18 + .../refused/staging/references_to_entries.cwl | 16 + .../staging/renamed_and_referenced.cwl | 12 + .../refused/staging/renamed_and_written.cwl | 11 + .../refused/staging/renamed_entries.cwl | 19 + .../data/nextflow/refused/staging/sort.cwl | 9 + .../refused/staging/sort_an_entry.cwl | 11 + .../refused/staging/sort_by_its_glob.cwl | 9 + .../refused/staging/sort_dot_slash.cwl | 9 + .../stderr_inside_a_staged_directory.cwl | 8 + .../staging/stdout_at_a_staged_file.cwl | 8 + .../refused/staging/stdout_at_an_entry.cwl | 10 + .../nextflow/refused/staging/workflow.wic | 60 ++ .../core/data/nextflow/rejected/boundary.yaml | 157 ---- tests/core/data/nextflow/rejected/calls.yaml | 136 --- .../core/data/nextflow/rejected/commands.yaml | 365 -------- .../data/nextflow/rejected/conditions.yaml | 66 -- tests/core/data/nextflow/rejected/inputs.yaml | 24 - .../core/data/nextflow/rejected/outputs.yaml | 258 ------ .../core/data/nextflow/rejected/scatter.yaml | 106 --- .../core/data/nextflow/rejected/staging.yaml | 283 ------ .../data/nextflow/runs/commands/expected.yaml | 2 +- .../nextflow/runs/commands/print_bindings.cwl | 3 + .../nextflow/runs/commands/three_commands.cwl | 3 +- .../data/nextflow/runs/commands/workflow.wic | 4 +- tests/core/nextflow/conftest.py | 82 -- tests/core/nextflow/test_capabilities.py | 252 ++---- tests/core/nextflow/test_channels.py | 87 +- tests/core/nextflow/test_conditions.py | 191 ----- tests/core/nextflow/test_executable_ir.py | 271 +++--- tests/core/nextflow/test_float_text.py | 37 +- tests/core/nextflow/test_import.py | 810 ++++++------------ tests/core/nextflow/test_lowering.py | 207 +---- tests/core/nextflow/test_lowering_outcomes.py | 45 +- tests/core/nextflow/test_properties.py | 289 ++----- tests/core/nextflow/test_public_api.py | 177 ++-- .../core/nextflow/test_real_world_examples.py | 187 ---- .../nextflow/test_reference_differential.py | 34 +- tests/core/nextflow/test_safe_subset.py | 189 ++-- tests/core/nextflow/test_step_inputs.py | 198 ----- tests/core/nextflow/test_support_table.py | 124 ++- tests/core/nextflow/testkit.py | 59 +- tests/core/provocations.py | 31 +- tests/core/test_ci_coverage.py | 11 +- tests/core/test_run_local.py | 5 +- 180 files changed, 2965 insertions(+), 4277 deletions(-) create mode 100644 tests/core/data/nextflow/cli/raw.cwl create mode 100644 tests/core/data/nextflow/cli/refused.wic delete mode 100644 tests/core/data/nextflow/lowered/commands.yaml delete mode 100644 tests/core/data/nextflow/lowered/inherited.yaml delete mode 100644 tests/core/data/nextflow/lowered/staging.yaml delete mode 100644 tests/core/data/nextflow/lowered/workflow.yaml create mode 100644 tests/core/data/nextflow/refused/boundary/a_made_input_with_no_value.wic create mode 100644 tests/core/data/nextflow/refused/boundary/a_parameter_named_like_a_tool_default.wic create mode 100644 tests/core/data/nextflow/refused/boundary/an_explicit_null.wic create mode 100644 tests/core/data/nextflow/refused/boundary/an_explicit_null.yml create mode 100644 tests/core/data/nextflow/refused/boundary/classless.cwl create mode 100644 tests/core/data/nextflow/refused/boundary/colliding_ports.cwl create mode 100644 tests/core/data/nextflow/refused/boundary/defaulted.cwl create mode 100644 tests/core/data/nextflow/refused/boundary/expected.yaml create mode 100644 tests/core/data/nextflow/refused/boundary/resources.cwl create mode 100644 tests/core/data/nextflow/refused/boundary/runtime_glob.cwl create mode 100644 tests/core/data/nextflow/refused/boundary/say.cwl create mode 100644 tests/core/data/nextflow/refused/boundary/steps_that_normalize_alike.wic create mode 100644 tests/core/data/nextflow/refused/boundary/wide_numbers.cwl create mode 100644 tests/core/data/nextflow/refused/boundary/workflow.wic create mode 100644 tests/core/data/nextflow/refused/calls/copy.cwl create mode 100644 tests/core/data/nextflow/refused/calls/copy_all.cwl create mode 100644 tests/core/data/nextflow/refused/calls/copy_source.wic create mode 100644 tests/core/data/nextflow/refused/calls/defaulted.wic create mode 100644 tests/core/data/nextflow/refused/calls/expected.yaml create mode 100644 tests/core/data/nextflow/refused/calls/long_input.wic create mode 100644 tests/core/data/nextflow/refused/calls/long_output.wic create mode 100644 tests/core/data/nextflow/refused/calls/make_long.cwl create mode 100644 tests/core/data/nextflow/refused/calls/ports.wic create mode 100644 tests/core/data/nextflow/refused/calls/relay.wic create mode 100644 tests/core/data/nextflow/refused/calls/relay_inside.wic create mode 100644 tests/core/data/nextflow/refused/calls/relays.wic create mode 100644 tests/core/data/nextflow/refused/calls/take_long.cwl create mode 100644 tests/core/data/nextflow/refused/calls/with_hints.wic create mode 100644 tests/core/data/nextflow/refused/calls/with_requirements.wic create mode 100644 tests/core/data/nextflow/refused/calls/workflow.wic create mode 100644 tests/core/data/nextflow/refused/calls/write.cwl create mode 100644 tests/core/data/nextflow/refused/calls/write_all.cwl create mode 100644 tests/core/data/nextflow/refused/commands/a_shell_inherited_beside_a_container.wic create mode 100644 tests/core/data/nextflow/refused/commands/absent_values.cwl create mode 100644 tests/core/data/nextflow/refused/commands/argument_position_true.cwl create mode 100644 tests/core/data/nextflow/refused/commands/arguments_as_a_string.cwl create mode 100644 tests/core/data/nextflow/refused/commands/array_separate_false.cwl create mode 100644 tests/core/data/nextflow/refused/commands/array_value_from.cwl create mode 100644 tests/core/data/nextflow/refused/commands/blank_prefix.cwl create mode 100644 tests/core/data/nextflow/refused/commands/computed.cwl create mode 100644 tests/core/data/nextflow/refused/commands/computed_binding.cwl create mode 100644 tests/core/data/nextflow/refused/commands/containers.cwl create mode 100644 tests/core/data/nextflow/refused/commands/dollar_javascript.cwl create mode 100644 tests/core/data/nextflow/refused/commands/dollar_property.cwl create mode 100644 tests/core/data/nextflow/refused/commands/dollar_runtime.cwl create mode 100644 tests/core/data/nextflow/refused/commands/dollar_self.cwl create mode 100644 tests/core/data/nextflow/refused/commands/double.cwl create mode 100644 tests/core/data/nextflow/refused/commands/empty_in_a_container.cwl create mode 100644 tests/core/data/nextflow/refused/commands/empty_prefix.cwl create mode 100644 tests/core/data/nextflow/refused/commands/env_list.cwl create mode 100644 tests/core/data/nextflow/refused/commands/env_map.cwl create mode 100644 tests/core/data/nextflow/refused/commands/expected.yaml create mode 100644 tests/core/data/nextflow/refused/commands/flags.cwl create mode 100644 tests/core/data/nextflow/refused/commands/lists.cwl create mode 100644 tests/core/data/nextflow/refused/commands/make_lists.cwl create mode 100644 tests/core/data/nextflow/refused/commands/maybe_text.cwl create mode 100644 tests/core/data/nextflow/refused/commands/on_the_host.cwl create mode 100644 tests/core/data/nextflow/refused/commands/optional_boolean_value_from.cwl create mode 100644 tests/core/data/nextflow/refused/commands/per_item.cwl create mode 100644 tests/core/data/nextflow/refused/commands/prefixed_shell_input.cwl create mode 100644 tests/core/data/nextflow/refused/commands/requirements_as_a_name.cwl create mode 100644 tests/core/data/nextflow/refused/commands/runtime_beside_an_optional.cwl create mode 100644 tests/core/data/nextflow/refused/commands/separate_false_boolean.cwl create mode 100644 tests/core/data/nextflow/refused/commands/separate_false_string.cwl create mode 100644 tests/core/data/nextflow/refused/commands/separate_null_boolean.cwl create mode 100644 tests/core/data/nextflow/refused/commands/separate_null_string.cwl create mode 100644 tests/core/data/nextflow/refused/commands/tool_fields.cwl create mode 100644 tests/core/data/nextflow/refused/commands/unquoted.cwl create mode 100644 tests/core/data/nextflow/refused/commands/unquoted_without_shell.cwl create mode 100644 tests/core/data/nextflow/refused/commands/values_read_as_paths.cwl create mode 100644 tests/core/data/nextflow/refused/commands/workflow.wic create mode 100644 tests/core/data/nextflow/refused/commands/x.txt create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/a.txt create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/a_when_on_a_step_with_no_inputs.wic create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/an_absent_optional_file.wic create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/count.cwl create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/count_default.cwl create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/expected.yaml create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/make_files.cwl create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/say.cwl create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/say_all.cwl create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/say_maybe_twice.cwl create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/show.cwl create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/show_maybe.cwl create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/touch_done.cwl create mode 100644 tests/core/data/nextflow/refused/conditions_and_step_inputs/workflow.wic create mode 100644 tests/core/data/nextflow/refused/outputs/a_step_reads_an_optional_output.wic create mode 100644 tests/core/data/nextflow/refused/outputs/an_output_from_a_port_its_step_lacks.wic create mode 100644 tests/core/data/nextflow/refused/outputs/an_output_from_a_step_that_is_not_there.wic create mode 100644 tests/core/data/nextflow/refused/outputs/an_output_named_inside_a_call.wic create mode 100644 tests/core/data/nextflow/refused/outputs/an_output_without_a_source.wic create mode 100644 tests/core/data/nextflow/refused/outputs/captures.cwl create mode 100644 tests/core/data/nextflow/refused/outputs/evals.cwl create mode 100644 tests/core/data/nextflow/refused/outputs/expected.yaml create mode 100644 tests/core/data/nextflow/refused/outputs/inner.wic create mode 100644 tests/core/data/nextflow/refused/outputs/many_files.cwl create mode 100644 tests/core/data/nextflow/refused/outputs/maybe_file.cwl create mode 100644 tests/core/data/nextflow/refused/outputs/named_by_an_array.cwl create mode 100644 tests/core/data/nextflow/refused/outputs/read_maybe.cwl create mode 100644 tests/core/data/nextflow/refused/outputs/read_text.cwl create mode 100644 tests/core/data/nextflow/refused/outputs/say_text.cwl create mode 100644 tests/core/data/nextflow/refused/outputs/workflow.wic create mode 100644 tests/core/data/nextflow/refused/scatter/expected.yaml create mode 100644 tests/core/data/nextflow/refused/scatter/make_files.cwl create mode 100644 tests/core/data/nextflow/refused/scatter/pair.cwl create mode 100644 tests/core/data/nextflow/refused/scatter/requirements_of_the_wrong_shape.wic create mode 100644 tests/core/data/nextflow/refused/scatter/say.cwl create mode 100644 tests/core/data/nextflow/refused/scatter/say_all.cwl create mode 100644 tests/core/data/nextflow/refused/scatter/show.cwl create mode 100644 tests/core/data/nextflow/refused/scatter/show_nested.cwl create mode 100644 tests/core/data/nextflow/refused/scatter/workflow.wic create mode 100644 tests/core/data/nextflow/refused/scatter/workflow_requirements.wic create mode 100644 tests/core/data/nextflow/refused/staging/directory_fields.cwl create mode 100644 tests/core/data/nextflow/refused/staging/emit.cwl create mode 100644 tests/core/data/nextflow/refused/staging/emit_a_directory.cwl create mode 100644 tests/core/data/nextflow/refused/staging/emit_into_a_directory.cwl create mode 100644 tests/core/data/nextflow/refused/staging/entries.cwl create mode 100644 tests/core/data/nextflow/refused/staging/entry_of_a_number.cwl create mode 100644 tests/core/data/nextflow/refused/staging/expected.yaml create mode 100644 tests/core/data/nextflow/refused/staging/glob_at_a_staged_file.cwl create mode 100644 tests/core/data/nextflow/refused/staging/glob_inside_a_staged_directory.cwl create mode 100644 tests/core/data/nextflow/refused/staging/in.txt create mode 100644 tests/core/data/nextflow/refused/staging/in/keep.txt create mode 100644 tests/core/data/nextflow/refused/staging/linked_by_basename.cwl create mode 100644 tests/core/data/nextflow/refused/staging/list_into_it.cwl create mode 100644 tests/core/data/nextflow/refused/staging/list_of_globs.cwl create mode 100644 tests/core/data/nextflow/refused/staging/listing_not_a_list.cwl create mode 100644 tests/core/data/nextflow/refused/staging/object_streams.cwl create mode 100644 tests/core/data/nextflow/refused/staging/references.cwl create mode 100644 tests/core/data/nextflow/refused/staging/references_to_entries.cwl create mode 100644 tests/core/data/nextflow/refused/staging/renamed_and_referenced.cwl create mode 100644 tests/core/data/nextflow/refused/staging/renamed_and_written.cwl create mode 100644 tests/core/data/nextflow/refused/staging/renamed_entries.cwl create mode 100644 tests/core/data/nextflow/refused/staging/sort.cwl create mode 100644 tests/core/data/nextflow/refused/staging/sort_an_entry.cwl create mode 100644 tests/core/data/nextflow/refused/staging/sort_by_its_glob.cwl create mode 100644 tests/core/data/nextflow/refused/staging/sort_dot_slash.cwl create mode 100644 tests/core/data/nextflow/refused/staging/stderr_inside_a_staged_directory.cwl create mode 100644 tests/core/data/nextflow/refused/staging/stdout_at_a_staged_file.cwl create mode 100644 tests/core/data/nextflow/refused/staging/stdout_at_an_entry.cwl create mode 100644 tests/core/data/nextflow/refused/staging/workflow.wic delete mode 100644 tests/core/data/nextflow/rejected/boundary.yaml delete mode 100644 tests/core/data/nextflow/rejected/calls.yaml delete mode 100644 tests/core/data/nextflow/rejected/commands.yaml delete mode 100644 tests/core/data/nextflow/rejected/conditions.yaml delete mode 100644 tests/core/data/nextflow/rejected/inputs.yaml delete mode 100644 tests/core/data/nextflow/rejected/outputs.yaml delete mode 100644 tests/core/data/nextflow/rejected/scatter.yaml delete mode 100644 tests/core/data/nextflow/rejected/staging.yaml delete mode 100644 tests/core/nextflow/conftest.py delete mode 100644 tests/core/nextflow/test_conditions.py delete mode 100644 tests/core/nextflow/test_real_world_examples.py delete mode 100644 tests/core/nextflow/test_step_inputs.py diff --git a/design_docs/one-target-table-design.md b/design_docs/one-target-table-design.md index 16ca4b4fb..07b29a452 100644 --- a/design_docs/one-target-table-design.md +++ b/design_docs/one-target-table-design.md @@ -122,7 +122,7 @@ the pointer nor the file stays: - nothing in the docs promised it: `docs/cli-reference.md`, `docs/running.md` and `docs/checks-and-errors.md` name `error_.txt` only for a failure Sophios did not expect, and `docs/nextflow.md` named it nowhere; - one test pinned it, `test_nextflow_cli_conversion_error_is_concise_and_actionable`, now folded into - `test_a_refusal_is_reported_on_stderr_as_a_diagnostic`, which keeps its point: a refusal leaves none of the four + `tests/core/nextflow/test_public_api.py`, which keeps its point: a refusal leaves none of the four files an earlier write left; - a refusal is a reported problem, which exit 1 already describes as "its diagnostics are on stderr"; the file is for a traceback, and a refusal has none. The crash handler keeps its `error_.txt`. @@ -191,7 +191,7 @@ released; when Nextflow learns a construct its code is retired and its row says is refused for its type (`nf-s048`) too, and an array step output is refused at its producer (`nf-s031`). `nf-s007`, a `nested_crossproduct` result read by a later step: two scattered inputs make an array of arrays, which the reading port must declare (`nf-s048`) or Link refuses (`wic023`), and one scattered input is a `dotproduct`, -which lowers (`tests/core/data/nextflow/rejected/scatter.yaml`, `a_nested_crossproduct_result_read_by_a_later_step`). +which lowers (`tests/core/data/nextflow/refused/scatter`, step `reads_pairs`). Each stays its own code: the scatter is its own construct, and a target that learns nested arrays still refuses it. **The list** is `docs/error_codes.md`; `test_the_error_codes_page_says_what_the_code_says` keeps it equal to the @@ -220,8 +220,8 @@ Refusals a case still reaches stay, coded, and so do the listing checks a tool w ## 7. Tests, and what was measured -Every rejected case (`tests/core/data/nextflow/rejected/*.yaml`) names its refusals' codes in order, and new cases -reach each code and each family of §5 no case reached. Other tests pin the table against `--target` and the +Every refused family (`tests/core/data/nextflow/refused/`) names its refusals' codes in order, and new +cases reach each code and each family of §5 no case reached. Other tests pin the table against `--target` and the `Literal`, an unknown target, a refusal's layout from Python and the command line, `check()` returning refusals, `--explain nf-s007`, and `--allow_raw_cwl` under Nextflow. diff --git a/tests/core/data/nextflow/cli/raw.cwl b/tests/core/data/nextflow/cli/raw.cwl new file mode 100644 index 000000000..5e56a1d3f --- /dev/null +++ b/tests/core/data/nextflow/cli/raw.cwl @@ -0,0 +1,11 @@ +cwlVersion: v1.2 +class: Workflow +doc: A plain CWL workflow of the shipped echo tool. +inputs: + msg: {type: string, default: hi} +outputs: {} +steps: + say: + run: ../../../../../cwl_adapters/echo.cwl + in: {message: msg} + out: [stdout] diff --git a/tests/core/data/nextflow/cli/refused.wic b/tests/core/data/nextflow/cli/refused.wic new file mode 100644 index 000000000..0ec9b4cf8 --- /dev/null +++ b/tests/core/data/nextflow/cli/refused.wic @@ -0,0 +1,6 @@ +# A when the safe subset refuses: < compares numbers, and the message is a string. +steps: + echo: + in: + message: !ii hi + when: $(inputs.message < "27") diff --git a/tests/core/data/nextflow/lowered/commands.yaml b/tests/core/data/nextflow/lowered/commands.yaml deleted file mode 100644 index 433c08a86..000000000 --- a/tests/core/data/nextflow/lowered/commands.yaml +++ /dev/null @@ -1,129 +0,0 @@ -# Commands the target lowers (design §6, Commands). `lowered` is the replaced test's IR literal in payload form (the -# fields test_executable_ir.py's payload table pins); a whole token list is the tool's bindings in CWL position order, -# derived by hand from the document, never read off a lowering. -- id: flag_tokens_take_their_cwl_position_among_other_bindings - why: A flag is ordered by position like any other binding, not appended. - tool: {id: SORT, inputs: {source: {type: File, inputBinding: {position: 3}}, reverse: {type: boolean, inputBinding: - {position: 2, prefix: -r}}}, arguments: [{position: 1, valueFrom: --stable}]} - job: {source: {class: File, path: in.txt}, reverse: true} - lowered: {processes: [{command: {tokens: [{segments: [{kind: literal, value: SORT}]}, {segments: [{kind: literal, - value: --stable}]}, {kind: flag, name: reverse, prefix: -r}, {segments: [{kind: input, name: source}]}]}}]} -- id: array_of_scalars_lowers_to_a_val_array_port_with_a_binding - why: &array An array input is one array-marked port, bound per item. - tool: &list {id: LIST, inputs: {names: {type: {type: array, items: string}, inputBinding: {position: 1, prefix: - --name}}}} - job: {names: [alice, bob]} - lowered: {processes: [{inputs: [{name: names, qualifier: val, emit: null, glob: null, path_kind: null, is_array: true, - entry: null, capture: null, optional: false}], command: {tokens: [{segments: [{kind: literal, - value: LIST}]}, - {kind: array, name: names, prefix: --name}]}}]} -- id: array_of_files_lowers_to_a_path_array_port - why: *array - tool: {id: CAT, inputs: {sources: {type: {type: array, items: File}, inputBinding: {position: 1}}}} - job: {sources: [{class: File, path: a.txt}, {class: File, path: b.txt}]} - lowered: {processes: [{inputs: [{name: sources, qualifier: path, emit: null, glob: null, path_kind: file, is_array: - true, entry: null, capture: null, optional: false}], command: {tokens: [&cat {segments: [{kind: literal, - value: CAT}]}, {kind: array, name: sources, prefix: null}]}}]} -- {id: array_binding_without_a_prefix_lowers_correctly, why: *array, tool: {id: CAT, inputs: {sources: {type: {type: - array, items: string}, inputBinding: {}}}}, job: {sources: [a, b]}, lowered: {processes: [{command: {tokens: [*cat, - {kind: array, name: sources, prefix: null}]}}]}} -- {id: empty_array_value_is_accepted_and_distinct_from_absent, why: 'A supplied [] is a present, valid, zero-length - value, not absence.', tool: *list, job: {names: []}, lowered: {params: {exact: {names: []}}}} -- id: shell_quote_false_literal_lowers_to_a_raw_shell_literal_token - why: &unquoted 'design §6, Commands: a literal valueFrom under ShellCommandRequirement is unquoted text.' - tool: {id: REDIRECT, outputs: &result {result: {type: File, outputBinding: {glob: out.txt}}}, requirements: - &shell_mode {ShellCommandRequirement: {}}, arguments: [{position: 1, valueFrom: hello}, - {position: 2, valueFrom: - '>>', shellQuote: false}, {position: 3, valueFrom: out.txt}]} - out: &out [result] - lowered: {processes: [{command: {tokens: [{segments: [{kind: literal, value: REDIRECT}]}, &hello {segments: [{kind: - literal, value: hello}]}, &append {kind: shell_literal, text: '>>'}, &out_txt {segments: [{kind: literal, - value: out.txt}]}]}}]} -- {id: shell_quote_false_takes_precedence_over_boolean_flag_lowering, why: 'A literal valueFrom fully overrides - type-specific binding, even on a boolean input.', job: {flag: true}, tool: {id: LITERAL, requirements: *shell_mode, - inputs: {flag: {type: boolean, inputBinding: {position: 1, valueFrom: --literal, shellQuote: false}}}}, lowered: { - processes: [{command: {tokens: [{segments: [{kind: literal, value: LITERAL}]}, {kind: shell_literal, text: - --literal}]}}]}} -- {id: command_of_only_shell_literals_still_runs_a_program, why: 'A shell literal is itself executable command text, - not an empty command.', tool: {id: LITERAL, requirements: *shell_mode, baseCommand: null, arguments: [{position: 1, - valueFrom: printf ok, shellQuote: false}]}, lowered: {processes: [{command: {tokens: [{kind: shell_literal, text: - printf ok}]}}]}} -- {id: accepts_shell_command_requirement_with_no_shell_quote_false, why: 'ShellCommandRequirement alone changes - nothing: no shellQuote:false, nothing to reject.', out: *out, tool: &shell {id: SHELL, outputs: *result, - requirements: *shell_mode, arguments: [hello]}, lowered: {processes: [{command: {tokens: [&shell_word {segments: - [{kind: literal, value: SHELL}]}, *hello]}}]}} -- {id: accepts_literal_shell_quote_false_binding, why: *unquoted, out: *out, tool: {<<: *shell, arguments: [{valueFrom: - '>>', shellQuote: false}, out.txt]}, lowered: {processes: [{command: {tokens: [*shell_word, *append, *out_txt]}}]}} -- {id: a_command_of_only_flags_still_runs_a_program, why: A flag-only argv would render an empty script that silently - exits zero., job: {verbose: true}, tool: {baseCommand: null, inputs: {verbose: {type: boolean, - inputBinding: {position: 1, prefix: --verbose}}}}, lowered: {processes: [{command: {tokens: [{segments: [{kind: - literal, value: 'true'}]}, {kind: flag, name: verbose, prefix: --verbose}]}}]}} -- id: basename_lowers_to_a_typed_segment_in_every_template_position - why: 'design §6, Basename references: a basename is a typed segment wherever a template stands.' - tool: {id: COPY, inputs: {source: {type: File, inputBinding: {position: 1}}}, outputs: {result: {type: File, - outputBinding: {glob: $(inputs.source.basename).copy}}}, arguments: [{position: 2, valueFrom: - $(inputs.source.basename).copy}], stdout: $(inputs.source.basename).log} - out: *out - job: {source: {class: File, path: lines.txt}} - lowered: {processes: [{outputs: [{glob: {segments: © [{kind: basename, name: source}, {kind: literal, value: - .copy}]}}], command: {tokens: [{segments: [{kind: literal, value: COPY}]}, {segments: [{kind: input, name: - source}]}, {segments: *copy}], stdout: {segments: [{kind: basename, name: source}, {kind: literal, value: - .log}]}}}]} -- id: base_command_and_prefix_are_literals-string - why: &literals A baseCommand and a prefix are literal text, never read for references. - tool: &literal {id: LITERAL, inputs: {s: {type: string, inputBinding: {prefix: -$(inputs.s)}}}, baseCommand: - pre$(inputs.s)} - job: &s {s: x} - lowered: &literal_tokens {processes: [{command: {tokens: [{segments: [{kind: literal, value: pre$(inputs.s)}]}, - {segments: [{kind: literal, value: -$(inputs.s)}]}, - {segments: [{kind: input, name: s}]}]}}]} -- {id: base_command_and_prefix_are_literals-list, why: *literals, job: *s, lowered: *literal_tokens, tool: {<<: - *literal, baseCommand: [pre$(inputs.s)]}} -- id: a_whole_boolean_valuefrom_is_a_flag-argument - why: &boolean_value_from A valueFrom that is exactly a boolean input is that input's flag, or nothing without a - prefix. - tool: &flag {id: FLAG, inputs: {b: {type: boolean}}, baseCommand: echo, arguments: [{valueFrom: $(inputs.b), prefix: - --flag}]} - job: &b {b: true} - lowered: &echo_flag {processes: [{command: {tokens: [&echo {segments: [{kind: literal, value: echo}]}, {kind: flag, - name: b, prefix: --flag}]}}]} -- {id: a_whole_boolean_valuefrom_is_a_flag-argument-without-a-prefix, why: *boolean_value_from, job: *b, tool: {<<: - *flag, arguments: [{valueFrom: $(inputs.b)}]}, lowered: &echo_alone {processes: [{command: {tokens: [*echo]}}]}} -- {id: a_whole_boolean_valuefrom_is_a_flag-string-input-binding, why: *boolean_value_from, job: &bs {b: true, s: x}, - lowered: *echo_flag, tool: {<<: *flag, arguments: [], inputs: {b: {type: boolean}, s: {type: string, inputBinding: - {valueFrom: $(inputs.b), prefix: --flag}}}}} -- {id: a_whole_boolean_valuefrom_is_a_flag-string-input-binding-without-a-prefix, why: *boolean_value_from, job: *bs, - lowered: *echo_alone, tool: {<<: *flag, arguments: [], inputs: {b: {type: boolean}, s: {type: string, inputBinding: - {valueFrom: $(inputs.b)}}}}} -- id: env_var_requirement_lowers_each_variable_to_an_export-list - why: &env The task exports each variable, shell-quoted, as the script's first lines; the map form's key names the - variable, over an envName inside it, as schema-salad resolves it. - tool: &env_tool {id: ENV, inputs: {s: {type: string}}, requirements: {EnvVarRequirement: {envDef: [{envName: A, - envValue: cost $5}, {envName: B, envValue: ' $(inputs.s) '}]}}} - job: {s: v} - lowered: &exports {processes: [{command: {env: [{name: A, value: {segments: [{kind: literal, value: cost $5}]}}, - {name: B, value: {segments: [{kind: input, name: s}]}}]}}]} - render: &export_lines [" \"\"\"\nexport A=${__sophios_shell_quote_9f72e('cost $5')}\nexport - B=${__sophios_shell_quote_9f72e(s.toString())}\n"] -- {id: env_var_requirement_lowers_each_variable_to_an_export-map, why: *env, job: {s: v}, lowered: *exports, render: - *export_lines, tool: {<<: *env_tool, requirements: {EnvVarRequirement: {envDef: {A: cost $5, B: {envName: C, - envValue: ' $(inputs.s) '}}}}}} -- {id: absent_optional_input_bound_directly_into_the_command_lowers_to_an_optional_binding, why: 'CWL adds nothing for - a null input: its own binding is presence-gated, prefix included.', job: {message: null}, tool: {id: OPTIONAL, - inputs: {message: {type: ['null', string], inputBinding: {position: 1, prefix: --message}}}}, lowered: {processes: - [{command: {tokens: [{segments: [{kind: literal, value: OPTIONAL}]}, {kind: optional_binding, name: message, prefix: - --message, separate: true}]}}], params: {exact: {message: []}}}} -- {id: accepts_unreferenced_absent_optional_input, why: 'An optional val input with no inputBinding is never - dereferenced, so absence is safe.', job: {message: null}, tool: {id: OPTIONAL, inputs: {message: {type: ['null', - string]}}}, lowered: {params: {exact: {message: []}}, connections: {contains: [{kind: workflow_input, from_port: - message, to_process: _OPTIONAL, to_port: message, adapter: null}]}}} -- {id: a_file_reference_embedded_in_text-whole-file, why: &json 'design §6, Commands: CWL renders an embedded File - object as JSON; the reference alone, or its path or basename in text, is what the target takes.', job: &f_s {f: - {class: File, path: in.txt}, s: x}, tool: &embedded {inputs: {f: {type: File}, s: {type: string}}, - arguments: [$(inputs.f)]}} -- {id: a_file_reference_embedded_in_text-embedded-path, why: *json, job: *f_s, tool: {<<: *embedded, arguments: - ['--input=$(inputs.f.path)']}} -- {id: a_file_reference_embedded_in_text-embedded-basename, why: *json, job: *f_s, tool: {<<: *embedded, arguments: - ['--input=$(inputs.f.basename)']}} -- {id: a_file_reference_embedded_in_text-embedded-string, why: *json, job: *f_s, tool: {<<: *embedded, arguments: - ['--name=$(inputs.s)']}} diff --git a/tests/core/data/nextflow/lowered/inherited.yaml b/tests/core/data/nextflow/lowered/inherited.yaml deleted file mode 100644 index 3f1aee479..000000000 --- a/tests/core/data/nextflow/lowered/inherited.yaml +++ /dev/null @@ -1,23 +0,0 @@ -# Requirements and hints a tool inherits (resolved-view design §8): for each class the tool's own requirement, else the -# innermost inherited requirement, else its own hint, else the innermost inherited hint. -- id: a_tools_own_requirement_beats_an_inherited_hint - why: The tool's requirement comes after what it inherits, and a lookup takes the last requirement first. - workflow: {steps: [{id: SAY}], hints: {DockerRequirement: {dockerPull: 'workflow/image'}}} - tools: [&say {id: SAY, baseCommand: [echo, hi], requirements: {DockerRequirement: {dockerPull: 'tool/image'}}}] - render: [" container 'tool/image'\n"] -- id: an_inherited_requirement_beats_a_tools_own_hint - why: Any requirement beats any hint. - workflow: {steps: [{id: SAY}], requirements: {DockerRequirement: {dockerPull: 'workflow/image'}}} - tools: [{<<: *say, requirements: {}, hints: {DockerRequirement: {dockerPull: 'tool/image'}}}] - render: [" container 'workflow/image'\n"] -- id: the_innermost_inherited_requirement_wins - why: A step's requirement inside a nested workflow comes after the root's, so it is the one the tool reads. - workflow: {steps: [{id: child.wic, subtree: {steps: [{id: SAY, requirements: {ResourceRequirement: {coresMin: 2}}}]}}], - requirements: {ResourceRequirement: {coresMin: 1}}} - tools: [{<<: *say, requirements: {}}] - render: [" cpus 2\n"] -- id: an_environment_variable_inherited_from_the_root - why: An inherited entry lowers as the same entry written on the tool. - workflow: {steps: [{id: SAY}], requirements: {EnvVarRequirement: {envDef: {GREETING: hello}}}} - tools: [{<<: *say, requirements: {}}] - render: ["export GREETING=${__sophios_shell_quote_9f72e('hello')}\n"] diff --git a/tests/core/data/nextflow/lowered/staging.yaml b/tests/core/data/nextflow/lowered/staging.yaml deleted file mode 100644 index aa4ee5c2c..000000000 --- a/tests/core/data/nextflow/lowered/staging.yaml +++ /dev/null @@ -1,125 +0,0 @@ -# Staged inputs, entries, references and output captures the target lowers (design §6, Inputs and channels, Basename -# references, Outputs). `lowered` is the replaced test's IR literal in payload form. -- id: every_iwdr_entry_is_one_the_task_makes-a-bare-reference - why: &entries 'design §6, Inputs and channels: under its own basename or a literal name, linked or copied.' - tool: &stage {inputs: {source: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: - out.txt}}}, arguments: [cat, renamed.txt], stdout: out.txt, requirements: {InitialWorkDirRequirement: {listing: - [$(inputs.source)]}}} - out: &out [result] - job: &in_txt {source: {class: File, path: in.txt}} - lowered: &linked {processes: [{inputs: [{entry: {name: null, copy: false}}]}]} -- {id: every_iwdr_entry_is_one_the_task_makes-tool_builder-stage, why: *entries, out: *out, job: *in_txt, lowered: - *linked, tool: {<<: *stage, requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), entryname: - $(inputs.source.basename)}]}}}} -- {id: every_iwdr_entry_is_one_the_task_makes-not-writable, why: *entries, out: *out, job: *in_txt, lowered: *linked, - tool: {<<: *stage, requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), writable: - false}]}}}} -- {id: every_iwdr_entry_is_one_the_task_makes-the-image-workflows-plugins-outDir, why: *entries, out: *out, job: - *in_txt, tool: {<<: *stage, requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), writable: - true}]}}}, lowered: &copied {processes: [{inputs: [{entry: {name: null, copy: true}}]}]}} -- {id: every_iwdr_entry_is_one_the_task_makes-renamed, why: *entries, out: *out, job: *in_txt, tool: {<<: *stage, - requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), entryname: renamed.txt}]}}}, lowered: - {processes: [{inputs: [{entry: {name: renamed.txt, copy: false}}]}]}} -- {id: every_iwdr_entry_is_one_the_task_makes-renamed-writable, why: *entries, out: *out, job: *in_txt, tool: {<<: - *stage, requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), entryname: reads*.fq, - writable: true}]}}}, lowered: {processes: [{inputs: [{entry: {name: reads*.fq, copy: true}}]}]}} -- id: an_entry_under_its_own_basename_may_be_referenced-$(inputs.source) - why: &plugin 'The plugin shape: --outDir $(inputs.outDir) and glob: $(inputs.outDir.basename) name the entry.' - tool: &out_dir {inputs: {source: {type: Directory, inputBinding: {prefix: --outDir}}}, outputs: {result: - {type: Directory, outputBinding: {glob: $(inputs.source.basename)}}}, requirements: {InitialWorkDirRequirement: - {listing: [$(inputs.source)]}}, arguments: [$(inputs.source)]} - out: *out - job: &out_job {source: {class: Directory, path: out}} - lowered: *linked -- {id: an_entry_under_its_own_basename_may_be_referenced-$(inputs.source.path), why: *plugin, out: *out, job: *out_job, - lowered: *linked, tool: {<<: *out_dir, arguments: [$(inputs.source.path)]}} -- {id: an_entry_under_its_own_basename_may_be_referenced-$(inputs.source.basename), why: *plugin, out: *out, job: - *out_job, lowered: *linked, tool: {<<: *out_dir, arguments: [$(inputs.source.basename)]}} -- {id: an_entry_under_its_own_basename_may_be_referenced-$(inputs.source)-writable, why: *plugin, out: *out, job: - *out_job, lowered: *copied, tool: {<<: *out_dir, requirements: &writable_source {InitialWorkDirRequirement: {listing: - [{entry: $(inputs.source), writable: true}]}}}} -- {id: an_entry_under_its_own_basename_may_be_referenced-$(inputs.source.path)-writable, why: *plugin, out: *out, job: - *out_job, lowered: *copied, tool: {<<: *out_dir, requirements: *writable_source, arguments: [$(inputs.source.path)]}} -- {id: an_entry_under_its_own_basename_may_be_referenced-$(inputs.source.basename)-writable, why: *plugin, out: *out, - job: *out_job, lowered: *copied, tool: {<<: *out_dir, requirements: *writable_source, arguments: - [$(inputs.source.basename)]}} -- id: a_reference_where_it_stands-glob-File-$(inputs.f.basename).out - why: &stands 'design §6, Basename references: a basename names a new file a glob collects, an entry is under the - output directory, and stdin reads a staged File by its whole `.path`. Each case is a cell of cwltool''s own run of - the tool.' - tool: &ref {inputs: {f: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: - $(inputs.f.basename).out}}}} - out: *out - job: &f {f: {class: File, path: in}} -- {id: a_reference_where_it_stands-glob-File-$(inputs.f.basename)-linked, why: *stands, out: *out, job: *f, tool: {<<: - *ref, outputs: {result: {type: File, outputBinding: {glob: $(inputs.f.basename)}}}, requirements: &linked_f { - InitialWorkDirRequirement: {listing: [$(inputs.f)]}}}} -- {id: a_reference_where_it_stands-glob-Directory-$(inputs.f.basename)/keep.txt-linked, why: *stands, out: *out, job: &d - {f: {class: Directory, path: in}}, tool: {inputs: {f: {type: Directory}}, outputs: {result: {type: - Directory, outputBinding: {glob: $(inputs.f.basename)/keep.txt}}}, requirements: *linked_f}} -- {id: a_reference_where_it_stands-glob-Directory-$(inputs.f.path)-writable, why: *stands, out: *out, job: *d, tool: { - inputs: {f: {type: Directory}}, outputs: {result: {type: Directory, - outputBinding: {glob: $(inputs.f.path)}}}, - requirements: &writable_f {InitialWorkDirRequirement: {listing: [{entry: $(inputs.f), writable: true}]}}}} -- {id: a_reference_where_it_stands-glob-File-$(inputs.f.path).out-linked, why: *stands, out: *out, job: *f, tool: {<<: - *ref, outputs: {result: {type: File, outputBinding: {glob: $(inputs.f.path).out}}}, requirements: *linked_f}} -- {id: a_reference_where_it_stands-stdin-File-$(inputs.f.path), why: *stands, out: *out, job: *f, - tool: &stream {inputs: {f: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: done.txt}}}, stdin: - $(inputs.f.path)}} -- {id: a_reference_where_it_stands-stdout-File-$(inputs.f.basename).log, why: *stands, out: *out, job: *f, tool: - {inputs: {f: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: done.txt}}}, stdout: - $(inputs.f.basename).log}} -- {id: a_reference_where_it_stands-stdout-File-$(inputs.f.basename)-writable, why: *stands, out: *out, job: *f, tool: { - inputs: {f: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: done.txt}}}, stdout: - $(inputs.f.basename), requirements: *writable_f}} -- id: an_output_whose_name_no_link_is_known_to_share-another-name - why: &no_link A copy is the task's own; a workflow input's or a pattern's name is known only when the task runs; a - glob collects an entry, which cwltool stages in the output directory as well. - workflow: &chain {steps: [{id: EMIT, out: [{out: {wic_anchor: emitted}}]}, {id: SORT, in: {src: {wic_alias: emitted}}, - out: [out]}], inputs: {given: {type: File}}} - tools: [&emitted {id: EMIT, outputs: {out: {type: File, outputBinding: {glob: emitted.txt}}}, stdout: emitted.txt}, - &sort {id: SORT, inputs: {src: {type: File, inputBinding: {position: 1}}}, outputs: {out: {type: File, - outputBinding: {glob: sorted.txt}}}, stdout: sorted.txt}] - job: &given {given: {class: File, path: in.txt}} - lowered: &two {processes: [{}, {}]} -- {id: an_output_whose_name_no_link_is_known_to_share-pattern, why: *no_link, workflow: *chain, job: *given, lowered: - *two, tools: [{id: EMIT, outputs: {out: {type: File, outputBinding: {glob: '*.txt'}}}, stdout: '*.txt'}, {<<: *sort, - outputs: {out: {type: File, outputBinding: {glob: '*.txt'}}}}]} -- {id: an_output_whose_name_no_link_is_known_to_share-workflow-input, why: *no_link, job: *given, lowered: *two, tools: - [&sorted {id: EMIT, outputs: {out: {type: File, outputBinding: {glob: sorted.txt}}}, stdout: sorted.txt}, *sort], - workflow: &from_given {<<: *chain, steps: [{id: EMIT, out: [out]}, {id: SORT, in: {src: given}, out: [out]}]}} -- {id: an_output_whose_name_no_link_is_known_to_share-writable-entry, why: *no_link, workflow: *chain, job: *given, - lowered: *two, tools: [*sorted, {<<: *sort, inputs: {src: {type: File}}, requirements: {InitialWorkDirRequirement: - {listing: [{entry: $(inputs.src), writable: true}]}}}]} -- {id: an_output_whose_name_no_link_is_known_to_share-glob-collects-a-renamed-entry, why: *no_link, workflow: *chain, - job: *given, lowered: *two, tools: [*emitted, &renamed {id: SORT, inputs: {src: {type: File}}, outputs: {out: {type: - File, outputBinding: {glob: sorted.txt}}}, arguments: [-o, sorted.txt], requirements: {InitialWorkDirRequirement: - {listing: [{entry: $(inputs.src), entryname: sorted.txt}]}}}]} -- {id: an_output_whose_name_no_link_is_known_to_share-glob-collects-a-renamed-workflow-input, why: *no_link, workflow: - *from_given, job: *given, lowered: *two, tools: [*emitted, *renamed]} -- {id: an_output_whose_name_no_link_is_known_to_share-glob-collects-an-entry-under-its-basename, why: *no_link, - workflow: *chain, job: *given, lowered: *two, tools: [*sorted, - {<<: *renamed, requirements: {InitialWorkDirRequirement: - {listing: [{entry: $(inputs.src)}]}}}]} -- id: the_admitted_cardinality_declaration_lowers_to_a_capture_marker - why: &capture An admitted outputEval lowers to its capture marker. - tool: &make {inputs: {message: {type: string, inputBinding: {position: 1}}}, outputs: {result: {type: File, - outputBinding: {glob: out.txt, outputEval: '$(self[0])'}}}} - out: *out - job: &hi {message: hi} - lowered: &single {processes: [{outputs: [{name: result, qualifier: path, capture: single}]}]} -- {id: surrounding_whitespace_is_trimmed-newline, why: Surrounding whitespace is trimmed., out: *out, job: *hi, lowered: - *single, tool: {<<: *make, outputs: {result: {type: File, - outputBinding: {glob: out.txt, outputEval: " $(self[0])\n"}}}}} -- {id: surrounding_whitespace_is_trimmed-tab, why: Surrounding whitespace is trimmed., out: *out, job: *hi, lowered: - *single, tool: {<<: *make, outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: "\t$(self[0]) - "}}}}} -- {id: a_declared_but_unused_inline_javascript_requirement_stays_legal, why: 'The requirement is a declaration; the - violation is a non-admitted form.', out: *out, job: *hi, lowered: *single, tool: {<<: *make, requirements: - {InlineJavascriptRequirement: {}}}} -- {id: the_admitted_file_text_capture_lowers_to_a_value_port, why: *capture, out: *out, job: *hi, tool: {<<: *make, - outputs: {result: {type: string, outputBinding: {glob: out.txt, loadContents: true, outputEval: - '$(self[0].contents)'}}}}, lowered: {processes: [{outputs: [{name: result, qualifier: val, capture: text}]}]}} -- {id: an_optional_output_with_a_pattern_glob_reaching_a_workflow_output, why: An optional output of a pattern glob is - checked at its workflow output., out: [o], tool: {baseCommand: 'true', outputs: {o: {type: 'File?', - outputBinding: {glob: '*.log'}}}}, lowered: {processes: [{outputs: [{optional: true}]}]}} diff --git a/tests/core/data/nextflow/lowered/workflow.yaml b/tests/core/data/nextflow/lowered/workflow.yaml deleted file mode 100644 index 437a7b1c5..000000000 --- a/tests/core/data/nextflow/lowered/workflow.yaml +++ /dev/null @@ -1,182 +0,0 @@ -# Parameters, scatter, wiring and resources the target lowers (design §5.2, §6). `lowered` is the replaced test's IR -# literal in payload form; a `contains` list is what the test asserted holds among the connections. -- id: applies_unwired_scalar_default_before_lowering - why: An unwired tool input with a default becomes a parameter holding the default. - workflow: {steps: [{id: DEFAULT, out: [result]}], outputs: {result: {type: File, outputSource: DEFAULT/result}}} - tools: [{id: DEFAULT, inputs: {message: {type: string, default: hello default, inputBinding: {position: 1}}}, - outputs: {result: {type: File, outputBinding: {glob: result.txt}}}, arguments: [{position: 2, valueFrom: - result.txt}]}] - lowered: {params: {exact: {_DEFAULT_message: hello default}}, connections: {contains: [{kind: workflow_input, - from_port: _DEFAULT_message, to_process: _DEFAULT, to_port: message, adapter: null}]}} - render: ["Channel.value(__sophios_input_9f72e('_DEFAULT_message', params._DEFAULT_message, 'string'))"] -- id: a_default_is_held_as_a_value_written_on_a_step_is - why: A workflow input's default, which only a .wic file writes, and a tool's are held as a value written on a step - is, so an int given for a float is the float, written as its text, and a path given as text is the File there. - workflow: {steps: [{id: take, in: {x: y}, out: [result]}], inputs: {y: {type: float, default: 5}}, outputs: {result: - {type: File, outputSource: take/result}}} - tools: [{id: take, inputs: {x: {type: float, inputBinding: {position: 1}}, r: {type: ['null', float], default: 7, - inputBinding: {position: 2}}, f: {type: File, default: /data/a.txt}}, outputs: {result: {type: File, - outputBinding: {glob: result.txt}}}}] - params_file: {y: '5.0', take_r: '7.0', take_f: {class: File, path: /data/a.txt}} -- id: every_parameter_records_its_declared_type - why: Workflow inputs carry their own declarations; a tool default carries its tool input's. - workflow: {steps: [{id: TAKE, in: {name: name, count: count, files: files, dirs: dirs}, out: [result]}], - inputs: {name: - {type: string}, count: {type: ['null', int]}, files: {type: {type: array, items: File}}, dirs: {type: - ['null', {type: array, items: Directory}]}, unread: {type: boolean}}, outputs: {result: {type: File, - outputSource: TAKE/result}}} - tools: [{id: TAKE, inputs: {name: {type: string, inputBinding: {position: 1}}, count: {type: ['null', int]}, files: - {type: {type: array, items: File}, inputBinding: {position: 2}}, dirs: {type: ['null', {type: array, items: - Directory}], inputBinding: {position: 3}}, ratio: {type: float, default: 0.5}}, outputs: {result: {type: - File, outputBinding: {glob: result.txt}}}}] - job: {name: n, count: 1, files: [], dirs: [], unread: true} - lowered: {param_types: {exact: {name: string, count: 'int?', files: 'File[]', dirs: 'Directory[]?', unread: boolean, - _TAKE_ratio: float}}} -- {id: accepts_a_boolean_source_wired_into_a_boolean_flag, why: 'The supported wiring stays supported: a boolean source - into a flag input.', workflow: {steps: [{id: SORT, in: {reverse: flagval}}], inputs: {flagval: {type: boolean}}}, - tools: [{id: SORT, inputs: {reverse: {type: boolean, inputBinding: {position: 1, prefix: -r}}}}], job: {flagval: - false}, lowered: {params: {exact: {flagval: false}}}} -- {id: maps_docker_requirement, why: A DockerRequirement is the process's container., tool: {id: CONTAINER, - requirements: {DockerRequirement: {dockerPull: 'ubuntu:24.04'}}}, - lowered: {processes: [{container: 'ubuntu:24.04'}]}} -- {id: host_and_container_tools_lower_into_one_workflow, why: A host tool and a containerized tool lower side by side., - workflow: {steps: [{id: CONTAINERIZED}, {id: HOST}]}, tools: [{id: CONTAINERIZED, requirements: {DockerRequirement: - {dockerPull: 'ubuntu:24.04'}}}, {id: HOST}], lowered: {processes: [{container: 'ubuntu:24.04'}, {container: null}]}} -- {id: maps_cpu_and_memory_requirements, why: 'CWL reserves the minimum; a maximum alone is all there is to request.', - workflow: {steps: [{id: RESOURCES}, {id: CEILING_ONLY}]}, tools: [{id: RESOURCES, requirements: {ResourceRequirement: - {coresMin: 1, coresMax: 2, ramMin: 512, ramMax: 1024}}}, {id: CEILING_ONLY, requirements: {ResourceRequirement: - {coresMax: 2, ramMax: 1024}}}], lowered: {processes: [{resources: {cpus: 1, memory_mb: 512, accelerator: null, - cuda_version_min: null, cuda_compute_capability: null}}, {resources: {cpus: 2, memory_mb: 1024, accelerator: null, - cuda_version_min: null, cuda_compute_capability: null}}]}} -- {id: preserves_fanout, why: One output feeds every step that reads it., workflow: {steps: [{id: A, out: [{out: - {wic_anchor: a_out}}]}, {id: B, in: {value: {wic_alias: a_out}}}, {id: C, in: {value: {wic_alias: a_out}}}]}, tools: - [{id: A, outputs: {out: {type: File, outputBinding: {glob: out.txt}}}}, {id: B, inputs: {value: {type: File}}}, {id: - C, inputs: {value: {type: File}}}], lowered: {connections: {contains: [{kind: process, from_process: _A, from_port: - out, to_process: _B, to_port: value}, {kind: process, from_process: _A, from_port: out, to_process: _C, to_port: - value}]}}} -- id: cuda_requirement_lowers_to_the_accelerator_directive-requirements-none - why: &cuda 'The count cwltool''s job requests: the minimum, else the maximum, else 1 (design §6).' - tool: {requirements: {'cwltool:CUDARequirement': {}}} - lowered: &gpu1 {processes: [{resources: {cpus: null, memory_mb: null, accelerator: 1, cuda_version_min: null, - cuda_compute_capability: null}}]} - render: &accelerator1 ["\n accelerator 1\n"] - notes: [] -- {id: cuda_requirement_lowers_to_the_accelerator_directive-hints-none, why: *cuda, tool: {hints: - {'cwltool:CUDARequirement': {}}}, lowered: *gpu1, render: *accelerator1, notes: []} -- {id: cuda_requirement_lowers_to_the_accelerator_directive-requirements-min, why: *cuda, - tool: {requirements: { - 'cwltool:CUDARequirement': {cudaDeviceCountMin: 2}}}, lowered: &gpu2 {processes: [{resources: {cpus: null, memory_mb: - null, accelerator: 2, cuda_version_min: null, cuda_compute_capability: null}}]}, - render: &accelerator2 ["\n accelerator 2\n"], notes: []} -- {id: cuda_requirement_lowers_to_the_accelerator_directive-hints-min, why: *cuda, tool: {hints: { - 'cwltool:CUDARequirement': {cudaDeviceCountMin: 2}}}, lowered: *gpu2, render: *accelerator2, notes: []} -- {id: cuda_requirement_lowers_to_the_accelerator_directive-requirements-max, why: *cuda, - tool: {requirements: { - 'cwltool:CUDARequirement': {cudaDeviceCountMax: 3}}}, lowered: &gpu3 {processes: [{resources: {cpus: null, memory_mb: - null, accelerator: 3, cuda_version_min: null, cuda_compute_capability: null}}]}, - render: &accelerator3 ["\n accelerator 3\n"], notes: []} -- {id: cuda_requirement_lowers_to_the_accelerator_directive-hints-max, why: *cuda, tool: {hints: { - 'cwltool:CUDARequirement': {cudaDeviceCountMax: 3}}}, lowered: *gpu3, render: *accelerator3, notes: []} -- {id: cuda_requirement_lowers_to_the_accelerator_directive-requirements-min-and-max, why: *cuda, tool: {requirements: - {'cwltool:CUDARequirement': {cudaDeviceCountMin: 2, cudaDeviceCountMax: 4}}}, lowered: *gpu2, render: - *accelerator2, notes: []} -- {id: cuda_requirement_lowers_to_the_accelerator_directive-hints-min-and-max, why: *cuda, tool: {hints: { - 'cwltool:CUDARequirement': {cudaDeviceCountMin: 2, cudaDeviceCountMax: 4}}}, lowered: *gpu2, render: *accelerator2, - notes: []} -- id: the_unchecked_cuda_fields_are_notes_and_ride_in_the_ext_directive - why: The fields the target does not check are notes, and the process carries them in its ext directive. - tool: {id: GPU, hints: {'cwltool:CUDARequirement': {cudaDeviceCountMin: 1, cudaVersionMin: '11.4', - cudaComputeCapability: ['3.0', '7.5']}}} - lowered: {processes: [{resources: {cpus: null, memory_mb: null, accelerator: 1, cuda_version_min: '11.4', - cuda_compute_capability: ['3.0', '7.5']}}]} - render: ["\n accelerator 1\n ext cudaVersionMin: '11.4', cudaComputeCapability: ['3.0', '7.5']\n"] - notes: [{severity: note, code: UNCHECKED_CUDA_FIELD, step: GPU, index: null, port: null, message: {startswith: - "cwltool:CUDARequirement cudaVersionMin '11.4' is not checked"}}, {severity: note, code: UNCHECKED_CUDA_FIELD, - step: GPU, index: null, port: null, message: {startswith: "cwltool:CUDARequirement cudaComputeCapability - ['3.0', '7.5'] is not checked"}}] -- id: a_null_scatter_is_no_scatter - why: 'CWL reads `scatter: null` as no scatter, so the input takes its source as one value.' - workflow: {steps: [{id: ONE, in: {item: items}, out: [result], scatter: null}], inputs: {items: {type: string}}} - tools: [{id: ONE, inputs: {item: {type: string, inputBinding: {position: 1}}}, outputs: {result: {type: File, - outputBinding: {glob: out.txt}}}}] - job: {items: a} - lowered: {connections: {contains: [{kind: workflow_input, from_port: items, to_process: _ONE, to_port: item, adapter: - null}]}} -- id: accepts_multi_input_scatter-dotproduct - why: &every_method A multi-input scatter lowers under each of CWL's three methods. - workflow: &pair {steps: [{id: SCATTER, in: {first: firsts, second: seconds}, out: [result], scatter: [first, second], - scatterMethod: dotproduct}], inputs: {firsts: {type: &strings {type: array, items: string}}, - seconds: {type: *strings}}} - tools: &pair_tools [{id: SCATTER, inputs: {first: {type: string, inputBinding: {position: 1}}, second: {type: string, - inputBinding: {position: 2}}}, outputs: &result {result: {type: File, outputBinding: {glob: - out.txt}}}}] - job: {firsts: [a], seconds: [b]} - lowered: {connections: {contains: [{kind: workflow_input, from_port: firsts, to_process: _SCATTER, to_port: first, - adapter: dotproduct}, {kind: workflow_input, from_port: seconds, to_process: _SCATTER, to_port: second, - adapter: dotproduct}]}} -- {id: accepts_multi_input_scatter-flat_crossproduct, why: *every_method, tools: *pair_tools, - job: {firsts: [a], seconds: - [b]}, workflow: {<<: *pair, steps: [{id: SCATTER, in: {first: firsts, second: seconds}, out: [result], scatter: - [first, second], scatterMethod: flat_crossproduct}]}, - lowered: {connections: {contains: [{kind: workflow_input, from_port: firsts, to_process: _SCATTER, to_port: first, - adapter: flat_crossproduct}, {kind: workflow_input, from_port: seconds, to_process: _SCATTER, to_port: second, - adapter: flat_crossproduct}]}}} -- {id: accepts_multi_input_scatter-nested_crossproduct, why: *every_method, tools: *pair_tools, job: {firsts: [a], - seconds: [b]}, workflow: {<<: *pair, steps: [{id: SCATTER, in: {first: firsts, second: seconds}, out: [result], - scatter: [first, second], scatterMethod: nested_crossproduct}]}, - lowered: {connections: {contains: [{kind: workflow_input, from_port: firsts, to_process: _SCATTER, to_port: first, - adapter: nested_crossproduct}, {kind: workflow_input, from_port: seconds, to_process: _SCATTER, to_port: second, - adapter: nested_crossproduct}]}}} -- id: an_inert_scatter_method_at_one_scattered_input-absent - why: &inert All three methods coincide at one scattered input, so each is inert, as is either spelling of one input. - workflow: &one {steps: [&scatter_step {id: SCATTER, in: {item: items}, out: [result], scatter: [item]}], inputs: - {items: {type: *strings}}} - tools: &one_tool [{id: SCATTER, inputs: {item: {type: string, inputBinding: {position: 1}}}, outputs: *result}] - job: &ab {items: [a, b]} - lowered: &one_edge {connections: [{kind: workflow_input, from_port: items, to_process: _SCATTER, to_port: item, - adapter: dotproduct}]} -- {id: an_inert_scatter_method_at_one_scattered_input-dotproduct, why: *inert, tools: *one_tool, job: *ab, lowered: - *one_edge, workflow: {<<: *one, steps: [{<<: *scatter_step, scatterMethod: dotproduct}]}} -- {id: an_inert_scatter_method_at_one_scattered_input-flat_crossproduct, why: *inert, tools: *one_tool, job: *ab, - lowered: *one_edge, workflow: {<<: *one, steps: [{<<: *scatter_step, scatterMethod: flat_crossproduct}]}} -- {id: an_inert_scatter_method_at_one_scattered_input-nested_crossproduct, why: *inert, tools: *one_tool, job: *ab, - lowered: *one_edge, workflow: {<<: *one, steps: [{<<: *scatter_step, scatterMethod: nested_crossproduct}]}} -- {id: both_single_input_scatter_spellings-string-form, why: *inert, tools: *one_tool, job: *ab, lowered: *one_edge, - workflow: {<<: *one, steps: [{<<: *scatter_step, scatter: item}]}} -- {id: inert_workflow_level_scatter_requirement-mapping, why: A ScatterFeatureRequirement on the workflow is inert., - tools: *one_tool, job: *ab, lowered: *one_edge, workflow: {<<: *one, requirements: {ScatterFeatureRequirement: {}}}} -- {id: inert_workflow_level_scatter_requirement-list, why: A ScatterFeatureRequirement on the workflow is inert., tools: - *one_tool, job: *ab, lowered: *one_edge, workflow: {<<: *one, requirements: [{class: ScatterFeatureRequirement}]}} -- id: an_unscattered_steps_output_reaches_a_scattered_steps_other_input_as_one_value - why: An unscattered step's output is one value, which each scattered task takes whole. - workflow: {steps: [{id: PRODUCER, out: [{out: {wic_anchor: produced}}]}, {id: SCATTER, in: {item: items, extra: - {wic_alias: produced}}, out: [result], scatter: [item]}], inputs: {items: {type: *strings}}} - tools: [{id: PRODUCER, outputs: {out: {type: File, outputBinding: {glob: produced.txt}}}}, - {id: SCATTER, inputs: {item: - {type: string, inputBinding: {position: 1}}, extra: {type: File, inputBinding: {position: 2}}}, outputs: - *result}] - job: {items: [a]} - lowered: {connections: {contains: [{kind: process, from_process: _PRODUCER, from_port: out, to_process: _SCATTER, - to_port: extra}]}} - render: ['_SCATTER(ch__SCATTER_scatter, _PRODUCER.out.out.first())'] -- {id: accepts_a_workflow_output_of_a_scattered_step, why: A scattered step's output is an array a workflow output - takes., - tools: *one_tool, job: *ab, workflow: {<<: *one, outputs: {each: {type: {type: array, items: File}, outputSource: - SCATTER/result}}}, lowered: {connections: {contains: [{kind: workflow_output, from_process: _SCATTER, from_port: - result, to_port: each}]}}} -- {id: accepts_a_scattered_boolean_flag_source, why: 'A scattered flag port receives one element, so the element type is - what must be boolean.', workflow: {<<: *one, inputs: {items: {type: {type: array, items: boolean}}}}, job: {items: - [true, false]}, tools: [{id: SCATTER, inputs: {item: {type: boolean, inputBinding: {prefix: --flag}}}, outputs: - *result}], lowered: {processes: [{command: {tokens: [{segments: [{kind: literal, value: SCATTER}]}, {kind: flag, - name: item, prefix: --flag}]}}]}} -- id: a_when_reads_an_optional_tool_input_a_required_source_feeds - why: A `when` is typed by what its input delivers, so a required source gives an optional tool input a value. - workflow: {steps: [{id: GATED, in: {a: a}, when: $(inputs.a > 1)}], inputs: {a: int}} - tools: [{id: GATED, inputs: {a: {type: ['null', int]}}, baseCommand: 'true'}] - job: {a: 2} -- id: a_step_input_expression_requirement_is_a_declaration - why: A declaration is not a use (resolved-view design §8); a valueFrom it would allow stays refused by name. - workflow: {steps: [{id: ECHO, in: {message: message}}], inputs: {message: string}, requirements: - {StepInputExpressionRequirement: {}}} - tools: [{id: ECHO, inputs: {message: {type: string, inputBinding: {position: 1}}}, baseCommand: echo}] - job: {message: hi} diff --git a/tests/core/data/nextflow/refused/boundary/a_made_input_with_no_value.wic b/tests/core/data/nextflow/refused/boundary/a_made_input_with_no_value.wic new file mode 100644 index 000000000..380d1862c --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/a_made_input_with_no_value.wic @@ -0,0 +1,4 @@ +# A step's required input bound by nothing: the input the compiler makes for it has no value, and the step owns it. +steps: +- id: needs_word + run: say diff --git a/tests/core/data/nextflow/refused/boundary/a_parameter_named_like_a_tool_default.wic b/tests/core/data/nextflow/refused/boundary/a_parameter_named_like_a_tool_default.wic new file mode 100644 index 000000000..ff76ff01a --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/a_parameter_named_like_a_tool_default.wic @@ -0,0 +1,8 @@ +# A workflow input and the parameter a tool's default makes for defaulted~message would normalize to one name. +inputs: + defaulted_message: {type: string, default: given} +steps: +- id: says_defaulted + run: say + in: {word: defaulted_message} +- id: defaulted diff --git a/tests/core/data/nextflow/refused/boundary/an_explicit_null.wic b/tests/core/data/nextflow/refused/boundary/an_explicit_null.wic new file mode 100644 index 000000000..6794cf023 --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/an_explicit_null.wic @@ -0,0 +1,7 @@ +# A required workflow input given an explicit null by its job, an_explicit_null.yml: a null is no value. +inputs: + message: string +steps: +- id: says + run: say + in: {word: message} diff --git a/tests/core/data/nextflow/refused/boundary/an_explicit_null.yml b/tests/core/data/nextflow/refused/boundary/an_explicit_null.yml new file mode 100644 index 000000000..353dd1f76 --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/an_explicit_null.yml @@ -0,0 +1 @@ +message: null diff --git a/tests/core/data/nextflow/refused/boundary/classless.cwl b/tests/core/data/nextflow/refused/boundary/classless.cwl new file mode 100644 index 000000000..0220a63b6 --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/classless.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A requirement and a hint that name no class. +requirements: [{directive: '${System.exit(3)}'}] +hints: [{directive: '${System.exit(3)}'}] +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/nextflow/refused/boundary/colliding_ports.cwl b/tests/core/data/nextflow/refused/boundary/colliding_ports.cwl new file mode 100644 index 000000000..50d087257 --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/colliding_ports.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Two inputs whose names normalize alike. +baseCommand: echo +inputs: + out-dir: {type: string, default: first} + out_dir: {type: string, default: second} +outputs: {} diff --git a/tests/core/data/nextflow/refused/boundary/defaulted.cwl b/tests/core/data/nextflow/refused/boundary/defaulted.cwl new file mode 100644 index 000000000..355202df1 --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/defaulted.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Echo a message, a tool default unless a step binds it. +baseCommand: echo +inputs: + message: {type: string, default: tool default, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/boundary/expected.yaml b/tests/core/data/nextflow/refused/boundary/expected.yaml new file mode 100644 index 000000000..dbf4efaaa --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/expected.yaml @@ -0,0 +1,55 @@ +why: A required workflow input has a value, never null, a default is a JSON scalar, and two names that normalize alike + would be one parameter; a workflow output names a step output; a glob reads inputs only; a requirement names its + class; a long and a double are refused where they are declared; a core count is whole and a CUDA device count a + positive whole number. +# Each refusal: its code, its step, and its subject (a tool's file and field, or a port). +roots: + workflow.wic: + - [nf-s002, colliding_ports, 'colliding_ports.cwl: inputs'] + - [nf-s045, runtime_glob, null] + - [nf-s055, classless, 'classless.cwl: requirements.0'] + - [nf-s055, classless, 'classless.cwl: hints.0'] + - [nf-s048, wide_numbers, 'wide_numbers.cwl: inputs.a_long.type'] + - [nf-s048, wide_numbers, 'wide_numbers.cwl: inputs.a_double.type'] + - [nf-s048, wide_numbers, 'wide_numbers.cwl: inputs.longs.type'] + - [nf-s048, wide_numbers, 'wide_numbers.cwl: inputs.doubles.type'] + - [nf-s048, wide_numbers, 'wide_numbers.cwl: inputs.defaulted.type'] + - [nf-s048, wide_numbers, 'wide_numbers.cwl: outputs.long_out.type'] + - [nf-s031, wide_numbers, 'wide_numbers.cwl: outputs.long_out.type'] + - [nf-s048, wide_numbers, 'wide_numbers.cwl: outputs.double_out.type'] + - [nf-s031, wide_numbers, 'wide_numbers.cwl: outputs.double_out.type'] + - [nf-s040, resources, 'resources.cwl: requirements.ResourceRequirement.coresMax'] + - [nf-s054, resources, 'resources.cwl: hints.0.cudaComputeCapabilityMin'] + - [nf-s055, resources, 'resources.cwl: hints.1.cudaDeviceCountMin'] + - [nf-s055, resources, 'resources.cwl: hints.1.cudaDeviceCountMax'] + - [nf-s055, resources, 'resources.cwl: hints.2.cudaDeviceCountMin'] + - [nf-s055, resources, 'resources.cwl: hints.2.cudaDeviceCountMax'] + - [nf-s055, resources, 'resources.cwl: hints.3.cudaDeviceCountMin'] + - [nf-s040, resources, 'resources.cwl: hints.3.cudaDeviceCountMax'] + - [nf-s002, null, null] + - [nf-s014, null, 'message'] + - [nf-s017, null, 'listed'] + - [nf-s048, null, 'a_long'] + - [nf-s014, null, 'a_long'] + - [nf-s048, null, 'a_double'] + - [nf-s014, null, 'a_double'] + - [nf-s048, wide_numbers, 'wide_numbers~longs'] + - [nf-s014, wide_numbers, 'wide_numbers~longs'] + - [nf-s048, wide_numbers, 'wide_numbers~doubles'] + - [nf-s014, wide_numbers, 'wide_numbers~doubles'] + - [nf-s048, null, 'long_out'] + - [nf-s048, null, 'double_out'] + - [nf-s048, null, 'wide_numbers~long_out'] + - [nf-s048, null, 'wide_numbers~double_out'] + - [nf-s025, null, null] + a_parameter_named_like_a_tool_default.wic: + - [nf-s002, null, null] + an_explicit_null.wic: + - [wic012, null, 'message'] + - [wic012, says, 'say.cwl: inputs.word'] + a_made_input_with_no_value.wic: + - [nf-s014, needs_word, 'needs_word~word'] + - [wic012, needs_word, 'say.cwl: inputs.word'] + steps_that_normalize_alike.wic: + - [nf-s002, null, null] + - [nf-s002, null, null] diff --git a/tests/core/data/nextflow/refused/boundary/resources.cwl b/tests/core/data/nextflow/refused/boundary/resources.cwl new file mode 100644 index 000000000..71692e46f --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/resources.cwl @@ -0,0 +1,16 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Ask for a fractional number of cores, and for GPUs with a field cwltool does not declare and counts that are not + positive whole numbers. +$namespaces: + cwltool: http://commonwl.org/cwltool# +requirements: + ResourceRequirement: {coresMax: 2.5} +hints: +- {class: 'cwltool:CUDARequirement', cudaComputeCapabilityMin: '3.0'} +- {class: 'cwltool:CUDARequirement', cudaDeviceCountMin: 0, cudaDeviceCountMax: -1} +- {class: 'cwltool:CUDARequirement', cudaDeviceCountMin: true, cudaDeviceCountMax: 1.5} +- {class: 'cwltool:CUDARequirement', cudaDeviceCountMin: '2', cudaDeviceCountMax: $(inputs.n)} +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/nextflow/refused/boundary/runtime_glob.cwl b/tests/core/data/nextflow/refused/boundary/runtime_glob.cwl new file mode 100644 index 000000000..6bcbff495 --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/runtime_glob.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Collect a file by a glob that reads the runtime, not an input. +baseCommand: [touch, result.txt] +inputs: {} +outputs: + result: {type: File, outputBinding: {glob: $(runtime.outdir)/result.txt}} diff --git a/tests/core/data/nextflow/refused/boundary/say.cwl b/tests/core/data/nextflow/refused/boundary/say.cwl new file mode 100644 index 000000000..65a35be7f --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/say.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Echo one word. +baseCommand: echo +inputs: + word: {type: string, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/boundary/steps_that_normalize_alike.wic b/tests/core/data/nextflow/refused/boundary/steps_that_normalize_alike.wic new file mode 100644 index 000000000..02cff694e --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/steps_that_normalize_alike.wic @@ -0,0 +1,11 @@ +# A repeated step id carries `@`, and it and a written id may normalize alike. +steps: +- id: touch + run: say + in: {word: !ii a} +- id: touch + run: say + in: {word: !ii b} +- id: touch_2 + run: say + in: {word: !ii c} diff --git a/tests/core/data/nextflow/refused/boundary/wide_numbers.cwl b/tests/core/data/nextflow/refused/boundary/wide_numbers.cwl new file mode 100644 index 000000000..fcf6d7fff --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/wide_numbers.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A long and a double as inputs, as array items and as outputs; one long has a default. +baseCommand: echo +inputs: + a_long: {type: long, inputBinding: {position: 1}} + a_double: {type: double, inputBinding: {position: 2}} + longs: {type: {type: array, items: long}, inputBinding: {position: 3}} + doubles: {type: {type: array, items: double}, inputBinding: {position: 4}} + defaulted: {type: long, default: 1} +outputs: + long_out: {type: long, outputBinding: {glob: out.txt}} + double_out: {type: double, outputBinding: {glob: out.txt}} diff --git a/tests/core/data/nextflow/refused/boundary/workflow.wic b/tests/core/data/nextflow/refused/boundary/workflow.wic new file mode 100644 index 000000000..bcf485afa --- /dev/null +++ b/tests/core/data/nextflow/refused/boundary/workflow.wic @@ -0,0 +1,35 @@ +# The workflow boundary, names, numbers and resources the Nextflow target refuses, all in one workflow: lowering it +# reports every refusal expected.yaml lists for this file, at once. The other .wic files here are each refused for one +# reason, which is reported only when nothing else is. +inputs: + message: string # no value: a required input needs one + listed: {type: string, default: [not, scalar]} # a default is a JSON scalar + out-dir: {type: string, default: first} # two names that normalize alike would be one parameter + out_dir: {type: string, default: second} + a_long: long + a_double: double + +steps: +- id: says_message + run: say + in: {word: message} +- id: says_listed + run: say + in: {word: listed} +- id: says_out_dir + run: say + in: {word: out-dir} +- id: says_out_dir_again + run: say + in: {word: out_dir} +- id: colliding_ports +- id: runtime_glob +- id: classless +- id: wide_numbers + in: {a_long: a_long, a_double: a_double} +- id: resources + +outputs: + long_out: {type: long, outputSource: wide_numbers/long_out} + double_out: {type: double, outputSource: wide_numbers/double_out} + forwarded: {type: string, outputSource: message} # a workflow output that forwards an input has no process diff --git a/tests/core/data/nextflow/refused/calls/copy.cwl b/tests/core/data/nextflow/refused/calls/copy.cwl new file mode 100644 index 000000000..5a8e2a3b1 --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/copy.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Copy the source to copy.txt. +baseCommand: cp +arguments: [{position: 2, valueFrom: copy.txt}] +inputs: + source: {type: File, inputBinding: {position: 1}} +outputs: + result: {type: File, outputBinding: {glob: copy.txt}} diff --git a/tests/core/data/nextflow/refused/calls/copy_all.cwl b/tests/core/data/nextflow/refused/calls/copy_all.cwl new file mode 100644 index 000000000..8ac21b46e --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/copy_all.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Copy the sources into out/. +baseCommand: cp +arguments: [{position: 2, valueFrom: out}] +inputs: + source: {type: 'File[]', inputBinding: {position: 1}} +outputs: + result: {type: 'File[]', outputBinding: {glob: 'out/*'}} diff --git a/tests/core/data/nextflow/refused/calls/copy_source.wic b/tests/core/data/nextflow/refused/calls/copy_source.wic new file mode 100644 index 000000000..efd4c36dd --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/copy_source.wic @@ -0,0 +1,8 @@ +# Copy the source it is given. +inputs: + source: File +outputs: + result: {type: File, outputSource: copy/result} +steps: +- id: copy + in: {source: source} diff --git a/tests/core/data/nextflow/refused/calls/defaulted.wic b/tests/core/data/nextflow/refused/calls/defaulted.wic new file mode 100644 index 000000000..e506eba51 --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/defaulted.wic @@ -0,0 +1,6 @@ +# Copy the source it is given, or a default one. +inputs: + source: {type: File, default: {class: File, path: fallback.txt}} +steps: +- id: copy + in: {source: source} diff --git a/tests/core/data/nextflow/refused/calls/expected.yaml b/tests/core/data/nextflow/refused/calls/expected.yaml new file mode 100644 index 000000000..94b748ba6 --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/expected.yaml @@ -0,0 +1,39 @@ +why: A call's input takes one source as it is, computes nothing and replaces the called workflow's default; a call is + neither scattered nor conditional; the called workflow's ports, requirements and hints are judged as the root's are; + a workflow output relaying a nested input nothing binds refuses that input once, at the call that leaves it unbound. +# Each refusal: its code, its step, and its subject (a tool's file and field, a port, or a requirement). +roots: + workflow.wic: + - [nf-s016, joined, 'source'] + - [nf-s016, joined, 'source'] + - [nf-s016, joined, 'source'] + - [nf-s016, joined, 'source'] + - [nf-s019, computed, 'source'] + - [nf-s016, defaulted, 'source'] + - [nf-s003, scattered, null] + - [nf-s009, conditional, null] + - [nf-s048, ports, 'source'] + - [nf-s024, ports, 'source'] + - [nf-s048, ports, 'result'] + - [nf-s048, long_input, 'source'] + - [nf-s048, long_output, 'result'] + - [nf-s048, long_output, 'make_long~n'] + - [nf-s031, write_all, 'write_all.cwl: outputs.result.type'] + - [nf-s036, hinted_first~copy, 'SoftwareRequirement'] + - [nf-s036, hinted_second~copy, 'SoftwareRequirement'] + - [nf-s036, required~copy, 'SoftwareRequirement'] + - [nf-s031, ports~copy_all, 'copy_all.cwl: outputs.result.type'] + - [nf-s048, make_long, 'make_long.cwl: outputs.n.type'] + - [nf-s034, make_long, 'make_long.cwl: outputs.n.outputBinding'] + - [nf-s048, long_input~take_long, 'take_long.cwl: inputs.n.type'] + - [nf-s048, long_output~make_long, 'make_long.cwl: outputs.n.type'] + - [nf-s034, long_output~make_long, 'make_long.cwl: outputs.n.outputBinding'] + - [nf-s048, null, 'ports~result'] + - [nf-s048, null, 'make_long~n'] + - [nf-s048, null, 'long_output~result'] + - [nf-s048, null, 'long_output~make_long~n'] + relays.wic: + - [nf-s025, relay, 'extra'] + - [nf-s025, two_calls~relay, 'extra'] + - [nf-s025, two_calls, 'x'] + - [nf-s025, relayed, 'extra'] diff --git a/tests/core/data/nextflow/refused/calls/long_input.wic b/tests/core/data/nextflow/refused/calls/long_input.wic new file mode 100644 index 000000000..edc0dfe2f --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/long_input.wic @@ -0,0 +1,6 @@ +# Echo the long it is given. +inputs: + source: long +steps: +- id: take_long + in: {n: source} diff --git a/tests/core/data/nextflow/refused/calls/long_output.wic b/tests/core/data/nextflow/refused/calls/long_output.wic new file mode 100644 index 000000000..c0b8170b7 --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/long_output.wic @@ -0,0 +1,5 @@ +# Give a long. +outputs: + result: {type: long, outputSource: make_long/n} +steps: +- id: make_long diff --git a/tests/core/data/nextflow/refused/calls/make_long.cwl b/tests/core/data/nextflow/refused/calls/make_long.cwl new file mode 100644 index 000000000..6edd4262b --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/make_long.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Give 1 as a long. +baseCommand: [echo, '1'] +inputs: {} +stdout: n.txt +outputs: + n: {type: long, outputBinding: {glob: n.txt, loadContents: true, outputEval: '$(self[0].contents)'}} diff --git a/tests/core/data/nextflow/refused/calls/ports.wic b/tests/core/data/nextflow/refused/calls/ports.wic new file mode 100644 index 000000000..9833f52e0 --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/ports.wic @@ -0,0 +1,8 @@ +# Copy the sources it is given; its ports declare what no step reads: secondary files, and names of array schemas. +inputs: + source: {type: {type: array, items: File, name: inputs}, secondaryFiles: [.fai]} +outputs: + result: {type: {type: array, items: File, name: outputs}, outputSource: copy_all/result} +steps: +- id: copy_all + in: {source: source} diff --git a/tests/core/data/nextflow/refused/calls/relay.wic b/tests/core/data/nextflow/refused/calls/relay.wic new file mode 100644 index 000000000..57088719e --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/relay.wic @@ -0,0 +1,7 @@ +# Give back the optional file it is given. +inputs: + extra: File? +outputs: + passed: {type: 'File?', outputSource: extra} +steps: +- id: write diff --git a/tests/core/data/nextflow/refused/calls/relay_inside.wic b/tests/core/data/nextflow/refused/calls/relay_inside.wic new file mode 100644 index 000000000..aabd65305 --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/relay_inside.wic @@ -0,0 +1,12 @@ +# Call relay.wic, binding nothing, or binding the input x it leaves unbound. +inputs: + x: File? +outputs: + passed: {type: 'File?', outputSource: relay/passed} + bound: {type: 'File?', outputSource: relay_x/passed} +steps: +- id: relay + run: relay.wic +- id: relay_x + run: relay.wic + in: {extra: x} diff --git a/tests/core/data/nextflow/refused/calls/relays.wic b/tests/core/data/nextflow/refused/calls/relays.wic new file mode 100644 index 000000000..747b009fa --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/relays.wic @@ -0,0 +1,18 @@ +# A workflow output relaying a nested input nothing binds would be dropped without a word, so the input is refused, +# once, at the call that leaves it unbound, however many calls surround it and through a step output. +outputs: + passed: {type: 'File?', outputSource: relay/passed} + inside: {type: 'File?', outputSource: two_calls/passed} + bound: {type: 'File?', outputSource: two_calls/bound} + forwarded: {type: 'File?', outputSource: forward/passed} +steps: +- id: relay + run: relay.wic +- id: two_calls + run: relay_inside.wic +- id: relayed + run: relay.wic + out: [passed: !& passed] +- id: forward + run: relay.wic + in: {extra: !* passed} diff --git a/tests/core/data/nextflow/refused/calls/take_long.cwl b/tests/core/data/nextflow/refused/calls/take_long.cwl new file mode 100644 index 000000000..9c5152c3c --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/take_long.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Echo a long. +baseCommand: echo +inputs: + n: {type: long, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/calls/with_hints.wic b/tests/core/data/nextflow/refused/calls/with_hints.wic new file mode 100644 index 000000000..e271286f0 --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/with_hints.wic @@ -0,0 +1,8 @@ +# Copy the source it is given, with a SoftwareRequirement among its hints. +hints: + SoftwareRequirement: {packages: []} +inputs: + source: File +steps: +- id: copy + in: {source: source} diff --git a/tests/core/data/nextflow/refused/calls/with_requirements.wic b/tests/core/data/nextflow/refused/calls/with_requirements.wic new file mode 100644 index 000000000..d432114f7 --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/with_requirements.wic @@ -0,0 +1,8 @@ +# Copy the source it is given, with a SoftwareRequirement among its requirements. +requirements: + SoftwareRequirement: {packages: []} +inputs: + source: File +steps: +- id: copy + in: {source: source} diff --git a/tests/core/data/nextflow/refused/calls/workflow.wic b/tests/core/data/nextflow/refused/calls/workflow.wic new file mode 100644 index 000000000..8c80a60a6 --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/workflow.wic @@ -0,0 +1,50 @@ +# Calls the Nextflow target refuses, all in one workflow: lowering it reports every refusal expected.yaml lists for +# this file, at once. A call is inlined, so what it or the workflow it calls says is lowered or refused before the +# boundary is crossed. The other .wic files here are the workflows called, and relays.wic is refused on its own. +steps: +- id: write + out: [result: !& written] +- id: write_all + out: [result: !& all_written] + +# A call's input takes one source as it is, computes nothing, and replaces the called workflow's default. +- id: joined + run: copy_source.wic + in: {source: !cwl {source: [!* written, !* written], linkMerge: merge_nested, pickValue: first_non_null, default: 1}} +- id: computed + run: copy_source.wic + in: {source: !cwl {source: !* written, valueFrom: $(self)}} +- id: defaulted + run: defaulted.wic + in: {source: !* written} + +# A call is not scattered or conditional, and its requirements and hints are judged at each step that inherits them. +- id: scattered + run: copy_source.wic + scatter: [source] + in: {source: !* all_written} +- id: conditional + run: copy_source.wic + in: {source: !* written} + when: $(true) +- id: hinted_first + run: with_hints.wic + in: {source: !* written} +- id: hinted_second + run: with_hints.wic + in: {source: !* written} +- id: required + run: with_requirements.wic + in: {source: !* written} + +# A called workflow's ports are judged as the root's are, so a field cannot disappear in inlining. +- id: ports + run: ports.wic + in: {source: !* all_written} +- id: make_long + out: [n: !& long] +- id: long_input + run: long_input.wic + in: {source: !* long} +- id: long_output + run: long_output.wic diff --git a/tests/core/data/nextflow/refused/calls/write.cwl b/tests/core/data/nextflow/refused/calls/write.cwl new file mode 100644 index 000000000..8f741ff82 --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/write.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write message.txt. +baseCommand: [echo, hi] +inputs: {} +stdout: message.txt +outputs: + result: {type: File, outputBinding: {glob: message.txt}} diff --git a/tests/core/data/nextflow/refused/calls/write_all.cwl b/tests/core/data/nextflow/refused/calls/write_all.cwl new file mode 100644 index 000000000..daef6afef --- /dev/null +++ b/tests/core/data/nextflow/refused/calls/write_all.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write a.txt, and give the files that match *.txt. +baseCommand: [touch, a.txt] +inputs: {} +outputs: + result: {type: 'File[]', outputBinding: {glob: '*.txt'}} diff --git a/tests/core/data/nextflow/refused/commands/a_shell_inherited_beside_a_container.wic b/tests/core/data/nextflow/refused/commands/a_shell_inherited_beside_a_container.wic new file mode 100644 index 000000000..5a517b8b0 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/a_shell_inherited_beside_a_container.wic @@ -0,0 +1,6 @@ +# A ShellCommandRequirement beside a DockerRequirement is refused where its inherited half is written, which the tool's +# file does not hold. +requirements: + ShellCommandRequirement: {} +steps: +- id: on_the_host diff --git a/tests/core/data/nextflow/refused/commands/absent_values.cwl b/tests/core/data/nextflow/refused/commands/absent_values.cwl new file mode 100644 index 000000000..0ae3bc56a --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/absent_values.cwl @@ -0,0 +1,22 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Optional inputs a step leaves without a value, each read where its absence would change the command. +requirements: + ShellCommandRequirement: {} + EnvVarRequirement: + envDef: [{envName: A, envValue: $(inputs.exported)}] +baseCommand: echo +arguments: +- {position: 10, valueFrom: '--label=$(inputs.flag)'} # a flag's value, dereferenced +- {position: 11, valueFrom: $(inputs.message)} # read outside the input's own binding +- {position: 12, valueFrom: $(inputs.unbound)} # read by another binding, with none of its own +inputs: + flag: {type: 'boolean?', inputBinding: {position: 1, prefix: --verbose}} + message: {type: 'string?', inputBinding: {position: 2, prefix: --message}} + shell: {type: 'string?', inputBinding: {position: 3, valueFrom: printf optional, shellQuote: false}} + literal: {type: 'string?', inputBinding: {position: 4, prefix: --literal, valueFrom: literal}} + unbound: 'string?' + path: 'File?' + values: {type: 'string[]?', inputBinding: {position: 5, prefix: --value}} + exported: 'string?' +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/argument_position_true.cwl b/tests/core/data/nextflow/refused/commands/argument_position_true.cwl new file mode 100644 index 000000000..a80c7afdf --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/argument_position_true.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An argument whose position is true, which Python, not CWL, reads as 1. +baseCommand: echo +arguments: [{valueFrom: x, position: true}] +inputs: {} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/arguments_as_a_string.cwl b/tests/core/data/nextflow/refused/commands/arguments_as_a_string.cwl new file mode 100644 index 000000000..56100a25d --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/arguments_as_a_string.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Arguments written as a string. +baseCommand: echo +arguments: echo +inputs: + x: {type: string, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/array_separate_false.cwl b/tests/core/data/nextflow/refused/commands/array_separate_false.cwl new file mode 100644 index 000000000..d989af74c --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/array_separate_false.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An array input bound with separate false. +baseCommand: echo +inputs: + xs: {type: 'string[]', inputBinding: {position: 1, separate: false}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/array_value_from.cwl b/tests/core/data/nextflow/refused/commands/array_value_from.cwl new file mode 100644 index 000000000..3e037d11a --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/array_value_from.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An array input bound with a valueFrom. +baseCommand: echo +inputs: + xs: {type: 'string[]', inputBinding: {valueFrom: $(inputs.xs)}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/blank_prefix.cwl b/tests/core/data/nextflow/refused/commands/blank_prefix.cwl new file mode 100644 index 000000000..722ffc0ec --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/blank_prefix.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A flag whose prefix is blank. +baseCommand: echo +inputs: + b: {type: boolean, inputBinding: {prefix: ' '}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/computed.cwl b/tests/core/data/nextflow/refused/commands/computed.cwl new file mode 100644 index 000000000..3e6fcb6ef --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/computed.cwl @@ -0,0 +1,18 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A valueFrom that computes, which the target does not; only text and input references are kept. +baseCommand: echo +arguments: +- {prefix: -n, valueFrom: $(inputs.a * 2 + 1)} +- {prefix: -m, valueFrom: $(inputs.a > 1)} +- {prefix: -r, valueFrom: $(Math.round(inputs.b))} +- {prefix: -c, valueFrom: $(runtime.cores)} +- {prefix: -j, valueFrom: '${return 1}'} +inputs: + a: {type: int, inputBinding: {position: 1, valueFrom: $(inputs.a * 2 + 1)}} + b: {type: float, inputBinding: {position: 2, valueFrom: $(Math.round(inputs.b))}} + c: {type: int, inputBinding: {position: 3, valueFrom: $(inputs.c > 1)}} + d: {type: int, inputBinding: {position: 4, valueFrom: $(runtime.cores)}} + e: {type: int, inputBinding: {position: 5, valueFrom: '${return 1}'}} + f: {type: int, inputBinding: {position: 6, valueFrom: $(Math.round(inputs.b))}} # of another input +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/computed_binding.cwl b/tests/core/data/nextflow/refused/commands/computed_binding.cwl new file mode 100644 index 000000000..e424450cc --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/computed_binding.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A binding whose valueFrom computes from another input, the tool's one problem. +baseCommand: echo +inputs: + a: {type: int, inputBinding: {position: 1, valueFrom: $(Math.round(inputs.b))}} + b: float +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/containers.cwl b/tests/core/data/nextflow/refused/commands/containers.cwl new file mode 100644 index 000000000..b758d3006 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/containers.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A shell command line in a container, an image to build, and network access withheld. +requirements: + DockerRequirement: {dockerPull: alpine, dockerFile: FROM alpine} + ShellCommandRequirement: {} + NetworkAccess: {networkAccess: false} +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/dollar_javascript.cwl b/tests/core/data/nextflow/refused/commands/dollar_javascript.cwl new file mode 100644 index 000000000..2fbdfab34 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/dollar_javascript.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An argument whose `$` starts an expression that is not an input reference. +baseCommand: echo +arguments: ['${return 1}'] +inputs: + x: string +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/dollar_property.cwl b/tests/core/data/nextflow/refused/commands/dollar_property.cwl new file mode 100644 index 000000000..3e3566df1 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/dollar_property.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An argument whose `$` starts an expression that is not an input reference. +baseCommand: echo +arguments: [cost $5 $(inputs.x.size)] +inputs: + x: string +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/dollar_runtime.cwl b/tests/core/data/nextflow/refused/commands/dollar_runtime.cwl new file mode 100644 index 000000000..acf019f1d --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/dollar_runtime.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An argument whose `$` starts an expression that is not an input reference. +baseCommand: echo +arguments: [$(runtime.cores)] +inputs: + x: string +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/dollar_self.cwl b/tests/core/data/nextflow/refused/commands/dollar_self.cwl new file mode 100644 index 000000000..d29ceceec --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/dollar_self.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An argument whose `$` starts an expression that is not an input reference. +baseCommand: echo +arguments: [$$(self)] +inputs: + x: string +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/double.cwl b/tests/core/data/nextflow/refused/commands/double.cwl new file mode 100644 index 000000000..d72fadde9 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/double.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: ExpressionTool +doc: Double x; a process runs a CommandLineTool. +requirements: + InlineJavascriptRequirement: {} +inputs: + x: int +outputs: + y: int +expression: '$({y: inputs.x * 2})' diff --git a/tests/core/data/nextflow/refused/commands/empty_in_a_container.cwl b/tests/core/data/nextflow/refused/commands/empty_in_a_container.cwl new file mode 100644 index 000000000..509fd9b25 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/empty_in_a_container.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A containerized command that can render empty, so CWL would run the image's CMD. +requirements: + DockerRequirement: {dockerPull: 'ubuntu:24.04'} +inputs: + name: {type: 'string?', inputBinding: {prefix: --name}} + verbose: {type: boolean, inputBinding: {prefix: -v}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/empty_prefix.cwl b/tests/core/data/nextflow/refused/commands/empty_prefix.cwl new file mode 100644 index 000000000..8f826d8a1 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/empty_prefix.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A flag whose prefix is empty. +baseCommand: echo +inputs: + b: {type: boolean, inputBinding: {prefix: ''}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/env_list.cwl b/tests/core/data/nextflow/refused/commands/env_list.cwl new file mode 100644 index 000000000..277a98211 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/env_list.cwl @@ -0,0 +1,21 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Variables that are not literal text or one string input's value, read whole, and entries that are not entries. +requirements: + EnvVarRequirement: + envDef: + - {envName: FROM_AN_INT, envValue: $(inputs.n)} + - {envName: FROM_A_PATH, envValue: $(inputs.f.path)} + - {envName: FROM_A_BASENAME, envValue: $(inputs.s.basename)} + - {envName: BESIDE_TEXT, envValue: pre-$(inputs.s)} + - {envName: JAVASCRIPT, envValue: '${return 1}'} + - {envName: RUNTIME, envValue: $(runtime.cores)} + - {envName: 1A, envValue: x} + - {envName: NOT_TEXT, envValue: 3} + - A=x +baseCommand: env +inputs: + s: string + n: int + f: File +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/env_map.cwl b/tests/core/data/nextflow/refused/commands/env_map.cwl new file mode 100644 index 000000000..864202459 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/env_map.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A variable with a field nothing lowers. +requirements: + EnvVarRequirement: + envDef: {A: {envValue: x, foo: 1}} +baseCommand: env +inputs: {} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/expected.yaml b/tests/core/data/nextflow/refused/commands/expected.yaml new file mode 100644 index 000000000..58695855d --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/expected.yaml @@ -0,0 +1,97 @@ +why: An optional input with no value is read only by its own binding; a variable is literal text or a string input's + value, read whole; a flag is a boolean, bound with a prefix; only a literal valueFrom with no `$` is unquoted, under + ShellCommandRequirement and outside a container; .path and .basename read a File or Directory; an argument's `$` + starts only an input reference; a container is pulled and runs a command that cannot render empty. +# Each refusal: its code, its step, and its subject (a tool's file and field, or a requirement); a binding the lowering +# cannot write has no subject. +roots: + a_shell_inherited_beside_a_container.wic: + - [nf-s038, on_the_host, 'ShellCommandRequirement'] + workflow.wic: + - [nf-s041, env_list, 'env_list.cwl: requirements.EnvVarRequirement.envDef[0]'] + - [nf-s041, env_list, 'env_list.cwl: requirements.EnvVarRequirement.envDef[1]'] + - [nf-s041, env_list, 'env_list.cwl: requirements.EnvVarRequirement.envDef[2]'] + - [nf-s041, env_list, 'env_list.cwl: requirements.EnvVarRequirement.envDef[3]'] + - [nf-s041, env_list, 'env_list.cwl: requirements.EnvVarRequirement.envDef[4]'] + - [nf-s041, env_list, 'env_list.cwl: requirements.EnvVarRequirement.envDef[5]'] + - [nf-s041, env_list, 'env_list.cwl: requirements.EnvVarRequirement.envDef[6]'] + - [nf-s055, env_list, 'env_list.cwl: requirements.EnvVarRequirement.envDef[7]'] + - [nf-s055, env_list, 'env_list.cwl: requirements.EnvVarRequirement.envDef[8]'] + - [nf-s054, env_map, 'env_map.cwl: requirements.EnvVarRequirement.envDef.A.foo'] + - [nf-s046, flags, 'flags.cwl: inputs.suffixed.inputBinding.valueFrom'] + - [nf-s049, flags, 'flags.cwl: inputs.bools.inputBinding'] + - [nf-s049, flags, 'flags.cwl: inputs.bare_bools.inputBinding'] + - [nf-s049, flags, 'flags.cwl: inputs.maybe_bools.inputBinding'] + - [nf-s049, flags, 'flags.cwl: inputs.short_bools.inputBinding'] + - [nf-s049, flags, 'flags.cwl: inputs.typed_bools.inputBinding'] + - [nf-s049, flags, 'flags.cwl: inputs.aliased.inputBinding.valueFrom'] + - [nf-s049, flags, 'flags.cwl: inputs.literal.inputBinding.valueFrom'] + - [nf-s049, flags, 'flags.cwl: inputs.suffixed.inputBinding.valueFrom'] + - [nf-s022, flags, 'flags.cwl: arguments[0].loadContents'] + - [nf-s046, unquoted, 'unquoted.cwl: arguments[4].valueFrom'] + - [nf-s051, unquoted, 'unquoted.cwl: inputs.text.inputBinding.shellQuote'] + - [nf-s051, unquoted, 'unquoted.cwl: arguments[0].shellQuote'] + - [nf-s051, unquoted, 'unquoted.cwl: arguments[1].shellQuote'] + - [nf-s051, unquoted, 'unquoted.cwl: arguments[2].shellQuote'] + - [nf-s051, unquoted, 'unquoted.cwl: arguments[3].shellQuote'] + - [nf-s051, unquoted, 'unquoted.cwl: arguments[4].shellQuote'] + - [nf-s051, unquoted, 'unquoted.cwl: arguments[5].shellQuote'] + - [nf-s051, unquoted, 'unquoted.cwl: arguments[6].shellQuote'] + - [nf-s051, unquoted_without_shell, 'unquoted_without_shell.cwl: arguments[0].shellQuote'] + - [nf-s051, prefixed_shell_input, 'prefixed_shell_input.cwl: inputs.text.inputBinding.shellQuote'] + - [nf-s045, computed_binding, 'computed_binding.cwl: inputs.a.inputBinding.valueFrom'] + - [nf-s045, computed, 'computed.cwl: inputs.a.inputBinding.valueFrom'] + - [nf-s045, computed, 'computed.cwl: inputs.b.inputBinding.valueFrom'] + - [nf-s045, computed, 'computed.cwl: inputs.c.inputBinding.valueFrom'] + - [nf-s045, computed, 'computed.cwl: inputs.d.inputBinding.valueFrom'] + - [nf-s045, computed, 'computed.cwl: inputs.e.inputBinding.valueFrom'] + - [nf-s045, computed, 'computed.cwl: inputs.f.inputBinding.valueFrom'] + - [nf-s045, computed, 'computed.cwl: arguments[0].valueFrom'] + - [nf-s045, computed, 'computed.cwl: arguments[1].valueFrom'] + - [nf-s045, computed, 'computed.cwl: arguments[2].valueFrom'] + - [nf-s045, computed, 'computed.cwl: arguments[3].valueFrom'] + - [nf-s045, computed, 'computed.cwl: arguments[4].valueFrom'] + - [nf-s046, values_read_as_paths, 'values_read_as_paths.cwl: arguments[0]'] + - [nf-s046, values_read_as_paths, 'values_read_as_paths.cwl: inputs.s.inputBinding.valueFrom'] + - [nf-s046, values_read_as_paths, 'values_read_as_paths.cwl: inputs.n.inputBinding.valueFrom'] + - [nf-s046, values_read_as_paths, 'values_read_as_paths.cwl: inputs.x.inputBinding.valueFrom'] + - [nf-s046, values_read_as_paths, 'values_read_as_paths.cwl: stdout'] + - [nf-s046, values_read_as_paths, 'values_read_as_paths.cwl: outputs.result.outputBinding.glob'] + - [nf-s039, containers, 'containers.cwl: requirements.DockerRequirement.dockerFile'] + - [nf-s037, containers, 'containers.cwl: requirements.NetworkAccess.networkAccess'] + - [nf-s038, containers, 'containers.cwl'] + - [nf-s042, tool_fields, 'tool_fields.cwl: successCodes'] + - [nf-s036, tool_fields, 'tool_fields.cwl: requirements.ToolTimeLimit'] + - [nf-s048, tool_fields, 'tool_fields.cwl: inputs.flag.type'] + - [nf-s055, requirements_as_a_name, 'requirements_as_a_name.cwl: requirements'] + - [nf-s055, arguments_as_a_string, 'arguments_as_a_string.cwl: arguments'] + - [nf-s047, double, 'double.cwl: class'] + - [nf-s031, make_lists, 'make_lists.cwl: outputs.files.type'] + - [nf-s031, make_lists, 'make_lists.cwl: outputs.lists.type'] + - [nf-s050, per_item, null] + - [nf-s048, lists, null] + - [nf-s052, empty_prefix, null] + - [nf-s052, blank_prefix, null] + - [nf-s055, separate_false_string, null] + - [nf-s055, separate_false_boolean, null] + - [nf-s055, separate_null_string, null] + - [nf-s055, separate_null_boolean, null] + - [nf-s050, array_value_from, null] + - [nf-s050, array_separate_false, null] + - [nf-s055, argument_position_true, null] + - [nf-s049, optional_boolean_value_from, null] + - [nf-s053, empty_in_a_container, null] + - [nf-s045, dollar_runtime, null] + - [nf-s045, dollar_javascript, null] + - [nf-s045, dollar_property, null] + - [nf-s045, dollar_self, null] + - [nf-s045, after_a_skipped_step, null] + - [nf-s045, runtime_beside_an_optional, null] + - [nf-s020, absent_values, 'absent_values.cwl: inputs.flag'] + - [nf-s020, absent_values, 'absent_values.cwl: inputs.message'] + - [nf-s020, absent_values, 'absent_values.cwl: inputs.shell'] + - [nf-s020, absent_values, 'absent_values.cwl: inputs.literal'] + - [nf-s020, absent_values, 'absent_values.cwl: inputs.unbound'] + - [nf-s020, absent_values, 'absent_values.cwl: inputs.path'] + - [nf-s020, absent_values, 'absent_values.cwl: inputs.values'] + - [nf-s020, absent_values, 'absent_values.cwl: inputs.exported'] diff --git a/tests/core/data/nextflow/refused/commands/flags.cwl b/tests/core/data/nextflow/refused/commands/flags.cwl new file mode 100644 index 000000000..8c42d3a51 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/flags.cwl @@ -0,0 +1,17 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Bindings of booleans the target cannot write as cwltool does, and a binding's loadContents. +baseCommand: echo +arguments: +- {position: 0, valueFrom: x, loadContents: true} +inputs: + bools: {type: 'boolean[]', inputBinding: {position: 1, prefix: -x}} # cwltool writes -x alone + bare_bools: {type: {type: array, items: boolean}, inputBinding: {position: 2}} # and nothing at all + maybe_bools: {type: {type: array, items: ['null', boolean]}, inputBinding: {position: 3, prefix: -x}} + short_bools: {type: {type: array, items: 'boolean?'}, inputBinding: {position: 4, prefix: -x}} + typed_bools: {type: {type: array, items: {type: boolean}}, inputBinding: {position: 8}} + aliased: {type: boolean, inputBinding: {position: 5, prefix: --aliased, valueFrom: $(inputs.other)}} + literal: {type: boolean, inputBinding: {position: 6, prefix: --literal, valueFrom: 'true'}} + suffixed: {type: boolean, inputBinding: {position: 7, prefix: --suffixed, valueFrom: $(inputs.suffixed.basename)}} + other: boolean +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/lists.cwl b/tests/core/data/nextflow/refused/commands/lists.cwl new file mode 100644 index 000000000..dce5bdcc4 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/lists.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Echo lists of words. +baseCommand: echo +inputs: + lists: {type: {type: array, items: {type: array, items: string}}, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/make_lists.cwl b/tests/core/data/nextflow/refused/commands/make_lists.cwl new file mode 100644 index 000000000..1d0bb12fe --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/make_lists.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Give files, and lists of words. +baseCommand: [touch, a.txt] +inputs: {} +outputs: + files: {type: 'File[]', outputBinding: {glob: '*.txt'}} + lists: {type: {type: array, items: {type: array, items: string}}, outputBinding: {glob: a.txt}} diff --git a/tests/core/data/nextflow/refused/commands/maybe_text.cwl b/tests/core/data/nextflow/refused/commands/maybe_text.cwl new file mode 100644 index 000000000..709eac878 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/maybe_text.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print n, and give the text printed. +baseCommand: echo +inputs: + n: {type: int, inputBinding: {position: 1}} +stdout: out.txt +outputs: + text: {type: string, outputBinding: {glob: out.txt, loadContents: true, outputEval: '$(self[0].contents)'}} diff --git a/tests/core/data/nextflow/refused/commands/on_the_host.cwl b/tests/core/data/nextflow/refused/commands/on_the_host.cwl new file mode 100644 index 000000000..46732600e --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/on_the_host.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A tool that names its own container, beside a ShellCommandRequirement it inherits. +requirements: + DockerRequirement: {dockerPull: debian} +baseCommand: [echo, hi] +inputs: {} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/optional_boolean_value_from.cwl b/tests/core/data/nextflow/refused/commands/optional_boolean_value_from.cwl new file mode 100644 index 000000000..0dc1a5571 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/optional_boolean_value_from.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A boolean valueFrom on an optional input, which would write its absence. +baseCommand: echo +inputs: + b: boolean + s: {type: 'string?', inputBinding: {valueFrom: $(inputs.b), prefix: --flag}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/per_item.cwl b/tests/core/data/nextflow/refused/commands/per_item.cwl new file mode 100644 index 000000000..3f16999de --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/per_item.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Files each bound with its own prefix, and lists of words. +baseCommand: echo +inputs: + files: {type: {type: array, items: {type: File, inputBinding: {prefix: -I}}}, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/prefixed_shell_input.cwl b/tests/core/data/nextflow/refused/commands/prefixed_shell_input.cwl new file mode 100644 index 000000000..c575a83bc --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/prefixed_shell_input.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An input bound unquoted, with a prefix and no valueFrom. +requirements: + ShellCommandRequirement: {} +baseCommand: echo +inputs: + text: {type: string, inputBinding: {shellQuote: false, position: 1, prefix: echo}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/requirements_as_a_name.cwl b/tests/core/data/nextflow/refused/commands/requirements_as_a_name.cwl new file mode 100644 index 000000000..bf694dee6 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/requirements_as_a_name.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Requirements written as a class name. +requirements: DockerRequirement +baseCommand: echo +inputs: + x: {type: string, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/runtime_beside_an_optional.cwl b/tests/core/data/nextflow/refused/commands/runtime_beside_an_optional.cwl new file mode 100644 index 000000000..e9261b0bd --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/runtime_beside_an_optional.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An optional input beside an argument the target cannot read; the argument is the one refusal. +baseCommand: echo +arguments: [$(runtime.cores)] +inputs: + v: {type: 'string?', inputBinding: {}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/separate_false_boolean.cwl b/tests/core/data/nextflow/refused/commands/separate_false_boolean.cwl new file mode 100644 index 000000000..dbc52414d --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/separate_false_boolean.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A boolean input bound with separate false and no prefix, which cwltool refuses. +baseCommand: echo +inputs: + v: {type: boolean, inputBinding: {separate: false}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/separate_false_string.cwl b/tests/core/data/nextflow/refused/commands/separate_false_string.cwl new file mode 100644 index 000000000..83a8d4e9b --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/separate_false_string.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A string input bound with separate false and no prefix, which cwltool refuses. +baseCommand: echo +inputs: + v: {type: string, inputBinding: {separate: false}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/separate_null_boolean.cwl b/tests/core/data/nextflow/refused/commands/separate_null_boolean.cwl new file mode 100644 index 000000000..3e63df9de --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/separate_null_boolean.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A boolean input bound with separate null and no prefix, which cwltool refuses. +baseCommand: echo +inputs: + v: {type: boolean, inputBinding: {separate: null}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/separate_null_string.cwl b/tests/core/data/nextflow/refused/commands/separate_null_string.cwl new file mode 100644 index 000000000..cdcfa76a9 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/separate_null_string.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A string input bound with separate null and no prefix, which cwltool refuses. +baseCommand: echo +inputs: + v: {type: string, inputBinding: {separate: null}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/tool_fields.cwl b/tests/core/data/nextflow/refused/commands/tool_fields.cwl new file mode 100644 index 000000000..749748df5 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/tool_fields.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Exit codes besides 0, a union of a boolean and strings, and a requirement past what a task can withhold. +requirements: + ToolTimeLimit: {timelimit: 60} +successCodes: [0, 1] +baseCommand: echo +inputs: + flag: {type: ['null', boolean, {type: array, items: string}], inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/unquoted.cwl b/tests/core/data/nextflow/refused/commands/unquoted.cwl new file mode 100644 index 000000000..fc91d8f08 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/unquoted.cwl @@ -0,0 +1,18 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Unquoted words the target refuses; only a literal valueFrom, with no `$`, under ShellCommandRequirement is one. +requirements: + ShellCommandRequirement: {} +baseCommand: echo +arguments: +- {position: 1, shellQuote: false} # no valueFrom +- {position: 2, valueFrom: '>>', shellQuote: false, prefix: -x} # a prefix +- {position: 3, valueFrom: $(inputs.message), shellQuote: false} # an input's value +- {position: 4, valueFrom: prefix-$(inputs.message)-suffix, shellQuote: false} +- {position: 5, valueFrom: $(inputs.message.basename), shellQuote: false} +- {position: 6, valueFrom: '[$UNSET]', shellQuote: false} # a `$` the task's shell would expand +- {position: 7, valueFrom: '\$(date)', shellQuote: false} +inputs: + message: string + text: {type: string, inputBinding: {position: 8, prefix: echo, shellQuote: false}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/unquoted_without_shell.cwl b/tests/core/data/nextflow/refused/commands/unquoted_without_shell.cwl new file mode 100644 index 000000000..1324e22a1 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/unquoted_without_shell.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An unquoted word with no ShellCommandRequirement. +baseCommand: echo +arguments: +- {valueFrom: '>>', shellQuote: false} +inputs: {} +outputs: {} diff --git a/tests/core/data/nextflow/refused/commands/values_read_as_paths.cwl b/tests/core/data/nextflow/refused/commands/values_read_as_paths.cwl new file mode 100644 index 000000000..b184e10f7 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/values_read_as_paths.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: .path and .basename of values that are not a File or Directory, and a File object embedded in text. +baseCommand: echo +arguments: ['--input=$(inputs.f)'] +stdout: $(inputs.s.path).log +inputs: + s: {type: string, inputBinding: {prefix: -s, valueFrom: $(inputs.s.path)}} + n: {type: int, inputBinding: {prefix: -n, valueFrom: $(inputs.n.basename)}} + x: {type: float, inputBinding: {prefix: -x, valueFrom: $(inputs.x.path)}} + f: File +outputs: + result: {type: File, outputBinding: {glob: $(inputs.s.basename).txt}} diff --git a/tests/core/data/nextflow/refused/commands/workflow.wic b/tests/core/data/nextflow/refused/commands/workflow.wic new file mode 100644 index 000000000..c7c1f9e06 --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/workflow.wic @@ -0,0 +1,77 @@ +# Commands, bindings and variables the Nextflow target refuses, all in one workflow: lowering it reports every refusal +# expected.yaml lists for this file, at once. The tools above the blank line in the steps are refused field by field; +# each tool below it holds one binding the lowering cannot write, which is refused for the whole step. The other .wic +# file here is refused for one reason, which is reported only when nothing else is. +steps: +- id: absent_values # none of its optional inputs has a value +- id: env_list + in: {s: !ii v, n: !ii 1, f: !ii x.txt} +- id: env_map +- id: flags + in: {bools: !ii [true, false], bare_bools: !ii [true, false], maybe_bools: !ii [true, false], + short_bools: !ii [true, false], typed_bools: !ii [true], aliased: !ii true, literal: !ii true, + suffixed: !ii true, other: !ii false} +- id: unquoted + in: {message: !ii hi, text: !ii Hello} +- id: unquoted_without_shell +- id: prefixed_shell_input + in: {text: !ii Hello} +- id: computed_binding + in: {a: !ii 3, b: !ii 1.5} +- id: computed + in: {a: !ii 3, b: !ii 1.5, c: !ii 1, d: !ii 1, e: !ii 1, f: !ii 1} +- id: values_read_as_paths + in: {s: !ii x, n: !ii 1, x: !ii 1.5, f: !ii x.txt} +- id: containers +- id: tool_fields +- id: requirements_as_a_name + in: {x: !ii a} +- id: arguments_as_a_string + in: {x: !ii a} +- id: double + in: {x: !ii 1} +- id: make_lists + out: [files: !& files, lists: !& lists] +- id: per_item + in: {files: !* files} +- id: lists + in: {lists: !* lists} + +- id: empty_prefix + in: {b: !ii true} +- id: blank_prefix + in: {b: !ii true} +- id: separate_false_string + in: {v: !ii x} +- id: separate_false_boolean + in: {v: !ii true} +- id: separate_null_string + in: {v: !ii x} +- id: separate_null_boolean + in: {v: !ii true} +- id: array_value_from + in: {xs: !ii [x]} +- id: array_separate_false + in: {xs: !ii [a, b]} +- id: argument_position_true +- id: optional_boolean_value_from + in: {b: !ii true, s: !ii x} +- id: empty_in_a_container + in: {verbose: !ii false} +- id: dollar_runtime + in: {x: !ii v} +- id: dollar_javascript + in: {x: !ii v} +- id: dollar_property + in: {x: !ii v} +- id: dollar_self + in: {x: !ii v} +# The argument is refused, not the absence of a value a skipped step would leave, or that the step leaves. +- id: maybe_text + in: {n: !ii 2} + out: [text: !& maybe_text] + when: $(inputs.n > 1) +- id: after_a_skipped_step + run: runtime_beside_an_optional + in: {v: !* maybe_text} +- id: runtime_beside_an_optional diff --git a/tests/core/data/nextflow/refused/commands/x.txt b/tests/core/data/nextflow/refused/commands/x.txt new file mode 100644 index 000000000..587be6b4c --- /dev/null +++ b/tests/core/data/nextflow/refused/commands/x.txt @@ -0,0 +1 @@ +x diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/a.txt b/tests/core/data/nextflow/refused/conditions_and_step_inputs/a.txt new file mode 100644 index 000000000..9c59e24b8 --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/a.txt @@ -0,0 +1 @@ +first diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/a_when_on_a_step_with_no_inputs.wic b/tests/core/data/nextflow/refused/conditions_and_step_inputs/a_when_on_a_step_with_no_inputs.wic new file mode 100644 index 000000000..591e71165 --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/a_when_on_a_step_with_no_inputs.wic @@ -0,0 +1,5 @@ +# A step decides its condition each time its inputs arrive, so a step with none has nothing to gate on. +steps: +- id: no_inputs + run: touch_done + when: $(true) diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/an_absent_optional_file.wic b/tests/core/data/nextflow/refused/conditions_and_step_inputs/an_absent_optional_file.wic new file mode 100644 index 000000000..efd66744d --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/an_absent_optional_file.wic @@ -0,0 +1,7 @@ +# An optional File with no value has no lowering, even where a pickValue would pass over it. +inputs: + no_file: File? +steps: +- id: pick_a_file + run: show + in: {file: !cwl {source: [no_file, no_file], pickValue: first_non_null}} diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/count.cwl b/tests/core/data/nextflow/refused/conditions_and_step_inputs/count.cwl new file mode 100644 index 000000000..709eac878 --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/count.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print n, and give the text printed. +baseCommand: echo +inputs: + n: {type: int, inputBinding: {position: 1}} +stdout: out.txt +outputs: + text: {type: string, outputBinding: {glob: out.txt, loadContents: true, outputEval: '$(self[0].contents)'}} diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/count_default.cwl b/tests/core/data/nextflow/refused/conditions_and_step_inputs/count_default.cwl new file mode 100644 index 000000000..93e4651ed --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/count_default.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print n, which is 5 unless a step binds it. +baseCommand: echo +inputs: + n: {type: int, default: 5, inputBinding: {position: 1}} + m: int +outputs: {} diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/expected.yaml b/tests/core/data/nextflow/refused/conditions_and_step_inputs/expected.yaml new file mode 100644 index 000000000..52eb106c5 --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/expected.yaml @@ -0,0 +1,38 @@ +why: A `when` is a boolean of the step's own inputs in the safe subset, with at least one input to decide on; a skipped + step's null reaches only an optional value port; a step input joins its sources and takes a default as the idioms + can; a workflow input's default is a scalar and the steps that read it bind it; an optional File needs a value. +# Each refusal: its code, its step, and its subject (a tool's file and field, or a port). +roots: + a_when_on_a_step_with_no_inputs.wic: + - [nf-s012, no_inputs, null] + an_absent_optional_file.wic: + - [nf-s020, null, null] + workflow.wic: + - [nf-s011, reads_a_tool_default, null] + - [wic056, not_a_boolean, null] + - [nf-s010, outside_the_subset, null] + - [nf-s010, may_be_null, null] + - [nf-s031, make_maybe_files, 'make_files.cwl: outputs.files.type'] + - [nf-s017, null, 'xs'] + - [nf-s017, null, 'maybe_file'] + - [nf-s021, null, 'bound'] + - [nf-s019, value_from, 'word'] + - [nf-s013, make_maybe_files, null] + - [nf-s013, needs_text, 'word'] + - [nf-s013, reads_maybe_twice, 'word'] + - [nf-s013, shows_file, 'file'] + - [nf-s013, needs_texts, 'words'] + - [nf-s055, merge_deep, 'words'] + - [nf-s055, any_non_null, 'word'] + - [nf-s018, pick_from_one, 'word'] + - [nf-s018, default_beside_a_merge, 'words'] + - [nf-s017, array_default, 'words'] + - [nf-s017, mistyped_default, 'word'] + - [nf-s018, pick_over_an_array, 'word'] + - [nf-s017, default_over_an_array, 'words'] + - [nf-s018, nested_array, 'words'] + - [nf-s018, null_element, 'words'] + - [nf-s018, list_to_one, 'word'] + - [nf-s018, one_to_list, 'words'] + - [nf-s017, path_default, 'file'] + - [nf-s006, scattered_join, 'word'] diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/make_files.cwl b/tests/core/data/nextflow/refused/conditions_and_step_inputs/make_files.cwl new file mode 100644 index 000000000..b4bc9a81c --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/make_files.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make one file for n, and give it alone and as the files it matches. +baseCommand: touch +arguments: [out.txt] +inputs: + n: int +outputs: + file: {type: File, outputBinding: {glob: out.txt}} + files: {type: 'File[]', outputBinding: {glob: '*.txt'}} diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/say.cwl b/tests/core/data/nextflow/refused/conditions_and_step_inputs/say.cwl new file mode 100644 index 000000000..65a35be7f --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/say.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Echo one word. +baseCommand: echo +inputs: + word: {type: string, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/say_all.cwl b/tests/core/data/nextflow/refused/conditions_and_step_inputs/say_all.cwl new file mode 100644 index 000000000..ad32d5276 --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/say_all.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Echo a list of words. +baseCommand: echo +inputs: + words: {type: 'string[]', inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/say_maybe_twice.cwl b/tests/core/data/nextflow/refused/conditions_and_step_inputs/say_maybe_twice.cwl new file mode 100644 index 000000000..785250f33 --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/say_maybe_twice.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Echo an optional word with its prefix, and again on its own, where its absence would be written. +baseCommand: echo +arguments: [{position: 2, valueFrom: $(inputs.word)}] +inputs: + word: {type: 'string?', inputBinding: {position: 1, prefix: --word}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/show.cwl b/tests/core/data/nextflow/refused/conditions_and_step_inputs/show.cwl new file mode 100644 index 000000000..3323a0dc2 --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/show.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print a file. +baseCommand: echo +inputs: + file: {type: File, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/show_maybe.cwl b/tests/core/data/nextflow/refused/conditions_and_step_inputs/show_maybe.cwl new file mode 100644 index 000000000..73876097d --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/show_maybe.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print a file, if there is one. +baseCommand: echo +inputs: + file: {type: 'File?', inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/touch_done.cwl b/tests/core/data/nextflow/refused/conditions_and_step_inputs/touch_done.cwl new file mode 100644 index 000000000..d3e55e78f --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/touch_done.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Touch done.txt; it takes no input. +baseCommand: [touch, done.txt] +inputs: {} +outputs: {} diff --git a/tests/core/data/nextflow/refused/conditions_and_step_inputs/workflow.wic b/tests/core/data/nextflow/refused/conditions_and_step_inputs/workflow.wic new file mode 100644 index 000000000..8ffeb89a9 --- /dev/null +++ b/tests/core/data/nextflow/refused/conditions_and_step_inputs/workflow.wic @@ -0,0 +1,118 @@ +# Conditions and step inputs the Nextflow target refuses, all in one workflow: lowering it reports every refusal +# expected.yaml lists for this file, at once. As CWL the workflow is valid; each refusal is the target's, with its own +# code. The other .wic files here are each refused for one reason, which is reported only when nothing else is. +inputs: + x: {type: string, default: x} + y: {type: string, default: y} + xs: {type: 'string[]', default: [x]} + maybe: {type: 'string?', default: m} + maybe_n: {type: 'int?', default: 2} + maybe_file: {type: 'File?', default: {class: File, path: a.txt}} + bound: {type: string, default: b, inputBinding: {position: 1}} # a workflow input is bound by the steps that read it + +steps: +# A `when` reads the step's own inputs, which a tool's default is not; it gives a boolean, in the safe subset; it +# compares an optional input only with null. +- id: reads_a_tool_default + run: count_default + in: {m: !ii 1} + when: $(inputs.n > 3) +- id: not_a_boolean + run: count + in: {n: !ii 3} + when: $(inputs.n + 1) +- id: outside_the_subset + run: count + in: {n: !ii 3} + when: $(inputs.n ** 2) +- id: may_be_null + run: count + in: {n: maybe_n} + when: $(inputs.n > 1) + +# A skipped step's output is null, which an optional value port takes and a required one, a path or an array does not; +# an array output has no null to stand for a skipped step. +- id: maybe_text + run: count + in: {n: !ii 1} + out: [text: !& maybe_text] + when: $(inputs.n > 0) +- id: needs_text + run: say + in: {word: !* maybe_text} +- id: reads_maybe_twice + run: say_maybe_twice + in: {word: !* maybe_text} +- id: make_maybe_files + run: make_files + in: {n: !ii 1} + out: [file: !& maybe_file, files: !& maybe_files] + when: $(inputs.n > 0) +- id: shows_file + run: show_maybe + in: {file: !* maybe_file} +- id: maybe_texts + run: count + scatter: [n] + in: {n: !ii [1, 2]} + out: [text: !& maybe_texts] + when: $(inputs.n == 1) +- id: needs_texts + run: say_all + in: {words: !* maybe_texts} + +# A step input joins its sources and takes a default as the idioms can, or is refused. +- id: merge_deep + run: say_all + in: {words: !cwl {source: [x, y], linkMerge: merge_deep}} +- id: any_non_null + run: say + in: {word: !cwl {source: [x, y], linkMerge: merge_flattened, pickValue: any_non_null}} +- id: pick_from_one + run: say + in: {word: !cwl {source: x, pickValue: first_non_null}} +- id: default_beside_a_merge + run: say_all + in: {words: !cwl {source: [x, y], default: d}} +- id: array_default + run: say_all + in: {words: !cwl {default: [d]}} +- id: mistyped_default + run: say + in: {word: !cwl {default: 1}} +- id: pick_over_an_array + run: say + in: {word: !cwl {source: [xs, y], pickValue: first_non_null}} +- id: default_over_an_array + run: say_all + in: {words: !cwl {source: xs, default: [d]}} +- id: nested_array + run: say_all + in: {words: !cwl {source: [xs, y]}} +- id: null_element + run: say_all + in: {words: !cwl {source: [maybe, y]}} +- id: list_to_one + run: say + in: {word: !cwl {source: [x, y]}} +- id: one_to_list + run: say_all + in: {words: !cwl {source: [x, y], pickValue: first_non_null}} +- id: path_default + run: show + in: {file: !cwl {source: maybe_file, default: {class: File, path: a.txt}}} +- id: value_from + run: say + in: {word: !cwl {source: x, valueFrom: $(self)}} +- id: scattered_join + run: say + scatter: [word] + in: {word: !cwl {source: [xs], linkMerge: merge_flattened}} +- id: reads_bound + run: say + in: {word: bound} + +outputs: + files: {type: 'File[]', outputSource: make_maybe_files/files} +requirements: + StepInputExpressionRequirement: {} diff --git a/tests/core/data/nextflow/refused/outputs/a_step_reads_an_optional_output.wic b/tests/core/data/nextflow/refused/outputs/a_step_reads_an_optional_output.wic new file mode 100644 index 000000000..f7c45798a --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/a_step_reads_an_optional_output.wic @@ -0,0 +1,6 @@ +# A File? output may be null, which a workflow output takes and a step does not. +steps: +- id: maybe_file + out: [o: !& maybe] +- id: read_maybe + in: {source: !* maybe} diff --git a/tests/core/data/nextflow/refused/outputs/an_output_from_a_port_its_step_lacks.wic b/tests/core/data/nextflow/refused/outputs/an_output_from_a_port_its_step_lacks.wic new file mode 100644 index 000000000..d5399e76e --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/an_output_from_a_port_its_step_lacks.wic @@ -0,0 +1,6 @@ +# read_text has the output `result`, and no output `nope`. +outputs: + r: {type: File, outputSource: read_text/nope} +steps: +- id: read_text + in: {text: !ii hi} diff --git a/tests/core/data/nextflow/refused/outputs/an_output_from_a_step_that_is_not_there.wic b/tests/core/data/nextflow/refused/outputs/an_output_from_a_step_that_is_not_there.wic new file mode 100644 index 000000000..ba79457c7 --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/an_output_from_a_step_that_is_not_there.wic @@ -0,0 +1,6 @@ +# No step is called missing. +outputs: + r: {type: File, outputSource: missing/result} +steps: +- id: read_text + in: {text: !ii hi} diff --git a/tests/core/data/nextflow/refused/outputs/an_output_named_inside_a_call.wic b/tests/core/data/nextflow/refused/outputs/an_output_named_inside_a_call.wic new file mode 100644 index 000000000..792f151b1 --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/an_output_named_inside_a_call.wic @@ -0,0 +1,6 @@ +# CWL reads inner/made as the call's output. Sophios keeps the text as written and runs the call's steps in place, +# so the target finds no step called inner. +outputs: + made: {type: File, outputSource: inner/made} +steps: +- id: inner.wic diff --git a/tests/core/data/nextflow/refused/outputs/an_output_without_a_source.wic b/tests/core/data/nextflow/refused/outputs/an_output_without_a_source.wic new file mode 100644 index 000000000..09ea75a46 --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/an_output_without_a_source.wic @@ -0,0 +1,6 @@ +# A workflow output names the step output it comes from; this one names none. +outputs: + o: {type: File} +steps: +- id: read_text + in: {text: !ii hi} diff --git a/tests/core/data/nextflow/refused/outputs/captures.cwl b/tests/core/data/nextflow/refused/outputs/captures.cwl new file mode 100644 index 000000000..ff2601cc8 --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/captures.cwl @@ -0,0 +1,58 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Every output states one of the two outputEval declarations where it cannot be kept. +baseCommand: echo +inputs: + message: + type: string + inputBinding: {position: 1} +stdout: out.txt +outputs: + # $(self[0]) is the first match only of a glob that can match one file + first_of_a_star: + type: File + outputBinding: {glob: '*.txt', outputEval: '$(self[0])'} + first_of_a_question_mark: + type: File + outputBinding: {glob: 'out?.txt', outputEval: '$(self[0])'} + first_of_a_range: + type: File + outputBinding: {glob: 'out[0-9].txt', outputEval: '$(self[0])'} + first_of_an_input_reference: + type: File + outputBinding: {glob: '$(inputs.message)', outputEval: '$(self[0])'} + # loadContents and $(self[0].contents) are one declaration, and $(self[0]) takes no loadContents + load_contents_alone: + type: File + outputBinding: {glob: out.txt, loadContents: true} + first_with_load_contents: + type: File + outputBinding: {glob: out.txt, loadContents: true, outputEval: '$(self[0])'} + text_without_load_contents: + type: string + outputBinding: {glob: out.txt, outputEval: '$(self[0].contents)'} + text_with_load_contents_false: + type: string + outputBinding: {glob: out.txt, loadContents: false, outputEval: '$(self[0].contents)'} + # the text of a file is a string, of a glob that can match one file + text_as_an_int: + type: int + outputBinding: {glob: out.txt, loadContents: true, outputEval: '$(self[0].contents)'} + text_as_a_float: + type: float + outputBinding: {glob: out.txt, loadContents: true, outputEval: '$(self[0].contents)'} + text_as_a_file: + type: File + outputBinding: {glob: out.txt, loadContents: true, outputEval: '$(self[0].contents)'} + text_as_strings: + type: string[] + outputBinding: {glob: out.txt, loadContents: true, outputEval: '$(self[0].contents)'} + text_of_a_star: + type: string + outputBinding: {glob: '*.txt', loadContents: true, outputEval: '$(self[0].contents)'} + text_of_a_question_mark: + type: string + outputBinding: {glob: 'out?.txt', loadContents: true, outputEval: '$(self[0].contents)'} + text_of_a_range: + type: string + outputBinding: {glob: 'out[0-9].txt', loadContents: true, outputEval: '$(self[0].contents)'} diff --git a/tests/core/data/nextflow/refused/outputs/evals.cwl b/tests/core/data/nextflow/refused/outputs/evals.cwl new file mode 100644 index 000000000..0bf97f06c --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/evals.cwl @@ -0,0 +1,94 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Every output states an outputEval that is not one of the two the Nextflow target reads as a declaration. +baseCommand: echo +inputs: + message: + type: string + inputBinding: {position: 1} +stdout: out.txt +outputs: + # $(self[0]) with a space anywhere inside it is another text + spaces_inside: + type: File + outputBinding: {glob: out.txt, outputEval: '$( self[0] )'} + space_in_the_index: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[ 0 ])'} + space_before_the_end: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0] )'} + space_before_the_index: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self [0])'} + space_before_contents: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0] .contents)'} + # an expression is not evaluated, composed or recognised in part + arithmetic: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].size + 1)'} + a_method_call: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].basename.toUpperCase())'} + the_length: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self.length)'} + the_second_match: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[1])'} + a_conditional: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0] ? self[0] : null)'} + an_input: + type: File + outputBinding: {glob: out.txt, outputEval: '$(inputs.message)'} + a_function_body: + type: File + outputBinding: {glob: out.txt, outputEval: '${return self[0];}'} + a_function_body_that_trims: + type: File + outputBinding: {glob: out.txt, outputEval: '${ return self[0].contents.trim(); }'} + the_lines: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].contents.split(''\n''))'} + contents_called: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].contents())'} + text_before_it: + type: File + outputBinding: {glob: out.txt, outputEval: 'prefix-$(self[0])'} + written_twice: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0])$(self[0])'} + parsed_as_json: + type: File + outputBinding: {glob: out.txt, outputEval: '$(JSON.parse(self[0].contents))'} + parsed_as_a_number: + type: File + outputBinding: {glob: out.txt, outputEval: '$(parseInt(self[0].contents))'} + the_nameroot: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].nameroot)'} + the_nameext: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].nameext)'} + # a field of the file that a Nextflow task cannot give + the_dirname: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].dirname)'} + the_path: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].path)'} + the_location: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].location)'} + the_checksum: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].checksum)'} + the_secondary_files: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].secondaryFiles)'} + the_format: + type: File + outputBinding: {glob: out.txt, outputEval: '$(self[0].format)'} diff --git a/tests/core/data/nextflow/refused/outputs/expected.yaml b/tests/core/data/nextflow/refused/outputs/expected.yaml new file mode 100644 index 000000000..709f8d220 --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/expected.yaml @@ -0,0 +1,60 @@ +why: An outputEval is one of two declarations and nothing is evaluated; an output is one File or Directory, or a + file's text, and a null or a text is taken only by a workflow output; a workflow output names a step output. +# Each refusal: its code, its step, and its subject (a tool's file and field, or a step input). +roots: + workflow.wic: + - [nf-s033, evals, 'evals.cwl: outputs.spaces_inside.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.space_in_the_index.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.space_before_the_end.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.space_before_the_index.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.space_before_contents.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.arithmetic.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.a_method_call.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_length.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_second_match.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.a_conditional.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.an_input.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.a_function_body.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.a_function_body_that_trims.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_lines.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.contents_called.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.text_before_it.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.written_twice.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.parsed_as_json.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.parsed_as_a_number.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_nameroot.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_nameext.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_dirname.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_path.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_location.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_checksum.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_secondary_files.outputBinding'] + - [nf-s033, evals, 'evals.cwl: outputs.the_format.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.first_of_a_star.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.first_of_a_question_mark.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.first_of_a_range.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.first_of_an_input_reference.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.load_contents_alone.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.first_with_load_contents.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.text_without_load_contents.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.text_with_load_contents_false.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.text_as_an_int.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.text_as_a_float.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.text_as_a_file.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.text_as_strings.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.text_of_a_star.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.text_of_a_question_mark.outputBinding'] + - [nf-s034, captures, 'captures.cwl: outputs.text_of_a_range.outputBinding'] + - [nf-s031, many_files, 'many_files.cwl: outputs.results.type'] + - [nf-s050, named_by_an_array, null] + - [nf-s029, read_text, text] + a_step_reads_an_optional_output.wic: + - [nf-s030, null, null] + an_output_without_a_source.wic: + - [nf-s026, null, null] + an_output_from_a_port_its_step_lacks.wic: + - [nf-s028, null, null] + an_output_from_a_step_that_is_not_there.wic: + - [nf-s028, null, null] + an_output_named_inside_a_call.wic: + - [nf-s027, null, null] diff --git a/tests/core/data/nextflow/refused/outputs/inner.wic b/tests/core/data/nextflow/refused/outputs/inner.wic new file mode 100644 index 000000000..e71024a0a --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/inner.wic @@ -0,0 +1,6 @@ +# The workflow an_output_named_inside_a_call.wic calls. +outputs: + made: {type: File, outputSource: read_text/result} +steps: +- id: read_text + in: {text: !ii hi} diff --git a/tests/core/data/nextflow/refused/outputs/many_files.cwl b/tests/core/data/nextflow/refused/outputs/many_files.cwl new file mode 100644 index 000000000..673f9f76f --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/many_files.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make two files and give both. +baseCommand: [touch, a.txt, b.txt] +inputs: {} +outputs: + results: + type: File[] + outputBinding: {glob: '*.txt'} diff --git a/tests/core/data/nextflow/refused/outputs/maybe_file.cwl b/tests/core/data/nextflow/refused/outputs/maybe_file.cwl new file mode 100644 index 000000000..9deed320a --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/maybe_file.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Do nothing; maybe.txt is not made, so the output is null. +baseCommand: 'true' +inputs: {} +outputs: + o: + type: File? + outputBinding: {glob: maybe.txt} diff --git a/tests/core/data/nextflow/refused/outputs/named_by_an_array.cwl b/tests/core/data/nextflow/refused/outputs/named_by_an_array.cwl new file mode 100644 index 000000000..54778b6ed --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/named_by_an_array.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make each file named, and give the file named by the whole array. +baseCommand: touch +inputs: + xs: + type: string[] + inputBinding: {position: 1} +outputs: + o: + type: File + outputBinding: {glob: $(inputs.xs).txt} diff --git a/tests/core/data/nextflow/refused/outputs/read_maybe.cwl b/tests/core/data/nextflow/refused/outputs/read_maybe.cwl new file mode 100644 index 000000000..b286b6355 --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/read_maybe.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print the source, if there is one, to read.txt. +baseCommand: cat +inputs: + source: + type: File? + inputBinding: {position: 1} +stdout: read.txt +outputs: + result: + type: File + outputBinding: {glob: read.txt} diff --git a/tests/core/data/nextflow/refused/outputs/read_text.cwl b/tests/core/data/nextflow/refused/outputs/read_text.cwl new file mode 100644 index 000000000..77fd45e0b --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/read_text.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print the text to copy.txt. +baseCommand: echo +inputs: + text: + type: string + inputBinding: {position: 1} +stdout: copy.txt +outputs: + result: + type: File + outputBinding: {glob: copy.txt} diff --git a/tests/core/data/nextflow/refused/outputs/say_text.cwl b/tests/core/data/nextflow/refused/outputs/say_text.cwl new file mode 100644 index 000000000..19984c122 --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/say_text.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print the message, and give the text of what was printed. +baseCommand: echo +inputs: + message: + type: string + inputBinding: {position: 1} +stdout: out.txt +outputs: + text: + type: string + outputBinding: {glob: out.txt, loadContents: true, outputEval: '$(self[0].contents)'} diff --git a/tests/core/data/nextflow/refused/outputs/workflow.wic b/tests/core/data/nextflow/refused/outputs/workflow.wic new file mode 100644 index 000000000..f2e0624bf --- /dev/null +++ b/tests/core/data/nextflow/refused/outputs/workflow.wic @@ -0,0 +1,18 @@ +# Outputs the Nextflow target refuses, all in one workflow: lowering it reports every refusal expected.yaml lists +# for this file, at once. As CWL the workflow is valid; each refusal is the target's, with its own code. +# The other .wic files here are each refused for one reason, which is reported only when nothing else is refused. +steps: +- id: evals # each of its outputs states an outputEval the target does not read + in: {message: !ii hi} +- id: captures # each of its outputs states a declaration where it cannot be kept + in: {message: !ii hi} + +- id: say_text # the text of a file, as a string ... + in: {message: !ii hi} + out: [text: !& said] +- id: read_text # ... can be a workflow output, and cannot feed a step + in: {text: !* said} + +- id: many_files # a File[] output: an output is one File or Directory +- id: named_by_an_array # a glob reading an array input + in: {xs: !ii [a]} diff --git a/tests/core/data/nextflow/refused/scatter/expected.yaml b/tests/core/data/nextflow/refused/scatter/expected.yaml new file mode 100644 index 000000000..ba9cfd67f --- /dev/null +++ b/tests/core/data/nextflow/refused/scatter/expected.yaml @@ -0,0 +1,27 @@ +why: A scatter names one input or more, over two with a method of CWL's three, and a method needs a scatter; a scattered + input's source is one array of values its tool declares; a nested crossproduct reaches workflow outputs only; a + workflow's requirements are a mapping or list, each consumed or refused naming itself at the steps that inherit it. +# Each refusal: its code, its step, and its subject (a tool's file and field, a port, or a requirement). +roots: + requirements_of_the_wrong_shape.wic: + - [nf-s055, null, null] + workflow.wic: + - [nf-s031, make_files, 'make_files.cwl: outputs.files.type'] + - [nf-s048, reads_pairs, null] + - [nf-s017, null, 'words'] + - [nf-s048, null, 'anything'] + - [nf-s048, null, 'lists'] + - [nf-s017, null, 'flags'] + - [nf-s008, method_alone, null] + - [nf-s055, no_method, null] + - [nf-s055, not_a_method, null] + - [nf-s055, names_no_input, null] + - [nf-s006, over_anything, 'word'] + - [nf-s004, over_arrays, null] + - [nf-s005, over_a_step_only_input, 'enabled'] + - [nf-s006, over_one_value, 'file'] + - [nf-s007, reads_pairs, 'files'] + - [nf-s006, over_two_sources, 'word'] + workflow_requirements.wic: + - [nf-s036, each_word, 'SoftwareRequirement'] + - [nf-s054, null, 'ScatterFeatureRequirement'] diff --git a/tests/core/data/nextflow/refused/scatter/make_files.cwl b/tests/core/data/nextflow/refused/scatter/make_files.cwl new file mode 100644 index 000000000..2ab475d40 --- /dev/null +++ b/tests/core/data/nextflow/refused/scatter/make_files.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Make a.txt, and give the files that match *.txt. +baseCommand: [touch, a.txt] +inputs: {} +outputs: + files: {type: 'File[]', outputBinding: {glob: '*.txt'}} diff --git a/tests/core/data/nextflow/refused/scatter/pair.cwl b/tests/core/data/nextflow/refused/scatter/pair.cwl new file mode 100644 index 000000000..c0f200a83 --- /dev/null +++ b/tests/core/data/nextflow/refused/scatter/pair.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print first and second into out.txt. +baseCommand: echo +inputs: + first: {type: string, inputBinding: {position: 1}} + second: {type: string, inputBinding: {position: 2}} +stdout: out.txt +outputs: + out: {type: File, outputBinding: {glob: out.txt}} diff --git a/tests/core/data/nextflow/refused/scatter/requirements_of_the_wrong_shape.wic b/tests/core/data/nextflow/refused/scatter/requirements_of_the_wrong_shape.wic new file mode 100644 index 000000000..74fbaecc7 --- /dev/null +++ b/tests/core/data/nextflow/refused/scatter/requirements_of_the_wrong_shape.wic @@ -0,0 +1,7 @@ +# A workflow's requirements are a mapping or a list. +requirements: ScatterFeatureRequirement +steps: +- id: each_word + run: say + scatter: [word] + in: {word: !ii [a, b]} diff --git a/tests/core/data/nextflow/refused/scatter/say.cwl b/tests/core/data/nextflow/refused/scatter/say.cwl new file mode 100644 index 000000000..65a35be7f --- /dev/null +++ b/tests/core/data/nextflow/refused/scatter/say.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Echo one word. +baseCommand: echo +inputs: + word: {type: string, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/scatter/say_all.cwl b/tests/core/data/nextflow/refused/scatter/say_all.cwl new file mode 100644 index 000000000..ad32d5276 --- /dev/null +++ b/tests/core/data/nextflow/refused/scatter/say_all.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Echo a list of words. +baseCommand: echo +inputs: + words: {type: 'string[]', inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/scatter/show.cwl b/tests/core/data/nextflow/refused/scatter/show.cwl new file mode 100644 index 000000000..3323a0dc2 --- /dev/null +++ b/tests/core/data/nextflow/refused/scatter/show.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print a file. +baseCommand: echo +inputs: + file: {type: File, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/scatter/show_nested.cwl b/tests/core/data/nextflow/refused/scatter/show_nested.cwl new file mode 100644 index 000000000..f2b84285a --- /dev/null +++ b/tests/core/data/nextflow/refused/scatter/show_nested.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Print an array of arrays of files. +baseCommand: echo +inputs: + files: {type: {type: array, items: {type: array, items: File}}, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/scatter/workflow.wic b/tests/core/data/nextflow/refused/scatter/workflow.wic new file mode 100644 index 000000000..d9503f9a5 --- /dev/null +++ b/tests/core/data/nextflow/refused/scatter/workflow.wic @@ -0,0 +1,64 @@ +# Scattered steps the Nextflow target refuses, all in one workflow: lowering it reports every refusal expected.yaml +# lists for this file, at once. As CWL the workflow is valid; each refusal is the target's, with its own code. The +# other .wic files here are each refused for one reason, which is reported only when nothing else is. +inputs: + words: {type: 'string[]', default: [a, b]} + anything: {type: Any, default: a} + lists: {type: {type: array, items: {type: array, items: string}}, default: [[a], [b]]} + flags: {type: 'boolean[]', default: [true]} + +steps: +# A scatter names its inputs, over two of them with one of CWL's methods, and a method needs a scatter. +- id: no_method + run: pair + scatter: [first, second] + in: {first: words, second: words} +- id: not_a_method + run: say + scatter: [word] + scatterMethod: product + in: {word: words} +- id: names_no_input + run: say + scatter: [] + in: {word: !ii a} +- id: method_alone + run: say + scatterMethod: dotproduct + in: {word: !ii a} + +# A scattered input's source is one array of values, which an unscattered step's output and a join are not, and its +# tool declares it. +- id: over_anything + run: say + scatter: [word] + in: {word: anything} +- id: make_files + out: [files: !& made] +- id: over_one_value + run: show + scatter: [file] + in: {file: !* made} +- id: over_arrays + run: say_all + scatter: [words] + in: {words: lists} +- id: over_a_step_only_input + run: say + scatter: [enabled] + in: {word: !ii a, enabled: !cwl {source: flags}} +- id: over_two_sources + run: say + scatter: [word] + in: {word: !cwl {source: [words, words], linkMerge: merge_flattened}} + +# A nested crossproduct's array of arrays reaches workflow outputs only. +- id: pairs + run: pair + scatter: [first, second] + scatterMethod: nested_crossproduct + in: {first: words, second: words} + out: [out: !& pairs] +- id: reads_pairs + run: show_nested + in: {files: !* pairs} diff --git a/tests/core/data/nextflow/refused/scatter/workflow_requirements.wic b/tests/core/data/nextflow/refused/scatter/workflow_requirements.wic new file mode 100644 index 000000000..ba48a826e --- /dev/null +++ b/tests/core/data/nextflow/refused/scatter/workflow_requirements.wic @@ -0,0 +1,9 @@ +# A workflow's requirement is consumed, or refused naming itself, at each tool step that inherits it. +requirements: + ScatterFeatureRequirement: {method: dotproduct} + SoftwareRequirement: {packages: []} +steps: +- id: each_word + run: say + scatter: [word] + in: {word: !ii [a, b]} diff --git a/tests/core/data/nextflow/refused/staging/directory_fields.cwl b/tests/core/data/nextflow/refused/staging/directory_fields.cwl new file mode 100644 index 000000000..4d2c2702e --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/directory_fields.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A Directory whose listing is loaded, and a File with secondary files; each is staged whole and alone. +baseCommand: ls +inputs: + d: {type: Directory, loadListing: deep_listing, inputBinding: {position: 1}} + f: {type: File, secondaryFiles: [.bai], inputBinding: {position: 2}} +outputs: {} diff --git a/tests/core/data/nextflow/refused/staging/emit.cwl b/tests/core/data/nextflow/refused/staging/emit.cwl new file mode 100644 index 000000000..e3a66d20d --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/emit.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write sorted.txt. +baseCommand: [echo, b] +stdout: sorted.txt +inputs: {} +outputs: + out: {type: File, outputBinding: {glob: sorted.txt}} diff --git a/tests/core/data/nextflow/refused/staging/emit_a_directory.cwl b/tests/core/data/nextflow/refused/staging/emit_a_directory.cwl new file mode 100644 index 000000000..8fe63952a --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/emit_a_directory.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write the directory outdir. +baseCommand: [mkdir, outdir] +inputs: {} +outputs: + out: {type: Directory, outputBinding: {glob: outdir}} diff --git a/tests/core/data/nextflow/refused/staging/emit_into_a_directory.cwl b/tests/core/data/nextflow/refused/staging/emit_into_a_directory.cwl new file mode 100644 index 000000000..c3afc21ab --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/emit_into_a_directory.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Write out/sorted.txt. +baseCommand: [echo, b] +stdout: out/sorted.txt +inputs: {} +outputs: + out: {type: File, outputBinding: {glob: out/sorted.txt}} diff --git a/tests/core/data/nextflow/refused/staging/entries.cwl b/tests/core/data/nextflow/refused/staging/entries.cwl new file mode 100644 index 000000000..1259cd48f --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/entries.cwl @@ -0,0 +1,32 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Entries the target refuses; an entry is one input, staged under its own basename or one literal name. +requirements: + InitialWorkDirRequirement: + listing: + - {entry: $(inputs.a), writable: 'true'} # writable is a literal boolean + - {entry: $(inputs.b), writable: 1} + - {entry: $(inputs.c), writable: $(inputs.flag)} + - {entry: $(inputs.d), entryname: .sophios_entry_d} # the prefix the target stages under + - {entry: literal file content, entryname: x.txt} # a file the task would write + - {entry: $(inputs.e), entryname: $(inputs.e.path)} # a computed name + - {entry: $(inputs.f), entryname: sub/dir.txt} # a name in a directory + - $(inputs.nope) # an input the tool does not declare + - $(inputs.name) # a value, not a path + - $(inputs.files) # an array + - {entry: $(inputs.g), entryname: g.txt, foo: 1} # a field nothing lowers + - {entry: $(inputs.h), entryname: "a\0b"} # a NUL byte no file name holds +baseCommand: 'true' +inputs: + a: File + b: File + c: File + d: File + e: File + f: File + g: File + h: File + flag: boolean + name: string + files: 'File[]' +outputs: {} diff --git a/tests/core/data/nextflow/refused/staging/entry_of_a_number.cwl b/tests/core/data/nextflow/refused/staging/entry_of_a_number.cwl new file mode 100644 index 000000000..865e34431 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/entry_of_a_number.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An entry that is neither a reference nor a Dirent; a malformed listing stages what no check can know, so neither + the glob of the entry beside it nor the link it is under is checked. +requirements: + InitialWorkDirRequirement: {listing: [{entry: $(inputs.f), entryname: sorted.txt}, 123]} +baseCommand: 'true' +stdout: sorted.txt +inputs: + f: File +outputs: + result: {type: File, outputBinding: {glob: $(inputs.f.path)}} diff --git a/tests/core/data/nextflow/refused/staging/expected.yaml b/tests/core/data/nextflow/refused/staging/expected.yaml new file mode 100644 index 000000000..8a68f5f77 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/expected.yaml @@ -0,0 +1,60 @@ +why: An entry is one input, staged under its own basename or one literal name, copied or not as a literal says; a + renamed entry is named only by its literal; a plain reference is the object and `.path` is absolute, which neither a + stream nor a glob takes; nothing writes or globs the link a staged input is under; a Directory and a File are staged + whole and alone. +# Each refusal: its code, its step, and its subject (a tool's file and field); a staged name the lowering cannot write +# has no subject. +roots: + workflow.wic: + - [nf-s043, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[0]'] + - [nf-s043, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[1]'] + - [nf-s043, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[2]'] + - [nf-s043, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[3]'] + - [nf-s043, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[4]'] + - [nf-s043, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[5]'] + - [nf-s043, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[6]'] + - [nf-s043, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[7]'] + - [nf-s043, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[8]'] + - [nf-s043, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[9]'] + - [nf-s054, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[10].foo'] + - [nf-s055, entries, 'entries.cwl: requirements.InitialWorkDirRequirement.listing[11]'] + - [nf-s043, listing_not_a_list, 'listing_not_a_list.cwl: requirements.InitialWorkDirRequirement.listing'] + - [nf-s044, renamed_entries, 'renamed_entries.cwl: requirements.InitialWorkDirRequirement.listing[1]'] + - [nf-s044, renamed_entries, 'renamed_entries.cwl: requirements.InitialWorkDirRequirement.listing[3]'] + - [nf-s044, renamed_entries, 'renamed_entries.cwl: requirements.InitialWorkDirRequirement.listing'] + - [nf-s023, directory_fields, 'directory_fields.cwl: inputs.d.loadListing'] + - [nf-s024, directory_fields, 'directory_fields.cwl: inputs.f.secondaryFiles'] + - [nf-s046, references, 'references.cwl: stdin'] + - [nf-s046, references, 'references.cwl: stdout'] + - [nf-s046, references, 'references.cwl: stderr'] + - [nf-s046, references, 'references.cwl: outputs.plain.outputBinding.glob'] + - [nf-s046, references, 'references.cwl: outputs.suffixed.outputBinding.glob'] + - [nf-s046, references, 'references.cwl: outputs.path.outputBinding.glob'] + - [nf-s046, references, 'references.cwl: outputs.path_suffixed.outputBinding.glob'] + - [nf-s046, references, 'references.cwl: outputs.inside.outputBinding.glob'] + - [nf-s046, references, 'references.cwl: outputs.path_inside.outputBinding.glob'] + - [nf-s046, references_to_entries, 'references_to_entries.cwl: stdin'] + - [nf-s046, references_to_entries, 'references_to_entries.cwl: stdout'] + - [nf-s046, references_to_entries, 'references_to_entries.cwl: stderr'] + - [nf-s046, references_to_entries, 'references_to_entries.cwl: outputs.plain.outputBinding.glob'] + - [nf-s046, references_to_entries, 'references_to_entries.cwl: outputs.writable.outputBinding.glob'] + - [nf-s046, object_streams, 'object_streams.cwl: stdin'] + - [nf-s046, object_streams, 'object_streams.cwl: stdout'] + - [nf-s044, renamed_and_referenced, 'renamed_and_referenced.cwl: requirements.InitialWorkDirRequirement'] + - [nf-s044, renamed_and_written, 'renamed_and_written.cwl: requirements.InitialWorkDirRequirement'] + - [nf-s046, linked_by_basename, 'linked_by_basename.cwl: stdin'] + - [nf-s032, list_of_globs, null] + - [nf-s035, glob_at_a_staged_file, null] + - [nf-s035, glob_inside_a_staged_directory, null] + - [nf-s035, stdout_at_a_staged_file, null] + - [nf-s035, stderr_inside_a_staged_directory, null] + - [nf-s035, stdout_at_an_entry, null] + - [nf-s043, entry_of_a_number, 'entry_of_a_number.cwl: requirements.InitialWorkDirRequirement.listing[1]'] + - [nf-s023, directory_fields, 'directory_fields~d'] + - [nf-s024, directory_fields, 'directory_fields~f'] + - [nf-s035, sort, 'sort.cwl: stdout'] + - [nf-s035, sort_from_a_directory, 'sort.cwl: stdout'] + - [nf-s035, sort_dot_slash, 'sort_dot_slash.cwl: stdout'] + - [nf-s035, sort_by_its_glob, 'sort_by_its_glob.cwl: outputs.out.outputBinding.glob'] + - [nf-s035, list_into_it, 'list_into_it.cwl: stdout'] + - [nf-s035, sort_an_entry, 'sort_an_entry.cwl: stdout'] diff --git a/tests/core/data/nextflow/refused/staging/glob_at_a_staged_file.cwl b/tests/core/data/nextflow/refused/staging/glob_at_a_staged_file.cwl new file mode 100644 index 000000000..95e204828 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/glob_at_a_staged_file.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An output globbed at the name the staged file is linked under, or inside it. +baseCommand: 'true' +inputs: + source: File +outputs: + result: {type: File, outputBinding: {glob: ' $(inputs.source.basename) '}} diff --git a/tests/core/data/nextflow/refused/staging/glob_inside_a_staged_directory.cwl b/tests/core/data/nextflow/refused/staging/glob_inside_a_staged_directory.cwl new file mode 100644 index 000000000..fbca38971 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/glob_inside_a_staged_directory.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An output globbed at the name the staged directory is linked under, or inside it. +baseCommand: 'true' +inputs: + source: Directory +outputs: + result: {type: File, outputBinding: {glob: '$(inputs.source.basename)/keep.txt'}} diff --git a/tests/core/data/nextflow/refused/staging/in.txt b/tests/core/data/nextflow/refused/staging/in.txt new file mode 100644 index 000000000..587be6b4c --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/in.txt @@ -0,0 +1 @@ +x diff --git a/tests/core/data/nextflow/refused/staging/in/keep.txt b/tests/core/data/nextflow/refused/staging/in/keep.txt new file mode 100644 index 000000000..e69de29bb diff --git a/tests/core/data/nextflow/refused/staging/linked_by_basename.cwl b/tests/core/data/nextflow/refused/staging/linked_by_basename.cwl new file mode 100644 index 000000000..8b3552918 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/linked_by_basename.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An entry linked under its own basename, read as stdin by that basename. +requirements: + InitialWorkDirRequirement: {listing: [$(inputs.f)]} +baseCommand: cat +stdin: $(inputs.f.basename) +inputs: + f: File +outputs: {} diff --git a/tests/core/data/nextflow/refused/staging/list_into_it.cwl b/tests/core/data/nextflow/refused/staging/list_into_it.cwl new file mode 100644 index 000000000..93721e424 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/list_into_it.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: List src into outdir/listing.txt. +baseCommand: ls +stdout: outdir/listing.txt +inputs: + src: {type: Directory, inputBinding: {position: 1}} +outputs: + out: {type: File, outputBinding: {glob: outdir/listing.txt}} diff --git a/tests/core/data/nextflow/refused/staging/list_of_globs.cwl b/tests/core/data/nextflow/refused/staging/list_of_globs.cwl new file mode 100644 index 000000000..114c6f841 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/list_of_globs.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An output collected by a list of globs. +baseCommand: 'true' +inputs: + f: File +outputs: + result: {type: File, outputBinding: {glob: [$(inputs.f)]}} diff --git a/tests/core/data/nextflow/refused/staging/listing_not_a_list.cwl b/tests/core/data/nextflow/refused/staging/listing_not_a_list.cwl new file mode 100644 index 000000000..625b724e9 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/listing_not_a_list.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A listing that is not a list. +requirements: + InitialWorkDirRequirement: {listing: not-a-list} +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/nextflow/refused/staging/object_streams.cwl b/tests/core/data/nextflow/refused/staging/object_streams.cwl new file mode 100644 index 000000000..5891b45db --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/object_streams.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Streams that name the File object, under its own basename, or a gzip beside its path. +requirements: + InitialWorkDirRequirement: + listing: [$(inputs.linked)] +baseCommand: 'true' +inputs: + f: File + linked: File +outputs: {} +stdin: $(inputs.f.path).gz +stdout: $(inputs.f) +stderr: $(inputs.linked.basename).log diff --git a/tests/core/data/nextflow/refused/staging/references.cwl b/tests/core/data/nextflow/refused/staging/references.cwl new file mode 100644 index 000000000..06ec2fea1 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/references.cwl @@ -0,0 +1,18 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: References where the target does not take them; a plain File or Directory reference is the object, `.path` is + absolute, and a glob takes a `.path` only of an entry. +baseCommand: 'true' +inputs: + f: File + d: Directory +outputs: + plain: {type: File, outputBinding: {glob: $(inputs.f)}} + suffixed: {type: File, outputBinding: {glob: $(inputs.f).out}} + path: {type: File, outputBinding: {glob: $(inputs.f.path)}} + path_suffixed: {type: File, outputBinding: {glob: $(inputs.f.path).out}} + inside: {type: File, outputBinding: {glob: $(inputs.d)/keep.txt}} + path_inside: {type: File, outputBinding: {glob: $(inputs.d.path)/keep.txt}} +stdin: $(inputs.f) +stdout: $(inputs.f.path).log +stderr: $(inputs.f.path) diff --git a/tests/core/data/nextflow/refused/staging/references_to_entries.cwl b/tests/core/data/nextflow/refused/staging/references_to_entries.cwl new file mode 100644 index 000000000..3c7676b7f --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/references_to_entries.cwl @@ -0,0 +1,16 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: References to a linked entry and a writable one, which name the object or its absolute path. +requirements: + InitialWorkDirRequirement: + listing: [$(inputs.f), {entry: $(inputs.d), writable: true}] +baseCommand: 'true' +inputs: + f: File + d: Directory +outputs: + plain: {type: File, outputBinding: {glob: $(inputs.f)}} + writable: {type: Directory, outputBinding: {glob: $(inputs.d)}} +stdin: $(inputs.d.path) +stdout: $(inputs.f.path) +stderr: $(inputs.f) diff --git a/tests/core/data/nextflow/refused/staging/renamed_and_referenced.cwl b/tests/core/data/nextflow/refused/staging/renamed_and_referenced.cwl new file mode 100644 index 000000000..d5abd5abb --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/renamed_and_referenced.cwl @@ -0,0 +1,12 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An entry staged under a literal name, and referenced in the command by its input, which names the input. +requirements: + InitialWorkDirRequirement: + listing: [{entry: $(inputs.source), entryname: renamed.txt}] +baseCommand: cat +arguments: [$(inputs.source)] +stdout: $(inputs.source) +inputs: + source: File +outputs: {} diff --git a/tests/core/data/nextflow/refused/staging/renamed_and_written.cwl b/tests/core/data/nextflow/refused/staging/renamed_and_written.cwl new file mode 100644 index 000000000..f7d9292f3 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/renamed_and_written.cwl @@ -0,0 +1,11 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An entry staged under a literal name, which stdout names by its input; the rename alone is refused. +requirements: + InitialWorkDirRequirement: {listing: [{entry: $(inputs.f), entryname: x.txt}]} +baseCommand: 'true' +stdout: $(inputs.f) +inputs: + f: File +outputs: + result: {type: File, outputBinding: {glob: o}} diff --git a/tests/core/data/nextflow/refused/staging/renamed_entries.cwl b/tests/core/data/nextflow/refused/staging/renamed_entries.cwl new file mode 100644 index 000000000..0b1c73b2f --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/renamed_entries.cwl @@ -0,0 +1,19 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: An input staged twice, and two inputs staged under one name. +requirements: + InitialWorkDirRequirement: + listing: + - {entry: $(inputs.twice), entryname: one.txt} + - {entry: $(inputs.twice), entryname: two.txt} + - $(inputs.bare) + - {entry: $(inputs.bare), entryname: bare.txt} + - {entry: $(inputs.first), entryname: same.txt} + - {entry: $(inputs.second), entryname: same.txt} +baseCommand: cat +inputs: + twice: File + bare: File + first: File + second: File +outputs: {} diff --git a/tests/core/data/nextflow/refused/staging/sort.cwl b/tests/core/data/nextflow/refused/staging/sort.cwl new file mode 100644 index 000000000..702457a26 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/sort.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Sort src into sorted.txt. +baseCommand: sort +stdout: sorted.txt +inputs: + src: {type: File, inputBinding: {position: 1}} +outputs: + out: {type: File, outputBinding: {glob: sorted.txt}} diff --git a/tests/core/data/nextflow/refused/staging/sort_an_entry.cwl b/tests/core/data/nextflow/refused/staging/sort_an_entry.cwl new file mode 100644 index 000000000..71815f2c3 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/sort_an_entry.cwl @@ -0,0 +1,11 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Sort the entry sorted.txt into sorted.txt. +requirements: + InitialWorkDirRequirement: {listing: [{entry: $(inputs.src), entryname: sorted.txt}]} +baseCommand: [sort, sorted.txt] +stdout: sorted.txt +inputs: + src: File +outputs: + out: {type: File, outputBinding: {glob: sorted.txt}} diff --git a/tests/core/data/nextflow/refused/staging/sort_by_its_glob.cwl b/tests/core/data/nextflow/refused/staging/sort_by_its_glob.cwl new file mode 100644 index 000000000..f458075e2 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/sort_by_its_glob.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Sort src into sorted.txt, which the command names and the glob collects. +baseCommand: sort +arguments: [-o, sorted.txt] +inputs: + src: {type: File, inputBinding: {position: 1}} +outputs: + out: {type: File, outputBinding: {glob: sorted.txt}} diff --git a/tests/core/data/nextflow/refused/staging/sort_dot_slash.cwl b/tests/core/data/nextflow/refused/staging/sort_dot_slash.cwl new file mode 100644 index 000000000..006cc6310 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/sort_dot_slash.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: Sort src into ./sorted.txt. +baseCommand: sort +stdout: ./sorted.txt +inputs: + src: {type: File, inputBinding: {position: 1}} +outputs: + out: {type: File, outputBinding: {glob: sorted.txt}} diff --git a/tests/core/data/nextflow/refused/staging/stderr_inside_a_staged_directory.cwl b/tests/core/data/nextflow/refused/staging/stderr_inside_a_staged_directory.cwl new file mode 100644 index 000000000..c598089b3 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/stderr_inside_a_staged_directory.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A stderr written through the link the input is staged under, into the input. +baseCommand: 'true' +stderr: $(inputs.source.basename)/keep.txt +inputs: + source: Directory +outputs: {} diff --git a/tests/core/data/nextflow/refused/staging/stdout_at_a_staged_file.cwl b/tests/core/data/nextflow/refused/staging/stdout_at_a_staged_file.cwl new file mode 100644 index 000000000..684e6b7b0 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/stdout_at_a_staged_file.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A stdout written through the link the input is staged under, into the input. +baseCommand: 'true' +stdout: $(inputs.source.basename) +inputs: + source: File +outputs: {} diff --git a/tests/core/data/nextflow/refused/staging/stdout_at_an_entry.cwl b/tests/core/data/nextflow/refused/staging/stdout_at_an_entry.cwl new file mode 100644 index 000000000..f418b451d --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/stdout_at_an_entry.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +doc: A stdout written through the link the input is staged under, into the input. +requirements: + InitialWorkDirRequirement: {listing: [$(inputs.source)]} +baseCommand: 'true' +stdout: $(inputs.source.basename) +inputs: + source: File +outputs: {} diff --git a/tests/core/data/nextflow/refused/staging/workflow.wic b/tests/core/data/nextflow/refused/staging/workflow.wic new file mode 100644 index 000000000..a81985b34 --- /dev/null +++ b/tests/core/data/nextflow/refused/staging/workflow.wic @@ -0,0 +1,60 @@ +# Staged inputs, InitialWorkDirRequirement entries and references to them the Nextflow target refuses, all in one +# workflow: lowering it reports every refusal expected.yaml lists for this file, at once. +steps: +- id: entries + in: {a: !ii in.txt, b: !ii in.txt, c: !ii in.txt, d: !ii in.txt, e: !ii in.txt, f: !ii in.txt, g: !ii in.txt, + h: !ii in.txt, flag: !ii true, name: !ii n, files: !ii [in.txt]} +- id: listing_not_a_list +- id: renamed_entries + in: {twice: !ii in.txt, bare: !ii in.txt, first: !ii in.txt, second: !ii in.txt} +- id: directory_fields + in: {d: !ii in, f: !ii in.txt} +- id: references + in: {f: !ii in.txt, d: !ii in} +- id: references_to_entries + in: {f: !ii in.txt, d: !ii in} +- id: object_streams + in: {f: !ii in.txt, linked: !ii in.txt} + +# Refused for the whole step: a renamed entry referenced anywhere; a list of globs; a glob at, or a stream written +# through, the link a staged input is under, a name CWL does not match or that writes into the input. +- id: renamed_and_referenced + in: {source: !ii in.txt} +- id: renamed_and_written + in: {f: !ii in.txt} +- id: linked_by_basename + in: {f: !ii in.txt} +- id: list_of_globs + in: {f: !ii in.txt} +- id: glob_at_a_staged_file + in: {source: !ii in.txt} +- id: glob_inside_a_staged_directory + in: {source: !ii in} +- id: stdout_at_a_staged_file + in: {source: !ii in.txt} +- id: stderr_inside_a_staged_directory + in: {source: !ii in} +- id: stdout_at_an_entry + in: {source: !ii in.txt} +# A step's output named like the link its consumer stages it under: writing it writes through into the input. +- id: emit + out: [out: !& emitted] +- id: sort + in: {src: !* emitted} +- id: emit_into_a_directory + out: [out: !& emitted_inside] +- id: sort_from_a_directory + run: sort + in: {src: !* emitted_inside} +- id: sort_dot_slash + in: {src: !* emitted} +- id: sort_by_its_glob + in: {src: !* emitted} +- id: emit_a_directory + out: [out: !& emitted_directory] +- id: list_into_it + in: {src: !* emitted_directory} +- id: sort_an_entry + in: {src: !* emitted} +- id: entry_of_a_number # the listing alone is refused + in: {f: !* emitted} diff --git a/tests/core/data/nextflow/rejected/boundary.yaml b/tests/core/data/nextflow/rejected/boundary.yaml deleted file mode 100644 index 735481156..000000000 --- a/tests/core/data/nextflow/rejected/boundary.yaml +++ /dev/null @@ -1,157 +0,0 @@ -# The workflow boundary, names, types and requirements the target refuses (design §3, §6). Each `findings` or `error` -# is the diagnostic the replaced test wrote by hand from that rule, copied verbatim; nothing here was read off a run. -- {id: a_required_workflow_input_with_no_value, codes: [nf-s014], why: &missing 'Missing, null and a default are three things.', workflow: - {steps: &noop [{id: NOOP}], inputs: {message: {type: string}}}, tools: &noop_tool [{id: NOOP}], error: {re: required - workflow input value is missing}} -- {id: an_explicit_null_workflow_input, codes: [wic012], why: *missing, workflow: {steps: *noop, inputs: {message: {type: string}}}, - tools: *noop_tool, job: {message: null}, error: {re: explicit null input values}} -- {id: a_workflow_input_default_that_is_not_a_scalar, codes: [nf-s017], why: *missing, workflow: {steps: *noop, inputs: {message: - {type: string, default: [not, scalar]}}}, tools: *noop_tool, error: {re: JSON scalar defaults only}} -- id: workflow_input_collisions_aggregate_with_other_findings - codes: [nf-s002, nf-s054] - why: A naming collision is a finding beside the rest, not an error that hides them. - workflow: {steps: [{id: COLLISION, unknown_field: true}], inputs: &collide {out-dir: {type: string}, out_dir: {type: - string}}} - tools: [{id: COLLISION}] - job: &collision {out-dir: first, out_dir: second} - findings: {contains: [{re: 'workflow input: workflow input identifiers'}, {re: 'step ''COLLISION'': step: - unknown_field is not consumed'}]} -- {id: workflow_input_identifier_collisions, codes: [nf-s002], why: &normalize Two names that normalize alike would be one parameter., - workflow: {steps: *noop, inputs: *collide}, tools: *noop_tool, job: *collision, error: {re: "workflow input - identifiers 'out-dir', 'out_dir'.*normalize to 'out_dir'"}} -- {id: step_identifier_collisions_naming_both_steps, codes: [nf-s002], why: 'A repeated id carries `@`; it and an authored id - may normalize alike.', workflow: {steps: [{id: touch}, {id: touch}, {id: touch_2}]}, tools: [{id: touch}, {id: - touch}, {id: touch_2}], error: {re: 'workflow ''wf'': step: workflow step identifiers ''touch@2'', ''touch_2'' - normalize to ''touch_2'''}} -- {id: tool_port_identifier_collisions, codes: [nf-s002], why: *normalize, workflow: {steps: [{id: COLLISION}]}, tools: [{id: COLLISION, - inputs: {out-dir: {type: string, default: first}, out_dir: {type: string, default: second}}}], error: {re: "tool - input identifiers 'out-dir', 'out_dir'.*normalize to 'out_dir'"}} -- id: a_workflow_input_and_a_tool_default_normalizing_alike - codes: [nf-s002] - why: *normalize - workflow: {steps: [{id: DEFAULT}], inputs: {DEFAULT_message: {type: string}}} - tools: [{id: DEFAULT, inputs: {message: {type: string, default: tool default, inputBinding: {position: 1}}}}] - job: {DEFAULT_message: workflow value} - error: {re: "workflow parameter identifiers 'DEFAULT_message', 'DEFAULT~message' normalize to '_DEFAULT_message'"} -- {id: boundary_values_outside_supported_shape-string, codes: [nf-s015], why: &shape A value has the shape of its declared type., - workflow: {steps: *noop, inputs: {value: {type: string}}}, tools: *noop_tool, job: {value: [not, a, string]}, error: - &mismatch {re: does not match its supported CWL type}} -- {id: boundary_values_outside_supported_shape-int, codes: [nf-s015], why: *shape, workflow: {steps: *noop, inputs: {value: {type: int}}}, - tools: *noop_tool, job: {value: true}, error: *mismatch} -- {id: boundary_values_outside_supported_shape-File, codes: [nf-s015], why: *shape, workflow: {steps: *noop, inputs: {value: {type: - File}}}, tools: *noop_tool, job: {value: {class: File, path: reference.fa, secondaryFiles: [reference.fa.fai]}}, - error: *mismatch} -- {id: unknown_connection_source, codes: [nf-s028], why: A source names a step., workflow: {steps: [{id: B, out: [out]}], outputs: - {result: {type: File, outputSource: MISSING/out}}}, tools: [{id: B, outputs: {out: {type: File, outputBinding: - {glob: out.txt}}}}], error: {re: unknown source process 'MISSING'}} -- id: a_made_workflow_input_is_refused_at_the_step_it_was_made_for - codes: [nf-s014, wic012] - why: A workflow input the compiler made has no line of its own; the step input it was made for owns its refusal. - workflow: {steps: [{id: NEED}]} - tools: [{id: NEED, inputs: {message: {type: string, inputBinding: {position: 1}}}}] - findings: ['step ''NEED'': workflow input ''NEED~message'': required workflow input value is missing', 'step ''NEED'': - tool ''NEED.cwl: inputs.message'': resolves to an absent required value'] -- {id: output_glob_outside_typed_input_subset, codes: [nf-s045], why: A glob reads inputs only., workflow: {steps: [{id: BAD_GLOB, out: - [result]}]}, tools: [{id: BAD_GLOB, outputs: {result: {type: File, outputBinding: {glob: - $(runtime.outdir)/result.txt}}}}], error: {re: unsupported CWL expression}} -- {id: a_workflow_output_forwarding_an_input_is_a_workflow_finding, codes: [nf-s025], why: Boundary passthrough has no process to run., - workflow: {steps: [{id: ECHO}], inputs: {a: string}, outputs: {a_out: {type: string, outputSource: a}}}, tools: [{id: - ECHO}], job: {a: x}, findings: ['workflow ''wf'': workflow: workflow output ''a_out'' directly forwards a workflow - input; boundary passthrough is not executable on the Nextflow target']} -- {id: tool_requirement_without_class-requirements, codes: [nf-s055], why: &classless A requirement or hint names its class., tool: {id: - CLASSLESS, requirements: [{directive: '${System.exit(3)}'}]}, findings: ['step ''CLASSLESS'': tool ''CLASSLESS.cwl: - requirements.0'': a requirement or hint needs a string `class`']} -- {id: tool_requirement_without_class-hints, codes: [nf-s055], why: *classless, tool: {id: CLASSLESS, hints: [{directive: - '${System.exit(3)}'}]}, findings: ['step ''CLASSLESS'': tool ''CLASSLESS.cwl: hints.0'': a requirement or hint needs - a string `class`']} -- {id: a_long_input_with_a_default_has_only_the_type_finding, codes: [nf-s048], why: The type's finding names a long; its default is not - judged against it., workflow: {steps: [{id: N}]}, tools: [{id: N, inputs: {n: {type: long, default: 1}}}], findings: - ['step ''N'': tool ''N.cwl: inputs.n.type'': long is not supported: the Nextflow target lowers int and float; declare - one of those']} -- id: long_in_a_tool_input - codes: [nf-s048, nf-s048, nf-s014, wic012] - why: &long A long or a double is refused where it is declared, naming the type. - workflow: &produce_wf {steps: [{id: PRODUCE, in: {n: n}, out: [out]}], inputs: {n: {type: long}}, outputs: {out: - {type: File, outputSource: PRODUCE/out}}} - tools: [&produce {id: PRODUCE, inputs: {n: {type: long, inputBinding: {position: 1}}}, outputs: {out: {type: File, - outputBinding: {glob: out.txt}}}}] - error: {contains: ['step ''PRODUCE'': tool ''PRODUCE.cwl: inputs.n.type'': long is not supported', 'workflow ''wf'': - workflow input ''n'': type: long is not supported']} -- {id: double_in_a_tool_input, codes: [nf-s048, nf-s048, nf-s014, wic012], why: *long, workflow: {<<: *produce_wf, inputs: {n: {type: double}}}, tools: [{<<: - *produce, inputs: {n: {type: double, inputBinding: {position: 1}}}}], error: {contains: ['step ''PRODUCE'': tool - ''PRODUCE.cwl: inputs.n.type'': double is not supported', 'workflow ''wf'': workflow input ''n'': type: double is not - supported']}} -- {id: long_in_an_array_item, codes: [nf-s048, nf-s048, nf-s014], why: *long, workflow: {<<: *produce_wf, inputs: {n: {type: {type: array, items: long}}}}, - tools: [{<<: *produce, inputs: {n: {type: {type: array, items: long}, inputBinding: {position: 1}}}}], error: - {contains: ['step ''PRODUCE'': tool ''PRODUCE.cwl: inputs.n.type'': long is not supported']}} -- {id: double_in_an_array_item, codes: [nf-s048, nf-s048, nf-s014], why: *long, workflow: {<<: *produce_wf, inputs: {n: {type: {type: array, items: - double}}}}, tools: [{<<: *produce, inputs: {n: {type: {type: array, items: double}, inputBinding: {position: 1}}}}], - error: {contains: ['step ''PRODUCE'': tool ''PRODUCE.cwl: inputs.n.type'': double is not supported']}} -- id: long_in_a_tool_output - codes: [nf-s048, nf-s031, nf-s014, nf-s048] - why: *long - workflow: {<<: *produce_wf, inputs: &int {n: {type: int}}, outputs: {out: {type: long, outputSource: PRODUCE/out}}} - tools: [{<<: *produce, inputs: &int_input {n: {type: int, inputBinding: {position: 1}}}, outputs: {out: {type: long, - outputBinding: {glob: out.txt}}}}] - error: {contains: ['step ''PRODUCE'': tool ''PRODUCE.cwl: outputs.out.type'': long is not supported']} -- id: double_in_a_tool_output - codes: [nf-s048, nf-s031, nf-s014, nf-s048] - why: *long - workflow: {<<: *produce_wf, inputs: *int, outputs: {out: {type: double, outputSource: PRODUCE/out}}} - tools: [{<<: *produce, inputs: *int_input, outputs: {out: {type: double, outputBinding: {glob: out.txt}}}}] - error: {contains: ['step ''PRODUCE'': tool ''PRODUCE.cwl: outputs.out.type'': double is not supported']} -- {id: long_in_a_workflow_output, codes: [nf-s014, nf-s048, wic012], why: *long, tools: [{<<: *produce, inputs: *int_input}], workflow: {<<: *produce_wf, - inputs: *int, outputs: {out: {type: long, outputSource: PRODUCE/out}}}, error: {contains: ['workflow ''wf'': workflow - output ''out'': type: long is not supported']}} -- {id: double_in_a_workflow_output, codes: [nf-s014, nf-s048, wic012], why: *long, tools: [{<<: *produce, inputs: *int_input}], workflow: {<<: *produce_wf, - inputs: *int, outputs: {out: {type: double, outputSource: PRODUCE/out}}}, error: {contains: ['workflow ''wf'': - workflow output ''out'': type: double is not supported']}} -- {id: fractional_cpus, codes: [nf-s040], why: A cpu count is whole., tool: {id: RESOURCES, requirements: {ResourceRequirement: {coresMax: - 2.5}}}, error: {re: coresMax.*whole number}} -- {id: a_cuda_field_cwltool_does_not_declare, codes: [nf-s054], why: A field nothing lowers is refused naming itself., tool: {id: GPU, - hints: [{class: 'cwltool:CUDARequirement', cudaComputeCapabilityMin: '3.0'}]}, findings: ['step ''GPU'': tool - ''GPU.cwl: hints.0.cudaComputeCapabilityMin'': cudaComputeCapabilityMin is not consumed by the Nextflow lowering']} -- {id: cuda_device_count_min-0, codes: [nf-s055], why: &count A CUDA device count is a positive whole number., tool: {id: GPU, hints: - {'cwltool:CUDARequirement': {cudaDeviceCountMin: 0}}}, findings: ['step ''GPU'': tool ''GPU.cwl: - hints.cwltool:CUDARequirement.cudaDeviceCountMin'': a CUDA device count must be a positive whole number, got 0']} -- {id: cuda_device_count_min--1, codes: [nf-s055], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': {cudaDeviceCountMin: - -1}}}, findings: ['step ''GPU'': tool ''GPU.cwl: hints.cwltool:CUDARequirement.cudaDeviceCountMin'': a CUDA device - count must be a positive whole number, got -1']} -- {id: cuda_device_count_min-true, codes: [nf-s055], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': {cudaDeviceCountMin: - true}}}, findings: ['step ''GPU'': tool ''GPU.cwl: hints.cwltool:CUDARequirement.cudaDeviceCountMin'': a CUDA device - count must be a positive whole number, got True']} -- {id: cuda_device_count_min-1.5, codes: [nf-s055], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': {cudaDeviceCountMin: - 1.5}}}, findings: ['step ''GPU'': tool ''GPU.cwl: hints.cwltool:CUDARequirement.cudaDeviceCountMin'': a CUDA device - count must be a positive whole number, got 1.5']} -- {id: cuda_device_count_min-text, codes: [nf-s055], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': {cudaDeviceCountMin: - '2'}}}, findings: ['step ''GPU'': tool ''GPU.cwl: hints.cwltool:CUDARequirement.cudaDeviceCountMin'': a CUDA device - count must be a positive whole number, got ''2''']} -- {id: cuda_device_count_min-expression, codes: [nf-s040], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': - {cudaDeviceCountMin: $(inputs.n)}}}, findings: ['step ''GPU'': tool ''GPU.cwl: - hints.cwltool:CUDARequirement.cudaDeviceCountMin'': a CUDA device count must be a positive whole number, got - ''$(inputs.n)''']} -- {id: cuda_device_count_max-0, codes: [nf-s055], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': {cudaDeviceCountMin: 1, - cudaDeviceCountMax: 0}}}, findings: ['step ''GPU'': tool ''GPU.cwl: - hints.cwltool:CUDARequirement.cudaDeviceCountMax'': a CUDA device count must be a positive whole number, got 0']} -- {id: cuda_device_count_max--1, codes: [nf-s055], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': {cudaDeviceCountMin: 1, - cudaDeviceCountMax: -1}}}, findings: ['step ''GPU'': tool ''GPU.cwl: - hints.cwltool:CUDARequirement.cudaDeviceCountMax'': a CUDA device count must be a positive whole number, got -1']} -- {id: cuda_device_count_max-true, codes: [nf-s055], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': {cudaDeviceCountMin: - 1, cudaDeviceCountMax: true}}}, findings: ['step ''GPU'': tool ''GPU.cwl: - hints.cwltool:CUDARequirement.cudaDeviceCountMax'': a CUDA device count must be a positive whole number, got True']} -- {id: cuda_device_count_max-1.5, codes: [nf-s055], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': {cudaDeviceCountMin: - 1, cudaDeviceCountMax: 1.5}}}, findings: ['step ''GPU'': tool ''GPU.cwl: - hints.cwltool:CUDARequirement.cudaDeviceCountMax'': a CUDA device count must be a positive whole number, got 1.5']} -- {id: cuda_device_count_max-text, codes: [nf-s055], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': {cudaDeviceCountMin: - 1, cudaDeviceCountMax: '2'}}}, findings: ['step ''GPU'': tool ''GPU.cwl: - hints.cwltool:CUDARequirement.cudaDeviceCountMax'': a CUDA device count must be a positive whole number, got ''2''']} -- {id: cuda_device_count_max-expression, codes: [nf-s040], why: *count, tool: {id: GPU, hints: {'cwltool:CUDARequirement': - {cudaDeviceCountMin: 1, cudaDeviceCountMax: $(inputs.n)}}}, findings: ['step ''GPU'': tool ''GPU.cwl: - hints.cwltool:CUDARequirement.cudaDeviceCountMax'': a CUDA device count must be a positive whole number, got - ''$(inputs.n)''']} -- id: a_nan_for_a_float_input - why: The parameters are JSON, which holds no NaN. - codes: [nf-s015] - tool: {id: T, inputs: {x: {type: float, inputBinding: {position: 1}}}} - job: {x: .nan} - findings: ["workflow 'wf': workflow input 'x': supplied value does not match its supported CWL type"] diff --git a/tests/core/data/nextflow/rejected/calls.yaml b/tests/core/data/nextflow/rejected/calls.yaml deleted file mode 100644 index 203c9afa4..000000000 --- a/tests/core/data/nextflow/rejected/calls.yaml +++ /dev/null @@ -1,136 +0,0 @@ -# Calls of nested workflows the target refuses (design §6, Topology: a call is inlined, so what it or its nested -# workflow says is lowered or refused before the boundary is crossed). Each `findings` is the diagnostic the replaced -# test wrote by hand, copied verbatim, or the pattern it matched. -- id: a_nested_workflow_steps_input_takes_one_source_as_it_is - codes: [nf-s016, nf-s016, nf-s016, nf-s016] - why: The core compiler joins one source to each input a nested workflow step binds. - workflow: {steps: [&write {id: write, out: [{result: {wic_anchor: written}}]}, {id: child.wic, subtree: &child - {inputs: {source: File}, steps: [{id: copy, in: {source: source}}], outputs: {result: {type: File, outputSource: - copy/result}}}, parentargs: {in: {source: {wic_raw_cwl: {source: [{wic_alias: written}, {wic_alias: written}], - linkMerge: merge_nested, pickValue: first_non_null, default: 1}}}}}]} - tools: &tools - - {id: write, baseCommand: [echo, hi], stdout: message.txt, outputs: {result: {type: File, outputBinding: {glob: - message.txt}}}} - - {id: copy, baseCommand: cp, inputs: {source: {type: File, inputBinding: {position: 1}}}, arguments: [{position: 2, - valueFrom: copy.txt}], outputs: {result: {type: File, outputBinding: {glob: copy.txt}}}} - - {id: write_all, baseCommand: [touch, a.txt], outputs: {result: {type: &files {type: array, items: File}, - outputBinding: {glob: '*.txt'}}}} - - {id: copy_all, baseCommand: cp, inputs: {source: {type: *files, inputBinding: {position: 1}}}, arguments: - [{position: 2, valueFrom: out}], outputs: {result: {type: *files, outputBinding: {glob: 'out/*'}}}} - - {id: make_long, baseCommand: [echo, '1'], stdout: n.txt, outputs: {n: {type: long, outputBinding: {glob: n.txt, - loadContents: true, outputEval: '$(self[0].contents)'}}}} - - {id: take_long, baseCommand: echo, inputs: {n: {type: long, inputBinding: {position: 1}}}} - findings: - - 'step ''child'': input ''source'': default: a nested workflow step''s input takes one source as it is; merge on a - step inside the nested workflow' - - 'step ''child'': input ''source'': linkMerge: a nested workflow step''s input takes one source as it is; merge on a - step inside the nested workflow' - - 'step ''child'': input ''source'': pickValue: a nested workflow step''s input takes one source as it is; merge on a - step inside the nested workflow' - - 'step ''child'': input ''source'': source: a nested workflow step''s input takes one source as it is; merge on a - step inside the nested workflow' -- id: unconsumed_nested_workflow_port_fields - codes: [nf-s048, nf-s024, nf-s048, nf-s031, nf-s031] - why: &ports A nested workflow's ports are judged as the root workflow's are, so a field cannot disappear in inlining. - workflow: {steps: [{id: write_all, out: [{result: {wic_anchor: written}}]}, {id: child.wic, subtree: {inputs: {source: - {type: {<<: *files, name: inputs}, secondaryFiles: [.fai]}}, steps: [{id: copy_all, in: {source: source}}], outputs: - {result: {type: {<<: *files, name: outputs}, outputSource: copy_all/result}}}, parentargs: &bound {in: {source: - {wic_alias: written}}}}]} - tools: *tools - findings: {contains: [{re: secondaryFiles are not supported}, {re: 'step ''child'': workflow input ''\w+'': - type\.name: an array schema''s name'}, {re: 'step ''child'': workflow output ''\w+'': type\.name: an array schema''s - name'}]} -- id: unconsumed_workflow_call_input_semantics - codes: [nf-s019] - why: A call's binding is joined to the nested workflow's input as it is. - workflow: {steps: [*write, {id: child.wic, subtree: *child, parentargs: {in: {source: {wic_raw_cwl: {source: - {wic_alias: written}, valueFrom: $(self)}}}}}]} - tools: *tools - findings: {contains: [{re: a step input's valueFrom is not supported}]} -- id: nested_findings_aggregate_across_workflow_calls - codes: [nf-s036, nf-s036] - why: One finding per call, at the tool step that inherits the hint, and no third. - workflow: {steps: [*write, {id: child_0.wic, subtree: &hinted {<<: *child, hints: {SoftwareRequirement: {}}}, - parentargs: *bound}, {id: child_1.wic, subtree: *hinted, parentargs: *bound}]} - tools: *tools - findings: [{re: &software "requirement 'SoftwareRequirement': SoftwareRequirement is not supported"}, {re: *software}] -- id: scatter_on_a_resolved_subworkflow_call - codes: [nf-s003] - why: Scattering an inlined sub-DAG is not the single-process shape scatter supports. - workflow: {inputs: {sources: {type: *files}}, steps: [{id: child.wic, subtree: *child, parentargs: {in: {source: - sources}, scatter: [source]}}]} - tools: *tools - job: {sources: [{class: File, path: a.txt}]} - findings: {contains: [{re: scatter on a nested workflow step}]} -- id: when_on_a_resolved_subworkflow_call - codes: [nf-s009] - why: A when gates a tool step. - workflow: {steps: [*write, {id: child.wic, subtree: *child, parentargs: {<<: *bound, when: $(true)}}]} - tools: *tools - findings: {contains: [{re: a when on a nested-workflow step is not supported}]} -- id: unsupported_nested_workflow_requirements - codes: [nf-s036] - why: &requirements A nested workflow's requirements and hints are inherited by its tool steps, each judged as the - same entry written on its tool (resolved-view design §8). - workflow: {steps: [*write, {id: child.wic, subtree: {<<: *child, requirements: {SoftwareRequirement: {}}}, - parentargs: *bound}]} - tools: *tools - findings: {contains: [{re: "step 'child~copy': requirement 'SoftwareRequirement': SoftwareRequirement is not"}]} -- id: every_unconsumed_nested_workflow_field - codes: [nf-s036] - why: *requirements - workflow: {steps: [*write, {id: child.wic, subtree: *hinted, parentargs: *bound}]} - tools: *tools - findings: {contains: [{re: "step 'child~copy': requirement 'SoftwareRequirement': SoftwareRequirement is not"}]} -- id: a_nested_workflow_input_default_before_projection - codes: [nf-s016] - why: Inlining replaces a nested workflow's input with the call's binding, where CWL would apply the default to a null. - workflow: {steps: [*write, {id: child.wic, subtree: {<<: *child, inputs: {source: {type: File, default: - fallback.txt}}}, parentargs: *bound}]} - tools: *tools - findings: {contains: [{re: 'step ''child'': workflow input ''\w+'': default: a nested workflow input''s default'}]} -- id: long_on_a_nested_workflow_port_is_rejected_naming_the_type-inputs - codes: [nf-s048, nf-s048, nf-s034, nf-s048] - why: *ports - workflow: {steps: [{id: make_long, out: [{n: {wic_anchor: written}}]}, {id: child.wic, subtree: {inputs: {source: - long}, steps: [{id: take_long, in: {n: source}}]}, parentargs: *bound}]} - tools: *tools - findings: {contains: [{re: 'step ''child'': workflow input ''source'': type: long is not supported'}]} -- id: long_on_a_nested_workflow_port_is_rejected_naming_the_type-outputs - codes: [nf-s048, nf-s048, nf-s048, nf-s034] - why: *ports - workflow: {steps: [{id: child.wic, subtree: {steps: [{id: make_long}], outputs: {result: {type: long, outputSource: - make_long/n}}}}]} - tools: *tools - findings: {contains: [{re: 'step ''child'': workflow output ''result'': type: long is not supported'}]} -- id: a_root_output_relaying_a_nested_input_nothing_binds - why: An output with no source would be dropped without a word, so its input is refused at the call. - workflow: {steps: [{id: child.wic, subtree: &relay {inputs: {extra: 'File?'}, steps: [*write], outputs: {passed: - {type: 'File?', outputSource: extra}}}}], outputs: {passed: {type: 'File?', outputSource: child.wic/passed}}} - tools: *tools - findings: - - &unbound "step 'child': input 'extra': a workflow output relays it, but nothing binds it and it has no default" - codes: [nf-s025] -- id: a_relayed_nested_input_nothing_binds_is_refused_once_through_two_calls - why: The input is refused at the call that leaves it unbound, however many calls surround it. - workflow: {steps: [{id: mid.wic, subtree: {steps: [{id: child.wic, subtree: *relay}], outputs: {passed: {type: - 'File?', outputSource: child.wic/passed}}}}], outputs: {passed: {type: 'File?', outputSource: mid.wic/passed}}} - tools: *tools - findings: - - "step 'mid~child': input 'extra': a workflow output relays it, but nothing binds it and it has no default" -- id: a_relayed_input_bound_to_an_input_nothing_binds_names_that_input - why: The call binds the input, but to an input the caller leaves unbound, so that is what is refused, once. - workflow: {steps: [{id: mid.wic, subtree: {inputs: {x: 'File?'}, steps: [{id: child.wic, subtree: *relay, - parentargs: {in: {extra: x}}}], outputs: {passed: {type: 'File?', outputSource: child.wic/passed}}}}], outputs: - {passed: {type: 'File?', outputSource: mid.wic/passed}}} - tools: *tools - findings: - - "step 'mid': input 'x': a workflow output relays it, but nothing binds it and it has no default" -- id: a_relayed_input_bound_to_another_calls_output_is_refused_at_the_unbound_input - why: The chain runs through a step output and a second call, and the root output is the only thing that keeps it. - workflow: {steps: [{id: child.wic, subtree: *relay, parentargs: {out: [{passed: {wic_anchor: passed}}]}}, {id: - fwd.wic, subtree: {inputs: {extra: 'File?'}, outputs: {passed: {type: 'File?', outputSource: extra}}}, parentargs: - {in: {extra: {wic_alias: passed}}}}], outputs: {final: {type: 'File?', outputSource: fwd.wic/passed}}} - tools: *tools - findings: - - *unbound diff --git a/tests/core/data/nextflow/rejected/commands.yaml b/tests/core/data/nextflow/rejected/commands.yaml deleted file mode 100644 index d35e44174..000000000 --- a/tests/core/data/nextflow/rejected/commands.yaml +++ /dev/null @@ -1,365 +0,0 @@ -# Commands, bindings, flags, arrays and variables the target refuses (design §6, Expressions, Commands, Inputs and -# channels, Resources and containers). Each `findings` or `error` is the diagnostic the replaced test wrote by hand from -# that rule, copied verbatim; nothing here was read off a run. -- id: absent_optional_flag_that_is_also_dereferenced - codes: [nf-s020] - why: A flag only tests its value, but a template dereferences it, so absence would render `--label=[]`. - tool: {inputs: {verbose: {type: ['null', boolean], inputBinding: {position: 1, prefix: --verbose}}}, - arguments: [{position: 2, valueFrom: '--label=$(inputs.verbose)'}]} - job: {verbose: null} - findings: ['step ''make'': tool ''make.cwl: inputs.verbose'': absent optional values are supported only for a val - input whose absence leaves command rendering unchanged'] -- id: absent_optional_input_referenced_outside_its_own_binding - codes: [nf-s020] - why: Only the input's own binding is presence-gated; a reference elsewhere would render the sentinel. - tool: {id: OPTIONAL, inputs: {message: {type: ['null', string], inputBinding: {position: 1, prefix: --message}}}, - arguments: [{position: 2, valueFrom: $(inputs.message)}]} - job: &no_message {message: null} - error: &absent_message {re: 'step ''OPTIONAL'': tool ''OPTIONAL\.cwl: inputs\.message'': absent optional values are - supported only for a val input whose absence leaves command rendering unchanged'} -- id: absent_optional_input_whose_binding_emits_a_shell_literal - codes: [nf-s020] - why: CWL omits the entire binding when its optional source is absent. - tool: {id: OPTIONAL, requirements: {ShellCommandRequirement: {}}, inputs: {message: {type: ['null', string], - inputBinding: {position: 1, valueFrom: printf optional, shellQuote: false}}}} - job: *no_message - error: {re: 'step ''OPTIONAL'': tool ''OPTIONAL\.cwl: inputs\.message'': absent optional values are supported only for - a val input whose absence leaves command rendering unchanged'} -- {id: absent_optional_input_whose_binding_has_a_literal_value_from, codes: [nf-s020], job: *no_message, error: {re: 'step ''OPTIONAL'': - tool ''OPTIONAL\.cwl: inputs\.message'': absent optional values are supported only for a val input whose absence - leaves command rendering unchanged'}, why: CWL omits the prefix and the literal when the optional source is absent., - tool: {id: OPTIONAL, inputs: {message: {type: ['null', string], inputBinding: {position: 1, prefix: --message, - valueFrom: literal}}}}} -- {id: absent_optional_input_referenced_via_another_bindings_value_from, codes: [nf-s020], job: *no_message, error: {re: 'step - ''OPTIONAL'': tool ''OPTIONAL\.cwl: inputs\.message'': absent optional values are supported only for a val input - whose absence leaves command rendering unchanged'}, why: 'No binding of its own, but referenced elsewhere.', tool: - {id: OPTIONAL, inputs: {message: {type: ['null', string]}}, arguments: [{position: 1, valueFrom: - $(inputs.message)}]}} -- {id: absent_optional_path_input, codes: [nf-s020], why: Path channel construction always stages., job: *no_message, tool: {id: OPTIONAL, - inputs: {message: {type: ['null', File]}}}, error: {re: 'step ''OPTIONAL'': tool ''OPTIONAL\.cwl: inputs\.message'': - absent optional values are supported only for a val input whose absence leaves command rendering unchanged'}} -- {id: absent_optional_workflow_input_feeding_required_input, codes: [wic012], why: A required input takes a value., workflow: {steps: - [{id: REQUIRED, in: {message: message}}], inputs: {message: {type: ['null', string]}}}, tools: [{id: REQUIRED, - inputs: {message: {type: string}}}], error: {re: absent required}} -- id: absent_optional_array_input - codes: [nf-s020] - why: Absence (no array at all) is out of scope for the array lowering; empty is not absence. - tool: {inputs: {values: {type: ['null', {type: array, items: string}], inputBinding: {position: 1, prefix: - --value}}}} - job: {values: null} - error: {re: 'step ''make'': tool ''make\.cwl: inputs\.values'': absent optional'} -- id: an_env_var_from_an_absent_input - codes: [nf-s020] - why: An absent optional value has no text to export. - tool: &env {id: ENV, inputs: {s: {type: string}, n: {type: int}, f: {type: File}, o: {type: 'string?'}}, requirements: - {EnvVarRequirement: {envDef: [{envName: A, envValue: $(inputs.o)}]}}} - job: &env_job_without_o {s: v, n: 1, f: {class: File, path: x.txt}} - findings: ['step ''ENV'': tool ''ENV.cwl: inputs.o'': absent optional values are supported only for a val input whose - absence leaves command rendering unchanged'] -- {id: an_env_def_entry_with_an_unknown_field, codes: [nf-s054], why: A field nothing lowers is refused naming itself., tool: {<<: *env, - requirements: {EnvVarRequirement: {envDef: {A: {envValue: x, foo: 1}}}}}, job: &env_job {<<: *env_job_without_o, o: - w}, findings: ['step ''ENV'': tool ''ENV.cwl: requirements.EnvVarRequirement.envDef.A.foo'': foo is not consumed by - the Nextflow lowering']} -- {id: an_env_var_from_an_int_input, codes: [nf-s041], why: &env_value 'design §6, Resources and containers: a variable is literal text or - one string input''s value, read whole; every other value is refused by name.', job: *env_job, tool: {<<: *env, - requirements: {EnvVarRequirement: {envDef: [{envName: A, envValue: $(inputs.n)}]}}}, findings: [{re: '^step ''ENV'': - tool ''ENV\.cwl: requirements\.EnvVarRequirement\.envDef\[0\]'': .*needs a string input, read whole as - \$\(inputs\.\); n is declared ''int'''}]} -- {id: an_env_var_from_a_file_path, codes: [nf-s041], why: *env_value, job: *env_job, tool: {<<: *env, requirements: {EnvVarRequirement: - {envDef: [{envName: A, envValue: $(inputs.f.path)}]}}}, findings: [{re: '^step ''ENV'': tool ''ENV\.cwl: - requirements\.EnvVarRequirement\.envDef\[0\]'': .*needs a string input'}]} -- {id: an_env_var_from_a_basename, codes: [nf-s041], why: *env_value, job: *env_job, tool: {<<: *env, requirements: {EnvVarRequirement: - {envDef: [{envName: A, envValue: $(inputs.s.basename)}]}}}, findings: [{re: '^step ''ENV'': tool ''ENV\.cwl: - requirements\.EnvVarRequirement\.envDef\[0\]'': .*needs a string input'}]} -- {id: an_env_var_with_text_beside_a_reference, codes: [nf-s041], why: *env_value, job: *env_job, tool: {<<: *env, requirements: - {EnvVarRequirement: {envDef: [{envName: A, envValue: pre-$(inputs.s)}]}}}, findings: [{re: '^step ''ENV'': tool - ''ENV\.cwl: requirements\.EnvVarRequirement\.envDef\[0\]'': .*is not supported: write literal text or exactly - \$\(inputs\.\)'}]} -- {id: an_env_var_from_javascript, codes: [nf-s041], why: *env_value, job: *env_job, tool: {<<: *env, requirements: {EnvVarRequirement: - {envDef: [{envName: A, envValue: '${return 1}'}]}}}, findings: [{re: '^step ''ENV'': tool ''ENV\.cwl: - requirements\.EnvVarRequirement\.envDef\[0\]'': .*is not supported'}]} -- {id: an_env_var_from_the_runtime, codes: [nf-s041], why: *env_value, job: *env_job, tool: {<<: *env, requirements: {EnvVarRequirement: - {envDef: [{envName: A, envValue: $(runtime.cores)}]}}}, findings: [{re: '^step ''ENV'': tool ''ENV\.cwl: - requirements\.EnvVarRequirement\.envDef\[0\]'': .*is not supported'}]} -- {id: an_env_var_name_that_is_not_a_shell_name, codes: [nf-s041], why: *env_value, job: *env_job, tool: {<<: *env, requirements: - {EnvVarRequirement: {envDef: [{envName: 1A, envValue: x}]}}}, findings: [{re: '^step ''ENV'': tool ''ENV\.cwl: - requirements\.EnvVarRequirement\.envDef\[0\]'': .*environment variable name must be a shell variable name, got - ''1A'''}]} -- {id: an_env_var_value_that_is_not_text, codes: [nf-s055], why: *env_value, job: *env_job, tool: {<<: *env, requirements: - {EnvVarRequirement: {envDef: [{envName: A, envValue: 3}]}}}, findings: &env_entry [{re: '^step ''ENV'': tool - ''ENV\.cwl: requirements\.EnvVarRequirement\.envDef\[0\]'': .*an envDef entry needs a string envName and a string - envValue'}]} -- {id: an_env_def_entry_that_is_not_a_mapping, codes: [nf-s055], why: *env_value, job: *env_job, tool: {<<: *env, requirements: - {EnvVarRequirement: {envDef: [A=x]}}}, findings: [{re: '^step ''ENV'': tool ''ENV\.cwl: - requirements\.EnvVarRequirement\.envDef\[0\]'': .*an envDef entry needs a string envName and a string envValue'}]} -- {id: loadContents_on_an_arguments_entry, codes: [nf-s022], why: A binding's loadContents has no lowering., tool: {id: ARGS, arguments: - [{valueFrom: x, loadContents: true}]}, findings: ['step ''ARGS'': tool ''ARGS.cwl: arguments[0].loadContents'': a - binding''s loadContents is not supported']} -- id: shell_mode_in_a_container - codes: [nf-s038] - why: CWL runs the command as /bin/sh -c after the image's ENTRYPOINT, which the Nextflow task does not. - tool: {id: SHELL, requirements: {DockerRequirement: &ubuntu {dockerPull: 'ubuntu:24.04'}, ShellCommandRequirement: - {}}} - findings: ['step ''SHELL'': tool ''SHELL.cwl'': ShellCommandRequirement beside a DockerRequirement is not supported: - CWL runs the command as /bin/sh -c after the image''s ENTRYPOINT, which the Nextflow task does not'] -- id: shell_mode_inherited_beside_the_tools_own_container - codes: [nf-s038] - why: The pair is refused where its inherited half is written, which the tool's file does not hold (resolved-view - design §8). - workflow: {steps: [{id: say}], requirements: {ShellCommandRequirement: {}}} - tools: [{id: say, baseCommand: [echo, hi], requirements: {DockerRequirement: {dockerPull: debian}}}] - findings: ['step ''say'': requirement ''ShellCommandRequirement'': ShellCommandRequirement beside a DockerRequirement - is not supported: CWL runs the command as /bin/sh -c after the image''s ENTRYPOINT, which the Nextflow task does - not'] -- id: a_containerized_command_that_can_render_empty - codes: [nf-s053] - why: CWL then gives the container no arguments, so the image runs its CMD, which the Nextflow task does not. - tool: {id: ENTRY, baseCommand: null, requirements: {DockerRequirement: *ubuntu}, inputs: {name: {type: 'string?', - inputBinding: {prefix: --name}}, verbose: {type: boolean, inputBinding: {prefix: -v}}}} - job: {verbose: false} - findings: ['step ''ENTRY'': step: a containerized tool whose command can render empty is not supported: CWL then gives - the container no arguments, so the image runs its CMD, after its ENTRYPOINT if it has one, which the Nextflow task - does not; name the program in baseCommand'] -- id: nested_arrays - codes: [nf-s031, nf-s048] - why: &producer_feeds A producing step feeds the array, so the items' schema is refused rather than the value's shape. - workflow: &array_from_producer {steps: [{id: PRODUCER, out: [{out: {wic_anchor: produced}}]}, {id: ARRAY, in: {values: - {wic_alias: produced}}}]} - tools: [{id: PRODUCER, outputs: {out: {type: &nested {type: array, items: {type: array, items: string}}, - outputBinding: {glob: out.txt}}}}, {id: ARRAY, inputs: {values: {type: *nested, inputBinding: {position: 1}}}}] - error: {re: nested arrays are deferred} -- {id: per_item_input_binding_on_array_items, codes: [nf-s031, nf-s050], why: *producer_feeds, workflow: *array_from_producer, tools: [{id: - PRODUCER, outputs: {out: {type: {type: array, items: File}, outputBinding: {glob: '*.txt'}}}}, {id: ARRAY, inputs: - {values: {type: {type: array, items: {type: File, inputBinding: {prefix: -I}}}, inputBinding: - {position: 1}}}}], error: {re: per-item array element bindings are deferred}} -- {id: separate_false_on_an_array_binding, codes: [nf-s050], why: An array binding's separate false is deferred., tool: {id: ARRAY, - inputs: {values: {type: {type: array, items: string}, inputBinding: {position: 1, separate: false}}}}, job: {values: - [a, b]}, error: {re: 'separate: false on an array-typed inputBinding.*deferred'}} -- {id: array_value_with_a_mismatched_item_type, codes: [nf-s015], why: A value has the shape of its declared type., tool: {inputs: - {values: {type: {type: array, items: string}, inputBinding: {position: 1}}}}, job: {values: [a, 1]}, error: - {re: does not match its supported CWL type}} -- {id: a_boolean_argument_position, codes: [nf-s055], why: 'A position is an integer, and true is none, though Python reads it as 1.', - tool: {arguments: [{valueFrom: x, position: true}]}, error: {re: non-integer CWL command position}} -- {id: a_boolean_array_binding-prefix, codes: [nf-s049], why: &booleans 'cwltool renders [true, false] bound with prefix -x as -x alone, - and with no prefix as nothing.', job: &true_false {values: [true, false]}, tool: {id: ARRAY, inputs: {values: {type: - {type: array, items: boolean}, inputBinding: {position: 1, prefix: -x}}}}, error: &boolean_array {re: 'tool - ''ARRAY\.cwl: inputs\.values\.inputBinding'': a boolean array''s binding is not supported: CWL adds only its - prefix'}} -- {id: a_boolean_array_binding-no-prefix, codes: [nf-s049], why: *booleans, job: *true_false, error: {re: 'tool ''ARRAY\.cwl: - inputs\.values\.inputBinding'': a boolean array''s binding is not supported: CWL adds only its prefix'}, tool: {id: - ARRAY, inputs: {values: {type: {type: array, items: {type: boolean}}, inputBinding: {position: 1}}}}} -- {id: a_boolean_array_binding-optional, codes: [nf-s049], why: *booleans, job: *true_false, error: {re: 'tool ''ARRAY\.cwl: - inputs\.values\.inputBinding'': a boolean array''s binding is not supported: CWL adds only its prefix'}, tool: {id: - ARRAY, inputs: {values: {type: {type: array, items: ['null', boolean]}, inputBinding: {position: 1, prefix: -x}}}}} -- {id: a_boolean_array_binding-optional-shorthand, codes: [nf-s049], why: *booleans, job: *true_false, error: {re: 'tool ''ARRAY\.cwl: - inputs\.values\.inputBinding'': a boolean array''s binding is not supported: CWL adds only its prefix'}, tool: {id: - ARRAY, inputs: {values: {type: {type: array, items: 'boolean?'}, inputBinding: {position: 1, prefix: -x}}}}} -- id: shell_quote_false_without_shell_command_requirement - codes: [nf-s051] - why: &unquoted 'design §6, Commands: only a literal valueFrom, under ShellCommandRequirement, is unquoted.' - tool: {id: SHELL, outputs: &result {result: {type: File, outputBinding: {glob: out.txt}}}, arguments: [{valueFrom: - '>>', shellQuote: false}]} - out: &out [result] - error: {re: requires ShellCommandRequirement} -- {id: shell_quote_false_with_no_value_from, codes: [nf-s051], why: *unquoted, out: *out, error: {re: has no valueFrom}, tool: &shell {id: - SHELL, outputs: *result, requirements: {ShellCommandRequirement: {}}, arguments: [{shellQuote: false}]}} -- {id: shell_quote_false_with_a_prefix, codes: [nf-s051], why: *unquoted, out: *out, error: &prefixed {re: does not support a prefix}, - tool: {<<: *shell, arguments: [{valueFrom: '>>', shellQuote: false, prefix: -x}]}} -- {id: shell_quote_false_input_binding_with_no_value_from, codes: [nf-s051], why: 'shellQuote: false on a plain, no-valueFrom - inputBinding.', out: *out, error: *prefixed, job: {text: Hello}, tool: {outputs: *result, requirements: - {ShellCommandRequirement: {}}, inputs: {text: {type: string, inputBinding: {shellQuote: false, position: 1, prefix: - echo}}}}} -- {id: shell_quote_false_referencing_an_input-bare, codes: [nf-s051], out: *out, job: &hi {message: hi}, error: &references {re: - references an input}, why: &unquoting_input 'Unquoting a value derived from any input, directly or via a suffix, is - the boundary.', tool: &shell_input {<<: *shell, inputs: {message: {type: string}}, arguments: [{valueFrom: - $(inputs.message), shellQuote: false}]}} -- {id: shell_quote_false_referencing_an_input-embedded, codes: [nf-s051], why: *unquoting_input, out: *out, job: *hi, error: *references, - tool: {<<: *shell_input, arguments: [{valueFrom: prefix-$(inputs.message)-suffix, shellQuote: false}]}} -- {id: shell_quote_false_referencing_an_input-basename-suffix, codes: [nf-s046, nf-s051], why: *unquoting_input, out: *out, job: *hi, error: - *references, tool: {<<: *shell_input, arguments: [{valueFrom: $(inputs.message.basename), shellQuote: false}]}} -- {id: a_dollar_in_a_shell_quote_false_literal-variable, codes: [nf-s051], why: &expand "design §6, Commands: the task's bash -ue would - expand it, not CWL's sh -c.", out: *out, error: &dollar {re: "holds a '\\$', which the task's shell would expand"}, - tool: {<<: *shell, arguments: [{valueFrom: '[$UNSET]', shellQuote: false}]}} -- {id: a_dollar_in_a_shell_quote_false_literal-escaped_substitution, codes: [nf-s051], why: *expand, out: *out, error: *dollar, tool: {<<: - *shell, arguments: [{valueFrom: '\$(date)', shellQuote: false}]}} -- {id: value_from_aliasing_a_different_input_on_a_boolean_binding, codes: [nf-s049], job: {verbose: true, other: false}, why: Aliasing a - different input's presence onto this flag has no approved lowering., tool: {inputs: {verbose: {type: - boolean, inputBinding: {position: 1, prefix: --verbose, valueFrom: $(inputs.other)}}, other: {type: boolean}}}, - error: &boolean_value_from {re: valueFrom on a boolean inputBinding is supported only as}} -- {id: literal_value_from_on_a_boolean_binding, codes: [nf-s049], why: A literal string is not a provably-boolean valueFrom result., job: - &verbose {verbose: true}, error: *boolean_value_from, tool: {inputs: {verbose: {type: boolean, - inputBinding: {position: 1, prefix: --verbose, valueFrom: 'true'}}}}} -- {id: basename_suffixed_value_from_on_a_boolean_binding, codes: [nf-s046, nf-s049], why: 'A .basename suffix is never boolean-shaped, even on a - self-reference.', job: *verbose, error: *boolean_value_from, tool: {inputs: {verbose: {type: boolean, - inputBinding: {position: 1, prefix: --verbose, valueFrom: $(inputs.verbose.basename)}}}}} -- {id: a_boolean_valuefrom_on_an_optional_input, codes: [nf-s049], why: An optional input would render its absence., job: {b: true, s: x}, - tool: {baseCommand: echo, arguments: [], inputs: {b: {type: boolean}, s: {type: 'string?', inputBinding: - {valueFrom: $(inputs.b), prefix: --flag}}}}, error: {re: "a boolean valueFrom on optional input 's' is not - supported"}} -- {id: a_dollar_starting_a_runtime_expression, codes: [nf-s045], why: &expression 'design §6, Commands: a `$` followed by `(` or `{` - starts an expression, and only an input reference is one the target reads.', job: &x {x: v}, tool: - &args {baseCommand: echo, inputs: {x: {type: string}}, arguments: [$(runtime.cores)]}, error: &unsupported {re: - unsupported - CWL expression}} -- {id: a_dollar_starting_javascript, codes: [nf-s045], why: *expression, job: *x, error: *unsupported, tool: {<<: *args, arguments: - ['${return 1}']}} -- {id: a_dollar_starting_a_property_of_a_string, codes: [nf-s045], why: *expression, job: *x, error: *unsupported, tool: {<<: *args, - arguments: [cost $5 $(inputs.x.size)]}} -- {id: a_dollar_before_an_expression_on_self, codes: [nf-s045], why: *expression, job: *x, error: *unsupported, tool: {<<: *args, - arguments: [$$(self)]}} -- id: a_value_input_read_as_a_path - codes: [nf-s046] - why: &path_of_value 'design §6, Commands: `.path` and `.basename` read a File or Directory.' - tool: {id: BASENAME, inputs: {label: {type: string}}, outputs: {result: {type: File, outputBinding: {glob: - $(inputs.label.basename).txt}}}} - out: *out - job: {label: input} - findings: ['step ''BASENAME'': tool ''BASENAME.cwl: outputs.result.outputBinding.glob'': $(inputs.label.basename) - requires a File or Directory input, and label is declared ''string'''] -- {id: path_of_a_string, codes: [nf-s046, nf-s046], why: *path_of_value, job: {value: x}, tool: {id: SUFFIXED, stdout: $(inputs.value.path).log, - inputs: {value: {type: string, inputBinding: {prefix: -v, valueFrom: $(inputs.value.path)}}}}, findings: {contains: - ['step ''SUFFIXED'': tool ''SUFFIXED.cwl: inputs.value.inputBinding.valueFrom'': $(inputs.value.path) requires a File - or Directory input, and value is declared ''string''', 'step ''SUFFIXED'': tool ''SUFFIXED.cwl: stdout'': - $(inputs.value.path) requires a File or Directory input, and value is declared ''string''']}} -- {id: path_of_an_int, codes: [nf-s046, nf-s046], why: *path_of_value, job: {value: 1}, tool: {id: SUFFIXED, stdout: $(inputs.value.path).log, - inputs: {value: {type: int, inputBinding: {prefix: -v, valueFrom: $(inputs.value.path)}}}}, findings: {contains: - ['step ''SUFFIXED'': tool ''SUFFIXED.cwl: inputs.value.inputBinding.valueFrom'': $(inputs.value.path) requires a File - or Directory input, and value is declared ''int''', 'step ''SUFFIXED'': tool ''SUFFIXED.cwl: stdout'': - $(inputs.value.path) requires a File or Directory input, and value is declared ''int''']}} -- {id: path_of_a_float, codes: [nf-s046, nf-s046], why: *path_of_value, job: {value: 1.5}, tool: {id: SUFFIXED, stdout: $(inputs.value.path).log, - inputs: {value: {type: float, inputBinding: {prefix: -v, valueFrom: $(inputs.value.path)}}}}, findings: {contains: - ['step ''SUFFIXED'': tool ''SUFFIXED.cwl: inputs.value.inputBinding.valueFrom'': $(inputs.value.path) requires a File - or Directory input, and value is declared ''float''', 'step ''SUFFIXED'': tool ''SUFFIXED.cwl: stdout'': - $(inputs.value.path) requires a File or Directory input, and value is declared ''float''']}} -- {id: path_of_a_boolean, codes: [nf-s046, nf-s046], why: *path_of_value, job: {value: true}, tool: {id: SUFFIXED, stdout: - $(inputs.value.path).log, inputs: {value: {type: boolean, inputBinding: {prefix: -v, valueFrom: - $(inputs.value.path)}}}}, findings: {contains: ['step ''SUFFIXED'': tool ''SUFFIXED.cwl: - inputs.value.inputBinding.valueFrom'': $(inputs.value.path) requires a File or Directory input, and value is declared - ''boolean''', 'step ''SUFFIXED'': tool ''SUFFIXED.cwl: stdout'': $(inputs.value.path) requires a File or Directory - input, and value is declared ''boolean''']}} -- {id: basename_of_a_string, codes: [nf-s046, nf-s046], why: *path_of_value, job: {value: x}, tool: {id: SUFFIXED, stdout: - $(inputs.value.basename).log, inputs: {value: {type: string, inputBinding: {prefix: -v, valueFrom: - $(inputs.value.basename)}}}}, findings: {contains: ['step ''SUFFIXED'': tool ''SUFFIXED.cwl: - inputs.value.inputBinding.valueFrom'': $(inputs.value.basename) requires a File or Directory input, and value is - declared ''string''', 'step ''SUFFIXED'': tool ''SUFFIXED.cwl: stdout'': $(inputs.value.basename) requires a File or - Directory input, and value is declared ''string''']}} -- {id: basename_of_an_int, codes: [nf-s046, nf-s046], why: *path_of_value, job: {value: 1}, tool: {id: SUFFIXED, stdout: - $(inputs.value.basename).log, inputs: {value: {type: int, inputBinding: {prefix: -v, valueFrom: - $(inputs.value.basename)}}}}, findings: {contains: ['step ''SUFFIXED'': tool ''SUFFIXED.cwl: - inputs.value.inputBinding.valueFrom'': $(inputs.value.basename) requires a File or Directory input, and value is - declared ''int''', 'step ''SUFFIXED'': tool ''SUFFIXED.cwl: stdout'': $(inputs.value.basename) requires a File or - Directory input, and value is declared ''int''']}} -- {id: basename_of_a_float, codes: [nf-s046, nf-s046], why: *path_of_value, job: {value: 1.5}, tool: {id: SUFFIXED, stdout: - $(inputs.value.basename).log, inputs: {value: {type: float, inputBinding: {prefix: -v, valueFrom: - $(inputs.value.basename)}}}}, findings: {contains: ['step ''SUFFIXED'': tool ''SUFFIXED.cwl: - inputs.value.inputBinding.valueFrom'': $(inputs.value.basename) requires a File or Directory input, and value is - declared ''float''', 'step ''SUFFIXED'': tool ''SUFFIXED.cwl: stdout'': $(inputs.value.basename) requires a File or - Directory input, and value is declared ''float''']}} -- {id: basename_of_a_boolean, codes: [nf-s046, nf-s046, nf-s049], why: *path_of_value, job: {value: true}, tool: {id: SUFFIXED, stdout: - $(inputs.value.basename).log, inputs: {value: {type: boolean, inputBinding: {prefix: -v, valueFrom: - $(inputs.value.basename)}}}}, findings: {contains: ['step ''SUFFIXED'': tool ''SUFFIXED.cwl: - inputs.value.inputBinding.valueFrom'': $(inputs.value.basename) requires a File or Directory input, and value is - declared ''boolean''', 'step ''SUFFIXED'': tool ''SUFFIXED.cwl: stdout'': $(inputs.value.basename) requires a File or - Directory input, and value is declared ''boolean''']}} -- {id: a_file_reference_embedded_in_text, codes: [nf-s046], why: 'design §6, Commands: CWL renders an embedded File object as JSON.', job: - {f: {class: File, path: in.txt}, s: x}, tool: {id: EMBEDDED, inputs: {f: {type: File}, s: {type: string}}, arguments: - ['--input=$(inputs.f)']}, findings: ['step ''EMBEDDED'': tool ''EMBEDDED.cwl: arguments[0]'': $(inputs.f) embedded in - other text renders a File object as JSON in CWL; use $(inputs.f.path) or $(inputs.f.basename), or the reference - alone']} -- id: an_empty_boolean_prefix - codes: [nf-s052] - why: &lowering_only A rejection only the lowering finds is a finding at its step, beside the rest. - tool: {inputs: {b: {type: boolean, inputBinding: {prefix: ''}}}} - job: &b {b: true} - findings: &bad_prefix [{re: '^step ''make'': step: .*prefix for ''b'' must be a non-empty string'}] -- {id: a_blank_boolean_prefix, codes: [nf-s052], why: 'A blank prefix hits the named diagnostic, not the flag''s own invariant.', job: *b, - tool: {id: REJECTED, inputs: {b: {type: boolean, inputBinding: {prefix: ' '}}}}, findings: [{re: '^step - ''REJECTED'': step: .*prefix for ''b'' must be a non-empty string'}]} -- {id: separate_without_a_prefix, codes: [nf-s055], why: cwltool rejects separate without a prefix., job: {s: x}, tool: {id: REJECTED, - inputs: {s: {type: string, inputBinding: {separate: false}}}}, findings: &no_prefix [{re: '^step ''REJECTED'': step: - .*separate cannot be specified without a prefix'}]} -- {id: boolean_separate_without_a_prefix, codes: [nf-s055], why: cwltool rejects separate without a prefix., job: *b, tool: {id: REJECTED, - inputs: {b: {type: boolean, inputBinding: {separate: false}}}}, findings: [{re: '^step ''REJECTED'': step: .*separate - cannot be specified without a prefix'}]} -- {id: boolean_separate_null, codes: [nf-s055], why: &null_separate 'cwltool''s .get("separate", True) defaults only an absent key, so - separate: null rejects too.', job: *b, tool: {id: REJECTED, inputs: {b: {type: boolean, inputBinding: {separate: - null}}}}, findings: [{re: '^step ''REJECTED'': step: .*separate cannot be specified without a prefix'}]} -- {id: string_separate_null, codes: [nf-s055], why: *null_separate, job: {s: x}, findings: [{re: '^step ''REJECTED'': step: .*separate - cannot be specified without a prefix'}], tool: {id: REJECTED, inputs: {s: {type: string, inputBinding: {separate: - null}}}}} -- {id: a_value_from_on_an_array_binding, codes: [nf-s050], why: *lowering_only, job: {xs: [x]}, tool: {id: REJECTED, inputs: {xs: {type: - {type: array, items: string}, inputBinding: {valueFrom: $(inputs.xs)}}}}, findings: [{re: '^step ''REJECTED'': step: - .*valueFrom on an array-typed inputBinding'}]} -- id: lowering_rejections_aggregate_with_every_other_finding_by_step - codes: [nf-s010, wic056, nf-s036] - why: Each step's lowering rejection is a finding in step order, beside a capability finding. - workflow: {steps: [{id: GATED, in: {a: a}, when: $(inputs.a ** 2 > 1)}, {id: GATED, in: {a: a}, when: $(inputs.a + - 1)}, {id: UNSUPPORTED}], inputs: {a: int}} - tools: [&gated {id: GATED, inputs: {a: {type: int}}, baseCommand: 'true'}, *gated, {id: UNSUPPORTED, requirements: - {ToolTimeLimit: {timelimit: 60}}}] - job: {a: 1} - findings: [{startswith: 'step ''GATED@1'': when:'}, {re: '^step ''GATED@2'': when: .*must compute a boolean'}, - {startswith: 'step ''UNSUPPORTED'': tool ''UNSUPPORTED.cwl: requirements.ToolTimeLimit'':'}] -- id: a_command_error_is_reported_instead_of_a_wrong_cause_absence_finding - codes: [nf-s045] - why: The command's own error is the one finding, not an absence finding a skipped producer would cause. - workflow: {steps: [{id: PRODUCE, in: {x: x}, out: [{r: {wic_anchor: r}}], when: $(inputs.x > 1)}, {id: CONSUME, in: - {v: {wic_alias: r}}}], inputs: {x: int}} - tools: [{id: PRODUCE, inputs: {x: {type: int}}, baseCommand: echo, stdout: out.txt, outputs: {r: {type: string, - outputBinding: {glob: out.txt, loadContents: true, outputEval: '$(self[0].contents)'}}}}, {id: CONSUME, inputs: {v: - {type: 'string?'}}, arguments: [$(runtime.cores)]}] - job: {x: 2} - findings: [{startswith: 'step ''CONSUME'': step: CWL argument contains an unsupported CWL expression'}] -- {id: a_command_error_is_reported_instead_of_an_absent_optional_finding, codes: [nf-s045], why: The command's own error is the one - finding., tool: {id: ABSENT, inputs: {v: {type: 'string?', inputBinding: {}}}, arguments: [$(runtime.cores)]}, - findings: [{startswith: 'step ''ABSENT'': step: CWL argument contains an unsupported CWL expression'}]} -- id: network_access_withheld - codes: [nf-s037] - why: A Nextflow task has network access, and the pipeline cannot withhold it. - tool: {id: FETCH, requirements: {NetworkAccess: {networkAccess: false}}} - job: {} - findings: ['step ''FETCH'': tool ''FETCH.cwl: requirements.NetworkAccess.networkAccess'': only the literal true is - supported: a Nextflow task has network access, and the generated pipeline cannot withhold it'] -- id: a_docker_file - codes: [nf-s039] - why: An image is pulled, never built. - tool: {id: BUILD, requirements: {DockerRequirement: {dockerPull: alpine, dockerFile: FROM alpine}}} - job: {} - findings: ['step ''BUILD'': tool ''BUILD.cwl: requirements.DockerRequirement.dockerFile'': dockerFile is not - supported: use dockerPull'] -- id: success_codes_of_a_tool - codes: [nf-s042] - why: A nonzero exit fails a Nextflow task. - tool: {id: GREP, successCodes: [0, 1]} - job: {} - findings: ['step ''GREP'': tool ''GREP.cwl: successCodes'': successCodes is not supported: a nonzero exit fails the - task'] -- id: an_expression_tool_step - codes: [nf-s047] - why: A process runs a CommandLineTool. - workflow: {steps: [{id: DOUBLE, in: {x: x}, out: [y]}], inputs: {x: {type: int}}} - tools: [{id: DOUBLE, class: ExpressionTool, requirements: {InlineJavascriptRequirement: {}}, inputs: {x: {type: - int}}, outputs: {y: {type: int}}, expression: '$({y: inputs.x * 2})'}] - job: {x: 1} - findings: ['step ''DOUBLE'': tool ''DOUBLE.cwl: class'': unsupported compiled step class ''ExpressionTool'''] -- id: an_optional_union_of_a_boolean_and_strings - why: mm-workflows' docking tools declare this union, which the target does not lower; it is refused, not a crash. - codes: [nf-s048, nf-s048] - tool: {id: DOCK, inputs: {flag: {type: ['null', boolean, {type: array, items: string}], inputBinding: {position: - 1}}}} - job: {} - findings: ['step ''DOCK'': tool ''DOCK.cwl: inputs.flag.type'': unsupported optional CWL union [''null'', ''boolean'', - {''type'': ''array'', ''items'': ''string''}]', 'workflow ''wf'': workflow input ''flag'': type: unsupported optional - CWL union [''null'', ''boolean'', {''type'': ''array'', ''items'': ''string''}]'] -- id: requirements_written_as_a_class_name - why: A tool's requirements are a mapping or a list; a class name alone is CWL cwltool does not load. - codes: [nf-s055] - tool: {id: T, requirements: DockerRequirement, inputs: {x: {type: string, inputBinding: {position: 1}}}} - job: {x: a} - findings: ["step 'T': tool 'T.cwl: requirements': CommandLineTool requirements must be a mapping or list"] -- id: arguments_written_as_a_string - why: A tool's arguments are a list; a string is CWL cwltool does not load. - codes: [nf-s055] - tool: {id: T, arguments: echo, inputs: {x: {type: string, inputBinding: {position: 1}}}} - job: {x: a} - findings: ["step 'T': tool 'T.cwl: arguments': CommandLineTool arguments must be a list"] diff --git a/tests/core/data/nextflow/rejected/conditions.yaml b/tests/core/data/nextflow/rejected/conditions.yaml deleted file mode 100644 index 1851f9e6c..000000000 --- a/tests/core/data/nextflow/rejected/conditions.yaml +++ /dev/null @@ -1,66 +0,0 @@ -# Conditional steps the target refuses (design §6, Topology: a `when` lowers to a branch/mix skip with CWL null). Each -# `error` is the refusal the replaced test wrote by hand. -- id: when_cannot_read_a_tool_default_the_step_does_not_bind - codes: [nf-s011] - why: A `when` reads the step's own inputs, and a tool default is not one. - workflow: {steps: [{id: GATED, in: {a: a}, when: $(inputs.n > 3)}], inputs: {a: int}} - tools: [{id: GATED, inputs: {a: {type: int}, n: {type: int, default: 5}}, baseCommand: 'true'}] - job: &a1 {a: 1} - error: {re: 'reads inputs\.n, which the step does not bind'} -- id: an_array_typed_port_cannot_consume_a_conditional_scatter - codes: [nf-s013] - why: A skipped scatter position has no element for an array-typed port to gather. - workflow: {steps: [{id: PRODUCE, in: {x: xs}, out: [{r: {wic_anchor: r}}], scatter: [x], when: "$(inputs.x == 'a')"}, - {id: CONSUME, in: {rs: {wic_alias: r}}}], inputs: {xs: {type: {type: array, items: string}}}} - tools: [{id: PRODUCE, inputs: {x: {type: string}}, baseCommand: echo, stdout: out.txt, outputs: {r: {type: string, - outputBinding: &text {glob: out.txt, loadContents: true, outputEval: '$(self[0].contents)'}}}}, {id: CONSUME, - inputs: {rs: {type: {type: array, items: string}}}, baseCommand: 'true'}] - job: {xs: [a]} - error: {re: 'input ''rs'': an array-typed port cannot consume a conditional step''s output'} -- id: when_requires_a_boolean_result - codes: [wic056] - why: &when_subset A `when` is a boolean in the safe expression subset. - workflow: &when_wf {steps: [{id: PRODUCE, in: {a: a}, out: [result], when: $(inputs.a + 1)}], inputs: {a: int}, - outputs: {result: {type: 'string?', outputSource: PRODUCE/result}}} - tools: [&produce_text {id: PRODUCE, inputs: {a: {type: int}}, baseCommand: echo, arguments: [{position: 1, valueFrom: - ok}], stdout: out.txt, outputs: {result: {type: string, outputBinding: *text}}}] - job: &a3 {a: 3} - error: {re: 'must compute a boolean, not a number'} -- {id: when_outside_the_safe_subset_is_rejected_by_name, codes: [nf-s010], why: *when_subset, tools: [*produce_text], job: *a3, workflow: - {<<: *when_wf, steps: [{id: PRODUCE, in: {a: a}, out: [result], when: $(inputs.a ** 2)}]}, error: {re: "unsupported - construct '\\*\\*'"}} -- id: non_optional_consumer_of_a_conditional_output - codes: [nf-s013] - why: A skipped step's output is null, which only an optional port takes. - workflow: &consumed {steps: [{id: PRODUCE, in: {a: a}, out: [{result: {wic_anchor: result}}], when: $(inputs.a > 0)}, - {id: CONSUME, in: {result: {wic_alias: result}}, out: [done]}], inputs: {a: int}, outputs: {done: {type: File, - outputSource: CONSUME/done}}} - tools: [{id: PRODUCE, inputs: {a: {type: int}}, baseCommand: echo, outputs: {result: {type: string, outputBinding: - *text}}}, &consume {id: CONSUME, inputs: {result: {type: string}}, baseCommand: 'true', outputs: {done: {type: File, - outputBinding: {glob: done.txt}}}}] - job: *a1 - error: {re: non-optional port cannot consume a possibly-null} -- {id: path_consumer_of_a_conditional_output, codes: [nf-s013], why: 'Path channel construction always stages, so a null cannot reach - it.', workflow: *consumed, job: *a1, tools: [&produce_file {id: PRODUCE, inputs: {a: {type: int}}, baseCommand: echo, - outputs: {result: {type: File, outputBinding: {glob: out.txt}}}}, {<<: *consume, inputs: {result: {type: 'File?'}}}], - error: {re: a path consumer of a possibly-null}} -- {id: array_typed_output_of_a_conditional_step, codes: [nf-s031, nf-s013], why: An array-typed output has no null to stand for a skipped step., - job: *a1, tools: [{<<: *produce_file, outputs: {result: {type: {type: array, items: File}, outputBinding: {glob: - '*.txt'}}}}], workflow: {steps: [{id: PRODUCE, in: {a: a}, out: [result], when: $(inputs.a > 0)}], inputs: {a: int}, - outputs: {result: {type: {type: array, items: File}, outputSource: PRODUCE/result}}}, error: {re: array-typed output - of a conditional step}} -- id: a_bare_read_of_a_value_that_may_be_null - codes: [nf-s010] - why: A `when` is typed by what its input delivers; CWL fails a `when` that gives null, where Groovy would skip. - workflow: {steps: [{id: GATED, in: {a: a}, when: $(inputs.a > 1)}], inputs: {a: ['null', int]}} - tools: [{id: GATED, inputs: {a: {type: int}}, baseCommand: 'true'}] - job: {a: 2} - error: {re: 'optional inputs\.a may only be compared with null'} -- id: a_when_on_a_tool_with_no_inputs - codes: [nf-s012] - why: Nextflow decides a condition each time the step's inputs arrive, so a step with none has nothing to gate on. - workflow: {steps: [{id: TOUCH, in: {}, out: [], when: $(true)}], inputs: {}} - tools: [{id: TOUCH}] - job: {} - findings: ['step ''TOUCH'': when: process ''_TOUCH'' has a condition but no inputs: a conditional step is decided - once per invocation of its inputs, so it needs at least one input to gate on'] diff --git a/tests/core/data/nextflow/rejected/inputs.yaml b/tests/core/data/nextflow/rejected/inputs.yaml deleted file mode 100644 index 3e652c71a..000000000 --- a/tests/core/data/nextflow/rejected/inputs.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# Step and workflow inputs the target refuses (design_docs/one-target-table-design.md §5, inputs). -- id: a_join_that_gives_a_list_to_one_value - codes: [nf-s018] - why: Two sources merge into a list, which a string input does not take. - workflow: {steps: [{id: ECHO, in: {message: {wic_raw_cwl: {source: [a, b]}}}, out: []}], inputs: {a: {type: string}, - b: {type: string}}} - tools: [&echo {id: ECHO, inputs: {message: {type: string, inputBinding: {position: 1}}}}] - job: {a: x, b: y} - findings: ['step ''ECHO'': input ''message'': the step input gives a list, but its tool input declares ''string'''] -- id: a_step_input_value_from - codes: [nf-s019] - why: A step input's valueFrom is computation the target does not lower. - workflow: {steps: [{id: ECHO, in: {message: {wic_raw_cwl: {source: m, valueFrom: $(self)}}}, out: []}], inputs: {m: - {type: string}}, requirements: {StepInputExpressionRequirement: {}}} - tools: [*echo] - job: {m: x} - findings: ['step ''ECHO'': input ''message'': valueFrom: a step input''s valueFrom is not supported'] -- id: an_input_binding_on_a_workflow_input - codes: [nf-s021] - why: The steps that read a workflow input bind it. - workflow: {steps: [{id: ECHO, in: {message: m}, out: []}], inputs: {m: {type: string, inputBinding: {position: 1}}}} - tools: [*echo] - job: {m: x} - findings: ['workflow ''wf'': workflow input ''m'': inputBinding: a workflow input''s inputBinding is not supported'] diff --git a/tests/core/data/nextflow/rejected/outputs.yaml b/tests/core/data/nextflow/rejected/outputs.yaml deleted file mode 100644 index 3cd1f90d5..000000000 --- a/tests/core/data/nextflow/rejected/outputs.yaml +++ /dev/null @@ -1,258 +0,0 @@ -# Outputs the target refuses (design §6, Outputs): an outputEval is one of two capture declarations, and nothing is -# evaluated. Each `findings` or `error` is the diagnostic the replaced test wrote by hand, copied verbatim. -- id: internal_variation_of_the_admitted_literal-$( self[0] ) - codes: [nf-s033] - why: &variation Only surrounding whitespace is trimmed; any other variation is a text outside the admitted set. - tool: &make {id: make, inputs: {message: {type: string, inputBinding: {position: 1}}}, outputs: {result: {type: File, - outputBinding: {glob: out.txt, outputEval: '$( self[0] )'}}}} - out: &out [result] - job: &hi {message: hi} - findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$( self[0] )''; - the approved set is exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no - other expression is evaluated'] -- {id: 'internal_variation_of_the_admitted_literal-$(self[ 0 ])', codes: [nf-s033], why: *variation, out: *out, job: *hi, tool: {<<: - *make, outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[ 0 ])'}}}}, findings: [ - 'step ''make'': tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(self[ 0 ])''; the - approved set is exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other - expression is evaluated']} -- {id: 'internal_variation_of_the_admitted_literal-$(self[0] )', codes: [nf-s033], why: *variation, out: *out, job: *hi, tool: {<<: *make, - outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0] )'}}}}, findings: [ 'step - ''make'': tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(self[0] )''; the approved set - is exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other expression is - evaluated']} -- {id: 'internal_variation_of_the_admitted_literal-$(self [0])', codes: [nf-s033], why: *variation, out: *out, job: *hi, tool: {<<: *make, - outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self [0])'}}}}, findings: [ 'step - ''make'': tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(self [0])''; the approved set - is exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other expression is - evaluated']} -- {id: 'unadmitted_output_eval-$(self[0].size + 1)', codes: [nf-s033], why: &unadmitted 'No expression is evaluated, composed, or - partially recognized.', out: *out, job: *hi, tool: {<<: *make, outputs: {result: {type: File, outputBinding: {glob: - out.txt, outputEval: '$(self[0].size + 1)'}}}}, findings: ['step ''make'': tool ''make.cwl: - outputs.result.outputBinding'': unsupported outputEval ''$(self[0].size + 1)''; the approved set is exactly - ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other expression is evaluated']} -- {id: 'unadmitted_output_eval-$(self[0].basename.toUpperCase())', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: - *make, outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: - '$(self[0].basename.toUpperCase())'}}}}, findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding'': - unsupported outputEval ''$(self[0].basename.toUpperCase())''; the approved set is exactly ''$(self[0])'', - ''$(self[0].contents)'', recognized as capture declarations, and no other expression is evaluated']} -- {id: unadmitted_output_eval-$(self.length), codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, outputs: {result: - {type: File, outputBinding: {glob: out.txt, outputEval: $(self.length)}}}}, findings: ['step ''make'': tool - ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(self.length)''; the approved set is exactly - ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other expression is evaluated']} -- {id: 'unadmitted_output_eval-$(self[1])', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, outputs: {result: - {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[1])'}}}}, findings: ['step ''make'': tool ''make.cwl: - outputs.result.outputBinding'': unsupported outputEval ''$(self[1])''; the approved set is exactly ''$(self[0])'', - ''$(self[0].contents)'', recognized as capture declarations, and no other expression is evaluated']} -- {id: 'unadmitted_output_eval-$(self[0] ? self[0] : null)', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, - outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0] ? self[0] : null)'}}}}, - findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(self[0] ? - self[0] : null)''; the approved set is exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture - declarations, and no other expression is evaluated']} -- {id: unadmitted_output_eval-$(inputs.message), codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, outputs: { - result: {type: File, outputBinding: {glob: out.txt, outputEval: $(inputs.message)}}}}, findings: ['step ''make'': - tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(inputs.message)''; the approved set is - exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other expression is - evaluated']} -- {id: 'unadmitted_output_eval-${return self[0];}', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, outputs: { - result: {type: File, outputBinding: {glob: out.txt, outputEval: '${return self[0];}'}}}}, findings: ['step ''make'': - tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''${return self[0];}''; the approved set is - exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other expression is - evaluated']} -- {id: 'unadmitted_output_eval-${ return self[0].contents.trim(); }', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: - *make, outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: '${ return self[0].contents.trim(); - }'}}}}, findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''${ - return self[0].contents.trim(); }''; the approved set is exactly ''$(self[0])'', ''$(self[0].contents)'', recognized - as capture declarations, and no other expression is evaluated']} -- {id: "unadmitted_output_eval-$(self[0].contents.split('\\n'))", codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: - *make, outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: - "$(self[0].contents.split('\\n'))"}}}}, findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding'': - unsupported outputEval "$(self[0].contents.split(''\\n''))"; the approved set is exactly ''$(self[0])'', - ''$(self[0].contents)'', recognized as capture declarations, and no other expression is evaluated']} -- {id: 'unadmitted_output_eval-$(self[0] .contents)', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, outputs: - { result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0] .contents)'}}}}, findings: ['step - ''make'': tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(self[0] .contents)''; the - approved set is exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other - expression is evaluated']} -- {id: 'unadmitted_output_eval-$(self[0].contents())', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, outputs: - { result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0].contents())'}}}}, findings: ['step - ''make'': tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(self[0].contents())''; the - approved set is exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other - expression is evaluated']} -- {id: 'unadmitted_output_eval-prefix-$(self[0])', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, outputs: { - result: {type: File, outputBinding: {glob: out.txt, outputEval: 'prefix-$(self[0])'}}}}, findings: ['step ''make'': - tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''prefix-$(self[0])''; the approved set is - exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other expression is - evaluated']} -- {id: 'unadmitted_output_eval-$(self[0])$(self[0])', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, outputs: - { result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0])$(self[0])'}}}}, findings: ['step - ''make'': tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(self[0])$(self[0])''; the - approved set is exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other - expression is evaluated']} -- {id: 'unadmitted_output_eval-$(JSON.parse(self[0].contents))', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: - *make, outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: - '$(JSON.parse(self[0].contents))'}}}}, findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding'': - unsupported outputEval ''$(JSON.parse(self[0].contents))''; the approved set is exactly ''$(self[0])'', - ''$(self[0].contents)'', recognized as capture declarations, and no other expression is evaluated']} -- {id: 'unadmitted_output_eval-$(parseInt(self[0].contents))', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, - outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(parseInt(self[0].contents))'}}}}, - findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval - ''$(parseInt(self[0].contents))''; the approved set is exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as - capture declarations, and no other expression is evaluated']} -- {id: 'unadmitted_output_eval-$(self[0].nameroot)', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, outputs: { - result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0].nameroot)'}}}}, findings: ['step ''make'': - tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(self[0].nameroot)''; the approved set is - exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other expression is - evaluated']} -- {id: 'unadmitted_output_eval-$(self[0].nameext)', codes: [nf-s033], why: *unadmitted, out: *out, job: *hi, tool: {<<: *make, outputs: { - result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0].nameext)'}}}}, findings: ['step ''make'': - tool ''make.cwl: outputs.result.outputBinding'': unsupported outputEval ''$(self[0].nameext)''; the approved set is - exactly ''$(self[0])'', ''$(self[0].contents)'', recognized as capture declarations, and no other expression is - evaluated']} -- {id: 'named_projection-$(self[0].dirname)', codes: [nf-s033], why: &projection A named projection is refused explaining itself., out: - *out, job: *hi, tool: {<<: *make, outputs: {result: {type: File, outputBinding: {glob: out.txt, outputEval: - '$(self[0].dirname)'}}}}, findings: [{re: '^step ''make'': tool ''make\.cwl: outputs\.result\.outputBinding'': - outputEval ''\$\(self\[0\]\.dirname\)'' is not representable: .*is the Nextflow task work directory'}]} -- {id: 'named_projection-$(self[0].path)', codes: [nf-s033], why: *projection, out: *out, job: *hi, tool: {<<: *make, outputs: {result: { - type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0].path)'}}}}, findings: [{re: '^step ''make'': tool - ''make\.cwl: outputs\.result\.outputBinding'': outputEval ''\$\(self\[0\]\.path\)'' is not representable: .*is the - Nextflow task work directory'}]} -- {id: 'named_projection-$(self[0].location)', codes: [nf-s033], why: *projection, out: *out, job: *hi, tool: {<<: *make, outputs: - {result: { type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0].location)'}}}}, findings: [{re: '^step - ''make'': tool ''make\.cwl: outputs\.result\.outputBinding'': outputEval ''\$\(self\[0\]\.location\)'' is not - representable: .*a CWL location is a URI'}]} -- {id: 'named_projection-$(self[0].checksum)', codes: [nf-s033], why: *projection, out: *out, job: *hi, tool: {<<: *make, outputs: - {result: { type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0].checksum)'}}}}, findings: [{re: '^step - ''make'': tool ''make\.cwl: outputs\.result\.outputBinding'': outputEval ''\$\(self\[0\]\.checksum\)'' is not - representable: .*computing a checksum is computation'}]} -- {id: 'named_projection-$(self[0].secondaryFiles)', codes: [nf-s033], why: *projection, out: *out, job: *hi, tool: {<<: *make, outputs: { - result: {type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0].secondaryFiles)'}}}}, findings: [{re: - '^step ''make'': tool ''make\.cwl: outputs\.result\.outputBinding'': outputEval ''\$\(self\[0\]\.secondaryFiles\)'' - is not representable: .*secondary files have no approved lowering'}]} -- {id: 'named_projection-$(self[0].format)', codes: [nf-s033], why: *projection, out: *out, job: *hi, tool: {<<: *make, outputs: {result: - { type: File, outputBinding: {glob: out.txt, outputEval: '$(self[0].format)'}}}}, findings: [{re: '^step ''make'': - tool ''make\.cwl: outputs\.result\.outputBinding'': outputEval ''\$\(self\[0\]\.format\)'' is not representable: - .*output format annotations have no approved lowering'}]} -- {id: a_wildcard_glob_beside_a_cardinality_declaration-*.txt, codes: [nf-s034], why: &first_match 'Projecting the first match is provable - only when one match exists.', out: *out, job: *hi, tool: {<<: *make, outputs: {result: {type: File, outputBinding: { - glob: '*.txt', outputEval: '$(self[0])'}}}}, findings: &wildcard_capture [{re: '^step ''make'': tool ''make\.cwl: - outputs\.result\.outputBinding'': outputEval(?=.*requires a glob with no wildcard character)(?=.*glob match ordering - load-bearing, which is unproven)'}]} -- {id: 'a_wildcard_glob_beside_a_cardinality_declaration-out?.txt', codes: [nf-s034], why: *first_match, out: *out, job: *hi, tool: {<<: - *make, outputs: {result: {type: File, outputBinding: {glob: 'out?.txt', outputEval: '$(self[0])'}}}}, findings: [{re: - '^step ''make'': tool ''make\.cwl: outputs\.result\.outputBinding'': outputEval(?=.*requires a glob with no wildcard - character)(?=.*glob match ordering load-bearing, which is unproven)'}]} -- {id: 'a_wildcard_glob_beside_a_cardinality_declaration-out[0-9].txt', codes: [nf-s034], why: *first_match, out: *out, job: *hi, tool: { - <<: *make, outputs: {result: {type: File, outputBinding: {glob: 'out[0-9].txt', outputEval: '$(self[0])'}}}}, - findings: [{re: '^step ''make'': tool ''make\.cwl: outputs\.result\.outputBinding'': outputEval(?=.*requires a glob - with no wildcard character)(?=.*glob match ordering load-bearing, which is unproven)'}]} -- {id: an_input_reference_glob_beside_a_cardinality_declaration, codes: [nf-s034], why: "A reference's runtime value cannot be shown - wildcard-free at compile time.", out: *out, job: *hi, tool: {<<: *make, outputs: {result: {type: File, outputBinding: - {glob: $(inputs.message), outputEval: '$(self[0])'}}}}, findings: ['step ''make'': tool ''make.cwl: - outputs.result.outputBinding'': outputEval ''$(self[0])'' requires a glob with no input reference; a reference''s - runtime value cannot be shown wildcard-free at compile time']} -- {id: load_contents_without_its_paired_output_eval, codes: [nf-s034], why: &paired loadContents and the text capture are one - declaration., out: *out, job: *hi, tool: {<<: *make, outputs: {result: {type: File, outputBinding: {glob: out.txt, - loadContents: true}}}}, findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding'': loadContents on - output ''result'' has no approved lowering without its paired outputEval capture declaration']} -- {id: the_cardinality_declaration_is_not_paired_with_load_contents, codes: [nf-s034], why: *paired, out: *out, job: *hi, tool: {<<: - *make, outputs: {result: {type: File, outputBinding: {glob: out.txt, loadContents: true, outputEval: - '$(self[0])'}}}}, findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding'': outputEval - ''$(self[0])'' declares output cardinality and is not paired with loadContents']} -- {id: file_text_capture_requires_load_contents_true-absent, codes: [nf-s034], why: *paired, out: *out, job: *hi, tool: {<<: *make, - outputs: {result: {type: string, outputBinding: {glob: out.txt, outputEval: '$(self[0].contents)'}}}}, findings: - &needs_load_contents ['step ''make'': tool ''make.cwl: outputs.result.outputBinding'': outputEval - ''$(self[0].contents)'' captures file text and requires loadContents: true beside it']} -- {id: file_text_capture_requires_load_contents_true-false, codes: [nf-s034], why: *paired, out: *out, job: *hi, tool: {<<: *make, - outputs: {result: {type: string, outputBinding: {glob: out.txt, loadContents: false, outputEval: - '$(self[0].contents)'}}}}, findings: *needs_load_contents} -- {id: file_text_capture_requires_load_contents_true-text, codes: [nf-s034], why: *paired, out: *out, job: *hi, tool: {<<: *make, outputs: - {result: {type: string, outputBinding: {glob: out.txt, loadContents: 'true', outputEval: '$(self[0].contents)'}}}}, - findings: *needs_load_contents} -- {id: a_numeric_file_text_capture-int, codes: [nf-s034], why: &parse Parsing text into a number is computation., out: *out, job: *hi, - tool: {<<: *make, outputs: {result: {type: int, outputBinding: &text_capture {glob: out.txt, loadContents: true, - outputEval: '$(self[0].contents)'}}}}, findings: &numeric [{re: '^step ''make'': tool ''make\.cwl: - outputs\.result\.outputBinding'': outputEval(?=.*parsing that text into a number is computation rather than a - projection)(?=.*Declare type: string and parse downstream)'}]} -- {id: a_numeric_file_text_capture-float, codes: [nf-s034], why: *parse, out: *out, job: *hi, findings: [{re: '^step ''make'': tool - ''make\.cwl: outputs\.result\.outputBinding'': outputEval(?=.*parsing that text into a number is computation rather - than a projection)(?=.*Declare type: string and parse downstream)'}], tool: {<<: *make, outputs: {result: {type: - float, outputBinding: *text_capture}}}} -- {id: file_text_capture_on_a_non_string_non_numeric_output, codes: [nf-s034], why: Text is captured only as a string., out: *out, job: - *hi, tool: {<<: *make, outputs: {result: {type: File, outputBinding: *text_capture}}}, findings: ['step ''make'': - tool ''make.cwl: outputs.result.outputBinding'': outputEval ''$(self[0].contents)'' captures file text and is - admitted only on a type: string output; output ''result'' declares ''File''']} -- {id: a_wildcard_glob_beside_a_file_text_capture-*.txt, codes: [nf-s034], why: *first_match, out: *out, job: *hi, tool: {<<: *make, - outputs: {result: {type: string, outputBinding: {<<: *text_capture, glob: '*.txt'}}}}, findings: &wildcard_text [{re: - requires a glob with no wildcard character}]} -- {id: 'a_wildcard_glob_beside_a_file_text_capture-out?.txt', codes: [nf-s034], why: *first_match, out: *out, job: *hi, findings: - *wildcard_text, tool: {<<: *make, outputs: {result: {type: string, outputBinding: {<<: *text_capture, glob: - 'out?.txt'}}}}} -- {id: 'a_wildcard_glob_beside_a_file_text_capture-out[0-9].txt', codes: [nf-s034], why: *first_match, out: *out, job: *hi, findings: - *wildcard_text, tool: {<<: *make, outputs: {result: {type: string, outputBinding: {<<: *text_capture, glob: - 'out[0-9].txt'}}}}} -- id: a_captured_value_cannot_feed_another_process - codes: [nf-s029] - why: No qualifier agreement check exists for process edges, so this rejects. - workflow: {steps: [{id: produce, in: {message: message}, out: [{text: {wic_anchor: text}}]}, {id: consume, in: {text: - {wic_alias: text}}, out: [result]}], inputs: {message: string}, outputs: {result: {type: File, outputSource: - consume/result}}} - tools: [{id: produce, inputs: {message: {type: string, inputBinding: {position: 1}}}, outputs: {text: {type: string, - outputBinding: *text_capture}}}, {id: consume, inputs: {text: {type: string, inputBinding: {position: 1}}}, outputs: - {result: {type: File, outputBinding: {glob: copy.txt}}}}] - job: *hi - findings: ['step ''consume'': input ''text'': ''produce/text'' captures file text; its only approved sink is a - workflow output, because the executable graph has no qualifier agreement check for process edges'] -- {id: an_optional_output_with_a_pattern_glob_must_reach_a_workflow_output, codes: [nf-s030], why: 'An optional output of a pattern glob - is checked at its workflow output, so it must reach one.', workflow: {steps: [{id: LOGS, out: [o]}]}, tools: [{id: - LOGS, baseCommand: 'true', outputs: {o: {type: 'File?', outputBinding: {glob: '*.log'}}}}], error: {re: optional - outputs o must match at most one file and must reach a workflow}} -- {id: a_step_consuming_an_optional_output_is_a_finding, codes: [nf-s030], why: An optional output may be null; only a workflow output - takes it., workflow: {steps: [{id: MAYBE, out: [{o: {wic_anchor: o}}]}, {id: CONSUME, in: {source: {wic_alias: - o}}}]}, tools: [{id: MAYBE, outputs: {o: {type: 'File?', outputBinding: {glob: maybe.txt}}}}, {id: CONSUME, inputs: - {source: {type: 'File?', inputBinding: {position: 1}}}}], findings: ['workflow ''wf'': workflow: connection _MAYBE.o - -> _CONSUME.source consumes an optional output, which may be null; only a workflow output can take it']} -- {id: array_typed_outputs, codes: [nf-s031], why: An output is collected by glob as one File or Directory., workflow: {steps: [{id: MAKE, - out: [results]}]}, tools: [{id: MAKE, outputs: {results: {type: {type: array, items: File}, outputBinding: {glob: - '*.txt'}}}}], error: {re: 'outputs\.results\.type'': an output is collected by glob as a File or Directory'}} -- {id: an_array_typed_text_capture, codes: [nf-s034], why: A text capture gives one string; an array-typed output is not one string., - tool: {id: CAPTURE, outputs: {names: {type: {type: array, items: string}, outputBinding: {glob: out.txt, - loadContents: true, outputEval: '$(self[0].contents)'}}}}, out: [names], findings: ['step ''CAPTURE'': tool - ''CAPTURE.cwl: outputs.names.outputBinding'': outputEval ''$(self[0].contents)'' captures file text and is admitted - only on a type: string output; output ''names'' declares {''type'': ''array'', ''items'': ''string''}']} -- id: a_workflow_output_with_no_output_source - why: A workflow output names the step output it comes from. - codes: [nf-s026] - workflow: {steps: [{id: TOUCH, out: [o]}], outputs: {o: {type: File}}} - tools: [{id: TOUCH, outputs: {o: {type: File, outputBinding: {glob: o.txt}}}}] - job: {} - findings: ['workflow ''wf'': workflow: workflow output ''o'' must define outputSource'] -- id: a_nested_workflow_output_named_as_text - why: CWL reads `inner/made` as the call's output (tests/core/data/python_api_pairs/re_export.wic); Sophios keeps the - text as written, and the target follows only the outputs it resolves. - codes: [nf-s027] - workflow: - steps: - - {id: inner.wic, subtree: {steps: [{id: TOUCH, in: {filename: {wic_inline_input: empty.txt}}}], outputs: {made: - {type: File, outputSource: TOUCH/file}}}} - outputs: {made: {type: File, outputSource: inner/made}} - tools: [{id: TOUCH, inputs: {filename: {type: string, inputBinding: {position: 1}}}, outputs: {file: {type: File, - outputBinding: {glob: $(inputs.filename)}}}}] - job: {} - findings: ['workflow ''wf'': workflow: connection references unknown source process ''inner'''] -- id: a_glob_reading_an_array_input - why: An array input is read only by its own array binding; in a glob it would render as a list. - codes: [nf-s050] - tool: {id: T, inputs: {xs: {type: 'string[]', inputBinding: {position: 1}}}, outputs: {o: {type: File, - outputBinding: {glob: $(inputs.xs).txt}}}} - out: [o] - job: {xs: [a]} - findings: ["step 'T': step: process '_T' array-marked inputs may only be referenced by array bindings: xs"] -- id: an_output_source_naming_a_port_the_step_lacks - why: An outputSource names a port of its step; this one is no output of T. - codes: [nf-s028] - workflow: {steps: [{id: T, in: {x: a}, out: [o]}], inputs: {a: {type: string}}, outputs: {r: {type: File, - outputSource: T/nope}}} - tools: [{id: T, inputs: {x: {type: string, inputBinding: {position: 1}}}, outputs: {o: {type: File, outputBinding: - {glob: out}}}}] - job: {a: x} - findings: ["workflow 'wf': workflow: connection references unknown output port _T.nope"] diff --git a/tests/core/data/nextflow/rejected/scatter.yaml b/tests/core/data/nextflow/rejected/scatter.yaml deleted file mode 100644 index d064da0d4..000000000 --- a/tests/core/data/nextflow/rejected/scatter.yaml +++ /dev/null @@ -1,106 +0,0 @@ -# Scattered steps the target refuses (design §6, Topology). Each `findings` or `error` is the diagnostic the -# replaced test wrote by hand from that rule, copied verbatim; nothing here was read off a run. -- id: multi_input_scatter_without_a_scatter_method - codes: [nf-s055] - why: A multi-input scatter has no method to default to. - workflow: {steps: [{id: SCATTER, in: {first: firsts, second: seconds}, out: [result], scatter: [first, second]}], - inputs: {firsts: {type: &strings {type: array, items: string}}, seconds: {type: *strings}}} - tools: [{id: SCATTER, inputs: {first: {type: string, inputBinding: {position: 1}}, second: {type: string, - inputBinding: {position: 2}}}, outputs: &result {result: {type: File, outputBinding: {glob: out.txt}}}}] - job: {firsts: [a], seconds: [b]} - findings: ['step ''SCATTER'': scatter: multi-input scatter over 2 inputs requires an explicit scatterMethod'] -- {id: an_unsupported_scatter_method, codes: [nf-s055], why: The methods are CWL's three., tools: [&scatter {id: SCATTER, inputs: {item: - {type: string, inputBinding: {position: 1}}}, outputs: *result}], job: &ab {items: [a, b]}, workflow: {steps: [{<<: - &step {id: SCATTER, in: {item: items}, out: [result], scatter: [item]}, scatterMethod: product}], inputs: &items - {items: {type: *strings}}}, findings: ['step ''SCATTER'': scatter: unsupported CWL scatter method ''product''']} -- id: a_scatter_field_that_names_no_input - codes: [nf-s055] - why: A scatter names one input or more. - workflow: {steps: [{<<: *step, scatter: []}], inputs: {items: {type: string}}} - tools: [*scatter] - job: {items: a} - findings: ['step ''SCATTER'': scatter: scatter must name one input, as a string or a non-empty list'] -- id: scatter_over_a_non_array_workflow_input - codes: [nf-s048, nf-s006] - why: A scattered input's source is an array. - workflow: {steps: [*step], inputs: {items: {type: Any}}} - tools: [*scatter] - job: *ab - findings: ['workflow ''wf'': workflow input ''items'': type: unsupported CWL type for the Nextflow target: ''Any''', - 'step ''SCATTER'': input ''item'': a scattered input needs an array-typed source; ''items'' declares ''Any'''] -- id: scatter_over_an_unscattered_steps_output - codes: [nf-s031, nf-s006] - why: An unscattered step's output reaches a scattered step as one value, an array-typed one included. - workflow: {steps: [{id: PRODUCER, out: [{out: {wic_anchor: produced}}]}, {<<: *step, in: {item: {wic_alias: - produced}}}]} - tools: [{id: PRODUCER, outputs: {out: {type: {type: array, items: File}, outputBinding: {glob: '*.txt'}}}}, {<<: - *scatter, inputs: {item: {type: File, inputBinding: {position: 1}}}}] - findings: ['step ''PRODUCER'': tool ''PRODUCER.cwl: outputs.out.type'': an output is collected by glob as a File or - Directory, or captured as text with loadContents and outputEval', 'step ''SCATTER'': input ''item'': a scattered - input needs an array-typed source; ''PRODUCER/out'', from a step that is not scattered, is one value'] -- id: scatter_over_an_array_typed_port - codes: [nf-s048, nf-s004] - why: Scattering over an array of arrays is deferred. - workflow: {steps: [*step], inputs: {items: {type: {type: array, items: *strings}}}} - tools: [{<<: *scatter, inputs: {item: {type: *strings, inputBinding: {position: 1}}}}] - job: {items: [[a], [b]]} - findings: ['workflow ''wf'': workflow input ''items'': type: nested arrays are deferred beyond this lowering', 'step - ''SCATTER'': scatter: scattered input ''item'' is array-typed; scattering over an array of arrays is deferred beyond - this lowering'] -- id: workflow_requirement_with_an_unconsumed_field - codes: [nf-s054] - why: &workflow_requirements A workflow-level requirement is consumed, or refused naming itself. - workflow: {<<: &scatter_items {steps: [*step], inputs: *items}, requirements: {ScatterFeatureRequirement: {method: - dotproduct}}} - tools: [*scatter] - job: *ab - findings: ['workflow ''wf'': requirement ''ScatterFeatureRequirement'': method is not consumed by the Nextflow - lowering'] -- {id: workflow_requirement_of_an_unsupported_class, codes: [nf-s036], why: 'A workflow-level requirement a tool cannot have is refused at - each tool step that inherits it (resolved-view design §8).', tools: [*scatter], job: *ab, workflow: {<<: *scatter_items, - requirements: {SoftwareRequirement: {}}}, findings: ['step ''SCATTER'': requirement ''SoftwareRequirement'': - SoftwareRequirement is not supported: use DockerRequirement']} -- {id: workflow_requirements_of_the_wrong_shape, codes: [nf-s055], why: *workflow_requirements, tools: [*scatter], job: *ab, workflow: - {<<: *scatter_items, requirements: ScatterFeatureRequirement}, findings: ['workflow ''wf'': requirement: CWL Workflow - requirements must be a mapping or list']} -- id: a_scatter_over_a_step_only_input - codes: [nf-s005] - why: No process port receives the element of an input the step's tool does not declare. - workflow: {steps: [{id: ECHO, in: {message: m, enabled: {wic_raw_cwl: {source: flags}}}, out: [], scatter: - [enabled]}], inputs: {m: {type: string}, flags: {type: {type: array, items: boolean}}}} - tools: [{id: ECHO, inputs: {message: {type: string, inputBinding: {position: 1}}}}] - job: {m: hi, flags: [true]} - findings: ['step ''ECHO'': input ''enabled'': scatter over an input the step''s tool does not declare is not - supported'] -- id: a_scattered_input_with_two_sources - codes: [nf-s006] - why: A scattered input that joins two sources is refused once, for the one reason. - workflow: {steps: [{id: ECHO, in: {message: {wic_raw_cwl: {source: [a, b], linkMerge: merge_flattened}}}, out: [], - scatter: [message]}], inputs: {a: {type: *strings}, b: {type: *strings}}} - tools: [{id: ECHO, inputs: {message: {type: string, inputBinding: {position: 1}}}}] - job: {a: [x], b: [y]} - findings: ['step ''ECHO'': input ''message'': a scattered input takes its one source as it is'] -- id: a_nested_crossproduct_result_read_by_a_later_step - codes: [nf-s048, nf-s007] - why: A nested_crossproduct result reaches workflow outputs only. - workflow: - steps: - - {id: PAIR, in: {a: as, b: bs}, out: [{out: {wic_anchor: pairs}}], scatter: [a, b], scatterMethod: - nested_crossproduct} - - {id: SHOW, in: {texts: {wic_alias: pairs}}, out: []} - inputs: {as: {type: *strings}, bs: {type: *strings}} - tools: - - {id: PAIR, inputs: {a: {type: string, inputBinding: {position: 1}}, b: {type: string, inputBinding: {position: - 2}}}, stdout: out.txt, outputs: {out: {type: File, outputBinding: {glob: out.txt}}}} - - {id: SHOW, inputs: {texts: {type: {type: array, items: {type: array, items: File}}, inputBinding: {position: 1}}}} - job: {as: [a], bs: [b]} - findings: ['step ''SHOW'': step: nested arrays are deferred beyond this lowering', 'step ''SHOW'': input ''texts'': - ''PAIR/out'' is a nested_crossproduct result, which reaches workflow outputs only'] - -- id: a_scatter_method_with_no_scatter - why: cwltool reads a scatterMethod only beside a scatter; the target refuses one alone. - codes: [nf-s008] - workflow: {steps: [{id: ECHO, in: {message: m}, out: [], scatterMethod: dotproduct}], inputs: {m: {type: string}}} - tools: [{id: ECHO, inputs: {message: {type: string, inputBinding: {position: 1}}}}] - job: {m: hi} - findings: ['step ''ECHO'': scatter: scatterMethod without scatter is not executable'] diff --git a/tests/core/data/nextflow/rejected/staging.yaml b/tests/core/data/nextflow/rejected/staging.yaml deleted file mode 100644 index 5493585f4..000000000 --- a/tests/core/data/nextflow/rejected/staging.yaml +++ /dev/null @@ -1,283 +0,0 @@ -# Staged inputs, InitialWorkDirRequirement entries and the references to them the target refuses (design §6, Inputs -# and channels, Basename references). Each `findings` or `error` is the diagnostic the replaced test wrote by hand. -- id: iwdr_writable_that_is_not_a_literal_boolean-true - codes: [nf-s043] - why: &literal_writable Whether an entry is a copy is known before the task runs. - tool: &stage {id: STAGE, inputs: {source: {type: File}}, outputs: &result {result: {type: File, outputBinding: {glob: - out.txt}}}, arguments: [cat, renamed.txt], stdout: out.txt, requirements: {InitialWorkDirRequirement: {listing: - [{entry: $(inputs.source), writable: 'true'}]}}} - out: &out [result] - job: &in_txt {source: {class: File, path: in.txt}} - findings: ¬_literal ['step ''STAGE'': tool ''STAGE.cwl: requirements.InitialWorkDirRequirement.listing[0]'': - writable must be a literal boolean'] -- {id: iwdr_writable_that_is_not_a_literal_boolean-1, codes: [nf-s043], why: *literal_writable, out: *out, job: *in_txt, findings: - *not_literal, tool: {<<: *stage, requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), - writable: 1}]}}}} -- {id: iwdr_writable_that_is_not_a_literal_boolean-$(inputs.flag), codes: [nf-s043], why: *literal_writable, out: *out, job: *in_txt, - findings: *not_literal, tool: {<<: *stage, requirements: {InitialWorkDirRequirement: {listing: [{entry: - $(inputs.source), writable: $(inputs.flag)}]}}}} -- {id: iwdr_entryname_under_the_reserved_prefix, codes: [nf-s043], why: &entry_rules 'An entry is one input, staged under its own basename - or one literal name the task makes.', out: *out, job: *in_txt, tool: {<<: *stage, requirements: { - InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), entryname: .sophios_entry_source}]}}}, error: {re: - 'listing\[0\]'': entryname must not begin with ''.sophios_entry_'''}} -- {id: iwdr_inline_content_entry, codes: [nf-s043], why: *entry_rules, out: *out, job: *in_txt, tool: {<<: *stage, requirements: { - InitialWorkDirRequirement: {listing: [{entry: literal file content, entryname: x.txt}]}}}, error: {re: inline content - construction is deferred}} -- {id: iwdr_computed_entryname, codes: [nf-s043], why: *entry_rules, out: *out, job: *in_txt, tool: {<<: *stage, requirements: { - InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), entryname: $(inputs.source.path)}]}}}, error: {re: - computed or differently-referencing entryname}} -- {id: iwdr_entryname_with_path_separator, codes: [nf-s043], why: *entry_rules, out: *out, job: *in_txt, tool: {<<: *stage, requirements: - {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), entryname: sub/dir.txt}]}}}, error: {re: path - separator}} -- {id: iwdr_undeclared_input, codes: [nf-s043], why: *entry_rules, out: *out, job: *in_txt, error: {re: undeclared input}, tool: {<<: - *stage, requirements: {InitialWorkDirRequirement: {listing: [$(inputs.nope)]}}}} -- {id: iwdr_val_typed_target, codes: [nf-s043, nf-s014, wic012], why: *entry_rules, job: *in_txt, error: {re: non-path input}, workflow: &stage_wf {steps: - [{id: STAGE, in: {source: source}, out: [result]}], inputs: {source: {type: File}}, outputs: {result: {type: File, - outputSource: STAGE/result}}}, tools: [{<<: *stage, inputs: {source: {type: File}, name: {type: string}}, - requirements: {InitialWorkDirRequirement: {listing: [$(inputs.name)]}}}]} -- {id: iwdr_array_typed_target, codes: [nf-s043, nf-s014, wic012], why: *entry_rules, job: *in_txt, error: {re: array-typed input}, workflow: *stage_wf, - tools: [{<<: *stage, inputs: {source: {type: File}, files: {type: {type: array, items: File}}}, requirements: { - InitialWorkDirRequirement: {listing: [$(inputs.files)]}}}]} -- {id: iwdr_unsupported_dirent_field, codes: [nf-s054], why: *entry_rules, out: *out, job: *in_txt, tool: {<<: *stage, requirements: { - InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), entryname: x.txt, foo: 1}]}}}, error: {re: - 'listing\[0\]\.foo'': foo is not consumed'}} -- {id: iwdr_listing_entry_of_unsupported_shape, codes: [nf-s043], why: *entry_rules, out: *out, job: *in_txt, error: {re: 'bare .* - reference or a Dirent mapping'}, tool: {<<: *stage, requirements: {InitialWorkDirRequirement: {listing: [123]}}}} -- {id: iwdr_listing_that_is_not_a_list, codes: [nf-s043], why: *entry_rules, error: {re: listing must be a list}, workflow: {steps: [{id: - STAGE, out: [result]}]}, tools: [{id: STAGE, outputs: *result, requirements: {InitialWorkDirRequirement: {listing: - not-a-list}}}]} -- {id: iwdr_renamed_input_referenced_elsewhere, codes: [nf-s044], why: *entry_rules, out: *out, job: *in_txt, tool: {<<: *stage, - arguments: [cat, $(inputs.source)], requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), - entryname: renamed.txt}]}}}, error: {re: has an InitialWorkDirRequirement entry with a literal name}} -- {id: iwdr_listing_that_repeats_an_input-two-dirents, codes: [nf-s044], why: *entry_rules, out: *out, job: *in_txt, tool: {<<: *stage, - requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.source), entryname: one.txt}, {entry: - $(inputs.source), entryname: two.txt}]}}}, error: &repeated {re: input 'source' appears more than once}} -- {id: iwdr_listing_that_repeats_an_input-bare-and-dirent, codes: [nf-s044], why: *entry_rules, out: *out, job: *in_txt, error: *repeated, - tool: {<<: *stage, requirements: {InitialWorkDirRequirement: {listing: [$(inputs.source), {entry: $(inputs.source), - entryname: renamed.txt}]}}}} -- {id: iwdr_collision_same_literal_name, codes: [nf-s044], why: *entry_rules, out: *out, job: {a: {class: File, path: a.txt}, b: {class: - File, path: b.txt}}, tool: {id: STAGE, inputs: {a: {type: File}, b: {type: File}}, outputs: *result, arguments: [cat, - same.txt], stdout: out.txt, requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.a), entryname: - same.txt}, {entry: $(inputs.b), entryname: same.txt}]}}}, error: {re: staged under the same literal name}} -- id: a_glob_at_a_staged_input-$(inputs.source.basename) - codes: [nf-s035] - why: &staged_glob The task directory holds the staged input under that name, which a CWL glob does not match, and a - name inside a staged Directory is inside the input. - tool: © {id: copy, inputs: {source: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: - $(inputs.source.basename)}}}} - out: *out - job: *in_txt - findings: &globs_staged ['step ''copy'': step: process ''copy'' output ''result'' globs the staged input ''source'', - or a name inside it, which a CWL glob does not match: derive a new name from it, or make the input an - InitialWorkDirRequirement entry'] -- {id: a_glob_at_a_staged_input-padded, codes: [nf-s035], why: *staged_glob, out: *out, job: *in_txt, findings: *globs_staged, tool: {<<: - *copy, outputs: {result: {type: File, outputBinding: {glob: ' $(inputs.source.basename) '}}}}} -- {id: a_glob_at_a_staged_input-./$(inputs.source.basename), codes: [nf-s035], why: *staged_glob, out: *out, job: *in_txt, findings: - *globs_staged, tool: {<<: *copy, outputs: {result: {type: File, outputBinding: {glob: - ./$(inputs.source.basename)}}}}} -- {id: a_glob_at_a_staged_input-$(inputs.source.basename)/keep.txt, codes: [nf-s035], why: *staged_glob, out: *out, findings: - *globs_staged, job: &in_dir {source: {class: Directory, path: in.txt}}, tool: {<<: *copy, inputs: {source: {type: - Directory}}, outputs: {result: {type: File, outputBinding: {glob: $(inputs.source.basename)/keep.txt}}}}} -- id: a_stdout_at_a_staged_input-File-$(inputs.source.basename)-staged - codes: [nf-s035] - why: &writes_through Writing the link the task stages an input under writes through it into the input; cwltool writes - a new file in its output directory, and links an entry too, so both overwrite it. - tool: &write {id: write, inputs: {source: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: - done.txt}}}, stdout: $(inputs.source.basename)} - out: *out - job: *in_txt - findings: &stdout_through ['step ''write'': step: process ''write'' stdout writes through the link input ''source'' is - staged under, into what the input names: derive a new name from it, or make the input a writable - InitialWorkDirRequirement entry'] -- {id: a_stdout_at_a_staged_input-Directory-$(inputs.source.basename)/keep.txt-staged, codes: [nf-s035], why: *writes_through, out: *out, - job: *in_dir, findings: *stdout_through, tool: {<<: *write, inputs: {source: {type: Directory}}, stdout: - $(inputs.source.basename)/keep.txt}} -- {id: a_stdout_at_a_staged_input-File-$(inputs.source.basename)-entry, codes: [nf-s035], why: *writes_through, out: *out, job: *in_txt, - findings: *stdout_through, tool: {<<: *write, requirements: &linked_source {InitialWorkDirRequirement: {listing: - [$(inputs.source)]}}}} -- {id: a_stderr_at_a_staged_input-File-$(inputs.source.basename)-staged, codes: [nf-s035], why: *writes_through, out: *out, job: *in_txt, - tool: &write_stderr {id: write, inputs: {source: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: - done.txt}}}, stderr: $(inputs.source.basename)}, findings: &stderr_through ['step ''write'': step: process ''write'' - stderr writes through the link input ''source'' is staged under, into what the input names: derive a new name from - it, or make the input a writable InitialWorkDirRequirement entry']} -- {id: a_stderr_at_a_staged_input-Directory-$(inputs.source.basename)/keep.txt-staged, codes: [nf-s035], why: *writes_through, out: *out, - job: *in_dir, findings: *stderr_through, tool: {<<: *write_stderr, inputs: {source: {type: Directory}}, stderr: - $(inputs.source.basename)/keep.txt}} -- {id: a_stderr_at_a_staged_input-File-$(inputs.source.basename)-entry, codes: [nf-s035], why: *writes_through, out: *out, job: *in_txt, - findings: *stderr_through, tool: {<<: *write_stderr, requirements: *linked_source}} -- {id: a_reference_to_a_renamed_entry_has_the_renames_finding_alone, codes: [nf-s044], why: 'Every reference to a renamed entry is refused - for being one; a finding of where it stands would offer what that refusal then refuses.', out: *out, job: &f_in {f: - {class: File, path: in.txt}}, tool: {id: REF, inputs: {f: {type: File}}, outputs: {result: {type: File, - outputBinding: {glob: o}}}, stdout: $(inputs.f), requirements: {InitialWorkDirRequirement: {listing: [{entry: - $(inputs.f), entryname: x.txt}]}}}, findings: ['step ''REF'': tool ''REF.cwl: - requirements.InitialWorkDirRequirement'': input ''f'' has an InitialWorkDirRequirement entry with a literal name and - cannot also be referenced in the command, stream targets, or output globs; name the entry by its literal']} -- {id: a_malformed_listing_checks_no_reference_against_it, codes: [nf-s043], why: &malformed 'A malformed listing stages what no finding - can know: neither the entry''s glob nor a link is checked.', out: *out, job: *f_in, tool: {id: REF, inputs: {f: - {type: File}}, outputs: {result: {type: File, outputBinding: {glob: $(inputs.f.path)}}}, requirements: { - InitialWorkDirRequirement: {listing: [$(inputs.f), 5]}}}, findings: ['step ''REF'': tool ''REF.cwl: - requirements.InitialWorkDirRequirement.listing[1]'': must be a bare $(inputs.) reference or a Dirent mapping']} -- {id: a_list_of_globs_is_refused_for_being_a_list, codes: [nf-s032], why: 'Not for a reference in it: each item of a list is a whole - value, which no other text surrounds.', out: *out, job: &f {f: {class: File, path: in}}, tool: {id: REF, inputs: {f: - {type: File}}, outputs: {result: {type: File, outputBinding: {glob: [$(inputs.f)]}}}}, findings: ['step ''REF'': - step: CWL output glob lists for ''result'' are not supported by the Nextflow target']} -- id: a_reference_where_it_stands-glob-File-$(inputs.f) - codes: [nf-s046] - why: &stands 'design §6, Basename references: a plain File or Directory reference is the object, which no glob or - stream target takes; `.path` is absolute, so stdout and stderr take a basename, and a glob a `.path` only of an - entry, the one input under the output directory; stdin reads one staged File by its whole `.path`. Each case is a - cell of cwltool''s own run of the tool. What a finding offers instead is what the target then takes: not the - input''s own staged name, or a path inside it, where the link the input is staged under would be named.' - tool: &ref {inputs: {f: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: $(inputs.f)}}}} - out: *out - job: *f - findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding.glob'': $(inputs.f) is the File or Directory - object, which CWL does not take as a glob; derive a new name from it, or make the input an InitialWorkDirRequirement - entry'] -- {id: a_reference_where_it_stands-glob-File-$(inputs.f)-linked, codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {<<: *ref, - requirements: &linked {InitialWorkDirRequirement: {listing: [$(inputs.f)]}}}, findings: ['step ''make'': tool - ''make.cwl: outputs.result.outputBinding.glob'': $(inputs.f) is the File or Directory object, which CWL does not take - as a glob; use $(inputs.f.basename)']} -- {id: a_reference_where_it_stands-glob-Directory-$(inputs.f)-writable, codes: [nf-s046], why: *stands, out: *out, job: &d {f: {class: - Directory, path: in}}, tool: &ref_dir {inputs: {f: {type: Directory}}, outputs: {result: {type: Directory, - outputBinding: {glob: $(inputs.f)}}}, requirements: &writable {InitialWorkDirRequirement: {listing: [{entry: - $(inputs.f), writable: true}]}}}, findings: ['step ''make'': tool ''make.cwl: outputs.result.outputBinding.glob'': - $(inputs.f) is the File or Directory object, which CWL does not take as a glob; use $(inputs.f.basename)']} -- {id: a_reference_where_it_stands-glob-File-$(inputs.f).out, codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {<<: *ref, - outputs: {result: {type: File, outputBinding: {glob: $(inputs.f).out}}}}, findings: ['step ''make'': tool ''make.cwl: - outputs.result.outputBinding.glob'': $(inputs.f) embedded in other text renders a File object as JSON in CWL; use - $(inputs.f.basename)']} -- {id: a_reference_where_it_stands-glob-Directory-$(inputs.f)/keep.txt, codes: [nf-s046], why: *stands, out: *out, job: *d, tool: {id: - REF, inputs: {f: {type: Directory}}, outputs: {result: {type: Directory, outputBinding: {glob: - $(inputs.f)/keep.txt}}}}, findings: ['step ''REF'': tool ''REF.cwl: outputs.result.outputBinding.glob'': $(inputs.f) - embedded in other text renders a File object as JSON in CWL; derive a new name from it, or make the input an - InitialWorkDirRequirement entry']} -- {id: a_reference_where_it_stands-glob-File-$(inputs.f.path), codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {<<: *ref, - outputs: {result: {type: File, outputBinding: {glob: $(inputs.f.path)}}}}, findings: ['step ''make'': tool ''make.cwl: - outputs.result.outputBinding.glob'': $(inputs.f.path) is an absolute path outside the output directory, which no CWL - glob matches; derive a new name from it, or make the input an InitialWorkDirRequirement entry']} -- {id: a_reference_where_it_stands-glob-File-$(inputs.f.path).out, codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {<<: *ref, - outputs: {result: {type: File, outputBinding: {glob: $(inputs.f.path).out}}}}, findings: ['step ''make'': tool - ''make.cwl: outputs.result.outputBinding.glob'': $(inputs.f.path) is an absolute path outside the output directory, - which no CWL glob matches; use $(inputs.f.basename)']} -- {id: a_reference_where_it_stands-glob-Directory-$(inputs.f.path)/keep.txt, codes: [nf-s046], why: *stands, out: *out, job: *d, tool: { - id: REF, inputs: {f: {type: Directory}}, outputs: {result: {type: Directory, outputBinding: {glob: - $(inputs.f.path)/keep.txt}}}}, findings: ['step ''REF'': tool ''REF.cwl: outputs.result.outputBinding.glob'': - $(inputs.f.path) is an absolute path outside the output directory, which no CWL glob matches; derive a new name from - it, or make the input an InitialWorkDirRequirement entry']} -- {id: a_reference_where_it_stands-stdin-File-$(inputs.f), codes: [nf-s046], why: *stands, out: *out, job: *f, tool: &ref_stream {id: REF, - inputs: {f: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: done.txt}}}, stdin: $(inputs.f)}, - findings: ['step ''REF'': tool ''REF.cwl: stdin'': $(inputs.f) is the File or Directory object, which CWL does not - take as stdin; use $(inputs.f.path) alone']} -- {id: a_reference_where_it_stands-stdin-File-$(inputs.f.basename)-linked, codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {<<: - *ref_stream, stdin: $(inputs.f.basename), requirements: *linked}, findings: ['step ''REF'': tool ''REF.cwl: stdin'': - stdin names a file by its path, and $(inputs.f.basename) is only its name; use $(inputs.f.path) alone']} -- {id: a_reference_where_it_stands-stdin-File-$(inputs.f.path).gz, codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {<<: - *ref_stream, stdin: $(inputs.f.path).gz}, findings: ['step ''REF'': tool ''REF.cwl: stdin'': stdin reads a staged - file by its whole path, which $(inputs.f.path) inside other text is not; use $(inputs.f.path) alone']} -- {id: a_reference_where_it_stands-stdin-Directory-$(inputs.f.basename)/keep.txt-linked, codes: [nf-s046], why: *stands, out: *out, job: - *d, tool: &ref_stream_dir {<<: *ref_stream, inputs: {f: {type: Directory}}, stdin: $(inputs.f.basename)/keep.txt, - requirements: *linked}, findings: ['step ''REF'': tool ''REF.cwl: stdin'': stdin reads a staged file by its whole - path, which $(inputs.f.basename) inside other text is not; use $(inputs.f.path) alone']} -- {id: a_reference_where_it_stands-stdin-Directory-$(inputs.f.path)-writable, codes: [nf-s046], why: *stands, out: *out, job: *d, tool: { - <<: *ref_stream_dir, stdin: $(inputs.f.path), requirements: *writable}, findings: ['step ''REF'': tool ''REF.cwl: - stdin'': stdin reads a file, and $(inputs.f.path) names a Directory']} -- {id: a_reference_where_it_stands-stdout-File-$(inputs.f), codes: [nf-s046], why: *stands, out: *out, job: *f, tool: &ref_stdout {id: - REF, inputs: {f: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: done.txt}}}, stdout: - $(inputs.f)}, findings: ['step ''REF'': tool ''REF.cwl: stdout'': $(inputs.f) is the File or Directory object, which - CWL does not take as a stdout target; derive a new name from it, or make the input a writable - InitialWorkDirRequirement entry']} -- {id: a_reference_where_it_stands-stdout-File-$(inputs.f)-writable, codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {<<: - *ref_stdout, requirements: *writable}, findings: ['step ''REF'': tool ''REF.cwl: stdout'': $(inputs.f) is the File or - Directory object, which CWL does not take as a stdout target; use $(inputs.f.basename)']} -- {id: a_reference_where_it_stands-stdout-File-$(inputs.f.path)-linked, codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {<<: - *ref_stdout, stdout: $(inputs.f.path), requirements: *linked}, findings: ['step ''REF'': tool ''REF.cwl: stdout'': - $(inputs.f.path) is an absolute path, and CWL takes only a relative name as a stdout target; derive a new name from - it, or make the input a writable InitialWorkDirRequirement entry']} -- {id: a_reference_where_it_stands-stdout-File-$(inputs.f.path).log, codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {<<: - *ref_stdout, stdout: $(inputs.f.path).log}, findings: ['step ''REF'': tool ''REF.cwl: stdout'': $(inputs.f.path) is - an absolute path, and CWL takes only a relative name as a stdout target; use $(inputs.f.basename)']} -- {id: a_reference_where_it_stands-stdout-File-$(inputs.f).log, codes: [nf-s046], why: 'CWL would name the file after the object''s JSON; - the target refuses rather than do that.', out: *out, job: *f, tool: {<<: *ref_stdout, stdout: $(inputs.f).log}, - findings: ['step ''REF'': tool ''REF.cwl: stdout'': $(inputs.f) embedded in other text renders a File object as JSON - in CWL; use $(inputs.f.basename)']} -- {id: a_reference_where_it_stands-stderr-File-$(inputs.f)-linked, codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {id: REF, - inputs: {f: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: done.txt}}}, stderr: $(inputs.f), - requirements: *linked}, findings: ['step ''REF'': tool ''REF.cwl: stderr'': $(inputs.f) is the File or Directory - object, which CWL does not take as a stderr target; derive a new name from it, or make the input a writable - InitialWorkDirRequirement entry']} -- {id: a_reference_where_it_stands-stderr-File-$(inputs.f.path), codes: [nf-s046], why: *stands, out: *out, job: *f, tool: {id: REF, - inputs: {f: {type: File}}, outputs: {result: {type: File, outputBinding: {glob: done.txt}}}, stderr: - $(inputs.f.path)}, findings: ['step ''REF'': tool ''REF.cwl: stderr'': $(inputs.f.path) is an absolute path, and CWL - takes only a relative name as a stderr target; derive a new name from it, or make the input a writable - InitialWorkDirRequirement entry']} -- id: an_output_named_like_a_link_its_task_stages-upstream-glob - codes: [nf-s035] - why: &link Writing a staged input's link writes through it, so the run succeeds and leaves every sorted.txt empty. - workflow: &chain {steps: [{id: EMIT, out: [{out: {wic_anchor: emitted}}]}, {id: SORT, in: {src: {wic_alias: emitted}}, - out: [out]}], inputs: {given: {type: File}}} - tools: [&emit {id: EMIT, outputs: {out: {type: File, outputBinding: {glob: sorted.txt}}}, stdout: sorted.txt}, &sort { - id: SORT, inputs: {src: {type: File, inputBinding: {position: 1}}}, outputs: {out: {type: File, outputBinding: - {glob: sorted.txt}}}, stdout: sorted.txt}] - job: &given {given: {class: File, path: in.txt}} - error: &sorted_through {re: '(?s)\A(?!(.*writes through){2}).*step ''SORT'': tool ''SORT\.cwl: stdout'': writing - ''sorted\.txt'' writes through ''sorted\.txt'', the name input ''src'' is linked under in the task directory'} -- {id: an_output_named_like_a_link_its_task_stages-upstream-glob-in-a-directory, codes: [nf-s035], why: *link, workflow: *chain, job: - *given, tools: [{id: EMIT, outputs: {out: {type: File, outputBinding: {glob: out/sorted.txt}}}, stdout: - out/sorted.txt}, *sort], error: {re: '(?s)\A(?!(.*writes through){2}).*step ''SORT'': tool ''SORT\.cwl: stdout'': - writing ''sorted\.txt'' writes through ''sorted\.txt'', the name input ''src'' is linked under in the task - directory'}} -- {id: an_output_named_like_a_link_its_task_stages-dot-slash, codes: [nf-s035], why: *link, workflow: *chain, job: *given, tools: [*emit, - {<<: *sort, stdout: ./sorted.txt}], error: {re: '(?s)\A(?!(.*writes through){2}).*step ''SORT'': tool ''SORT\.cwl: - stdout'': writing ''\./sorted\.txt'' writes through ''sorted\.txt'', the name input ''src'' is linked under in the - task directory'}} -- {id: an_output_named_like_a_link_its_task_stages-glob-written-by-the-command, codes: [nf-s035], why: *link, workflow: *chain, job: - *given, tools: [*emit, {id: SORT, inputs: {src: {type: File, inputBinding: {position: 1}}}, outputs: {out: {type: - File, outputBinding: {glob: sorted.txt}}}, arguments: [-o, sorted.txt]}], error: {re: '(?s)\A(?!(.*writes - through){2}).*step ''SORT'': tool ''SORT\.cwl: outputs\.out\.outputBinding\.glob'': writing ''sorted\.txt'' writes - through ''sorted\.txt'', the name input ''src'' is linked under in the task directory'}} -- {id: an_output_named_like_a_link_its_task_stages-into-a-linked-directory, codes: [nf-s035], why: *link, job: {given: {class: Directory, - path: in.txt}}, workflow: {<<: *chain, inputs: {given: {type: Directory}}}, tools: [{id: EMIT, outputs: {out: {type: - Directory, outputBinding: {glob: outdir}}}, stdout: outdir}, {id: SORT, inputs: {src: {type: Directory, inputBinding: - {position: 1}}}, outputs: {out: {type: File, outputBinding: {glob: outdir/listing.txt}}}, stdout: - outdir/listing.txt}], error: {re: '(?s)\A(?!(.*writes through){2}).*step ''SORT'': tool ''SORT\.cwl: stdout'': - writing ''outdir/listing\.txt'' writes through ''outdir'', the name input ''src'' is linked under in the task - directory'}} -- {id: an_output_named_like_a_link_its_task_stages-entry-name, codes: [nf-s035], why: *link, workflow: *chain, job: *given, tools: - [&emitted {id: EMIT, outputs: {out: {type: File, outputBinding: {glob: emitted.txt}}}, stdout: emitted.txt}, - &renamed_sort {id: SORT, inputs: {src: {type: File}}, outputs: {out: {type: File, outputBinding: {glob: - sorted.txt}}}, stdout: sorted.txt, requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.src), - entryname: sorted.txt}]}}}], error: {re: '(?s)\A(?!(.*writes through){2}).*step ''SORT'': tool ''SORT\.cwl: stdout'': - writing ''sorted\.txt'' writes through ''sorted\.txt'', the name input ''src'' is linked under in the task - directory'}} -- {id: an_output_named_like_a_link_its_task_stages-entry-name-of-a-workflow-input, codes: [nf-s035], why: *link, job: *given, tools: - [*emitted, *renamed_sort], workflow: {<<: *chain, steps: [{id: EMIT, out: [out]}, {id: SORT, in: {src: given}, out: - [out]}]}, error: {re: '(?s)\A(?!(.*writes through){2}).*step ''SORT'': tool ''SORT\.cwl: stdout'': writing - ''sorted\.txt'' writes through ''sorted\.txt'', the name input ''src'' is linked under in the task directory'}} -- {id: a_malformed_listing_has_its_own_finding_alone, codes: [nf-s043], why: *malformed, workflow: *chain, job: *given, tools: [*emit, - {id: SORT, inputs: {src: {type: File}}, outputs: {out: {type: File, outputBinding: {glob: sorted.txt}}}, stdout: - sorted.txt, requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.src), entryname: renamed.txt}, - 5]}}}], findings: ['step ''SORT'': tool ''SORT.cwl: requirements.InitialWorkDirRequirement.listing[1]'': must be a - bare $(inputs.) reference or a Dirent mapping']} -- id: a_load_listing_on_a_directory_input - codes: [nf-s023] - why: A Directory is staged whole. - tool: {id: LIST, inputs: {d: {type: Directory, loadListing: deep_listing, inputBinding: {position: 1}}}} - job: {d: {class: Directory, path: d}} - findings: ['step ''LIST'': tool ''LIST.cwl: inputs.d.loadListing'': loadListing is not supported: a Directory is - staged whole'] -- id: secondary_files_on_a_tool_input - codes: [nf-s024] - why: Each file is staged as its own input. - tool: {id: INDEX, inputs: {f: {type: File, secondaryFiles: [.bai], inputBinding: {position: 1}}}} - job: {f: {class: File, path: a.bam}} - findings: ['step ''INDEX'': tool ''INDEX.cwl: inputs.f.secondaryFiles'': secondaryFiles are not supported: stage - each file as its own input'] -- id: an_entryname_holding_a_nul_byte - why: No file name holds a NUL byte. - codes: [nf-s055] - tool: {id: T, requirements: {InitialWorkDirRequirement: {listing: [{entry: $(inputs.f), entryname: "a\0b"}]}}, - inputs: {f: {type: File}}} - job: {f: {class: File, path: a.txt}} - findings: ["step 'T': tool 'T.cwl: requirements.InitialWorkDirRequirement.listing[0]': template literals cannot - contain NUL bytes"] diff --git a/tests/core/data/nextflow/runs/commands/expected.yaml b/tests/core/data/nextflow/runs/commands/expected.yaml index 1722632b0..a6a25a7db 100644 --- a/tests/core/data/nextflow/runs/commands/expected.yaml +++ b/tests/core/data/nextflow/runs/commands/expected.yaml @@ -14,7 +14,7 @@ outputs: three_commands~result: {class: File, basename: out.txt, contents: "first\nsecond\n"} three_commands~errors: {class: File, basename: err.txt, contents: "third\n"} print_bindings~result: {class: File, basename: bindings.txt, - contents: "hello there\n-v\n--ratio\n0.5\n1.25\n--tag\na b\n--label=x\n2.5\n"} + contents: "hello there\n-v\n--ratio\n0.5\n1.25\n--tag\na b\n--label=x\n2.5\n--again\n"} produce~result: {class: File, basename: data.txt, contents: fanout} read_once~result: {class: File, basename: read.txt, contents: fanout} read_again~result: {class: File, basename: read.txt, contents: fanout} diff --git a/tests/core/data/nextflow/runs/commands/print_bindings.cwl b/tests/core/data/nextflow/runs/commands/print_bindings.cwl index 5941e932a..6f876b5b1 100644 --- a/tests/core/data/nextflow/runs/commands/print_bindings.cwl +++ b/tests/core/data/nextflow/runs/commands/print_bindings.cwl @@ -5,6 +5,8 @@ requirements: EnvVarRequirement: envDef: {GREETING: hello there} baseCommand: [sh, -c, 'printf "%s\n" "$GREETING" "$@"', sh] +arguments: +- {position: 8, valueFrom: $(inputs.verbose), prefix: --again} # a valueFrom that is a boolean is its flag inputs: verbose: {type: boolean, inputBinding: {position: 1, prefix: -v}} quiet: {type: boolean, inputBinding: {position: 2, prefix: -q}} @@ -13,6 +15,7 @@ inputs: label: {type: 'string?', inputBinding: {position: 5, prefix: --label=, separate: false}} unset: {type: 'string?', inputBinding: {position: 6, prefix: --unset}} scale: {type: float, inputBinding: {position: 7}} + silent: {type: string, inputBinding: {position: 9, valueFrom: $(inputs.verbose)}} # a flag with no prefix stdout: bindings.txt outputs: result: diff --git a/tests/core/data/nextflow/runs/commands/three_commands.cwl b/tests/core/data/nextflow/runs/commands/three_commands.cwl index 68741444a..cd54244ea 100644 --- a/tests/core/data/nextflow/runs/commands/three_commands.cwl +++ b/tests/core/data/nextflow/runs/commands/three_commands.cwl @@ -15,7 +15,8 @@ arguments: - {position: 8, valueFrom: '>&2', shellQuote: false} - {position: 9, valueFrom: ;, shellQuote: false} - {position: 10, valueFrom: 'true'} -inputs: {} +inputs: + flag: {type: boolean, inputBinding: {position: 11, valueFrom: --literal, shellQuote: false}} # text, not a flag stdout: out.txt stderr: err.txt outputs: diff --git a/tests/core/data/nextflow/runs/commands/workflow.wic b/tests/core/data/nextflow/runs/commands/workflow.wic index 5481c1ce3..068c5be46 100644 --- a/tests/core/data/nextflow/runs/commands/workflow.wic +++ b/tests/core/data/nextflow/runs/commands/workflow.wic @@ -33,11 +33,13 @@ steps: # shellQuote: false is the one way to write shell syntax, and stdout and stderr take the whole command's output. - id: shell_redirect # redirected.txt holds the one quoted word - id: three_commands # out.txt holds the first two lines, err.txt the third + in: {flag: !ii true} # Bindings: a true flag is its prefix and a false one nothing; an array takes its prefix once; an optional input is # its prefix and value, apart or joined, or nothing when it has none; a float is printed as written. - id: print_bindings - in: {verbose: !ii true, quiet: !ii false, ratios: !ii [0.5, 1.25], tag: !ii a b, label: !ii x, scale: !ii 2.5} + in: {verbose: !ii true, quiet: !ii false, ratios: !ii [0.5, 1.25], tag: !ii a b, label: !ii x, scale: !ii 2.5, + silent: !ii unread} # One output read by two steps, from a tool that asks for 2 cores and 64 MiB. - id: produce diff --git a/tests/core/nextflow/conftest.py b/tests/core/nextflow/conftest.py deleted file mode 100644 index 27a99c41d..000000000 --- a/tests/core/nextflow/conftest.py +++ /dev/null @@ -1,82 +0,0 @@ -"""Compiled real-workflow fixtures shared across the Nextflow backend suites.""" - -import pytest - -from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl -from sophios.api.python._workflow_runtime import compile_workflow_result -from sophios.api.python.workflow import Step, Workflow -from sophios.ir.artifacts import CompilationResult - -from ..helpers import adapter_step - - -def _copy_step(step_name: str) -> Step: - tool = CommandLineTool("copy_file", Inputs(source=Input(cwl.file, position=1)), - Outputs(result=Output(cwl.file, glob="copy.txt"))) - return Step(tool.base_command("cp").argument("copy.txt", position=2), step_name=step_name) - - -@pytest.fixture(scope="session") -def real_linear_result() -> CompilationResult: - """Compile the shipped touch, append and cat tools as one workflow.""" - steps = [adapter_step("touch", filename="empty.txt"), adapter_step("append", str="Hello"), adapter_step("cat")] - return compile_workflow_result(Workflow(steps, "wf")) - - -@pytest.fixture(scope="session") -def real_supported_result() -> CompilationResult: - """Compile a wholly supported two-process workflow through the real API.""" - touch_tool = ( - CommandLineTool( - "touch_file", - Inputs(filename=Input(cwl.string, position=1)), - Outputs(result=Output(cwl.file, glob="$(inputs.filename)")), - ) - .base_command("touch") - ) - touch = Step(touch_tool, step_name="touch") - touch.inputs.filename = "message.txt" - - copy_step = _copy_step("copy") - copy_step.inputs.source = touch.outputs.result - return compile_workflow_result(Workflow([touch, copy_step], "wf")) - - -@pytest.fixture(scope="session") -def real_scattered_result() -> CompilationResult: - """Compile a real single-input scatter over an array-typed workflow input.""" - echo_tool = ( - CommandLineTool( - "echo_item", - Inputs(item=Input(cwl.string, position=1)), - Outputs(result=Output(cwl.file, glob="out.txt")), - ) - .base_command("echo") - .stdout("out.txt") - ) - echo = Step(echo_tool, step_name="echo_item") - echo.inputs.item = ["alpha", "beta"] - echo.scatter_on(echo.inputs.item) - return compile_workflow_result(Workflow([echo], "wf")) - - -@pytest.fixture(scope="session") -def real_nested_result() -> CompilationResult: - """Compile a real one-level subworkflow whose input comes from an outer step.""" - write_tool = ( - CommandLineTool( - "write_message", - Inputs(message=Input(cwl.string, position=1)), - Outputs(result=Output(cwl.file, glob="message.txt")), - ) - .base_command("echo") - .stdout("message.txt") - ) - write = Step(write_tool, step_name="write") - write.inputs.message = "nested composition" - inner_copy = _copy_step("inner_copy") - child = Workflow([inner_copy], "child") - inner_copy.inputs.source = child.inputs.source - child.inputs.source = write.outputs.result - - return compile_workflow_result(Workflow([write, child], "root")) diff --git a/tests/core/nextflow/test_capabilities.py b/tests/core/nextflow/test_capabilities.py index 176fc4aca..627e719b0 100644 --- a/tests/core/nextflow/test_capabilities.py +++ b/tests/core/nextflow/test_capabilities.py @@ -1,204 +1,86 @@ -"""Closed-world capability analysis: unsupported source semantics reject before artifacts.""" +"""Closed-world capability analysis: what the Nextflow target cannot run is refused, by code, before any artifact.""" # pylint: disable=missing-function-docstring -import copy from collections.abc import Callable from pathlib import Path -import re -from typing import Any, cast import pytest -from sophios.api.python._workflow_runtime import compile_workflow_result -from sophios.api.python.tool_builder import ( - CommandLineTool, - Input, - Inputs, - Output, - Outputs, - cwl, -) -from sophios.api.python.workflow import CompiledWorkflow, Step, StepInput, Workflow -from sophios.input_output_nf import render_nextflow -from sophios.ir.artifacts import CompilationResult -from sophios.ir.resolved import NotLowered -from sophios.utils_nf import NEXTFLOW +from sophios.api.python.nextflow import NotLowered +from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl +from sophios.api.python.workflow import Step, Workflow from sophios.wic_types import Yaml -from ..cases import cases, match -from ..helpers import ADAPTERS, adapter_step -from .testkit import lowered, lowered_case, refusal_lines +from ..cases import case_dirs +from ..helpers import ADAPTERS +from .test_public_api import supported_workflow +from .testkit import refusal_of @pytest.mark.fast -def test_the_shipped_touch_append_cat_workflow_compiles(real_linear_result: CompilationResult) -> None: - """The tutorials' tools: append's quoted message and its writable entry, cat's file-text capture.""" - executable = lowered(real_linear_result) - assert [process.name for process in executable.processes] == ["touch", "append", "cat"] - - -@pytest.mark.fast -def test_a_literal_file_into_a_format_declaring_input_lowers_to_its_path(tmp_path: Path) -> None: - """Sophios writes the input's `format` on the File value; like the input's, it is compile-time (design §3).""" - source = tmp_path / "in.mdin" - source.write_text("x", encoding="utf-8") - fmt = CommandLineTool( - "fmt", - Inputs(src=Input(cwl.file, position=1, format="edam:format_2330")), - Outputs(out=Output(cwl.file, glob="out.txt")), - ).base_command("cat") - step_ = Step(fmt, step_name="fmt") - step_.inputs.src = str(source) - result = compile_workflow_result(Workflow([step_], "wf")) - assert list(result.artifact.job_inputs.values()) == [ - {"class": "File", "location": str(source), "format": "edam:format_2330"} - ] - assert list(lowered(result).params.values()) == [{"class": "File", "path": str(source)}] - - -@pytest.mark.fast -def test_rejects_compiledworkflow_substitution() -> None: - empty = {"class": "Workflow", "cwlVersion": "v1.2", "inputs": {}, "outputs": {}, "steps": []} - compiled = CompiledWorkflow("wf", empty, {}) - with pytest.raises(TypeError, match="resolved view"): - NEXTFLOW.lower(cast(Any, compiled)) - - -def _findings(source: CompilationResult) -> list[str]: - """The refusals of one rejected lowering, as they print, less their spans.""" - with pytest.raises(NotLowered) as error: - lowered(source) - return refusal_lines(error.value) - - -def _copy_tool(name: str = "copy.txt") -> CommandLineTool: - return ( - CommandLineTool( - "copy_file", - Inputs(source=Input(cwl.file, position=1)), - Outputs(result=Output(cwl.file, glob=name)), - ) - .base_command("cp") - .argument(name, position=2) - ) - - -def _write_step() -> Step: - write_tool = ( - CommandLineTool( - "write_message", - Inputs(message=Input(cwl.string, position=1)), - Outputs(result=Output(cwl.file, glob="message.txt")), - ) - .base_command("echo") - .stdout("message.txt") - ) - write = Step(write_tool, step_name="write") - write.inputs.message = "nested composition" - return write - - -@pytest.mark.fast -def test_an_empty_resolved_subworkflow_projects_to_no_processes() -> None: - result = compile_workflow_result(Workflow([Workflow([], "child")], "root")) - assert lowered(result).processes == () - - -def _echo(name: str = "echo") -> Step: - return adapter_step("echo", name, message="Hello") - - -def _echo_with(extend: Callable[[Workflow, Step], None] | None) -> CompilationResult: - """One echo step, which `extend(flow, echo)` gives a step input its tool does not declare.""" - echo = _echo() - flow = Workflow([echo], "flow") - if extend is not None: - extend(flow, echo) - return compile_workflow_result(flow) - - -def _unread_from_a_workflow_input(flow: Workflow, echo: Step) -> None: - echo.inputs.enabled = StepInput(source=flow.inputs.loud.as_type("boolean?")) - - -def _unread_from_merged_workflow_inputs(flow: Workflow, echo: Step) -> None: - echo.inputs.enabled = StepInput( - source=[flow.inputs.loud.as_type("boolean?"), flow.inputs.quiet.as_type("boolean?")], - link_merge="merge_flattened", pick_value="first_non_null", default=True, - ) - - -def _unread_without_a_source(_flow: Workflow, echo: Step) -> None: - echo.inputs.enabled = StepInput(default=True) - - -@pytest.mark.fast -@pytest.mark.parametrize("extend, workflow_inputs", [ - pytest.param(_unread_from_a_workflow_input, ["loud"], id="workflow_input"), - pytest.param(_unread_from_merged_workflow_inputs, ["loud", "quiet"], id="merged_workflow_inputs_with_a_default"), - pytest.param(_unread_without_a_source, [], id="no_source"), -]) -def test_a_step_input_its_tool_does_not_declare_and_nothing_reads_generates_nothing( - extend: Callable[[Workflow, Step], None], workflow_inputs: list[str], -) -> None: - """CWL: a step input the tool does not declare, and that nothing reads, is no error; it changes no run.""" - plain = lowered(_echo_with(None)) - extended = lowered(_echo_with(extend)) - assert extended.processes == plain.processes - assert extended.connections == plain.connections - # The workflow inputs it names stay parameters of the workflow, each checked like any other. - plain_lines, extended_lines = render_nextflow(plain).splitlines(), render_nextflow(extended).splitlines() - added = [line for line in extended_lines if line not in plain_lines] - assert [line for line in plain_lines if line not in extended_lines] == [] - assert [re.fullmatch(r" __sophios_input_\w+\('(\w+)', params\.\1, 'boolean\?'\)", line) is not None - for line in added] == [True] * len(workflow_inputs) - assert sorted(set(extended.params) - set(plain.params)) == workflow_inputs - - -@pytest.mark.fast -def test_a_scatter_over_an_input_its_tool_does_not_declare_is_rejected_by_name() -> None: - def scattered(flow: Workflow, echo: Step) -> None: - echo.inputs.enabled = StepInput(source=flow.inputs.loud.as_type("boolean[]")) - echo.scatter_on(echo.inputs.enabled) - - assert _findings(_echo_with(scattered)) == [ - "workflow 'flow': workflow input 'loud': required workflow input value is missing", - "step 'echo': input 'enabled': scatter over an input the step's tool does not declare is not supported", - ] - - -@pytest.mark.fast -def test_a_refused_input_made_from_a_written_value_is_refused_where_the_value_was_written() -> None: - """A workflow input the compiler made from a value has no line of its own: the step owns its refusal, at the line - the value was written.""" +@pytest.mark.parametrize("family, expected", case_dirs("nextflow/refused", "roots")) +def test_a_family_of_constructs_is_refused_with_its_codes(family: Path, expected: Yaml) -> None: + """Each directory of tests/core/data/nextflow/refused holds the constructs of one kind the target refuses, written + as `.wic` roots and the tools they run. Every root, read as the command line reads a file, is refused in one + lowering with exactly the refusals expected.yaml lists for it, in order: the code, step and subject of each, never + its wording. `workflow.wic` holds every construct whose refusal is reported beside the others.""" + for root, refusals in expected["roots"].items(): + refused = refusal_of(family / root) + assert [[refusal.code.value, refusal.step, refusal.subject] for refusal in refused.refusals] == refusals, root + + +def _not_a_number() -> Workflow: + """A float given NaN, which the parameters' JSON cannot hold.""" + ratio = Step(CommandLineTool("ratio", Inputs(x=Input(cwl.float, position=1)), Outputs()).base_command("echo")) + ratio.inputs.x = float("nan") + return Workflow([ratio], "wf") + + +def _a_file_with_secondary_files() -> Workflow: + """A File value holding secondary files, which the target stages as files of their own or not at all.""" + index = Step(CommandLineTool("index", Inputs(f=Input(cwl.file, position=1)), Outputs()).base_command("cat")) + index.inputs.f = {"class": "File", "path": "reference.fa", + "secondaryFiles": [{"class": "File", "path": "reference.fa.fai"}]} + return Workflow([index], "wf") + + +def _an_optional_pattern_output() -> Workflow: + """An optional output of a pattern, which is checked where it reaches a workflow output, and reaches none.""" + logs = CommandLineTool("logs", Inputs(), Outputs(log=Output(cwl.file, glob="*.log", required=False))) + workflow = Workflow([*supported_workflow().steps, Step(logs.base_command("true"), step_name="logs")], "wf") + workflow.outputs.file = workflow.steps[0].outputs.file + return workflow + + +def _a_written_value_of_any() -> Workflow: + """A value written for an input typed Any, which the compiler makes a workflow input of.""" pick = Step(clt_path=ADAPTERS / "array_indices.cwl", step_name="pick") pick.inputs.input_indices = [0] pick.inputs.input_array = ["a", "b"] - written = Path(__file__).read_text(encoding="utf-8").splitlines().index( - ' pick.inputs.input_array = ["a", "b"]') + 1 - with pytest.raises(NotLowered) as raised: - lowered(compile_workflow_result(Workflow([pick], "flow"))) - assert f"{__file__}:{written}:1: error [nf-s048] workflow input 'pick~input_array': type: unsupported CWL type " \ - "for the Nextflow target: 'Any' (step 'pick')" in [str(line) for line in raised.value.diagnostics] + return Workflow([pick], "flow") @pytest.mark.fast -@pytest.mark.parametrize("case", cases( - "nextflow/rejected", "tool", "out", "job", "workflow", "tools", "error", "findings", "codes")) -def test_a_rejected_source_is_refused_as_its_case_says(case: Yaml) -> None: - """A case's source, its documents left as they were, is refused with exactly its `findings`, or with refusals - whose lines `error` matches (tests/core/cases.py reads both), each printed with the code of its reason, in order, - when the case names its `codes`. A refusal is read without its span: a case's document is written out by - `hermetic.bundle`, which decides its lines.""" - documents = copy.deepcopy(case) - with pytest.raises(NotLowered) as raised: - lowered_case(case) - assert case == documents - lines = refusal_lines(raised.value) - if "error" in case: - assert match(case["error"], "\n".join(lines)), lines - else: - assert match(case["findings"], lines), lines - if "codes" in case: - assert re.findall(r"\[((?:nf-s|wic)\d{3})\]", str(raised.value)) == case["codes"], str(raised.value) +@pytest.mark.parametrize("build, refusals", [ + (_not_a_number, [("nf-s015", "ratio", "ratio~x")]), + (_a_file_with_secondary_files, [("nf-s015", "index", "index~f")]), + (_an_optional_pattern_output, [("nf-s030", None, None)]), + (_a_written_value_of_any, [("nf-s033", "pick", "array_indices.cwl: outputs.output_array.outputBinding"), + ("nf-s048", "pick", "pick~input_array")]), +], ids=["not a number", "secondary files", "an optional pattern output", "a written value of Any"]) +def test_a_refusal_only_python_reaches_names_the_line_python_wrote( + build: Callable[[], Workflow], refusals: list[tuple[str, str | None, str | None]]) -> None: + """What no `.wic` file can write is refused as the rest are, by code, step and subject, at the line of the + Python that built it: a NaN and a File's secondary files, values JSON parameters cannot hold; an optional pattern + output no workflow output takes, which the file door refuses + sooner; a value written for an input of a type the target does not lower, at the line the value was written.""" + with pytest.raises(NotLowered) as refused: + build().compile(target="nextflow") + assert [(refusal.code.value, refusal.step, refusal.subject) for refusal in refused.value.refusals] == refusals + lines = Path(__file__).read_text(encoding="utf-8").splitlines() + for refusal, diagnostic in zip(refused.value.refusals, refused.value.diagnostics, strict=True): + if ".cwl: " not in (refusal.subject or ""): # a tool's refusal is at the tool's line + assert diagnostic.span is not None and Path(diagnostic.span.file) == Path(__file__), diagnostic + assert lines[diagnostic.span.start_line - 1].lstrip().startswith( + ("ratio.inputs.x", "index.inputs.f", "workflow = ", "pick.inputs.input_array")), diagnostic diff --git a/tests/core/nextflow/test_channels.py b/tests/core/nextflow/test_channels.py index 351ce8e51..7aca0fc42 100644 --- a/tests/core/nextflow/test_channels.py +++ b/tests/core/nextflow/test_channels.py @@ -2,11 +2,9 @@ # pylint: disable=missing-function-docstring -from dataclasses import replace import json import math from pathlib import Path -import re import subprocess from typing import Any @@ -35,17 +33,6 @@ def _run( return run_observed(workflow, directory, *arguments) -@pytest.mark.nextflow -@pytest.mark.serial -def test_a_dry_run_stops_at_its_first_task_and_writes_nothing(tmp_path: Path) -> None: - write_nextflow_artifacts(runtime_workflow(), tmp_path) - result = execute_nextflow(tmp_path, "-stub-run") - assert result.returncode == 1, result.stdout + result.stderr - assert NF_STUB_MESSAGE in result.stdout + result.stderr - assert not list((tmp_path / "work").rglob("message.txt")) - assert not list((tmp_path / "work").rglob("copy.txt")) - - class _JsonNumber(str): """Number text the params file holds as it is: Python writes no JSON number past the double range.""" @@ -83,10 +70,18 @@ class _Missing(str): ] +_WHEN = "$(inputs.n == 10)" +#: A value given on the command line, and the line the run writes or the value the check stops it at. +_COMMAND_LINE = [(None, ("trim", "false"), ["hi\n"], None), (_WHEN, ("n", "10"), ["hi"], None), + (_WHEN, ("n", "ten"), None, "ten")] + + @pytest.mark.nextflow @pytest.mark.serial def test_the_entry_check_passes_exact_values_and_stops_every_other(tmp_path: Path) -> None: - """Every case runs through the generated check under the pinned Nextflow, its value read from JSON.""" + """Every case runs through the generated check under the pinned Nextflow, its value read from JSON; and a value + given on the command line reaches the run as its type, so a false drops a flag and an int satisfies a when, or + the check stops the run before any task.""" (tmp_path / "f.txt").write_text("f", encoding="utf-8") (tmp_path / "d").mkdir() (tmp_path / "workflow.nf").write_text( @@ -124,16 +119,22 @@ def test_the_entry_check_passes_exact_values_and_stops_every_other(tmp_path: Pat assert outcome == [True, expected], (value, declared) if declared == "float": # == does not tell -0.0 from 0.0 assert math.copysign(1, outcome[1]) == math.copysign(1, expected), (value, declared) + for index, case in enumerate(_COMMAND_LINE): + _given_on_the_command_line(tmp_path / f"argv{index}", *case) -@pytest.mark.fast -@pytest.mark.parametrize("declared", ["File?", "Directory?"]) -def test_no_model_holds_an_absent_path_the_entry_check_stops(declared: str) -> None: - """Sophios never writes a parameter value its own entry check stops, read by a step or not.""" - workflow = runtime_workflow() - with pytest.raises(ValueError, match=re.escape(f"workflow input 'unread' is an absent optional {declared},")): - replace(workflow, params={**workflow.params, "unread": []}, - param_types={**workflow.param_types, "unread": declared}) +def _given_on_the_command_line(directory: Path, when: str | None, argv: tuple[str, str], line: list[str] | None, + stops: str | None) -> None: + """The echo flow run with `argv` on the command line writes `line`, or the check stops it at `stops`.""" + workflow = _lower(_echo_flow(when)) + result, observed = _run(workflow, directory, f"--{_param(workflow, argv[0])}", argv[1]) + if stops is None: + assert result.returncode == 0 and observed["line"] == line, result.stdout + result.stderr + else: + assert result.returncode != 0 + assert f"Sophios workflow input '{_param(workflow, 'n')}' must be int, not '{stops}'" in ( + result.stdout + result.stderr) + assert not (directory / "work").exists() or not list((directory / "work").glob("*/*")) def _echo_flow(when: str | None = None) -> Workflow: @@ -159,37 +160,17 @@ def _param(workflow: ExecutableNextflowWorkflow, port: str) -> str: ) -_WHEN = "$(inputs.n == 10)" - - -@pytest.mark.nextflow -@pytest.mark.serial -@pytest.mark.parametrize(("when", "argv", "line", "stops"), [ - pytest.param(None, ("trim", "false"), ["hi\n"], None, id="a command-line false drops it"), - pytest.param(_WHEN, ("n", "10"), ["hi"], None, id="a command-line int satisfies the when"), - pytest.param(_WHEN, ("n", "ten"), None, "ten", id="a mistyped value"), -]) -def test_a_command_line_value_reaches_the_run_as_its_type_or_stops_it( - when: str | None, argv: tuple[str, ...], line: list[str] | None, stops: str | None, tmp_path: Path) -> None: - workflow = _lower(_echo_flow(when)) - arguments = (f"--{_param(workflow, argv[0])}", argv[1]) if argv else () - result, observed = _run(workflow, tmp_path, *arguments) - if stops is None: - assert result.returncode == 0, result.stdout + result.stderr - assert observed["line"] == line - else: - assert result.returncode != 0 - assert f"Sophios workflow input '{_param(workflow, 'n')}' must be int, not '{stops}'" in ( - result.stdout + result.stderr) - assert not (tmp_path / "work").exists() or not list((tmp_path / "work").glob("*/*")) - - @pytest.mark.nextflow @pytest.mark.serial -def test_the_v1_script_parser_stops_the_run_before_any_task(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """The v1 parser would convert a command-line value before the entry check sees it.""" +def test_a_run_nextflow_cannot_run_as_cwl_does_stops_before_any_task( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A dry run stops at its first task, whose stub refuses it, and the v1 script parser, which would convert a + command-line value before the entry check sees it, stops the run before any task; neither writes a file.""" + write_nextflow_artifacts(runtime_workflow(), tmp_path / "dry") + result = execute_nextflow(tmp_path / "dry", "-stub-run") + assert result.returncode == 1 and NF_STUB_MESSAGE in result.stdout + result.stderr, result.stdout + result.stderr + assert not list((tmp_path / "dry" / "work").rglob("*.txt")) monkeypatch.setenv("NXF_SYNTAX_PARSER", "v1") - result, _ = _run(_echo_flow(), tmp_path) - assert result.returncode != 0 - assert NF_PARSER_MESSAGE in result.stdout + result.stderr - assert not (tmp_path / "work").exists() or not list((tmp_path / "work").glob("*/*")) + result, _ = _run(_echo_flow(), tmp_path / "v1") + assert result.returncode != 0 and NF_PARSER_MESSAGE in result.stdout + result.stderr + assert not (tmp_path / "v1" / "work").exists() or not list((tmp_path / "v1" / "work").glob("*/*")) diff --git a/tests/core/nextflow/test_conditions.py b/tests/core/nextflow/test_conditions.py deleted file mode 100644 index 4e7a1d682..000000000 --- a/tests/core/nextflow/test_conditions.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Conditional steps: `when` lowering to a branch/mix skip with CWL null (design §6, Topology).""" - -# pylint: disable=missing-function-docstring - -from typing import Any - -import pytest - -from sophios.input_output_nf import render_nextflow -from sophios.lang.subset import parse -from sophios.nf_types import ExecutableNextflowWorkflow, NfOptionalBinding - -from .testkit import lowered, lowered_case, step, tool - - -def _when_workflow( - when: str, - params: dict[str, Any], - *, - second_step: bool = False, - **inputs: Any, -) -> ExecutableNextflowWorkflow: - declared = { - name: cwl_type if isinstance(cwl_type, dict) else {"type": cwl_type} - for name, cwl_type in inputs.items() - } - produce = tool( - "PRODUCE", - inputs=declared, - baseCommand="echo", - arguments=[{"position": 1, "valueFrom": "ok"}], - stdout="out.txt", - outputs={ - "result": { - "type": "string", - "outputBinding": {"glob": "out.txt", "loadContents": True, "outputEval": "$(self[0].contents)"}, - } - }, - ) - result: str | dict[str, Any] = {"result": {"wic_anchor": "result"}} if second_step else "result" - steps = [step("PRODUCE", **{"in": {name: name for name in inputs}, "out": [result], "when": when})] - tools = [produce] - outputs = {"result": {"type": "string?", "outputSource": "PRODUCE/result"}} - if second_step: - consume = tool( - "CONSUME", - inputs={"maybe_result": {"type": "string?"}}, - baseCommand=["touch", "done.txt"], - outputs={"done": {"type": "File", "outputBinding": {"glob": "done.txt"}}}, - ) - steps.append(step("CONSUME", **{"in": {"maybe_result": {"wic_alias": "result"}}, "out": ["done"]})) - tools.append(consume) - outputs = { - "result": {"type": "string?", "outputSource": "PRODUCE/result"}, - "done": {"type": "File", "outputSource": "CONSUME/done"}, - } - workflow = { - "steps": steps, - "inputs": {name: definition["type"] for name, definition in declared.items()}, - "outputs": outputs, - } - return lowered_case({"workflow": workflow, "tools": tools, "job": params})[0] - - -@pytest.mark.fast -@pytest.mark.parametrize(("when", "inputs"), [ - ("$(true)", {"a": "int"}), - ("$(false)", {"a": "int"}), - ("$(inputs.flag)", {"flag": "boolean"}), - ("$(inputs.a > 1)", {"a": "int"}), - ("$(inputs.a == 2)", {"a": "int"}), - ("$(inputs.a === 2)", {"a": "int"}), - ("$(inputs.a > 1 && inputs.flag || !inputs.flag)", {"a": "int", "flag": "boolean"}), - ("$(Math.round(inputs.b) > 1)", {"b": "float"}), - ("$(inputs.maybe === null)", {"maybe": ["null", "int"]}), -]) -def test_admitted_when_cells_lower_to_a_process_condition(when: str, inputs: dict[str, Any]) -> None: - values = {name: (False if cwl_type == "boolean" else 1.5 if cwl_type == "float" else 1) - for name, cwl_type in inputs.items()} - workflow = _when_workflow(when, values, **inputs) - assert workflow.processes[0].condition is not None - - -@pytest.mark.fast -def test_a_conditional_step_whose_process_has_no_inputs_is_refused_at_its_when() -> None: - """A process decides its condition per invocation of its inputs; a step-only input counts as one (design §9).""" - with pytest.raises(ValueError, match=r"error \[nf-s012\] when: process '_PRODUCE' has a condition but no inputs" - r".*\(step 'PRODUCE'\)$"): - _when_workflow("$(true)", {}) - - -@pytest.mark.fast -@pytest.mark.parametrize(("when", "predicate"), [ - ("$(inputs.maybe === null)", "(__w0 == null || __w0 == [])"), - ("$(inputs.maybe == null)", "(__w0 == null || __w0 == [])"), - ("$(null === inputs.maybe)", "(__w0 == null || __w0 == [])"), - ("$(inputs.maybe !== null)", "(!(__w0 == null || __w0 == []))"), - ("$(inputs.maybe != null)", "(!(__w0 == null || __w0 == []))"), -]) -def test_a_null_check_renders_as_a_test_for_the_absent_sentinel(when: str, predicate: str) -> None: - # An absent optional input reaches the process as the [] sentinel, never as null. - workflow = _when_workflow(when, {}, maybe=["null", "int"]) - assert f" run: {predicate}\n" in render_nextflow(workflow) - - -@pytest.mark.fast -def test_a_when_diagnostic_names_the_authored_inputs() -> None: - rendered = render_nextflow(_when_workflow("$(inputs.n / inputs.d > 1)", {"n": 4, "d": 2}, n="int", d="int")) - assert "'(inputs.n / inputs.d)', [d: __w1, n: __w0]" in rendered - assert "inputs.__w" not in rendered - - -@pytest.mark.fast -def test_when_on_a_single_input_scattered_step_lowers() -> None: - produce = tool( - "PRODUCE", - inputs={"a": {"type": "int"}}, - baseCommand="echo", - outputs={"result": {"type": "File", "outputBinding": {"glob": "out.txt"}}}, - ) - workflow = { - "steps": [step("PRODUCE", **{ - "in": {"a": "a"}, "out": ["result"], "when": "$(inputs.a > 0)", "scatter": "a", - })], - "inputs": {"a": {"type": {"type": "array", "items": "int"}}}, - "outputs": {"result": {"type": {"type": "array", "items": "File"}, "outputSource": "PRODUCE/result"}}, - } - workflow_model, _notes = lowered_case({"workflow": workflow, "tools": [produce], "job": {"a": [1, 2]}}) - assert workflow_model.processes[0].condition is not None - - -@pytest.mark.fast -@pytest.mark.parametrize( - ("arguments", "admitted"), [([], True), ([{"position": 2, "valueFrom": "$(inputs.result)"}], False)] -) -def test_optional_binding_consumer_of_a_conditional_output(arguments: list[Any], admitted: bool) -> None: - """A skipped step's null reaches an optional input's own binding, and no other reference to it.""" - produce = tool( - "PRODUCE", - inputs={"a": {"type": "int"}}, - baseCommand="echo", - outputs={ - "result": { - "type": "string", - "outputBinding": {"glob": "out.txt", "loadContents": True, "outputEval": "$(self[0].contents)"}, - } - }, - ) - consume = tool( - "CONSUME", - inputs={"result": {"type": "string?", "inputBinding": {"position": 1, "prefix": "--result"}}}, - arguments=arguments, - baseCommand="echo", - outputs={"done": {"type": "File", "outputBinding": {"glob": "done.txt"}}}, - ) - workflow = { - "steps": [ - step("PRODUCE", **{"in": {"a": "a"}, "out": [{"result": {"wic_anchor": "result"}}], - "when": "$(inputs.a > 0)"}), - step("CONSUME", **{"in": {"result": {"wic_alias": "result"}}, "out": ["done"]}), - ], - "inputs": {"a": "int"}, - "outputs": {"done": {"type": "File", "outputSource": "CONSUME/done"}}, - } - case = {"workflow": workflow, "tools": [produce, consume], "job": {"a": 1}} - if admitted: - assert lowered_case(case)[0].processes[1].command.tokens[-1] == NfOptionalBinding("result", "--result") - else: - with pytest.raises(ValueError, match="not one the absent-optional lowering admits"): - lowered_case(case) - - -@pytest.mark.fast -def test_a_condition_inside_an_inlined_subworkflow_survives_inlining() -> None: - # pylint: disable=import-outside-toplevel - from sophios.api.python._workflow_runtime import compile_workflow_result - from sophios.api.python.workflow import Step, Workflow - from .test_capabilities import _copy_tool, _write_step - write = _write_step() - inner = Step(_copy_tool(), step_name="inner_copy") - inner.when = "$(false)" - child = Workflow([inner], "child") - inner.inputs.source = child.inputs.source - child.outputs.result = inner.outputs.result - child.inputs.source = write.outputs.result - workflow = lowered(compile_workflow_result(Workflow([write, child], "root"))) - conditions = {process.name: process.condition for process in workflow.processes} - assert [name for name, condition in conditions.items() if condition == parse("$(false)")] == [ - name for name in conditions if "inner_copy" in name - ] - assert sum(condition is not None for condition in conditions.values()) == 1 diff --git a/tests/core/nextflow/test_executable_ir.py b/tests/core/nextflow/test_executable_ir.py index ad0cc8050..fcf8fbbdd 100644 --- a/tests/core/nextflow/test_executable_ir.py +++ b/tests/core/nextflow/test_executable_ir.py @@ -11,6 +11,7 @@ from hypothesis import example, given, strategies as st import pytest +from sophios.api.python.workflow import CompiledWorkflow from sophios.input_output_nf import render_nextflow from sophios.lang.subset import Expr, parse from sophios.nf_symbols import ( @@ -34,14 +35,16 @@ NfProcessConnection, NfResources, NfShellLiteral, + NfStepInputConnection, NfTemplate, NfWorkflowInputConnection, NfWorkflowOutputConnection, ) +from sophios.utils_nf import NEXTFLOW + from ..budgets import budget -from ..cases import match -from .testkit import command, output_port, ref, template +from .testkit import command, output_port, ref, runtime_workflow, template BROKEN_BY = {"cycle": "workflow connections contain a cycle", "duplicate name": "duplicate process name", "missing": "unknown (source|destination) process 'MISSING'", "repeated emit": "duplicate output emit name", @@ -132,17 +135,6 @@ def test_a_graph_constructs_exactly_when_it_breaks_no_rule(graph: tuple[Any, ... ("if", False), ("class", False), ("_", False), ("9start", False), ("dash-name", False), ("😀", False)] -@pytest.mark.fast -@pytest.mark.parametrize(("name", "valid"), NAMES) -def test_a_name_is_an_identifier_exactly_as_nextflow_reads_it(name: str, valid: bool) -> None: - assert is_nextflow_identifier(name) is valid - if valid: - assert NfPort(name, "val").name == name - else: - with pytest.raises(ValueError, match="Nextflow identifier"): - NfPort(name, "val") - - def _proc( port: NfPort, *tokens: NfCommandToken, stdout: NfTemplate | None = None, outputs: tuple[NfPort, ...] = () ) -> NfProcess: @@ -329,18 +321,6 @@ def _conditional(condition: Any = None, *, is_array: Any = False) -> NfProcess: } -@pytest.mark.fast -@pytest.mark.parametrize(("build", "refusal"), UNREPRESENTABLE.values(), ids=UNREPRESENTABLE) -def test_a_malformed_ir_value_is_refused_at_construction(build: Callable[[], Any], refusal: Any) -> None: - """A malformed IR value or process is unrepresentable: construction refuses it, naming the field.""" - if refusal is None: - build() - return - error, pattern = refusal if isinstance(refusal, tuple) else (ValueError, refusal) - with pytest.raises(error, match=pattern): - build() - - def _one(params: dict[str, Any], types: dict[str, str] | None = None) -> ExecutableNextflowWorkflow: return ExecutableNextflowWorkflow("WF", [NfProcess("ONE", [NfPort("value", "val")], [], command("true"))], [NfWorkflowInputConnection("value", "ONE", "value")], params, types or {}) @@ -526,110 +506,161 @@ def _optional_producer() -> NfProcess: } -@pytest.mark.fast -@pytest.mark.parametrize(("build", "outcome"), WORKFLOWS.values(), ids=WORKFLOWS) -def test_a_workflow_constructs_exactly_when_its_channels_agree(build: Callable[[], Any], outcome: Any) -> None: - """Connections and params agree on channel kind, cardinality, scatter adapter, capture and optionality, or - construction fails naming the edge.""" - if isinstance(outcome, str): - with pytest.raises(ValueError, match=outcome): - build() - else: - built = build() - assert outcome is None or built == outcome - - -@pytest.mark.fast -@pytest.mark.parametrize(("value", "payload"), [ - (NfArrayBinding("names"), {"exact": {"kind": "array", "name": "names", "prefix": None}}), - (NfFlag("reverse", "-r"), {"exact": {"kind": "flag", "name": "reverse", "prefix": "-r"}}), - (NfBasenameReference("source"), {"exact": {"kind": "basename", "name": "source"}}), - (NfShellLiteral(">>"), {"exact": {"kind": "shell_literal", "text": ">>"}}), - (NfOptionalBinding("name", "--name=", False), - {"exact": {"kind": "optional_binding", "name": "name", "prefix": "--name=", "separate": False}}), - *((_entry_workflow(NfPort("source", "path", entry=entry)), - {"processes": [{"inputs": [{"entry": {"name": entry.name, "copy": entry.copy}}]}]}) - for entry in (NfEntry(), NfEntry(copy=True), NfEntry("renamed.txt"), NfEntry("a*b?.txt", True))), - (ExecutableNextflowWorkflow("wf", [], [], {}), - {"schema_version": ExecutableNextflowWorkflow.SCHEMA_VERSION, "representation_kind": "executable"}), -]) -def test_a_value_writes_its_payload_fields(value: Any, payload: dict[str, Any]) -> None: - """A command part's payload is exactly its fields; an entry and the workflow header are read out of a larger one.""" - assert match(payload, value.to_dict()) - - -@pytest.mark.fast -@pytest.mark.parametrize("segment", [NfInputReference("source"), NfBasenameReference("source")]) -def test_only_an_entry_under_its_own_basename_is_referenced(segment: NfInputReference | NfBasenameReference) -> None: - _entry_workflow(NfPort("source", "path", entry=NfEntry(copy=True)), tokens=("cat", NfTemplate((segment,)))) - with pytest.raises(ValueError, match="references an input whose InitialWorkDirRequirement entry has a literal name"): - _entry_workflow(NfPort("source", "path", entry=NfEntry("renamed.txt")), tokens=("cat", NfTemplate((segment,)))) +def _staged(segment: NfInputReference | NfBasenameReference) -> dict[str, tuple[Callable[[], Any], Any]]: + """design §6, Basename references: a glob at a staged input, or at a name inside it, is not a file a CWL glob + matches, and a stream written there writes through the link into the input; an entry is matched and a writable + one is a copy, and a name derived from the input's is a new one.""" + kind = type(segment).__name__ + globbed = "output 'result' globs the staged input 'source', or a name inside it" + rows: dict[str, tuple[Callable[[], Any], Any]] = {} + for before, after in (("", ""), ("./", ""), ("", "/keep.txt"), ("a/../", "/")): + output = NfPort("result", "path", "result", NfTemplate((NfLiteral(before), segment, NfLiteral(after)))) + rows[f"glob-{kind}-{before}{after}-staged"] = (partial(_entry_workflow, NfPort("source", "path"), + outputs=(output,)), globbed) + rows[f"glob-{kind}-{before}{after}-entry"] = (partial( + _entry_workflow, NfPort("source", "path", entry=NfEntry()), outputs=(output,)), None) + derived_names = (NfTemplate((segment, NfLiteral(".copy"))), NfTemplate((NfLiteral("out/"), segment))) + for index, derived in enumerate(derived_names): + rows[f"glob-{kind}-derived-{index}"] = (partial(_entry_workflow, NfPort("source", "path"), outputs=( + NfPort("result", "path", "result", derived),)), None) + for stream in ("stdout", "stderr"): + for after in ("", "/keep.txt"): + target = NfTemplate((segment, NfLiteral(after))) + for entry, outcome in ((None, f"{stream} writes through the link input 'source' is staged under"), + (NfEntry(), f"{stream} writes through the link input 'source' is staged under"), + (NfEntry(copy=True), None)): + rows[f"{stream}-{kind}{after}-{entry!r}"] = (partial( + _entry_workflow, NfPort("source", "path", entry=entry), streams={stream: target}), outcome) + rows[f"{stream}-{kind}-derived"] = (partial(_entry_workflow, NfPort("source", "path"), streams={ + stream: NfTemplate((segment, NfLiteral(".log")))}), None) + # Only an entry under its own basename is referenced: a literal name is the one the command reads. + rows[f"reference-{kind}-to-a-copied-entry"] = (partial(_entry_workflow, NfPort( + "source", "path", entry=NfEntry(copy=True)), tokens=("cat", NfTemplate((segment,)))), None) + rows[f"reference-{kind}-to-a-renamed-entry"] = (partial(_entry_workflow, NfPort( + "source", "path", entry=NfEntry("renamed.txt")), tokens=("cat", NfTemplate((segment,)))), + "references an input whose InitialWorkDirRequirement entry has a literal name") + return rows + + +def _optional(glob: str, capture: str | None, *connections: NfConnection) -> ExecutableNextflowWorkflow: + """An optional output of at most one file, which Nextflow checks only where it reaches a workflow output.""" + process = NfProcess("MAYBE", [], [NfPort("o", "path", "o", template(glob), capture=capture, optional=True)], + command("true")) + return ExecutableNextflowWorkflow("WF", [process], connections, {}) + + +def _merged(*sources: Any, link_merge: str = "merge_flattened", pick_value: str | None = None, + port: NfPort | None = None) -> ExecutableNextflowWorkflow: + """PAIR gathers into, and A and the parameter xs join at, JOIN's input.""" + pair = NfProcess("PAIR", [NfPort("item", "val")], [output_port("f", "f.txt")], command("true")) + produce = NfProcess("A", [], [output_port("f", "a.txt")], command("true")) + join = NfProcess("JOIN", [port or NfPort("files", "path", is_array=True)], [], command("true")) + return ExecutableNextflowWorkflow( + "WF", [pair, produce, join], + [NfWorkflowInputConnection("items", "PAIR", "item", "dotproduct"), + NfStepInputConnection(sources, link_merge, pick_value)], + {"items": ["x"], "xs": ["x.txt"], "one": "o.txt"}, {"items": "string[]", "xs": "File[]", "one": "File"}, + ) -@pytest.mark.fast -@pytest.mark.parametrize("segment", [NfInputReference("source"), NfBasenameReference("source")]) -@pytest.mark.parametrize(("before", "after"), [("", ""), ("./", ""), ("", "/keep.txt"), ("a/../", "/")]) -def test_a_glob_at_a_staged_input_is_rejected_unless_the_input_is_an_entry( - segment: NfInputReference | NfBasenameReference, before: str, after: str, -) -> None: - """design §6, Basename references: a staged input, or a name inside it, is not a file a CWL glob matches; an - entry is, and a name derived from the input's is a new one.""" - output = NfPort("result", "path", "result", NfTemplate((NfLiteral(before), segment, NfLiteral(after)))) - with pytest.raises(ValueError, match="output 'result' globs the staged input 'source', or a name inside it"): - _entry_workflow(NfPort("source", "path"), outputs=(output,)) - _entry_workflow(NfPort("source", "path", entry=NfEntry()), outputs=(output,)) - for derived in (NfTemplate((segment, NfLiteral(".copy"))), NfTemplate((NfLiteral("out/"), segment))): - _entry_workflow(NfPort("source", "path"), outputs=(replace(output, glob=derived),)) +_GATHERED = NfProcessConnection("PAIR", "f", "JOIN", "files", "gather") +_ONE = NfProcessConnection("A", "f", "JOIN", "files") +_XS = NfWorkflowInputConnection("xs", "JOIN", "files") +_ARRAY_JOIN = "an array source joins only by merge_flattened with no pickValue" +_CONDITION = NfProcess("CALC", [NfPort("a", "val", scalar_type="int")], [output_port("out", "out.txt")], + command("true"), condition=parse("$(Math.pow(inputs.a, 2) > 1)")) +_AT_MOST_ONE = "optional outputs o must match at most one file and must reach a workflow" + +#: Every row above, and the staged-input rules for both kinds of reference. +CONSTRUCTIONS: dict[str, tuple[Callable[[], Any], Any]] = { + **UNREPRESENTABLE, **WORKFLOWS, **_staged(NfInputReference("source")), **_staged(NfBasenameReference("source")), + **{f"optional-{glob}-alone": (partial(_optional, glob, capture), _AT_MOST_ONE) + for glob, capture in (("*.log", None), ("maybe.txt", "single"))}, + **{f"optional-{glob}-into-a-workflow-output": (partial(_optional, glob, capture, NfWorkflowOutputConnection( + "MAYBE", "o", "result")), None) for glob, capture in (("*.log", None), ("maybe.txt", "single"))}, + # A step input's sources join as the idioms can, at one process input, and are never scattered. + "step-input-one-value-to-an-array-port": (partial(_merged, _ONE, pick_value="first_non_null"), + "gives one value to a port that is array-typed"), + "step-input-a-list-to-a-scalar-port": (partial(_merged, _ONE, link_merge="merge_nested", port=NfPort( + "files", "path")), "gives a list to a port that is not array-typed"), + "step-input-an-array-merged-nested": (partial(_merged, _GATHERED, _ONE, link_merge="merge_nested"), _ARRAY_JOIN), + "step-input-an-array-picked": (partial(_merged, _XS, _ONE, pick_value="all_non_null"), _ARRAY_JOIN), + "step-input-a-val-array-into-a-path": (partial(_merged, NfWorkflowInputConnection("items", "JOIN", "files")), + "workflow input 'items' is val\\[\\], which its port's path cannot take"), + "step-input-two-processes": (partial(_merged, _ONE, NfProcessConnection("A", "f", "PAIR", "item")), + "must all reach one process input"), + "step-input-scattered": (partial(_merged, NfWorkflowInputConnection("xs", "JOIN", "files", "dotproduct")), + "a step input's sources cannot be scattered"), + "step-input-merge-deep": (partial(_merged, _ONE, link_merge="merge_deep"), "linkMerge must be one of"), + # The lowering reads the resolved view, never a compiled document. + "lowering-a-compiled-document": (partial(NEXTFLOW.lower, cast(Any, CompiledWorkflow("wf", { + "class": "Workflow", "cwlVersion": "v1.2", "inputs": {}, "outputs": {}, "steps": []}, {}))), + (TypeError, "resolved view")), + # Sophios never writes a parameter value its own entry check stops, read by a step or not. + **{f"absent-optional-{declared}": (partial(lambda declared: replace( + runtime_workflow(), params={**runtime_workflow().params, "unread": []}, + param_types={**runtime_workflow().param_types, "unread": declared}), declared), + re.escape(f"workflow input 'unread' is an absent optional {declared},")) + for declared in ("File?", "Directory?")}, + # A tree built without parsing, as the import builds one, is checked when its process is built. + **{f"condition-built-with-{name}": (partial(replace, _CONDITION, condition=replace( + cast(Expr, _CONDITION.condition), args=(node, *cast(Expr, _CONDITION.condition).args[1:]))), pattern) + for name, node, pattern in ( + ("a-call", Expr("Runtime.getRuntime().exec", (Expr("ref", value="a"),)), "unsupported construct"), + ("a-literal", Expr("number", value="010"), "not a strict-mode decimal"))}, +} -@pytest.mark.fast -@pytest.mark.parametrize("stream", ["stdout", "stderr"]) -@pytest.mark.parametrize("segment", [NfInputReference("source"), NfBasenameReference("source")]) -@pytest.mark.parametrize("after", ["", "/keep.txt"]) -def test_a_stream_writing_a_staged_input_is_rejected_unless_the_input_is_a_copy( - stream: str, segment: NfInputReference | NfBasenameReference, after: str, -) -> None: - """design §6, Basename references: writing the link an input is staged under, or a name inside it, writes - through the link into the input; a writable entry is a copy, and a name derived from the input's is a new one.""" - target = NfTemplate((segment, NfLiteral(after))) - for entry in (None, NfEntry()): - with pytest.raises(ValueError, match=f"{stream} writes through the link input 'source' is staged under"): - _entry_workflow(NfPort("source", "path", entry=entry), streams={stream: target}) - _entry_workflow(NfPort("source", "path", entry=NfEntry(copy=True)), streams={stream: target}) - _entry_workflow(NfPort("source", "path"), streams={stream: NfTemplate((segment, NfLiteral(".log")))}) +def _refusal(outcome: Any) -> tuple[Any, str | None] | None: + """The exception type and pattern `outcome` states, or None when it states that construction succeeds.""" + if isinstance(outcome, str): + return ValueError, outcome + if isinstance(outcome, tuple) and len(outcome) == 2 and (isinstance(outcome[0], type) or ( + isinstance(outcome[0], tuple) and all(isinstance(each, type) for each in outcome[0]))): + return outcome + return None -@pytest.mark.fast -@pytest.mark.parametrize(("name", "normalized"), [ - *((name, f"_{name}") for name in [*sorted(NEXTFLOW_SCRIPT_NAMES), "Math", "Élan", "if"]), ("9-café", "_9_café"), -]) -def test_no_name_takes_a_name_the_script_resolves(name: str, normalized: str) -> None: - assert normalize_nextflow_identifier(name) == normalized - assert normalize_nextflow_identifier(name, variable=False) == normalized +def _as_stated(build: Callable[[], Any], outcome: Any) -> str: + """Nothing when constructing as `build` does gives `outcome`; else what it gives.""" + refusal = _refusal(outcome) + try: + built = build() + except (ValueError, TypeError) as error: + stated = refusal is not None and isinstance(error, refusal[0]) and ( + refusal[1] is None or re.search(refusal[1], str(error)) is not None) + return "" if stated else f"raised {error!r}" + return "" if refusal is None and outcome in (None, built) else f"constructed {built!r}" @pytest.mark.fast -@pytest.mark.parametrize("name", sorted(NEXTFLOW_SCRIPT_DECLARED_NAMES - NEXTFLOW_SCRIPT_NAMES)) -def test_only_a_process_or_workflow_avoids_a_name_every_script_declares(name: str) -> None: - assert normalize_nextflow_identifier(name, variable=False) == f"_{name}" - assert normalize_nextflow_identifier(name) == name - with pytest.raises(ValueError, match="already declared by every Nextflow script"): - NfProcess(name, [], [output_port("o", "o.txt")], command("true")) - with pytest.raises(ValueError, match="already declared by every Nextflow script"): - ExecutableNextflowWorkflow(name, [], [], {}) +def test_an_ir_value_constructs_exactly_as_its_row_says() -> None: + """A malformed IR value, process or workflow is unrepresentable: construction refuses it, naming the field, or the + edge where connections and params disagree on channel kind, cardinality, scatter adapter, capture, optionality or + staging; its accepted neighbour constructs, as the canonical value where its row states one.""" + assert {name: problem for name, (build, outcome) in CONSTRUCTIONS.items() + if (problem := _as_stated(build, outcome))} == {} @pytest.mark.fast -@pytest.mark.parametrize(("glob", "capture"), [("*.log", None), ("maybe.txt", "single")], ids=["pattern", "single"]) -def test_an_optional_output_of_at_most_one_file_is_checked_at_its_workflow_output( - glob: str, capture: str | None -) -> None: - # Nextflow fails arity '1' when nothing matches, optional or not, and refuses '0..1'. - process = NfProcess( - "MAYBE", [], [NfPort("o", "path", "o", template(glob), capture=capture, optional=True)], command("true") - ) - with pytest.raises(ValueError, match="optional outputs o must match at most one file and must reach a workflow"): - ExecutableNextflowWorkflow("WF", [process], [], {}) - workflow = ExecutableNextflowWorkflow("WF", [process], [NfWorkflowOutputConnection("MAYBE", "o", "result")], {}) - rendered = render_nextflow(workflow) - assert "arity: '0..*', emit: o" in rendered and "optional: true" not in rendered +def test_a_name_is_an_identifier_exactly_as_nextflow_reads_it() -> None: + """A port takes a name Nextflow reads as an identifier, NAMES says which; normalizing a name the script resolves + to something else prefixes it; only a process or workflow avoids a name every script declares.""" + for name, valid in NAMES: + assert is_nextflow_identifier(name) is valid, name + if valid: + assert NfPort(name, "val").name == name + else: + with pytest.raises(ValueError, match="Nextflow identifier"): + NfPort(name, "val") + for name, normalized in [*((name, f"_{name}") for name in [*sorted(NEXTFLOW_SCRIPT_NAMES), "Math", "Élan", "if"]), + ("9-café", "_9_café")]: + assert (normalize_nextflow_identifier(name), normalize_nextflow_identifier(name, variable=False)) == ( + normalized, normalized), name + for name in sorted(NEXTFLOW_SCRIPT_DECLARED_NAMES - NEXTFLOW_SCRIPT_NAMES): + assert (normalize_nextflow_identifier(name, variable=False), normalize_nextflow_identifier(name)) == ( + f"_{name}", name) + with pytest.raises(ValueError, match="already declared by every Nextflow script"): + NfProcess(name, [], [output_port("o", "o.txt")], command("true")) + with pytest.raises(ValueError, match="already declared by every Nextflow script"): + ExecutableNextflowWorkflow(name, [], [], {}) diff --git a/tests/core/nextflow/test_float_text.py b/tests/core/nextflow/test_float_text.py index aae624ab5..286ed0f4b 100644 --- a/tests/core/nextflow/test_float_text.py +++ b/tests/core/nextflow/test_float_text.py @@ -10,13 +10,10 @@ from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl from sophios.api.python.workflow import Step, StepInput, Workflow -from sophios.input_output_nf import ( - NF_FLOAT_TEXT_FUNCTION, nextflow_params, render_nextflow, write_nextflow_artifacts, -) -from sophios.nf_types import NfPort, NfProcess, NfTemplate +from sophios.input_output_nf import write_nextflow_artifacts from .test_channels import _lower -from .testkit import command, execute_nextflow, output_port, ref, single_process_workflow, template +from .testkit import execute_nextflow def _doubles() -> list[float]: @@ -89,33 +86,3 @@ def test_every_float_reaches_the_command_as_python_prints_it(tmp_path: Path) -> expected = [*map(repr, doubles), *(str(json.loads(text)) for text in hand), given["a"], f"--b={given['b']}", given["c"], given["d"], "1e-07", "-0.0"] assert printed.splitlines() == expected - - -def _float_workflow(tokens: tuple[str | NfTemplate, ...], param_type: str) -> str: - process = NfProcess("SHOW", [NfPort("x", "val")], [output_port("result", "out.txt")], - command(*tokens, stdout="out.txt")) - return render_nextflow(single_process_workflow( - process, params={"x": 0.5}, param_types={"x": param_type}, output_port_name="result")) - - -@pytest.mark.fast -@pytest.mark.parametrize(("tokens", "param_type", "emitted"), [ - (("echo", template(ref("x"))), "float", True), - (("echo",), "float", False), - (("echo", template(ref("x"))), "string", False), -], ids=["rendered", "not-rendered", "no-float"]) -def test_the_float_text_helper_is_emitted_only_where_a_float_is_rendered( - tokens: tuple[str | NfTemplate, ...], param_type: str, emitted: bool, -) -> None: - assert (NF_FLOAT_TEXT_FUNCTION in _float_workflow(tokens, param_type)) is emitted - - -@pytest.mark.fast -def test_the_params_file_holds_each_float_as_its_python_text() -> None: - """A JSON number zero reaches Nextflow without its sign, so every float is written as the text the check reads.""" - process = NfProcess("SHOW", [NfPort("x", "val"), NfPort("xs", "val", is_array=True), NfPort("n", "val")], - [output_port("result", "out.txt")], command("echo", stdout="out.txt")) - workflow = single_process_workflow( - process, params={"x": -0.0, "xs": [1e-07, 5], "n": 2}, - param_types={"x": "float", "xs": "float[]", "n": "int"}, output_port_name="result") - assert nextflow_params(workflow) == {"x": "-0.0", "xs": ["1e-07", 5], "n": 2} diff --git a/tests/core/nextflow/test_import.py b/tests/core/nextflow/test_import.py index 47d12e183..805430b0b 100644 --- a/tests/core/nextflow/test_import.py +++ b/tests/core/nextflow/test_import.py @@ -1,282 +1,109 @@ -"""The import is the renderer's exact inverse over the workflows Sophios compiles (design §4.2): written files import -to a workflow that compiles back to the same model, layout-only rewrites included; edits stop at the line they name.""" +"""The import is the renderer's exact inverse over the workflows Sophios compiles (design §4.2): the pipeline of each +example workflow imports to a workflow that compiles back to the same model, layout-only rewrites included; an edit +outside the subset stops the import at the line it names.""" # pylint: disable=missing-function-docstring from collections.abc import Callable +import contextlib from contextlib import suppress from dataclasses import dataclass -from functools import cache +from functools import cache, partial import json import os from pathlib import Path import re -import shutil import tempfile import time from typing import Any -from hypothesis import given, strategies as st +from hypothesis import example, given, strategies as st import pytest from sophios.api.python._ports import ParameterNamespace from sophios.api.python.nextflow import import_nextflow from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl -from sophios.api.python.workflow import Inference, Step, StepInput, Workflow +from sophios.api.python.workflow import Inference, StepInput, Workflow from sophios.input_output_nf import ( NEXTFLOW_CONFIG, NEXTFLOW_PARAMS, NEXTFLOW_SCRIPT, NF_HELPER_FUNCTIONS, - Idiom, - Idioms, write_nextflow_artifacts, ) from sophios.lang.diagnostics import SophiosError from sophios.lang.error_codes import SophiosErrorCode from sophios.nf_reader import read_nextflow from sophios.nf_types import ExecutableNextflowWorkflow -from sophios.python_cwl_adapter import import_python_file from ..budgets import budget +from ..cases import DATA from ..hermetic import network_refused from ..provocations import IMPORT_EDITS, import_edited from .test_phase3_cells import calculator_workflow, predicates_workflow -from .test_real_world_examples import (flags_workflow, months_workflow, plan_workflow, summaries_workflow, - tallies_workflow) -from ..helpers import REPO_ROOT +from .testkit import example_workflow, examples - -def _echo(name: str, **inputs: Input) -> CommandLineTool: - """A tool that echoes its inputs in order into `.txt`.""" - return CommandLineTool(name, Inputs(**inputs), Outputs(out=Output(cwl.file, glob=f"{name}.txt"))).base_command( - "echo").stdout(f"{name}.txt") - - -def _bindings() -> Workflow: - """A flag, a prefixed array, a joined optional, both kinds of entry, a piped shell literal, variables, and - braces in globs: escaped in a pattern, kept as written in a literal name.""" - inputs = Inputs(v=Input(cwl.boolean, position=1, flag="-v"), - xs=Input(cwl.array(cwl.string), position=2, flag="--x"), - name=Input(cwl.string, required=False, position=3, flag="--name=", separate=False), - src=Input(cwl.file), out=Input(cwl.directory)) - tool = (CommandLineTool("bind", inputs, Outputs( - res=Output(cwl.directory, glob="$(inputs.out.basename)"), - one=Output(cwl.file, glob="one.txt", output_eval="$(self[0])"), - maybe=Output(cwl.file, glob="*.log", required=False), braced=Output(cwl.file, glob="a{b}.txt"), - named=Output(cwl.file, glob="$(inputs.out.basename)\\\\{x}"))) - .base_command("prog").argument("2>&1 | tee", shell_quote=False, position=4) - .argument("$(inputs.out.basename)", position=5).shell_command() - .stage(inputs.src, entryname="renamed.txt").stage(inputs.out, writable=True) - .stdout("o.txt").env_var("A", "lit $x").env_var("B", "$(inputs.name)")) - step = tool.to_step() - step.inputs.v, step.inputs.xs, step.inputs.src, step.inputs.out = True, ["p", "q"], "/data/s.txt", "/data/o" - step.inputs.name = "n" - workflow = Workflow([step], "bindings") - workflow.outputs.res, workflow.outputs.one, workflow.outputs.maybe = ( - step.outputs.res, step.outputs.one, step.outputs.maybe) - return workflow - - -def _crossproduct() -> Workflow: - """A conditional flat crossproduct gathered into an array, a step input picking a value, a conditional step - whose output's name holds a `_`, so the name of its channel, `ch_use_o_txt`, splits more than one way.""" - pair = _echo("pair", item=Input(cwl.string, position=1), tag=Input(cwl.string, position=2)).to_step() - use = CommandLineTool("use", Inputs(files=Input(cwl.array(cwl.file), position=1), n=Input(cwl.int, position=2)), - Outputs(o_txt=Output(cwl.file, glob="o.txt"))).base_command("cat").stdout( - "o.txt").to_step() - join = _echo("join", words=Input(cwl.string, position=1)).to_step() - workflow = Workflow([pair, use, join], "crossproduct") - pair.inputs.item, pair.inputs.tag = ["i", "j"], ["1", "2"] - pair.scatter_on(pair.inputs.item, pair.inputs.tag, method="flat_crossproduct") - use.inputs.files = pair.outputs.out - use.inputs.n = 3 - use.when = "$(inputs.n > 1)" - join.inputs.words = StepInput(source=[workflow.inputs.a.as_type("string?"), workflow.inputs.b.as_type("string?")], - link_merge="merge_nested", pick_value="first_non_null") - workflow.outputs.o, workflow.outputs.j = use.outputs.o_txt, join.outputs.out - return workflow - - -def _scatters(method: str) -> Callable[[], Workflow]: - def build() -> Workflow: - """A scatter over two inputs, an unscattered output into every task, and its outputs gathered.""" - first = _echo("first", word=Input(cwl.string, position=1)).to_step() - pair = _echo("pair", a=Input(cwl.string, position=1), b=Input(cwl.int, position=2), - context=Input(cwl.file, position=3)).to_step() - first.inputs.word = "context" - pair.inputs.a, pair.inputs.b, pair.inputs.context = ["x", "y"], [1, 2], first.outputs.out - pair.scatter_on(pair.inputs.a, pair.inputs.b, method=method) - steps: list[Step] = [first, pair] - if method != "nested_crossproduct": - report = CommandLineTool("report", Inputs(files=Input(cwl.array(cwl.file), position=1)), - Outputs(r=Output(cwl.file, glob="r.txt"))).base_command("cat").stdout("r.txt") - steps.append(report.to_step()) - steps[-1].inputs.files = pair.outputs.out - workflow = Workflow(steps, f"scatter_{method}") - workflow.outputs.pairs = pair.outputs.out - return workflow - return build - - -def _resources() -> Workflow: - """An image, cores, fractional memory, GPUs with a capability list, file text, and a float into a command.""" - tool = (CommandLineTool("res", Inputs(ratio=Input(cwl.float, position=1, flag="--ratio")), - Outputs(text=Output(cwl.string, glob="t.txt", load_contents=True, - output_eval="$(self[0].contents)"), - made=Output(cwl.directory, glob="made"))) - .base_command("run").docker("registry.io/a b:{1}'\"").resources(cores_min=2, ram_min=1.5) - .gpu(cuda_version_min="11.7", device_count_min=2, extra={"cudaComputeCapability": ["7.0", "8.0"]})) - step = tool.to_step() - step.inputs.ratio = 0.1 - workflow = Workflow([step], "resources") - workflow.outputs.text, workflow.outputs.made = step.outputs.text, step.outputs.made - return workflow - - -def _directories() -> Workflow: - """A Directory output into a Directory input, directly and gathered from a scatter.""" - make = CommandLineTool("make", Inputs(name=Input(cwl.string, position=1)), - Outputs(d=Output(cwl.directory, glob="$(inputs.name)"))).base_command("mkdir").to_step() - each = CommandLineTool("each", Inputs(dir=Input(cwl.directory, position=1), n=Input(cwl.string, position=2)), - Outputs(d=Output(cwl.directory, glob="$(inputs.n)"))).base_command("cp", "-r").to_step() - every = CommandLineTool("every", Inputs(dirs=Input(cwl.array(cwl.directory), position=1)), - Outputs(o=Output(cwl.file, glob="o.txt"))).base_command("ls").stdout("o.txt").to_step() - make.inputs.name = "made" - each.inputs.dir, each.inputs.n = make.outputs.d, ["a", "b"] - each.scatter_on(each.inputs.n) - every.inputs.dirs = each.outputs.d - workflow = Workflow([make, each, every], "directories") - workflow.outputs.o = every.outputs.o - return workflow - - -def _unary_whens() -> Workflow: - """Conditions of nested unary operators, whose canonical text is not a decrement, and of each spelling the - Groovy text writes as another's (`===`, `!==`, a unary `+`, null on the left, `!(x == null)`), with the other.""" - whens = ("$(-(-inputs.x) > 0)", "$(- -inputs.x > 0)", "$(+(+inputs.x) > 0)", "$(-(-3) > inputs.x)", - "$(inputs.s === 'it\"s' && !(inputs.o == null))", "$(inputs.s !== 'x' && null != inputs.o)") - steps = [_echo(f"w{index}", x=Input(cwl.int, position=1), s=Input(cwl.string, position=2), - o=Input(cwl.string, required=False)).to_step() for index in range(len(whens))] - workflow = Workflow(steps, "whens") - for step, when in zip(steps, whens): - step.inputs.x, step.inputs.s, step.inputs.o = 2, "it\"s", workflow.inputs.o.as_type("string?") - step.when = when - setattr(workflow.outputs, step.process_name, step.outputs.out) - return workflow - - -def _streams() -> Workflow: - """Each stream redirected, a shell literal `>` that is not one, and two adjacent shell literals, which the model - merges.""" - redirected = CommandLineTool("streams", Inputs(src=Input(cwl.file)), Outputs( - out=Output(cwl.file, glob="out.txt"), err=Output(cwl.file, glob="err.txt"))).base_command("cat").stdin( - "$(inputs.src.path)").stdout("out.txt").stderr("err.txt") - literal = CommandLineTool("literal", Inputs(), Outputs(o=Output(cwl.file, glob="o.txt"))).base_command( - "echo").argument(">", shell_quote=False, position=1).argument("o.txt", position=2).argument( - "&&", shell_quote=False, position=3).argument("true", shell_quote=False, position=4).shell_command() - first, second = redirected.to_step(), literal.to_step() - first.inputs.src = "/data/in.txt" - workflow = Workflow([first, second], "streams") - workflow.outputs.out, workflow.outputs.err, workflow.outputs.o = ( - first.outputs.out, first.outputs.err, second.outputs.o) - return workflow +#: The example workflows of tests/core/data/nextflow/runs, by name. +RUNS = [param.values[0].name for param in examples("runs")] +_FILES = (NEXTFLOW_SCRIPT, NEXTFLOW_PARAMS, NEXTFLOW_CONFIG) -def _merged() -> Workflow: - """Two outputs merged flat into one array input.""" - one, two = (_echo(name, w=Input(cwl.string, position=1)).to_step() for name in ("one", "two")) - cat = CommandLineTool("cat", Inputs(files=Input(cwl.array(cwl.file), position=1)), - Outputs(o=Output(cwl.file, glob="o.txt"))).base_command("cat").stdout("o.txt").to_step() - one.inputs.w, two.inputs.w = "1", "2" - workflow = Workflow([one, two, cat], "merged") - cat.inputs.files = StepInput(source=[one.outputs.out, two.outputs.out], link_merge="merge_flattened") - workflow.outputs.o = cat.outputs.o - return workflow +@cache +def _model(name: str) -> ExecutableNextflowWorkflow: + """The model the example `name` compiles to, read and compiled in a copy of its directory; `calculator` is the + subset differential's thirty conditions.""" + if name == "calculator": + return calculator_workflow().compile(target="nextflow").nextflow_workflow + with tempfile.TemporaryDirectory() as scratch: + directory = Path(scratch) / name + workflow = example_workflow(DATA / "nextflow" / "runs" / name, directory) + with contextlib.chdir(directory): + return workflow.compile(target="nextflow").nextflow_workflow -def _valued() -> Workflow: - """Values bound on workflow inputs: text CWL and Groovy escape, ints, files, an empty optional array; a required int - given to an optional binding, an optional int to a condition, a literal `$(` after a reference, a glob's brace.""" - count = CommandLineTool("count", Inputs( - word=Input(cwl.string, position=1), n=Input(cwl.int, required=False, position=2, flag="--n"), - files=Input(cwl.array(cwl.file), position=3), main=Input(cwl.file, position=4, flag="--in=", separate=False), - tag=Input(cwl.string, position=5, flag=" --tag=", separate=False), - extras=Input(cwl.array(cwl.string), position=6, flag="--extra")), - Outputs(o=Output(cwl.file, glob="$(inputs.word).txt"), braced=Output(cwl.file, glob="$(inputs.word){x}.txt")) - ).base_command("wc", "$(not) \\${x}").argument("a \\$(b) \\\\ c", position=7).stdout( - "$(inputs.word).txt").to_step() - again = _echo("again", word=Input(cwl.string, position=1), k=Input(cwl.int)).to_step() - again.when = "$(inputs.k > 1)" - workflow = Workflow([count, again], "valued") - word = workflow.inputs.word.as_type("string") - count.inputs.word, count.inputs.n, again.inputs.word = word, workflow.inputs.n.as_type("int"), word - count.inputs.files, count.inputs.main = workflow.inputs.files.as_type("File[]"), "/data/main.txt" - count.inputs.tag, again.inputs.k = "t", workflow.inputs.k.as_type("int") - count.inputs.extras = workflow.inputs.extras.as_type("string[]?") - workflow.inputs.unread.as_type("string") - workflow.inputs.word, workflow.inputs.n, workflow.inputs.k, workflow.inputs.unread = "w'\"$x", 3, 2, "kept" - workflow.inputs.files, workflow.inputs.extras = ["/data/a.txt", {"class": "File", "path": "/data/b.txt"}], [] - workflow.outputs.o, workflow.outputs.again = count.outputs.o, again.outputs.out - return workflow +@cache +def _texts(name: str | None) -> dict[str, str]: + """The three files written for the example `name`, or for the one-step workflow `import_edited` writes (None).""" + with tempfile.TemporaryDirectory() as directory: + if name is None: + import_edited(directory, NEXTFLOW_SCRIPT, "", "") + else: + write_nextflow_artifacts(_model(name), directory) + return {file: (Path(directory) / file).read_text(encoding="utf-8") for file in _FILES} -def _renamed() -> Workflow: - """Names normalization gives a leading `_`, which the import keeps: a capitalized step with a value written on - it, a capitalized tool input, workflow input and workflow output, and a reserved step name.""" - fetch = _echo("Fetch", word=Input(cwl.string, position=1), N=Input(cwl.int, position=2)).to_step() - task = _echo("task", word=Input(cwl.string, position=1)).to_step() - workflow = Workflow([fetch, task], "renamed") - fetch.inputs.word, fetch.inputs.N, task.inputs.word = "x", workflow.inputs.X.as_type("int"), "y" - workflow.inputs.X = 1 - workflow.outputs.Out, workflow.outputs.t = fetch.outputs.out, task.outputs.out - return workflow +def _imported(directory: Path) -> ExecutableNextflowWorkflow: + return import_nextflow(directory).compile(target="nextflow", inference=Inference(enabled=False)).nextflow_workflow -def _nested() -> Workflow: - """A subworkflow, inlined, whose input comes from an outer step.""" - write = _echo("write", message=Input(cwl.string, position=1)).to_step() - write.inputs.message = "nested composition" - copy = CommandLineTool("copy_file", Inputs(source=Input(cwl.file, position=1)), - Outputs(result=Output(cwl.file, glob="copy.txt"))).base_command("cp").argument( - "copy.txt", position=2).to_step(step_name="inner_copy") - child = Workflow([copy], "child") - copy.inputs.source = child.inputs.source - child.inputs.source = write.outputs.out - child.outputs.result = copy.outputs.result - workflow = Workflow([write, child], "root") - workflow.outputs.copied = child.outputs.result - return workflow +def _echo(name: str, **inputs: Input) -> CommandLineTool: + """A tool that echoes its inputs in order into `.txt`.""" + return CommandLineTool(name, Inputs(**inputs), Outputs(out=Output(cwl.file, glob=f"{name}.txt"))).base_command( + "echo").stdout(f"{name}.txt") -def _conditions() -> Workflow: - """A condition on a step of one input, which branches that input's channel, and on a scattered step, which - branches the scatter combined with its other inputs, one of them an optional File with a value.""" - one = _echo("one", n=Input(cwl.int, position=1)).to_step() - each = _echo("each", word=Input(cwl.string, position=1), n=Input(cwl.int, position=2), - f=Input(cwl.file, required=False)).to_step() - workflow = Workflow([one, each], "conditions") - one.inputs.n, one.when = 2, "$(inputs.n > 1)" - each.inputs.word, each.inputs.n, each.inputs.f = ["a", "b"], 3, workflow.inputs.f.as_type("File?") - workflow.inputs.f = "/data/f.txt" - each.scatter_on(each.inputs.word) - each.when = "$(inputs.n > 2)" - workflow.outputs.one, workflow.outputs.each = one.outputs.out, each.outputs.out - return workflow +@pytest.mark.parametrize("name", RUNS) +def test_the_pipeline_of_an_example_imports_to_its_model( + name: str, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """The three files written for each example of tests/core/data/nextflow/runs, alone in a directory and read with + the network refused, import to a workflow that compiles to the model they were written from; no path a parameter + names is looked at: not `nextflow_workflow.json`, no tool registry, no input file.""" + model = _model(name) + for file, text in _texts(name).items(): + (tmp_path / file).write_text(text, encoding="utf-8") + named = {item["path"] for value in model.to_dict()["params"].values() + for item in (value if isinstance(value, list) else [value]) if isinstance(item, dict)} + looked: list[str] = [] + stat = os.stat + def recording(path: Any, *args: Any, **kwargs: Any) -> os.stat_result: + looked.append(os.fspath(path) if isinstance(path, (str, os.PathLike)) else str(path)) + return stat(path, *args, **kwargs) -def _file_references() -> Workflow: - """`.path` references, which the import writes back with `.path`, since CWL reads a plain File or Directory - reference as the object: an argument that starts with one, and an entry's glob, alone and inside text.""" - fill = CommandLineTool("fill", Inputs(src=Input(cwl.file), out=Input(cwl.directory)), Outputs( - filled=Output(cwl.directory, glob="$(inputs.out.path)"), - copy=Output(cwl.file, glob="$(inputs.out.path)/copy.txt"))).base_command("cp").argument( - "$(inputs.src.path)", position=1).argument("$(inputs.out.path)/copy.txt", position=2) - step = fill.stage(fill.inputs.out, writable=True).to_step() - step.inputs.src, step.inputs.out = "/data/in.txt", "/data/out" - workflow = Workflow([step], "file_references") - workflow.outputs.filled, workflow.outputs.copy = step.outputs.filled, step.outputs.copy - return workflow + monkeypatch.setattr(os, "stat", recording) + with network_refused() as attempts: + imported = _imported(tmp_path) + assert (imported, attempts, named & set(looked)) == (model, [], set()) def _flag_first() -> Workflow: @@ -287,66 +114,9 @@ def _flag_first() -> Workflow: return Workflow([step], "flag_first") -def _cookbook(name: str, **values: Any) -> Callable[[], Workflow]: - """A cookbook workflow over this checkout's tools, its inputs given `values`.""" - def build() -> Workflow: - module = import_python_file(f"cookbook_{name}", REPO_ROOT / "docs" / "cookbook" / f"{name}.py") - setattr(module, "ADAPTERS", REPO_ROOT / "cwl_adapters") - workflow: Workflow = module.workflow() - for key, value in values.items(): - setattr(workflow.inputs, key, value) - return workflow - return build - - -def _waits() -> Workflow: - """A step-only input fed by a step output (resolved-view design §9, example 2): echo reads nothing of touch's, - and runs after it.""" - touch = Step(clt_path=REPO_ROOT / "cwl_adapters" / "touch.cwl") - echo = Step(clt_path=REPO_ROOT / "cwl_adapters" / "echo.cwl") - touch.inputs.filename, echo.inputs.message = "db", "query" - workflow = Workflow([touch, echo], "waits") - echo.inputs.after = StepInput(source=touch.outputs.file) - workflow.outputs.said = echo.outputs.stdout - return workflow - - -CASES: dict[str, Callable[[], Workflow]] = { - "bindings": _bindings, "crossproduct": _crossproduct, "dotproduct": _scatters("dotproduct"), - "flat_crossproduct": _scatters("flat_crossproduct"), "nested_crossproduct": _scatters("nested_crossproduct"), - "resources": _resources, "directories": _directories, "unary_whens": _unary_whens, "streams": _streams, - "merged": _merged, "valued": _valued, "renamed": _renamed, "nested": _nested, "conditions": _conditions, - "file_references": _file_references, "flag_first": _flag_first, - # Step-only inputs a process carries: one a when reads, and one fed by a step output. - "when": _cookbook("when", loud=True), "greeting_if": _cookbook("greeting_if", show=False), "waits": _waits, - # The one workflow in examples/ the Nextflow target compiles. - "helloworld_pyapi": lambda: import_python_file( - "helloworld_pyapi", REPO_ROOT / "examples" / "scripts" / "helloworld_pyapi.py").workflow(), - "plan": plan_workflow, "months": lambda: months_workflow(Path("/data")), "summaries": summaries_workflow, - "tallies": tallies_workflow, "flags": flags_workflow, - "calculator": calculator_workflow, "predicates": predicates_workflow, -} -_FILES = (NEXTFLOW_SCRIPT, NEXTFLOW_PARAMS, NEXTFLOW_CONFIG) - - -def _compiled(name: str) -> ExecutableNextflowWorkflow: - return CASES[name]().compile(target="nextflow").nextflow_workflow - - -def _imported(directory: Path) -> ExecutableNextflowWorkflow: - return import_nextflow(directory).compile(target="nextflow", inference=Inference(enabled=False)).nextflow_workflow - - -@pytest.mark.parametrize("name", CASES) -def test_the_import_of_a_compiled_pipeline_compiles_to_its_model(name: str, tmp_path: Path) -> None: - model = _compiled(name) - write_nextflow_artifacts(model, tmp_path) - assert _imported(tmp_path) == model - - def test_a_pipeline_v0_7_0_wrote_imports() -> None: """v0.7.0 indented a script's lines, and wrote a command that starts with a flag without parentheses.""" - assert _imported(Path(__file__).parents[1] / "data" / "nextflow" / "v0.7.0") == _compiled("flag_first") + assert _imported(DATA / "nextflow" / "v0.7.0") == _flag_first().compile(target="nextflow").nextflow_workflow # Text with what CWL, Groovy and the shell each escape. A base command is not interpolated, so any text is @@ -433,51 +203,15 @@ def _generated(draw: st.DrawFn) -> Workflow: @budget(100) @given(_generated()) +@example(calculator_workflow()) +@example(predicates_workflow()) def test_the_import_of_a_generated_tool_compiles_to_its_model(workflow: Workflow) -> None: + """Pinned: the conditions the subset differential runs, which each operator of the subset writes.""" compiled = workflow.compile(target="nextflow") with tempfile.TemporaryDirectory() as directory: assert _imported(compiled.write(directory)) == compiled.nextflow_workflow -#: The forms the reader reads by filling them and looking up what it read, as `ch_{process}_{emit}` splits more -#: than one way: the reader matches every other form. -_LOOKED_UP = (Idioms.PROCESS_OUTPUT, Idioms.CONDITIONAL_OUTPUT) - - -def test_every_idiom_is_written_and_read_for_some_case(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """For some case, the renderer fills each form with holes in the idiom table, and the reader matches it.""" - used: set[Idiom] = set() - - def recording(method: Callable[..., Any]) -> Callable[..., Any]: - def record(idiom: Idiom, *args: Any, **holes: Any) -> Any: - if found := method(idiom, *args, **holes): - used.add(idiom) - return found - return record - - with monkeypatch.context() as patch: - patch.setattr(Idiom, "fill", recording(Idiom.fill)) - for name in CASES: - write_nextflow_artifacts(_compiled(name), tmp_path / name) - filled = set(used) - used.clear() - with monkeypatch.context() as patch: - patch.setattr(Idiom, "match", recording(Idiom.match)) - patch.setattr(Idiom, "find", recording(Idiom.find)) - for name in CASES: - read_nextflow(tmp_path / name) - idioms = {name: idiom for name, idiom in vars(Idioms).items() if isinstance(idiom, Idiom)} - assert [name for name, idiom in idioms.items() if idiom not in filled] == [] - assert [name for name, idiom in idioms.items() if idiom not in used and idiom not in _LOOKED_UP] == [] - - -def test_every_hole_is_read_once() -> None: - """Each hole of each form, named the first time or again, opens an atomic group that ends where the next hole's - opens: matching never goes back into a hole it has read, so it is linear in the length of the line.""" - patterns = {name: idiom.pattern.pattern for name, idiom in vars(Idioms).items() if isinstance(idiom, Idiom)} - assert [name for name, pattern in patterns.items() if pattern.count("(?P") != pattern.count("(?>(?P")] == [] - - _STRINGS = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"") @@ -599,128 +333,110 @@ class Layout: ) -def _everything(files: dict[str, str], layouts: tuple[Layout, ...] = LAYOUTS) -> dict[str, str]: - # The process blocks are found by their unchanged layout, so they move first. - for layout in layouts: - files = layout.apply(files) - return files - - -LAYOUTS += (Layout("all at once", _everything, "Each rewrite above is layout, so their composition is."),) - - -@pytest.mark.parametrize("layout", LAYOUTS, ids=[layout.name for layout in LAYOUTS]) -@pytest.mark.parametrize("name", CASES) -def test_layout_leaves_the_import_unchanged(layout: Layout, name: str, tmp_path: Path) -> None: - model = _compiled(name) - write_nextflow_artifacts(model, tmp_path) - files = {file: (tmp_path / file).read_text(encoding="utf-8") for file in _FILES} - for file, text in layout.apply(files).items(): - (tmp_path / file).write_bytes(text.encode("utf-8")) - assert _imported(tmp_path) == model +@budget(10) +@given(chosen=st.sets(st.sampled_from(LAYOUTS))) +@example(chosen=set(LAYOUTS)) +def test_layout_leaves_the_import_unchanged(chosen: set[Layout]) -> None: + """Any of the rewrites above, alone or together, applied to the pipeline of each example: the import is the model + the pipeline was written from. Every pipeline is rewritten for every set drawn, and for all the rewrites at once.""" + for name in RUNS: + files = _texts(name) + # In the order above: the process blocks are found by their unchanged layout, so they move first. + for layout in LAYOUTS: + files = layout.apply(files) if layout in chosen else files + with tempfile.TemporaryDirectory() as scratch: + for file, text in files.items(): + (Path(scratch) / file).write_bytes(text.encode("utf-8")) + assert _imported(Path(scratch)) == _model(name), name _CODE = SophiosErrorCode _DEEP = 3000 # nested deeper than Python's default recursion limit, 1000 -# More edits than one per code: the constructs the import is most often handed. -_EDITS = [ - *((code, *edit) for code, edit in IMPORT_EDITS.items()), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, " greet(message)\n", " greet(message.view())\n", ".view()"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "nextflow.enable.dsl=2\n", - "nextflow.enable.dsl=2\ninclude { X } from './x'\n", "include"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "\nworkflow {\n", - "\nworkflow.onComplete { println('done') }\nworkflow {\n", "onComplete"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, " input:\n", " cpus params.threads\n input:\n", "cpus"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, " greet(message)\n", - " greet(message)\n other(message)\n", "other("), - # A second block of a process, which nothing else would read. - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "\nworkflow provoke {\n", - '\nprocess greet {\n script:\n """\n rm o\n """\n}\n\nworkflow provoke {\n', "process greet"), - (_CODE.IMPORT_FOREIGN_SCRIPT, NEXTFLOW_SCRIPT, " exit 1\n", " exit 0\n", "stub:"), - (_CODE.IMPORT_MISMATCH, NEXTFLOW_SCRIPT, " val message\n", " val message, arity: '1'\n", "arity"), - # Only a command with no shell literal is written on one line, where a literal's `;` would end the command. - (_CODE.IMPORT_MISMATCH, NEXTFLOW_SCRIPT, "('echo')} ", "('echo')} ; ", "('echo')} ;"), - # Text after a script's opening quotes is in the script, quotes open one only after `script:` or `stub:`, and a - # lone carriage return ends no line. - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, ' script:\n """\n', ' script:\n """ \n', '"""'), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, " input:\n", ' input:\n """\n', '"""'), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, " input:\n", " input:\r", "input:"), - # A value the compile writes otherwise, as a text parameter's 3 is "3", or not at all. - (_CODE.IMPORT_PARAMS, NEXTFLOW_PARAMS, '"hi"', "3", '"message": 3'), - (_CODE.IMPORT_PARAMS, NEXTFLOW_PARAMS, '"hi"', "null", '"message": null'), - # The compile renames a capitalized workflow, and refuses an empty command word. - (_CODE.IMPORT_UNWRITABLE, NEXTFLOW_SCRIPT, "provoke", "Provoke", "workflow Provoke"), - (_CODE.IMPORT_UNWRITABLE, NEXTFLOW_SCRIPT, "('echo')", "('')", "workflow provoke"), - # After a script's closing quotes, a comment is layout but code is not. - (_CODE.IMPORT_FOREIGN_DECLARATION, NEXTFLOW_SCRIPT, ' """\n\n stub:', ' """ x\n\n stub:', " x"), - # A byte that is not UTF-8, the 0xff \udcff stands for, in each file; nesting deeper than Python recurses in a - # call, a script's interpolation and the params file; and an integer longer than Python converts. - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, " val message\n", " val message // \udcff\n", - "val message"), - (_CODE.IMPORT_PARAMS, NEXTFLOW_PARAMS, '"hi"', '"h\udcffi"', '"message"'), - (_CODE.IMPORT_CONFIG, NEXTFLOW_CONFIG, "false", "false // \udcff", "false //"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "greet(message)", - "greet(" + "(" * _DEEP + "message" + ")" * _DEEP + ")", "greet((("), - (_CODE.IMPORT_FOREIGN_SCRIPT, NEXTFLOW_SCRIPT, "${__sophios_shell_quote_9f72e('echo')}", - "${" + "(" * _DEEP + "__sophios_shell_quote_9f72e('echo')" + ")" * _DEEP + "}", "${((("), - (_CODE.IMPORT_PARAMS, NEXTFLOW_PARAMS, '"hi"', "[" * _DEEP + "]" * _DEEP, '"message": [[['), - (_CODE.IMPORT_PARAMS, NEXTFLOW_PARAMS, '"hi"', "9" * 5000, "{"), -] -# A value Sophios never writes, on each kind of line that holds one, in a case whose pipeline has that line: the -# import stops at that line, not at the process or workflow the line is in. -_VALUE_EDITS = [ - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "container 'registry.io/a b:{1}\\'\"'", "container ''", - "container ''", "resources"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "cpus 2", "cpus 0", "cpus 0", "resources"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, 'memory "1.5 MB"', 'memory "0 MB"', 'memory "0 MB"', "resources"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "cudaVersionMin: '11.7'", "cudaVersionMin: ['11.7']", - "cudaVersionMin: ['11.7']", "resources"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "Directory: ['made']", "Directory: [made]", "Directory: [made]", - "resources"), - (_CODE.IMPORT_FOREIGN_DECLARATION, NEXTFLOW_SCRIPT, 'path "${word}.txt"', 'path "${word.size()}.txt"', - "word.size()", "valued"), - (_CODE.IMPORT_FOREIGN_SCRIPT, NEXTFLOW_SCRIPT, "('wc')", "('\\u0000')", "('\\u0000')", "valued"), - (_CODE.IMPORT_FOREIGN_SCRIPT, NEXTFLOW_SCRIPT, "('renamed.txt')}\n", "('a/b')}\n", "('a/b')", "bindings"), - (_CODE.IMPORT_FOREIGN_SCRIPT, NEXTFLOW_SCRIPT, "('lit $x')", "('\\u0000')", "export A=", "bindings"), - # The command of a parenthesized script is on the line after `(`, and its redirects on the `)` line. - (_CODE.IMPORT_FOREIGN_SCRIPT, NEXTFLOW_SCRIPT, "('prog')", "('\\u0000')", "('\\u0000')", "bindings"), - (_CODE.IMPORT_FOREIGN_SCRIPT, NEXTFLOW_SCRIPT, ") > ${", ") >> ${", ") >>", "bindings"), - # A number that is not a finite decimal, a string outside the subset, and a condition that is not a boolean. - *((_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "Double.valueOf('1')", f"Double.valueOf({number})", - f"Double.valueOf({number})", "valued") for number in ("'0x1'", "'abc'", "'1e999'")), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "(__w1 == 'it\"s')", "(__w1 == 'é')", "'é'", "unary_whens"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "run: (((__w1) as double) > Double.valueOf('1'))", - "run: Double.valueOf('1')", "run: Double.valueOf('1')", "valued"), - # A channel no statement makes, where a merge, a scatter or a branch reads it. - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "word.merge(k)", "word.merge(nope)", "merge(nope)", "valued"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, ".merge(o) {", ".merge(nope) {", ".merge(nope)", "unary_whens"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "= pair_a.map", "= nope.map", "nope.map", "dotproduct"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "= one_1_n.branch", "= nope.branch", "nope.branch", "conditions"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, ".combine(each_2_n.map", ".combine(nope.map", ".combine(nope", - "conditions"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "'merge_nested', 'first_non_null')", "'bogus', 'first_non_null')", - "'bogus'", "crossproduct"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "params.word, 'string')", "params.word, 'strin')", "'strin'", - "valued"), - # A carrier names exactly the process's last val inputs, in order. - (_CODE.IMPORT_MISMATCH, NEXTFLOW_SCRIPT, "WorkflowStepInput: ['enabled']", "WorkflowStepInput: ['message']", - "WorkflowStepInput", "when"), - # A key another value names, and an absent optional File, which has no lowering. - (_CODE.IMPORT_PARAMS, NEXTFLOW_PARAMS, '"a": [],\n "b": []', '"a": "b",\n "b": 3', '"b": 3', "crossproduct"), - (_CODE.IMPORT_PARAMS, NEXTFLOW_PARAMS, '"f": {\n "class": "File",\n "path": "/data/f.txt"\n }', '"f": []', - '"f": []', "conditions"), - # Nesting deeper than Python recurses in a string's interpolation, and in a condition. - (_CODE.IMPORT_FOREIGN_DECLARATION, NEXTFLOW_SCRIPT, 'path "${word}.txt"', - 'path "${' + "(" * _DEEP + "word" + ")" * _DEEP + '}.txt"', 'path "${(((', "valued"), - (_CODE.IMPORT_FOREIGN_STATEMENT, NEXTFLOW_SCRIPT, "run: (((__w1) as double) > Double.valueOf('1'))", - "run: " + "(!" * _DEEP + "(((__w1) as double) > Double.valueOf('1'))" + ")" * _DEEP, "run: (!(!", "valued"), -] -_ALL_EDITS = [*((*edit, None) for edit in _EDITS), *_VALUE_EDITS] - - -def test_the_unedited_pipeline_imports(tmp_path: Path) -> None: - """The pipeline every edit below starts from is one the import reads.""" - assert isinstance(import_edited(str(tmp_path), NEXTFLOW_SCRIPT, "", ""), Workflow) +_NF, _PARAMS = NEXTFLOW_SCRIPT, NEXTFLOW_PARAMS +#: An edit: the code the import stops with, the file edited, the text replaced wherever it occurs (or the texts, each +#: by its own), its replacement, and text on the line the import stops at. +Edit = tuple[SophiosErrorCode, str, str | tuple[str, ...], str | tuple[str, ...], str] +#: Edits of a pipeline, by the pipeline: an example's, or the one-step pipeline `import_edited` writes (None). One +#: edit per code; then text Sophios never writes, each where a check that no other edit reaches reads it. +EDITS: dict[str, tuple[str | None, list[Edit]]] = { + "one per code": (None, [(code, *edit) for code, edit in IMPORT_EDITS.items()]), + "one step": (None, [ + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, " greet(message)\n", " greet(message.view())\n", ".view()"), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, " greet(message)\n", " greet(message)\n other(message)\n", + "other("), + # A second block of a process, which nothing else would read, and a process after a workflow. + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "\nworkflow provoke {\n", + '\nprocess greet {\n script:\n """\n rm o\n """\n}\n\nworkflow provoke {\n', "process greet"), + (_CODE.IMPORT_MISMATCH, _NF, "\nworkflow provoke {\n", + "\nworkflow first {\n}\n\nprocess other {\n}\n\nworkflow provoke {\n", "process other"), + # A lone carriage return ends no line; after a script's closing quotes, a comment is layout but code is not. + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, " input:\n", " input:\r", "input:"), + (_CODE.IMPORT_FOREIGN_DECLARATION, _NF, ' """\n\n stub:', ' """ x\n\n stub:', " x"), + # The stub is Sophios's, word for word; a command on one line holds no shell literal, whose `;` would end it. + (_CODE.IMPORT_FOREIGN_SCRIPT, _NF, " exit 1\n", " exit 0\n", "stub:"), + (_CODE.IMPORT_MISMATCH, _NF, "('echo')} ", "('echo')} ; ", "('echo')} ;"), + (_CODE.IMPORT_FOREIGN_SCRIPT, _NF, "${__sophios_shell_quote_9f72e('echo')}", + "${" + "(" * _DEEP + "__sophios_shell_quote_9f72e('echo')" + ")" * _DEEP + "}", "${((("), + # The compile renames a capitalized workflow and refuses an empty command word; the tool builder keeps the + # port name `keys` for a method; a parameter's value is never null. + (_CODE.IMPORT_UNWRITABLE, _NF, "provoke", "Provoke", "workflow Provoke"), + (_CODE.IMPORT_UNWRITABLE, _NF, "('echo')", "('')", "workflow provoke"), + (_CODE.IMPORT_UNWRITABLE, _NF, (" val message\n", "(message.toString())"), + (" val keys\n", "(keys.toString())"), "process greet"), + (_CODE.IMPORT_PARAMS, _PARAMS, '"hi"', "null", '"message": null'), + # Lines of tens of KB that nearly match a form with several holes: one after a merge, which the reader tries + # as the merge's next step, and one in `main:`, where it tries every statement as a scatter's shape. + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, " greet(message)\n", + " ch_greet_in = a.merge(b) { __w0, __w1 -> tuple(__w0, __w1) }\n .merge(" + + "a) { __merged, b -> tuple(" * 1000 + "}" * 1000 + "\n greet(message)\n", ".merge(a) { __merged"), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, " greet(message)\n", + " ch_greet_shape = " + "a.map { b -> [[" * 1000 + "}" * 1000 + "\n greet(message)\n", + "ch_greet_shape = a.map"), + ]), + "commands": ("commands", [ + (_CODE.IMPORT_FOREIGN_DECLARATION, _NF, 'path "${filename}"', + 'path "${' + "(" * _DEEP + "filename" + ")" * _DEEP + '}"', 'path "${((('), + (_CODE.IMPORT_FOREIGN_SCRIPT, _NF, "('hello there')", "('\\u0000')", "export GREETING="), + # The command of a parenthesized script is on the line after `(`, and its redirects on the `)` line. + (_CODE.IMPORT_FOREIGN_SCRIPT, _NF, ") > ${", ") >> ${", ") >>"), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "params.emit_message, 'string')", "params.emit_message, 'strin')", + "'strin'"), + # A float parameter's value is its text, "2.5": never a number, nor text that is no finite float. + *((_CODE.IMPORT_PARAMS, _PARAMS, '"print_bindings_scale": "2.5"', f'"print_bindings_scale": {value}', + f'"print_bindings_scale": {value}') for value in ("2", '"x"', '"1e999"')), + ]), + "resources": ("resources", [ + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, " cpus 2\n", " container ''\n cpus 2\n", "container ''"), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, 'memory "64 MB"', 'memory "0 MB"', 'memory "0 MB"'), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "cudaVersionMin: '11.4'", "cudaVersionMin: ['11.4']", + "cudaVersionMin: ['11.4']"), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "Directory: ['result']", "Directory: [result]", "Directory: [result]"), + ]), + "conditions_and_scatter": ("conditions_and_scatter", [ + # A string outside the subset; a channel no statement makes; a carrier names exactly the last val inputs. + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "(__w0 != 'b')", "(__w0 != 'é')", "'é'"), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "= pair_unless_b_first.map", "= nope.map", "nope.map"), + (_CODE.IMPORT_MISMATCH, _NF, "WorkflowStepInput: ['enabled']", "WorkflowStepInput: ['go']", + "WorkflowStepInput"), + ]), + "calculator": ("calculator", [ + # A condition nested deeper than Python recurses; a number literal that is not finite; an operand, a check's + # parts and a check's value each as no compile writes them. + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "run: (Double.valueOf('3') == Double.valueOf('3'))", + "run: " + "(!" * _DEEP + "(Double.valueOf('3') == Double.valueOf('3'))" + ")" * _DEEP, "run: (!(!"), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "run: (Double.valueOf('3') == Double.valueOf('3'))", + "run: (Double.valueOf('3') == Double.valueOf('1e999'))", "Double.valueOf('1e999')"), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "run: (Double.valueOf('3') == Double.valueOf('3'))", + "run: (Double.valueOf('3') == three)", "three)"), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "7.5)', '(inputs.i + 0.5)'", "7.5)'; '(inputs.i + 0.5)'", + "; '(inputs.i + 0.5)'"), + (_CODE.IMPORT_FOREIGN_STATEMENT, _NF, "__sophios_round_9f72e(Double.valueOf('1e19'))", + "Double.valueOf('1e19')", "Double.valueOf('1e19'), 'c12"), + ]), + "staging": ("staging", [ + (_CODE.IMPORT_FOREIGN_SCRIPT, _NF, "('renamed.txt')}\n", "('a/b')}\n", "('a/b')"), + ]), +} def _stops(code: SophiosErrorCode, path: Path, at: str, importing: Callable[[], object]) -> None: @@ -728,65 +444,101 @@ def _stops(code: SophiosErrorCode, path: Path, at: str, importing: Callable[[], with pytest.raises(SophiosError) as caught: importing() (diagnostic,) = caught.value.diagnostics - assert diagnostic.code is code, diagnostic - assert diagnostic.span is not None and Path(diagnostic.span.file) == path + assert diagnostic.code is code, (at, diagnostic) + assert diagnostic.span is not None and Path(diagnostic.span.file) == path, (at, diagnostic) assert at in path.read_bytes().decode("utf-8", "surrogateescape").split("\n")[diagnostic.span.start_line - 1] - assert at in diagnostic.message + assert at in diagnostic.message, diagnostic -@pytest.mark.parametrize("code, file, old, new, at, case", _ALL_EDITS, ids=[ - f"{edit[0].name}-{edit[4]!r}" + (f"-{edit[5]}" if edit[5] else "") for edit in _ALL_EDITS]) -def test_an_edit_outside_the_subset_stops_the_import_at_its_line( - code: SophiosErrorCode, file: str, old: str, new: str, at: str, case: str | None, tmp_path: Path) -> None: - workflow = CASES[case]() if case else None - _stops(code, tmp_path / file, at, lambda: import_edited(str(tmp_path), file, old, new, workflow)) - - -# Lines of tens of KB that nearly match a form with several holes: one after a merge, which the reader tries as the -# merge's next step, and one in `main:`, where it tries every statement as a scatter's shape. -_NEAR_MISSES = { - "merge": (" ch_greet_in = a.merge(b) { __w0, __w1 -> tuple(__w0, __w1) }\n .merge(" - + "a) { __merged, b -> tuple(" * 1000 + "}" * 1000 + "\n", ".merge(a) { __merged"), - "shape": (" ch_greet_shape = " + "a.map { b -> [[" * 1000 + "}" * 1000 + "\n", "ch_greet_shape = a.map"), -} +def _edited(directory: Path, pipeline: str | None, file: str, old: str | tuple[str, ...], + new: str | tuple[str, ...]) -> Workflow: + """The files `_texts(pipeline)`, each `old` replaced by its `new` in `file`, written into `directory`, imported.""" + olds, news = (old,) if isinstance(old, str) else old, (new,) if isinstance(new, str) else new + for name, text in _texts(pipeline).items(): + if name == file: + for replaced, replacement in zip(olds, news, strict=True): + assert replaced in text, replaced + text = text.replace(replaced, replacement) + (directory / name).write_text(text, encoding="utf-8") + return import_nextflow(directory) -@pytest.mark.parametrize("lines, at", _NEAR_MISSES.values(), ids=list(_NEAR_MISSES)) -def test_a_long_near_miss_stops_the_import_at_its_line(lines: str, at: str, tmp_path: Path) -> None: - """A line of tens of KB that nearly matches a form stops the import at its line, as other text Sophios does not - write does, and within seconds: each hole is read once, so the time is linear in the line's length.""" - call = " greet(message)\n" - started = time.perf_counter() - _stops(_CODE.IMPORT_FOREIGN_STATEMENT, tmp_path / NEXTFLOW_SCRIPT, at, - lambda: import_edited(str(tmp_path), NEXTFLOW_SCRIPT, call, lines + call)) - assert time.perf_counter() - started < 5.0 - - -@cache -def _bytes(name: str) -> dict[str, bytes]: - """The three files written for a case.""" - with tempfile.TemporaryDirectory() as directory: - write_nextflow_artifacts(_compiled(name), directory) - return {file: (Path(directory) / file).read_bytes() for file in _FILES} +@pytest.mark.parametrize("pipeline, edits", EDITS.values(), ids=EDITS) +def test_an_edit_outside_the_subset_stops_the_import_at_its_line( + pipeline: str | None, edits: list[Edit], tmp_path: Path) -> None: + """Each edit stops the import with its code, at a line that holds the text the edit names (`_stops`), and within + seconds: each hole of a form is read once, so a line of tens of KB that nearly matches one is read in linear + time.""" + for index, (code, file, old, new, at) in enumerate(edits): + directory = tmp_path / str(index) + directory.mkdir() + started = time.perf_counter() + _stops(code, directory / file, at, partial(_edited, directory, pipeline, file, old, new)) + assert time.perf_counter() - started < 5.0, at + + +def _unread(tmp_path: Path, name: str) -> Path: + """A one-step pipeline holding a parameter no step reads, named `name` in all three files.""" + step = _echo("greet", message=Input(cwl.string, position=1)).to_step() + workflow = Workflow([step], "unread") + step.inputs.message = "hi" + workflow.inputs.placeholder.as_type("string") # pylint: disable=no-member + workflow.inputs.placeholder = "kept" + workflow.outputs.out = step.outputs.out + workflow.compile(target="nextflow").write(tmp_path) + for file in _FILES: + path = tmp_path / file + path.write_text(path.read_text(encoding="utf-8").replace("placeholder", name), encoding="utf-8") + return tmp_path + + +#: Words the pipeline `_unread` writes, which a parameter's name would be read as. +_WRITTEN = re.compile(r"\w+") + + +@budget(30) +@given(st.sampled_from(sorted(dir(ParameterNamespace))) | st.from_regex(r"_{0,2}[a-z][a-z0-9_]{0,5}", fullmatch=True)) +@example("keys") +@example("_items") +@example("_store") +@example("__x__") +def test_a_parameter_imports_exactly_when_a_python_workflow_can_take_its_input(name: str) -> None: + """A parameter is a workflow input: a pipeline whose parameter is renamed `name` imports exactly when + `flow.inputs. = value` works. An attribute of the port namespace, such as `_store`, is read as itself, so it + stops the import at its workflow, not with an AttributeError; `keys` and `_items` import.""" + with tempfile.TemporaryDirectory() as scratch: + directory = _unread(Path(scratch) / "written", "placeholder") + written = set(_WRITTEN.findall("".join((directory / file).read_text(encoding="utf-8") for file in _FILES))) + if name in written or name == "placeholder": + return + directory = _unread(Path(scratch) / "renamed", name) + try: + setattr(Workflow([], "python").inputs, name, "kept") + except ValueError: + _stops(_CODE.IMPORT_UNWRITABLE, directory / NEXTFLOW_SCRIPT, "workflow unread", + lambda: import_nextflow(directory)) + else: + assert name in [port.name for port in import_nextflow(directory).inputs] @st.composite def _corrupted(draw: st.DrawFn) -> tuple[str, str, bytes]: - """A case of values of each kind or thirty conditions, with one of its three files cut short or holding a non-UTF-8 - byte, an integer longer than Python converts, or nesting deeper than it recurses.""" - case, file = draw(st.sampled_from(["valued", "calculator"])), draw(st.sampled_from(_FILES)) - data = _bytes(case)[file] + """The example of step inputs or of commands, or thirty conditions, with one of its three files cut short or + holding a non-UTF-8 byte, an integer longer than Python converts, or nesting deeper than it recurses.""" + name = draw(st.sampled_from(["step_inputs", "commands", "calculator"])) + file = draw(st.sampled_from(_FILES)) + data = _texts(name)[file].encode("utf-8") kind = draw(st.sampled_from(["cut", "byte", "digits", "nesting"])) if kind == "cut": - return case, file, data[:draw(st.integers(0, len(data) - 1))] + return name, file, data[:draw(st.integers(0, len(data) - 1))] if kind == "nesting": at = draw(st.sampled_from([0, *(index + 1 for index, byte in enumerate(data) if byte in b"([{'\"")])) opener, closer = draw(st.sampled_from([(b"(", b""), (b"(", b")"), (b"[", b"]"), (b"{", b"}"), (b"${", b"}"), (b"(!", b")")])) - return case, file, data[:at] + opener * _DEEP + closer * _DEEP + data[at:] + return name, file, data[:at] + opener * _DEEP + closer * _DEEP + data[at:] at = draw(st.integers(0, len(data))) inserted = b"9" * 5000 if kind == "digits" else draw(st.sampled_from([b"\xff", b"\xc3", b"\xed\xa0\x80"])) - return case, file, data[:at] + inserted + data[at:] + return name, file, data[:at] + inserted + data[at:] @budget(300) @@ -794,10 +546,10 @@ def _corrupted(draw: st.DrawFn) -> tuple[str, str, bytes]: def test_whatever_bytes_the_files_hold_the_read_returns_a_model_or_stops_with_a_code( corrupted: tuple[str, str, bytes]) -> None: """The read returns a model or raises SophiosError or OSError, as its docstring says, and nothing else.""" - case, file, data = corrupted + name, file, data = corrupted with tempfile.TemporaryDirectory() as directory: - for name, written in _bytes(case).items(): - (Path(directory) / name).write_bytes(data if name == file else written) + for each, text in _texts(name).items(): + (Path(directory) / each).write_bytes(data if each == file else text.encode("utf-8")) with suppress(SophiosError, OSError): read_nextflow(directory) @@ -821,78 +573,4 @@ def too_deep(_model: ExecutableNextflowWorkflow) -> str: monkeypatch.setattr("sophios.nf_reader.render_nextflow", too_deep) _stops(_CODE.IMPORT_FOREIGN_STATEMENT, tmp_path / NEXTFLOW_SCRIPT, "workflow provoke", - lambda: import_edited(str(tmp_path), NEXTFLOW_SCRIPT, "", "")) - - -def test_an_int_for_a_float_parameter_stops_the_import(tmp_path: Path) -> None: - """Sophios writes a float parameter's value as its text, `"1.0"` and never the int `1`, which an import would - write back as `"1.0"`.""" - write_nextflow_artifacts(_compiled("resources"), tmp_path) - path = tmp_path / NEXTFLOW_PARAMS - path.write_text(path.read_text(encoding="utf-8").replace('"0.1"', "1"), encoding="utf-8") - _stops(_CODE.IMPORT_PARAMS, path, '"res_ratio": 1', lambda: import_nextflow(tmp_path)) - - -def test_a_process_block_after_the_workflows_stops_the_import(tmp_path: Path) -> None: - """The process blocks are free in their order among themselves, not past the workflows (design §4.2).""" - import_edited(str(tmp_path), NEXTFLOW_SCRIPT, "", "") - path = tmp_path / NEXTFLOW_SCRIPT - text = path.read_text(encoding="utf-8") - (block,) = _PROCESS_BLOCKS.findall(text) - path.write_text(text.replace(block, "") + "\n" + block, encoding="utf-8") - _stops(_CODE.IMPORT_MISMATCH, path, "process greet", lambda: import_nextflow(tmp_path)) - - -def test_a_port_the_tool_builder_cannot_name_stops_the_import_at_its_process(tmp_path: Path) -> None: - """A CWL tool may call a port `keys`, which `Inputs` keeps for its method, so no workflow built through the - tool builder compiles to the pipeline.""" - step = Step.from_cwl_document({ - "cwlVersion": "v1.2", "class": "CommandLineTool", "baseCommand": "echo", "stdout": "o.txt", - "inputs": {"keys": {"type": "string", "inputBinding": {"position": 1}}}, - "outputs": {"out": {"type": "File", "outputBinding": {"glob": "o.txt"}}}}, process_name="tool") - workflow = Workflow([step], "reserved") - step.inputs.keys, workflow.outputs.out = "x", step.outputs.out - workflow.compile(target="nextflow").write(tmp_path) - _stops(_CODE.IMPORT_UNWRITABLE, tmp_path / NEXTFLOW_SCRIPT, "process tool", lambda: import_nextflow(tmp_path)) - - -@pytest.mark.parametrize("name", sorted({*dir(ParameterNamespace), "keys", "_items", "_x", "__x__"})) -def test_a_parameter_imports_exactly_when_a_python_workflow_can_take_its_input(name: str, tmp_path: Path) -> None: - """A parameter is a workflow input: a pipeline whose parameter `unread` is renamed in all three files imports - exactly when `flow.inputs. = value` works. An attribute of the port namespace, such as `_store`, is read - as itself, so it stops the import at its workflow, not with an AttributeError; `keys` and `_items` import.""" - write_nextflow_artifacts(_compiled("valued"), tmp_path) - for file in _FILES: - path = tmp_path / file - path.write_text(path.read_text(encoding="utf-8").replace("unread", name), encoding="utf-8") - try: - setattr(Workflow([], "python").inputs, name, "kept") - except ValueError: - _stops(_CODE.IMPORT_UNWRITABLE, tmp_path / NEXTFLOW_SCRIPT, "workflow valued", - lambda: import_nextflow(tmp_path)) - else: - assert name in [port.name for port in import_nextflow(tmp_path).inputs] - - -def test_the_import_reads_the_three_files_alone(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """Copied alone into an empty directory, with the network refused, the files import, and no path a parameter - names is looked at: not `nextflow_workflow.json`, no tool registry, no network, no input file.""" - model = _compiled("valued") - write_nextflow_artifacts(model, tmp_path / "written") - (tmp_path / "alone").mkdir() - for file in _FILES: - shutil.copy(tmp_path / "written" / file, tmp_path / "alone" / file) - named = {item["path"] for value in model.to_dict()["params"].values() - for item in (value if isinstance(value, list) else [value]) if isinstance(item, dict)} - looked: list[str] = [] - stat = os.stat - - def recording(path: Any, *args: Any, **kwargs: Any) -> os.stat_result: - looked.append(os.fspath(path) if isinstance(path, (str, os.PathLike)) else str(path)) - return stat(path, *args, **kwargs) - - monkeypatch.setattr(os, "stat", recording) - with network_refused() as attempts: - imported = _imported(tmp_path / "alone") - assert (imported, attempts, named & set(looked)) == (model, [], set()) - assert named, "the case names no file" + partial(_edited, tmp_path, None, NEXTFLOW_SCRIPT, "", "")) diff --git a/tests/core/nextflow/test_lowering.py b/tests/core/nextflow/test_lowering.py index 1dc2fb11e..88f0f9e35 100644 --- a/tests/core/nextflow/test_lowering.py +++ b/tests/core/nextflow/test_lowering.py @@ -1,144 +1,34 @@ -"""Semantic lowering: supported CWL source becomes typed executable IR.""" +"""Semantic lowering: supported CWL source becomes typed executable IR, as CWL reads it (design §6). What a lowered +workflow does is the example workflows'; here, laws of how a binding's text is read.""" # pylint: disable=missing-function-docstring -import copy from typing import Any from cwl_utils.expression import interpolate from hypothesis import example, given, strategies as st import pytest -from sophios.input_output_nf import nextflow_params, render_nextflow -from sophios.ir.artifacts import CompilationResult -from sophios.nf_types import ( - NfFlag, - NfLiteral, - NfPort, - NfTemplate, - NfProcessConnection, - NfWorkflowInputConnection, - NfWorkflowOutputConnection, -) -from sophios.compiler import resolved_view -from sophios.utils_nf import cwl_type_to_nf_qualifier, nextflow_names -from sophios.wic_types import Yaml -from ..budgets import budget -from ..cases import cases, diagnostic, match -from .testkit import lowered, lowered_case, one_step, tool - - -@pytest.mark.fast -@pytest.mark.parametrize(("cwl_type", "qualifier"), [ - ("File", "path"), ("Directory", "path"), ("string", "val"), ("int", "val"), ("float", "val"), ("boolean", "val"), - ("File?", "path"), ("Any", None), ("File[]", None), ({"type": "array", "items": "File"}, None), -], ids=["file", "directory", "string", "int", "float", "boolean", "optional-file", "any", "array-shorthand", "array"]) -def test_a_cwl_type_has_its_qualifier_or_is_refused(cwl_type: Any, qualifier: str | None) -> None: - if qualifier is None: - with pytest.raises(ValueError, match="unsupported CWL type"): - cwl_type_to_nf_qualifier(cwl_type) - else: - assert cwl_type_to_nf_qualifier(cwl_type) == qualifier - - -# Each real fixture's workflow name, (process, inputs) list, connections and params. -GOLDEN_GRAPHS = { - "real_supported_result": ( - "wf", - [("touch", (NfPort("filename", "val", scalar_type="string"),)), - ("copy", (NfPort("source", "path", path_kind="file"),))], - ( - NfWorkflowInputConnection("touch_filename", "touch", "filename"), - NfProcessConnection("touch", "result", "copy", "source"), - NfWorkflowOutputConnection("touch", "result", "touch_result"), - NfWorkflowOutputConnection("copy", "result", "copy_result"), - ), - {"touch_filename": "message.txt"}, - ), - # A scattered port stays a scalar element port; its parameter carries the whole source array. - "real_scattered_result": ( - "wf", - [("echo_item", (NfPort("item", "val", scalar_type="string"),))], - ( - NfWorkflowInputConnection("echo_item_item", "echo_item", "item", "dotproduct"), - NfWorkflowOutputConnection("echo_item", "result", "echo_item_result"), - ), - {"echo_item_item": ["alpha", "beta"]}, - ), - # The subworkflow's step is a namespaced process that reads the outer producer. - "real_nested_result": ( - "root", - [("write", (NfPort("message", "val", scalar_type="string"),)), - ("child_inner_copy", (NfPort("source", "path", path_kind="file"),))], - ( - NfWorkflowInputConnection("write_message", "write", "message"), - NfProcessConnection("write", "result", "child_inner_copy", "source"), - NfWorkflowOutputConnection("write", "result", "write_result"), - NfWorkflowOutputConnection("child_inner_copy", "result", "child_inner_copy_result"), - ), - {"write_message": "nested composition"}, - ), -} +from sophios.api.python.workflow import Workflow +from sophios.nf_types import NfFlag - -@pytest.mark.fast -@pytest.mark.parametrize("fixture", sorted(GOLDEN_GRAPHS)) -def test_a_real_compilation_lowers_to_its_exact_graph(fixture: str, request: pytest.FixtureRequest) -> None: - name, processes, connections, params = GOLDEN_GRAPHS[fixture] - workflow = lowered(request.getfixturevalue(fixture)) - assert workflow.name == name - assert [(process.name, process.inputs) for process in workflow.processes] == processes - assert workflow.connections == connections - assert workflow.params == params - - -@pytest.mark.fast -def test_composes_command_arguments_bindings_and_redirects() -> None: - run_tool = tool( - "RUN", - inputs={ - "message": {"type": "string", "inputBinding": {"position": 2, "prefix": "--message"}}, - "source": {"type": "File"}, - }, - outputs={"report": {"type": "File", "outputBinding": {"glob": "stdout.txt"}}}, - baseCommand=["python", "script.py"], - arguments=[{"position": 1, "prefix": "--mode", "valueFrom": "fast"}], - stdin="$(inputs.source.path)", - stdout="stdout.txt", - stderr="stderr.txt", - ) - workflow = lowered_case(one_step(run_tool, ["report"], message="hello", - source={"class": "File", "path": "input.txt"}))[0] - process = workflow.processes[0] - rendered = render_nextflow(workflow) - command_line = next(line for line in rendered.splitlines() if " < " in line) - assert command_line.count("__sophios_shell_quote_9f72e") == 9 - for fragment in ("'python'", "'script.py'", "'--mode'", "'fast'", "'--message'"): - assert fragment in command_line - assert "message.toString()" in command_line - assert "< ${__sophios_shell_quote_9f72e(source.toString())}" in command_line - assert "> ${__sophios_shell_quote_9f72e('stdout.txt')}" in command_line - assert "2> ${__sophios_shell_quote_9f72e('stderr.txt')}" in command_line - assert process.outputs[0].glob == NfTemplate((NfLiteral("stdout.txt"),)) +from ..budgets import budget +from .testkit import lowered_case, one_step, tool @pytest.mark.fast -@pytest.mark.parametrize( - "binding", [{"prefix": "--verbose"}, {}, {"separate": True}], ids=["prefix", "no-prefix", "separate-no-prefix"] -) -@pytest.mark.parametrize("value_from", [None, "$(inputs.verbose)"], ids=["no-valuefrom", "self-valuefrom"]) -@pytest.mark.parametrize(("declared", "value"), [ - ("boolean", True), ("boolean", False), (["null", "boolean"], True), (["null", "boolean"], False), - (["null", "boolean"], None), -]) +@budget(30) +@given(st.sampled_from([{"prefix": "--verbose"}, {}, {"separate": True}]), + st.sampled_from([None, "$(inputs.verbose)"]), + st.sampled_from([("boolean", True), ("boolean", False), (["null", "boolean"], True), + (["null", "boolean"], False), (["null", "boolean"], None), ("boolean?", None)])) +@example({"prefix": "--verbose"}, "$(inputs.verbose)", (["null", "boolean"], None)) +@example({"separate": True}, None, ("boolean", False)) def test_a_boolean_binding_is_a_flag_token_exactly_when_it_has_a_prefix( - binding: dict[str, Any], value_from: str | None, declared: Any, value: bool | None -) -> None: - """A flag tests its value and never dereferences it, so false and an absent optional lower alike. - - A valueFrom restating its own input is the same flag, and cwltool accepts - separate: true without a prefix; only a falsy separate rejects. - """ + binding: dict[str, Any], value_from: str | None, typed: tuple[Any, bool | None]) -> None: + """A flag tests its value and never dereferences it, so false and an absent optional lower alike; a valueFrom + restating its own input is the same flag, and cwltool accepts separate: true without a prefix.""" + declared, value = typed input_binding = {"position": 1, **binding, **({} if value_from is None else {"valueFrom": value_from})} flag_tool = tool("FLAGS", inputs={"verbose": {"type": declared, "inputBinding": input_binding}}) workflow = lowered_case(one_step(flag_tool, verbose=value))[0] @@ -147,51 +37,6 @@ def test_a_boolean_binding_is_a_flag_token_exactly_when_it_has_a_prefix( assert workflow.processes[0].command.tokens[1:] == flags -@pytest.mark.fast -@pytest.mark.parametrize(("shorthand", "expanded", "value"), [ - ("string[]", {"type": "array", "items": "string"}, ["a", "b"]), - ("File[]", {"type": "array", "items": "File"}, [{"class": "File", "path": "a.txt"}]), - ("int[]?", ["null", {"type": "array", "items": "int"}], [1]), - (["null", "string[]"], ["null", {"type": "array", "items": "string"}], []), -]) -def test_an_array_type_in_shorthand_lowers_as_written_out(shorthand: Any, expanded: Any, value: Any) -> None: - """CWL reads `T[]` as `{type: array, items: T}` (CWL v1.2, Type DSL); a .cwl tool may declare either.""" - def lower(cwl_type: Any) -> Any: - return lowered_case(one_step(tool("T", inputs={"x": {"type": cwl_type, "inputBinding": {}}}), x=value))[0] - assert lower(shorthand) == lower(expanded) - - -@pytest.mark.fast -def test_forward_conversion_uses_resolved_graph_edges( - real_supported_result: CompilationResult, -) -> None: - compilation = copy.deepcopy(real_supported_result) - steps = compilation.artifact.cwl["steps"] - steps[1]["in"]["source"]["source"] = "not_the_resolved_edge/result" - cwl = copy.deepcopy(compilation.artifact.cwl) - - connections = lowered(compilation).connections - - assert compilation.artifact.cwl == cwl, "lowering reads the compilation and never writes it" - assert NfProcessConnection("touch", "result", "copy", "source") in connections - - -@pytest.mark.fast -@pytest.mark.parametrize("fixture", ["real_supported_result", "real_scattered_result", "real_nested_result"]) -def test_the_names_a_run_maps_back_are_the_names_the_lowering_makes( - fixture: str, request: pytest.FixtureRequest -) -> None: - """Each process and workflow output of the lowered model has exactly one Sophios name.""" - result: CompilationResult = request.getfixturevalue(fixture) - workflow = lowered(result) - names = nextflow_names(resolved_view(result)) - assert sorted(names["processes"]) == sorted(process.name for process in workflow.processes) - assert sorted(names["outputs"]) == sorted( - connection.to_port for connection in workflow.connections - if isinstance(connection, NfWorkflowOutputConnection) - ) - - # design §6, Commands: a `$` before no `(` or `{` is text; the last two were once refused beside a reference, and # an empty argument is kept. @budget(200) @@ -208,18 +53,6 @@ def test_a_dollar_starting_no_expression_is_text_as_cwltool_reads_it(texts: list @pytest.mark.fast -@pytest.mark.parametrize("case", cases( - "nextflow/lowered", "tool", "out", "job", "workflow", "tools", "lowered", "render", "notes", "params_file")) -def test_a_supported_source_lowers_as_its_case_says(case: Yaml) -> None: - """A case's source lowers, its documents left as they were, to a model whose payload holds `lowered`, with - `params_file` as its params file, each `render` fragment in its script, and exactly its `notes` when it lists them - (tests/core/cases.py reads each form). A case with none of `lowered`, `render`, `notes` or `params_file` asserts - only that its source lowers.""" - documents = copy.deepcopy(case) - workflow, notes = lowered_case(case) - assert case == documents - assert match(case.get("lowered", {}), workflow.to_dict()) - assert nextflow_params(workflow) == case.get("params_file", nextflow_params(workflow)) - rendered = render_nextflow(workflow) - assert [text for text in case.get("render", []) if text not in rendered] == [] - assert match(case.get("notes", [diagnostic(note) for note in notes]), [diagnostic(note) for note in notes]) +def test_a_call_of_an_empty_workflow_lowers_to_no_process() -> None: + """A call is inlined, so a call of a workflow with no step leaves nothing to run, and nothing to note.""" + assert Workflow([Workflow([], "child")], "root").compile(target="nextflow").nextflow_workflow.processes == () diff --git a/tests/core/nextflow/test_lowering_outcomes.py b/tests/core/nextflow/test_lowering_outcomes.py index 5899e18cb..fc8a8ec57 100644 --- a/tests/core/nextflow/test_lowering_outcomes.py +++ b/tests/core/nextflow/test_lowering_outcomes.py @@ -2,11 +2,11 @@ refusal for each construct it cannot lower, or the compile's own `SophiosError` (design_docs/one-target-table-design.md §5). Any other exception is a crash: an uncoded refusal a case has not reached yet. """ -import contextlib +import copy from typing import Any import pytest -from hypothesis import given, strategies as st +from hypothesis import example, given, strategies as st from sophios.ir.resolved import NotLowered from sophios.lang.diagnostics import SophiosError @@ -76,8 +76,7 @@ @st.composite def _cases(draw: st.DrawFn) -> dict[str, Any]: - """A one-step case of `tests/core/data/nextflow/rejected`'s `tool` form, its tool drawn from the shapes CWL takes - and from shapes it does not.""" + """A one-step case (testkit.one_step), its tool drawn from the shapes CWL takes and from shapes it does not.""" odd = draw(st.booleans()) inputs = draw(st.dictionaries(st.sampled_from(["x", "y", "xs"]), _INPUT if odd else _PLAIN_INPUT, max_size=3)) outputs = draw(st.dictionaries(st.sampled_from(["o", "p"]), _OUTPUT if odd else _PLAIN_OUTPUT, max_size=2)) @@ -131,10 +130,42 @@ def _workflows(draw: st.DrawFn) -> dict[str, Any]: "job": {"name": draw(_PLAIN_VALUE), "names": ["a", "b"], "flag": draw(_PLAIN_VALUE)}} +def _written_out(cwl_type: Any) -> Any: + """`cwl_type` with CWL's shorthand written out: `T[]` as `{type: array, items: T}`, `T?` as `[null, T]`.""" + if isinstance(cwl_type, list): + return [_written_out(each) for each in cwl_type] + if isinstance(cwl_type, str) and cwl_type.endswith("?"): + return ["null", _written_out(cwl_type[:-1])] + if isinstance(cwl_type, str) and cwl_type.endswith("[]"): + return {"type": "array", "items": _written_out(cwl_type[:-2])} + return cwl_type + + +def _outcome(case: dict[str, Any]) -> Any: + """The model `case` lowers to, the codes of its refusals, or that it does not compile.""" + try: + return lowered_case(case)[0] + except NotLowered as refused: + return [refusal.code for refusal in refused.refusals] + except SophiosError: + return "does not compile" + + @pytest.mark.fast @budget(60) @given(_cases() | _workflows()) +# A valueFrom YAML reads as a boolean, a requirement that is not a mapping, and a list input given one value. +@example({"tool": {"id": "T", "inputs": {}, "outputs": {}, "arguments": [{"valueFrom": True}]}, "out": [], "job": {}}) +@example({"tool": {"id": "T", "inputs": {}, "outputs": {}, "requirements": {"DockerRequirement": "ubuntu"}}, + "out": [], "job": {}}) +@example({"tool": {"id": "T", "inputs": {"xs": {"type": "string[]", "inputBinding": {"position": 1}}}, "outputs": {}}, + "out": [], "job": {"xs": "a"}}) def test_lowering_ends_in_a_model_a_coded_refusal_or_a_compile_error(case: dict[str, Any]) -> None: - """Whatever a tool says, lowering it to Nextflow lowers it, refuses it with a code, or never compiles.""" - with contextlib.suppress(NotLowered, SophiosError): - lowered_case(case) + """Whatever a tool says, lowering it to Nextflow lowers it, refuses it with a code, or never compiles; and its + input types written out, as CWL reads its shorthand (CWL v1.2, Type DSL), it ends the same way.""" + outcome = _outcome(case) + if "tool" in case: + written = copy.deepcopy(case) + for port in written["tool"]["inputs"].values(): + port["type"] = _written_out(port["type"]) + assert _outcome(written) == outcome diff --git a/tests/core/nextflow/test_properties.py b/tests/core/nextflow/test_properties.py index 9544c353f..9865a16f4 100644 --- a/tests/core/nextflow/test_properties.py +++ b/tests/core/nextflow/test_properties.py @@ -1,4 +1,5 @@ -"""Property-based adversarial tests for the executable Nextflow boundary.""" +"""Laws of the executable Nextflow boundary: names, quoting, how a command is read, and what the pipeline +writes, each over generated values.""" # pylint: disable=missing-function-docstring @@ -53,242 +54,114 @@ @budget(300) -@given( - st.text( - alphabet=st.characters(blacklist_categories=SURROGATE_CATEGORIES), - min_size=1, - max_size=80, - ) -) -def test_identifier_normalization_is_valid_and_idempotent(value: str) -> None: +@given(st.text(alphabet=st.characters(blacklist_categories=SURROGATE_CATEGORIES), min_size=1, max_size=80), + st.from_regex(r"[a-z][a-z0-9]{0,12}", fullmatch=True), st.from_regex(r"[a-z][a-z0-9]{0,12}", fullmatch=True)) +def test_a_name_normalizes_to_one_identifier_and_two_names_never_to_one_silently( + value: str, prefix: str, suffix: str) -> None: normalized = normalize_nextflow_identifier(value) assert is_nextflow_identifier(normalized) assert normalize_nextflow_identifier(normalized) == normalized - - -@budget(120) -@given( - st.from_regex(r"[a-z][a-z0-9]{0,12}", fullmatch=True), - st.from_regex(r"[a-z][a-z0-9]{0,12}", fullmatch=True), -) -def test_identifier_normalization_collisions_are_never_last_wins( - prefix: str, - suffix: str, -) -> None: with pytest.raises(ValueError, match="normalize to"): - _normalized_identifiers( - (f"{prefix}-{suffix}", f"{prefix}_{suffix}"), - context="workflow input", - ) + _normalized_identifiers((f"{prefix}-{suffix}", f"{prefix}_{suffix}"), context="workflow input") @budget(200) -@given(SAFE_TEXT | st.just("")) -def test_literal_template_is_exactly_one_shell_argument(value: str) -> None: +@given(SAFE_TEXT | st.just(""), SAFE_TEXT, st.text(alphabet=st.characters( + blacklist_categories=SURROGATE_CATEGORIES)).filter(str.strip)) +def test_a_text_reaches_the_shell_and_groovy_as_itself(value: str, suffix: str, any_text: str) -> None: + """A literal or interpolated template is one shell argument; a literal glob stays a single-quoted string and an + interpolated one escapes no backtick, which Groovy cannot; every single-quoted position of the pipeline uses the + one escaper and writes no control character.""" assert shlex.split(_shell_quote(value)) == [value] - assert "__sophios_shell_quote_9f72e" in _render_template( - NfTemplate((NfLiteral(value),)), {} - ) - - -@budget(200) -@given(SAFE_TEXT, SAFE_TEXT) -def test_interpolated_template_remains_one_argument(prefix: str, suffix: str) -> None: - value = "adversarial ' value; $(touch SHOULD_NOT_EXIST)" - template = NfTemplate( - (NfLiteral(prefix), NfInputReference("value"), NfLiteral(suffix)) - ) - rendered = _render_template(template, {}) - assert "value.toString()" in rendered - assert shlex.split(_shell_quote(f"{prefix}{value}{suffix}")) == [ - f"{prefix}{value}{suffix}" - ] - - -@budget(150) -@given(SAFE_TEXT | st.just("")) -def test_literal_globs_never_become_gstrings(value: str) -> None: - rendered = _render_glob(NfTemplate((NfLiteral(value),)), {}) - assert rendered.startswith("'") and rendered.endswith("'") - - -@budget(150) -@given(SAFE_TEXT | st.just("")) -def test_interpolated_glob_literals_use_only_valid_gstring_escapes(value: str) -> None: - rendered = _render_glob(NfTemplate(( - NfLiteral(f"`{value}"), - NfInputReference("name"), - )), {}) - # Groovy has no \\` escape, so no backtick may be escaped. A bare - # substring check is not that property: the escaper doubles every - # backslash, so a literal backslash before a backtick also matches it - # while being correctly escaped. Count the run instead -- an even run - # leaves the backtick unescaped. - body = rendered[1:-1] + assert "__sophios_shell_quote_9f72e" in _render_template(NfTemplate((NfLiteral(value),)), {}) + injected = "adversarial ' value; $(touch SHOULD_NOT_EXIST)" + assert "value.toString()" in _render_template(NfTemplate( + (NfLiteral(value), NfInputReference("value"), NfLiteral(suffix))), {}) + assert shlex.split(_shell_quote(f"{value}{injected}{suffix}")) == [f"{value}{injected}{suffix}"] + literal = _render_glob(NfTemplate((NfLiteral(value),)), {}) + assert literal.startswith("'") and literal.endswith("'") + # Groovy has no \` escape, so no backtick may be escaped: the escaper doubles every backslash, so an even run of + # them before a backtick leaves it unescaped. + body = _render_glob(NfTemplate((NfLiteral(f"`{value}"), NfInputReference("name"))), {})[1:-1] for index, char in enumerate(body): if char == "`": - prefix = body[:index] - assert (len(prefix) - len(prefix.rstrip("\\"))) % 2 == 0 - assert "${name}" in rendered - - -@budget(150) -@given(st.text(alphabet=st.characters(blacklist_categories=SURROGATE_CATEGORIES)).filter(str.strip)) -def test_every_single_quoted_groovy_position_uses_the_one_escaper(value: str) -> None: + assert (len(body[:index]) - len(body[:index].rstrip("\\"))) % 2 == 0 + assert "${name}" in body # An entry name is one path component, and never `.`, `..` or the reserved staging prefix. - staged = "_" + value.translate(str.maketrans("/\x00", "__")) - spoken = "".join(char for char in value if " " <= char <= "~" and char != "\\") # a when literal's alphabet - process = NfProcess( - "TASK", - [NfPort("s", "val"), NfPort("src", "path", entry=NfEntry(staged))], - [], - NfCommand((NfTemplate((NfLiteral("true"),)),)), - container=value, - condition=Expr("==", (Expr("ref", (), "s"), Expr("string", (), spoken))), - ) + staged = "_" + any_text.translate(str.maketrans("/\x00", "__")) + spoken = "".join(char for char in any_text if " " <= char <= "~" and char != "\\") # a when literal's alphabet + process = NfProcess("TASK", [NfPort("s", "val"), NfPort("src", "path", entry=NfEntry(staged))], [], + NfCommand((NfTemplate((NfLiteral("true"),)),)), container=any_text, + condition=Expr("==", (Expr("ref", (), "s"), Expr("string", (), spoken)))) rendered = render_nextflow(ExecutableNextflowWorkflow( - "PIPELINE", - [process], - [NfWorkflowInputConnection(name, "TASK", name) for name in ("s", "src")], - {"s": "x", "src": "in.txt"}, {"s": "string", "src": "File"}, - )) - for literal in (groovy_literal(value), groovy_literal(staged), groovy_literal(spoken)): - assert literal in rendered + "PIPELINE", [process], [NfWorkflowInputConnection(name, "TASK", name) for name in ("s", "src")], + {"s": "x", "src": "in.txt"}, {"s": "string", "src": "File"})) + for written in (groovy_literal(any_text), groovy_literal(staged), groovy_literal(spoken)): + assert written in rendered assert not any(ord(char) < 32 and char != "\n" or ord(char) == 127 for char in rendered) @budget(300) -@given(st.lists(st.sampled_from(INTERPOLATION_PIECES), max_size=8).map("".join)) +@given(st.lists(st.sampled_from(INTERPOLATION_PIECES), max_size=8).map("".join), + st.permutations(("zeta", "alpha", "middle"))) # Once refused: the text on the two sides of a token joined into `${`, `$(`. -@example("{$$(inputs.x){$") -@example("($$(inputs.x)($") -@example("$\\$((") -def test_template_interpolation_agrees_with_cwltool(text: str) -> None: +@example("{$$(inputs.x){$", ("zeta", "alpha", "middle")) +@example("($$(inputs.x)($", ("alpha", "middle", "zeta")) +@example("$\\$((", ("middle", "zeta", "alpha")) +def test_a_command_is_read_as_cwltool_reads_it(text: str, order: tuple[str, ...]) -> None: + """A template interpolates as cwltool interpolates it, or is refused where cwltool fails; inputs bound at one + position come in the order of their names, after the arguments, whatever order they are declared in.""" try: # cwltool interpolates a string only when it contains an expression. expected = interpolate(text, {"inputs": {"x": "VALUE"}}) if "$(" in text or "${" in text else text except (JavascriptException, SubstitutionError): with pytest.raises(ValueError, match="unsupported CWL expression"): lower_template(text, context="property") - return - template = lower_template(text, context="property") - lowered = "".join(segment.value if isinstance(segment, NfLiteral) else "VALUE" for segment in template.segments) - assert lowered == expected + else: + template = lower_template(text, context="property") + assert "".join(segment.value if isinstance(segment, NfLiteral) else "VALUE" + for segment in template.segments) == expected + command = lower_command({"baseCommand": "cmd", "arguments": ["a", "b", "c"], + "inputs": {name: {"type": "string", "inputBinding": {}} for name in order}}) + templates = [token for token in command.tokens if isinstance(token, NfTemplate)] + assert [[segment.value if isinstance(segment, NfLiteral) else getattr(segment, "name") + for segment in token.segments] for token in templates] == [ + ["cmd"], ["a"], ["b"], ["c"], ["alpha"], ["middle"], ["zeta"]] + assert len(templates) == len(command.tokens) -@budget(120) -@given(SAFE_TEXT, st.sampled_from(("file", "directory"))) -@example("input.txt", "file") -@example("input[1]", "directory") -def test_a_path_parameter_is_one_channel_of_its_kind_whatever_its_value_shape(path: str, path_kind: str) -> None: - """A path parameter is a bare path or the object the compiler writes; either is one channel of the declared - kind, staged without globbing, and the port keeps its kind in the model.""" +@budget(150) +@given(SAFE_TEXT, st.sampled_from(("file", "directory")), + st.one_of(st.integers(min_value=1, max_value=10**30), + st.floats(min_value=0.000001, max_value=10**15, allow_nan=False, allow_infinity=False)), + st.integers(min_value=1, max_value=1_000_000).map(lambda value: value + 0.5), + st.lists(st.booleans(), max_size=10)) +@example("input.txt", "file", 1234567, 2.5, [False]) +@example("input[1]", "directory", 1, 1.5, [True]) +def test_a_pipeline_writes_its_parameters_and_directives_as_the_model_holds_them( + path: str, path_kind: str, memory_mb: int | float, cpus: float, containers: list[bool]) -> None: + """A path parameter, a bare path or the object the compiler writes, is one channel of its kind staged without + globbing; memory is written without an exponent and keeps its value; a fractional core count is unrepresentable; + Docker is enabled exactly when a process has a container.""" declared = "Directory" if path_kind == "directory" else "File" - process = NfProcess( - "READ", - (NfPort("source", "path", path_kind=path_kind),), - (), - NfCommand((NfTemplate((NfLiteral("true"),)),)), - ) + read = NfProcess("READ", (NfPort("source", "path", path_kind=path_kind),), (), + NfCommand((NfTemplate((NfLiteral("true"),)),)), resources=NfResources(memory_mb=memory_mb)) connections = (NfWorkflowInputConnection("source", "READ", "source"),) - from_string = ExecutableNextflowWorkflow("wf", (process,), connections, {"source": path}, {"source": declared}) + from_string = ExecutableNextflowWorkflow("wf", (read,), connections, {"source": path}, {"source": declared}) from_mapping = ExecutableNextflowWorkflow( - "wf", (process,), connections, {"source": {"class": declared, "path": path}}, {"source": declared}, - ) - assert render_nextflow(from_string) == render_nextflow(from_mapping) + "wf", (read,), connections, {"source": {"class": declared, "path": path}}, {"source": declared}) + rendered = render_nextflow(from_string) + assert rendered == render_nextflow(from_mapping) assert (f"Channel.value(file(__sophios_input_9f72e('source', params.source, '{declared}'), glob: false))" - in render_nextflow(from_string)) + in rendered) assert from_string.to_dict()["processes"][0]["inputs"][0]["path_kind"] == path_kind - - -@budget(100) -@given(st.integers(min_value=1, max_value=1_000_000).map(lambda value: value + 0.5)) -@example(2.5) -def test_fractional_cpu_requests_are_unrepresentable(cpus: float) -> None: + memory = next(line.strip() for line in rendered.splitlines() if "memory " in line) + written = memory.removeprefix('memory "').removesuffix(' MB"') + assert "e" not in written.lower() and Decimal(written) == Decimal(str(memory_mb)) with pytest.raises(ValueError, match="positive integer"): NfResources(cpus=cast(Any, cpus)) - - -@budget(150) -@given( - st.one_of( - st.integers(min_value=1, max_value=10**30), - st.floats( - min_value=0.000001, - max_value=10**15, - allow_nan=False, - allow_infinity=False, - ), - ) -) -@example(1234567) -def test_memory_rendering_is_non_exponential_and_value_preserving( - memory_mb: int | float, -) -> None: - process = NfProcess( - "TASK", - (), - (), - NfCommand((NfTemplate((NfLiteral("true"),)),)), - resources=NfResources(memory_mb=memory_mb), - ) - rendered = render_nextflow(ExecutableNextflowWorkflow("wf", (process,), (), {})) - line = next(line.strip() for line in rendered.splitlines() if "memory " in line) - rendered_number = line.removeprefix('memory "').removesuffix(' MB"') - - assert "e" not in rendered_number.lower() - assert Decimal(rendered_number) == Decimal(str(memory_mb)) - - -@budget(60) -@given(st.lists(st.booleans(), max_size=10)) -@example([False]) -@example([True]) -def test_docker_is_enabled_exactly_when_a_process_has_a_container(modes: list[bool]) -> None: - processes = tuple( - NfProcess( - f"P{index}", - (), - (), - NfCommand((NfTemplate((NfLiteral("true"),)),)), - container="ubuntu:24.04" if containerized else None, - ) - for index, containerized in enumerate(modes) - ) - workflow = ExecutableNextflowWorkflow("wf", processes, (), {}) - assert render_nextflow_config(workflow) == f"docker.enabled = {str(any(modes)).lower()}\n" - - -@budget(80) -@given(st.permutations(("zeta", "alpha", "middle"))) -def test_equal_position_input_bindings_order_by_field_name(order: tuple[str, ...]) -> None: - inputs = { - name: {"type": "string", "inputBinding": {}} - for name in order - } - command = lower_command({"baseCommand": "cmd", "arguments": ["a", "b", "c"], "inputs": inputs}) - templates = [token for token in command.tokens if isinstance(token, NfTemplate)] - assert len(templates) == len(command.tokens), "string bindings never lower to flag tokens" - references = [ - segment.name - for token in templates - for segment in token.segments - if isinstance(segment, NfInputReference) - ] - literals: list[str] = [] - for token in templates[:4]: - segment = token.segments[0] - assert isinstance(segment, NfLiteral) - literals.append(segment.value) - assert literals == ["cmd", "a", "b", "c"] - assert references == ["alpha", "middle", "zeta"] - - -def test_value_from_literal_and_reference_is_one_typed_token() -> None: - command = lower_command({ - "baseCommand": "cp", - "arguments": [{"valueFrom": "my report $(inputs.name).txt"}], - "inputs": {"name": {"type": "string"}}, - }) - rendered = _render_template(command.tokens[-1], {}) - assert "'my report ' + name.toString() + '.txt'" in rendered + processes = tuple(NfProcess(f"P{index}", (), (), NfCommand((NfTemplate((NfLiteral("true"),)),)), + container="ubuntu:24.04" if containerized else None) + for index, containerized in enumerate(containers)) + assert render_nextflow_config(ExecutableNextflowWorkflow("wf", processes, (), {})) == ( + f"docker.enabled = {str(any(containers)).lower()}\n") diff --git a/tests/core/nextflow/test_public_api.py b/tests/core/nextflow/test_public_api.py index 555f2906e..66c0d7876 100644 --- a/tests/core/nextflow/test_public_api.py +++ b/tests/core/nextflow/test_public_api.py @@ -11,18 +11,14 @@ from sophios import cli import sophios.main as sophios_main from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl -from sophios.api.python.workflow import ( - CompiledNextflowWorkflow, - CompiledWorkflow, - Step, - Workflow, -) +from sophios.api.python.workflow import CompiledNextflowWorkflow, CompiledWorkflow, Step, Workflow from sophios.lang import SophiosErrorCode from sophios.lang.diagnostics import lines from sophios.nf_reader import read_nextflow from sophios.nf_types import NfWorkflowOutputConnection -from ..helpers import ADAPTERS, adapter_step, run_cli +from ..cases import DATA +from ..helpers import adapter_step, run_cli def supported_workflow() -> Workflow: @@ -55,19 +51,18 @@ def gpu_workflow() -> Workflow: return workflow -CUDA_NOTES = [ - f"note [wic046] cwltool:CUDARequirement {field} {value!r} is not checked: the Nextflow accelerator directive " - "asks only for a number of GPUs (step 'gpu')" - for field, value in (("cudaVersionMin", "11.4"), ("cudaComputeCapability", "3.0")) -] +#: The notes of `gpu_workflow()`: the two CUDA fields the Nextflow accelerator directive does not check. +CUDA_NOTES = [("note", "wic046", "gpu")] * 2 FOUR_FILES = {"nextflow_workflow.json", "workflow.nf", "nextflow.config", "nextflow_params.json"} @pytest.mark.fast @pytest.mark.filterwarnings("error::UserWarning") -def test_a_nextflow_compile_keeps_every_note_and_warns_with_none(capsys: pytest.CaptureFixture[str]) -> None: - """The CWL compile's version and notes, then the lowering's notes, kept on the result and printed on stderr; - nothing warns.""" +def test_a_nextflow_compile_keeps_every_note_and_only_the_outputs_it_declares( + capsys: pytest.CaptureFixture[str]) -> None: + """The CWL compile's version and notes, then the lowering's, kept on the result and printed on stderr, and nothing + warns; and the workflow outputs are the ones it declares, so a declared `emit_text_file` is not the step output + `emit_text~file`, whose Nextflow name it would share.""" consume = CommandLineTool("consume", Inputs(data=Input(cwl.file, position=1)), Outputs(result=Output(cwl.file, glob="result.txt"))).base_command("cat") workflow = Workflow([*gpu_workflow().steps, Step(consume)], "nextflow_noted") @@ -77,26 +72,23 @@ def test_a_nextflow_compile_keeps_every_note_and_warns_with_none(capsys: pytest. assert [note for note in core.diagnostics if note.code is SophiosErrorCode.INFERENCE_GUESS] assert (compiled.lang_version, *compiled.diagnostics) == (core.lang_version, *core.diagnostics, *compiled.diagnostics[len(core.diagnostics):]) - assert [str(note) for note in compiled.diagnostics[len(core.diagnostics):]] == CUDA_NOTES + assert [(note.severity.value, note.code.value, note.locator and note.locator.step) for note in + compiled.diagnostics[len(core.diagnostics):]] == CUDA_NOTES assert printed == lines(compiled.diagnostics) assert compiled.nextflow_workflow.processes[0].resources.accelerator == 2 - - -@pytest.mark.fast -def test_a_python_workflow_is_lowered_with_only_the_outputs_it_declares() -> None: - """As `compile()` returns it, so a declared `emit_text_file` is not the step output `emit_text~file`, whose - Nextflow name it would share.""" - workflow = supported_workflow() - workflow.outputs.emit_text_file = workflow.steps[0].outputs.file - compiled = workflow.compile(target="nextflow") - assert [connection.to_port for connection in compiled.nextflow_workflow.connections + declared = supported_workflow() + declared.outputs.emit_text_file = declared.steps[0].outputs.file + assert [connection.to_port for connection in declared.compile(target="nextflow").nextflow_workflow.connections if isinstance(connection, NfWorkflowOutputConnection)] == ["file", "emit_text_file"] @pytest.mark.fast -def test_the_cli_reports_each_cuda_note_through_the_diagnostics_report( +def test_the_cli_reports_notes_and_refusals_as_diagnostics( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: + """A note reaches the diagnostics report in either form, and the pipeline is written; a workflow the target + cannot run is reported as any error is, on stderr, at its line, with its code and step, exit 1 and no file to go + and read; and it leaves none of the files an earlier write left.""" monkeypatch.chdir(tmp_path) wic = gpu_workflow().write_wic(tmp_path) capsys.readouterr() @@ -106,11 +98,18 @@ def notes(form: str) -> list[str]: "--diagnostics", form) is None return [line for line in capsys.readouterr().err.splitlines() if line.startswith(("note", "{"))] - assert notes("text") == CUDA_NOTES - assert [(note["severity"], note["code"], note["step"]) for note in map(json.loads, notes("json"))] == [ - ("note", "wic046", "gpu")] * 2 + assert [line.split("]")[0] for line in notes("text")] == ["note [wic046"] * 2 + assert [(note["severity"], note["code"], note["step"]) for note in map(json.loads, notes("json"))] == CUDA_NOTES assert "accelerator 2" in (tmp_path / "out" / "workflow.nf").read_text(encoding="utf-8") + supported_workflow().compile(target="nextflow").write("autogenerated") + refused = DATA / "nextflow" / "cli" / "refused.wic" + assert run_cli(monkeypatch, "--yaml", refused, "--target", "nextflow") == 1 + printed = capsys.readouterr().err + assert "refused.wic:3:3: error [nf-s010]" in printed and "(step 'echo')" in printed, printed + assert not (tmp_path / "error_refused.txt").exists() + assert not any((tmp_path / "autogenerated").iterdir()) + @pytest.mark.fast def test_write_returns_the_directory_it_filled_and_replaces_the_pipeline_there( @@ -132,81 +131,43 @@ def test_write_returns_the_directory_it_filled_and_replaces_the_pipeline_there( replacement.nextflow_workflow.to_json()) +_OPTION_GROUPS = {"every target": cli.neutral, **cli.target_options} + + @pytest.mark.fast -def test_the_target_argument_defaults_to_cwl_and_rejects_what_it_does_not_know() -> None: +def test_a_target_takes_its_own_options_and_no_other(capsys: pytest.CaptureFixture[str]) -> None: + """The target defaults to cwl, and one Sophios does not know is refused; every option belongs to exactly one + group, every target or one target, and an option set for another target is refused naming the target it is for; + the run modes act under nextflow, and an option only a CWL run reads does not; an unknown argument points to + --passthrough_flags under every target.""" workflow = supported_workflow() default = workflow.compile() assert isinstance(default, CompiledWorkflow) and workflow.compile(target="cwl") == default - with pytest.raises(ValueError, match="^unknown target 'unknown'; the targets are cwl, nextflow$"): + with pytest.raises(ValueError, match="unknown target 'unknown'"): cast(Any, workflow).compile(target="unknown") assert cli.get_args("workflow.wic").target == "cwl" - with pytest.raises(SystemExit, match="2"): - cli.get_args("workflow.wic", ["--target", "nextflow", "--inputs_file", "inputs.yml"]) - - -_OPTION_GROUPS = {"every target": cli.neutral, **cli.target_options} - - -@pytest.mark.fast -def test_every_cli_option_belongs_to_exactly_one_group() -> None: declared = [action for action in cli.parser._actions if action.dest != "help"] grouped = [action for group in _OPTION_GROUPS.values() for action in group._group_actions] assert sorted(map(id, declared)) == sorted(map(id, grouped)) - - -@pytest.mark.fast -@pytest.mark.parametrize("target", cli.target_options) -def test_an_option_set_for_another_target_is_rejected(target: str, capsys: pytest.CaptureFixture[str]) -> None: - for owner, group in _OPTION_GROUPS.items(): - for action in group._group_actions: - args = cli.get_args("workflow.wic", ["--target", target]) - setattr(args, action.dest, object()) - if owner in {"every target", target}: - cli.validate_target_args(args) - continue - with pytest.raises(SystemExit, match="2"): - cli.validate_target_args(args) - assert f"{action.option_strings[0]} (--target {owner})" in capsys.readouterr().err - - -@pytest.mark.fast -@pytest.mark.parametrize("target", cli.target_options) -def test_an_unknown_argument_names_passthrough_flags_under_every_target( - target: str, capsys: pytest.CaptureFixture[str] -) -> None: - """Each target's runner takes passthrough arguments: CWL's runners, and Nextflow.""" - with pytest.raises(SystemExit, match="2"): - sophios_main._main(cli.get_args("workflow.wic", ["--target", target]), ["--bogus"]) - error = capsys.readouterr().err.splitlines()[-1] - assert error == ("main: error: unrecognized arguments: --bogus. Flags for the runner need " - "--passthrough_flags yes") - - -@pytest.mark.fast -def test_a_plain_cwl_workflow_under_allow_raw_cwl_is_lowered_under_nextflow( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] -) -> None: - (tmp_path / "raw.cwl").write_text( - "cwlVersion: v1.2\nclass: Workflow\ninputs:\n msg: {type: string, default: hi}\noutputs: {}\n" - f"steps:\n say:\n run: {ADAPTERS / 'echo.cwl'}\n" - " in: {message: msg}\n out: [stdout]\n", - encoding="utf-8", - ) - monkeypatch.chdir(tmp_path) - with pytest.raises(SystemExit, match="1"): - sophios_main._main(cli.get_args("raw.cwl", ["--allow_raw_cwl", "--homedir", str(tmp_path)]), []) - assert "Please specify either --generate_cwl_workflow" in capsys.readouterr().out - sophios_main._main(cli.get_args("raw.cwl", [ - "--allow_raw_cwl", "--homedir", str(tmp_path), "--target", "nextflow", "--basepath", "out"]), []) - assert {path.name for path in (tmp_path / "out").iterdir()} == FOUR_FILES - - -@pytest.mark.fast -def test_the_run_modes_act_under_nextflow_and_an_option_only_a_cwl_run_reads_does_not() -> None: + for target in cli.target_options: + for owner, group in _OPTION_GROUPS.items(): + for action in group._group_actions: + args = cli.get_args("workflow.wic", ["--target", target]) + setattr(args, action.dest, object()) + if owner in {"every target", target}: + cli.validate_target_args(args) + continue + with pytest.raises(SystemExit, match="2"): + cli.validate_target_args(args) + assert f"{action.option_strings[0]} (--target {owner})" in capsys.readouterr().err + with pytest.raises(SystemExit, match="2"): + sophios_main._main(cli.get_args("workflow.wic", ["--target", target]), ["--bogus"]) + assert "--passthrough_flags" in capsys.readouterr().err.splitlines()[-1] for flags in (["--run_local"], ["--check"], ["--generate_run_script"], ["--passthrough_flags", "yes"]): assert cli.get_args("workflow.wic", ["--target", "nextflow", *flags]).target == "nextflow" for flags in (["--generate_cwl_workflow"], ["--quiet"], ["--cwl_runner", "toil-cwl-runner"], - ["--container_engine", "podman"], ["--cachedir", "cache"], ["--outdir", "out"]): + ["--container_engine", "podman"], ["--cachedir", "cache"], ["--outdir", "out"], + ["--inputs_file", "inputs.yml"]): with pytest.raises(SystemExit, match="2"): cli.get_args("workflow.wic", ["--target", "nextflow", *flags]) with pytest.raises(SystemExit, match="2"): @@ -214,24 +175,16 @@ def test_the_run_modes_act_under_nextflow_and_an_option_only_a_cwl_run_reads_doe @pytest.mark.fast -def test_a_refusal_is_reported_on_stderr_as_a_diagnostic( - monkeypatch: pytest.MonkeyPatch, - tmp_path: Path, - capsys: pytest.CaptureFixture[str], +def test_a_plain_cwl_workflow_under_allow_raw_cwl_is_lowered_under_nextflow( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: - """A workflow the target cannot run is reported as any error is: on stderr, at its line, with its code and step, - and exit 1, with no file to go and read; and it leaves none of the files an earlier write left.""" - workflow = tmp_path / "refused.wic" - workflow.write_text('steps:\n echo:\n in:\n message: !ii hi\n when: $(inputs.message < "27")\n', - encoding="utf-8") + """Under the CWL target a plain workflow needs a mode to run in; under the Nextflow target it is lowered and + written.""" + raw = str(DATA / "nextflow" / "cli" / "raw.cwl") monkeypatch.chdir(tmp_path) - supported_workflow().compile(target="nextflow").write("autogenerated") - - assert run_cli(monkeypatch, "--yaml", workflow, "--target", "nextflow") == 1 - printed = capsys.readouterr() - assert ("refused.wic:2:3: error [nf-s010] when: '$(inputs.message < \"27\")' is outside the safe JavaScript " - "subset: < requires number operands, not string (step 'echo')") in printed.err - assert f"Failed to compile {workflow}" in printed.err - assert not (tmp_path / "error_refused.txt").exists() - # None of the four files an earlier write left is left. - assert not any((tmp_path / "autogenerated").iterdir()) + with pytest.raises(SystemExit, match="1"): + sophios_main._main(cli.get_args(raw, ["--allow_raw_cwl", "--homedir", str(tmp_path)]), []) + assert "--generate_cwl_workflow" in capsys.readouterr().out + sophios_main._main(cli.get_args(raw, [ + "--allow_raw_cwl", "--homedir", str(tmp_path), "--target", "nextflow", "--basepath", "out"]), []) + assert {path.name for path in (tmp_path / "out").iterdir()} == FOUR_FILES diff --git a/tests/core/nextflow/test_real_world_examples.py b/tests/core/nextflow/test_real_world_examples.py deleted file mode 100644 index 0d2cfb4e5..000000000 --- a/tests/core/nextflow/test_real_world_examples.py +++ /dev/null @@ -1,187 +0,0 @@ -"""Multi-step workflows written in Sophios, each with its own builder function, which test_import.py's fixed point -reads; test_runtime.py's scatter property runs their shapes.""" - -# pylint: disable=missing-function-docstring - -from pathlib import Path -from typing import Any - -from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl -from sophios.api.python.workflow import Step, StepInput, Workflow - -# One line per region the task covers. -_EMIT = 'group=$1; year=$2; shift 2; for region in "$@"; do printf "%s %s %s\\n" "$group" "$year" "$region"; done' -# One line, from the fetched file among the arguments that is this task's year. -_FROM_FETCH = ('year=$1; region=$2; shift 2; for data in "$@"; do read -r kind of < "$data"; ' - '[ "$of" = "$year" ] && printf "alpha %s %s %s\\n" "$year" "$region" "$kind"; done; true') -# A group's line count, then its lines, across every piece of every group. -_TALLY = ('group=$1; shift; lines=$(cat "$@" CommandLineTool: - """A tool that runs `script` under sh with its inputs as positional parameters, and keeps stdout.""" - outputs = Outputs(**{output: Output(cwl.file, glob=f"{output}.txt")}) - tool = CommandLineTool(name, Inputs(**inputs), outputs) - return tool.base_command("sh", "-c", script, name).stdout(f"{output}.txt") - - -def _report(**files: Any) -> Step: - """One report: every file of each input, in input order.""" - tool = CommandLineTool( - "report", Inputs(**{name: Input(cwl.array(cwl.file), position=index) for index, name in enumerate(files, 1)}), - Outputs(report=Output(cwl.file, glob="report.txt")), - ).base_command("cat").stdout("report.txt") - report = Step(tool, step_name="report") - for name, source in files.items(): - setattr(report.inputs, name, source) - return report - - -# Modelled on Matthew's repo, main.nf. -def plan_workflow() -> Workflow: - """(year, region) pairs; a crossproduct; one task per year over a list; an empty scatter.""" - per_region = _sh("per_region", _EMIT, "piece", group=Input(cwl.string, position=1), - year=Input(cwl.int, position=2), region=Input(cwl.string, position=3)) - - fetch = Step(_sh("fetch", 'printf "data %s\\n" "$1"', "data", year=Input(cwl.int, position=1)), - step_name="fetch") - fetch.inputs.year = list(_REGIONS) - fetch.scatter_on(fetch.inputs.year) - - # alpha: a dotproduct over (year, region) pairs; each task is given every - # fetched file and keeps the one for its own year. - pairs = [(year, region) for year, regions in _REGIONS.items() for region in regions] - alpha = Step(_sh("from_fetch", _FROM_FETCH, "piece", year=Input(cwl.int, position=1), - region=Input(cwl.string, position=2), fetched=Input(cwl.array(cwl.file), position=3)), - step_name="alpha") - alpha.inputs.year = [year for year, _ in pairs] - alpha.inputs.region = [region for _, region in pairs] - alpha.inputs.fetched = fetch.outputs.data - alpha.scatter_on(alpha.inputs.year, alpha.inputs.region) - - # beta: a region list crossed with the years. - beta = Step(per_region, step_name="beta") - beta.inputs.group = "beta" - beta.inputs.year = [2002, 2003] - beta.inputs.region = ["north", "south"] - beta.scatter_on(beta.inputs.year, beta.inputs.region, method="flat_crossproduct") - - # delta: one task per year over a whole region list. - delta = Step(_sh("per_year", _EMIT, "piece", group=Input(cwl.string, position=1), - year=Input(cwl.int, position=2), regions=Input(cwl.array(cwl.string), position=3)), - step_name="delta") - delta.inputs.group = "delta" - delta.inputs.year = [2002, 2003] - delta.inputs.regions = _REGIONS[2002] - delta.scatter_on(delta.inputs.year) - - # gamma: no years, so no tasks; its tally still runs. - gamma = Step(per_region, step_name="gamma") - gamma.inputs.group = "gamma" - gamma.inputs.year = [] - gamma.inputs.region = [] - gamma.scatter_on(gamma.inputs.year, gamma.inputs.region) - - groups = {"alpha": alpha, "beta": beta, "delta": delta, "gamma": gamma} - tally = Step(_sh("tally", _TALLY, "tally", group=Input(cwl.string, position=1), - **{f"pieces_{name}": Input(cwl.array(cwl.file), position=2) for name in groups}), - step_name="tally") - tally.inputs.group = list(groups) - for name, group in groups.items(): - setattr(tally.inputs, f"pieces_{name}", group.outputs.piece) - tally.scatter_on(tally.inputs.group) - - return Workflow([fetch, *groups.values(), tally, _report(tallies=tally.outputs.tally)], "plan") - - -# The (year, month) pairs of each lane. -_LANES = {"lane_a": [(2001, 11), (2001, 12), (2002, 1), (2002, 2)], "lane_b": [(2002, 6), (2002, 7)]} - - -# Modelled on Matthew's repo, satellite.nf. -def months_workflow(headers: Path) -> Workflow: - """Each lane's step is a dotproduct over (year, month) pairs; the report reads lane headers, - `//header.txt`.""" - per_month = _sh("per_month", 'printf "%s %04d-%02d\\n" "$1" "$2" "$3"', "piece", - lane=Input(cwl.string, position=1), year=Input(cwl.int, position=2), - month=Input(cwl.int, position=3)) - steps = {} - for lane, pairs in _LANES.items(): - step = steps[lane] = Step(per_month, step_name=lane) - step.inputs.lane = lane - step.inputs.year = [year for year, _ in pairs] - step.inputs.month = [month for _, month in pairs] - step.scatter_on(step.inputs.year, step.inputs.month) - report = _report(headers=[{"class": "File", "path": str(headers / lane / "header.txt")} for lane in _LANES], - **{name: step.outputs.piece for name, step in steps.items()}) - return Workflow([*steps.values(), report], "months") - - -# Modelled on Matthew's repo, nlcd.nf. -def summaries_workflow() -> Workflow: - """A year's fetched file reaches every task of that year's summary; another step reads them all merged.""" - fetch_tool = _sh("fetch", 'printf "data %s\\n" "$1"', "data", year=Input(cwl.int, position=1)) - summarise_tool = _sh("summarise", 'read -r kind of < "$2"; printf "%s %s %s\\n" "$of" "$1" "$kind"', "summary", - region=Input(cwl.string, position=1), data=Input(cwl.file, position=2)) - fetches, summaries = [], {} - for year, regions in _REGIONS.items(): - fetch = Step(fetch_tool, step_name=f"fetch_{year}") - fetch.inputs.year = year - summarise = summaries[f"summarise_{year}"] = Step(summarise_tool, step_name=f"summarise_{year}") - summarise.inputs.region = regions - summarise.inputs.data = fetch.outputs.data - summarise.scatter_on(summarise.inputs.region) - fetches.append(fetch) - - # Every task is given every fetched file, all named data.txt, and keeps the one for its own year. - pairs = [(year, region) for year, regions in _REGIONS.items() for region in regions] - across = Step(_sh("from_fetch", _FROM_FETCH, "summary", year=Input(cwl.int, position=1), - region=Input(cwl.string, position=2), fetched=Input(cwl.array(cwl.file), position=3)), - step_name="across") - across.inputs.year = [year for year, _ in pairs] - across.inputs.region = [region for _, region in pairs] - across.inputs.fetched = StepInput(source=[fetch.outputs.data for fetch in fetches], link_merge="merge_flattened") - across.scatter_on(across.inputs.year, across.inputs.region) - - report = _report(**{name: step.outputs.summary for name, step in {**summaries, "across": across}.items()}) - return Workflow([*fetches, *summaries.values(), across, report], "summaries") - - -# Modelled on Matthew's repo, quality.nf. -def tallies_workflow() -> Workflow: - """Scattered groups, one with no tasks, merge_flattened into one input of a scattered tally.""" - per_region = _sh("per_region", _EMIT, "piece", group=Input(cwl.string, position=1), - year=Input(cwl.int, position=2), region=Input(cwl.string, position=3)) - groups = {name: Step(per_region, step_name=name) for name in ("alpha", "beta", "gamma")} - for name, group in groups.items(): - group.inputs.group = name - alpha, beta, gamma = groups.values() - alpha.inputs.year, alpha.inputs.region = [2001, 2002], ["north", "south"] - beta.inputs.year, beta.inputs.region = [2002, 2003], ["north", "west"] - gamma.inputs.year, gamma.inputs.region = [], [] - alpha.scatter_on(alpha.inputs.year, alpha.inputs.region) - beta.scatter_on(beta.inputs.year, beta.inputs.region, method="flat_crossproduct") - gamma.scatter_on(gamma.inputs.year, gamma.inputs.region) - - tally = Step(_sh("tally", _TALLY, "tally", group=Input(cwl.string, position=1), - pieces=Input(cwl.array(cwl.file), position=2)), step_name="tally") - tally.inputs.group = list(groups) - tally.inputs.pieces = StepInput(source=[group.outputs.piece for group in groups.values()], - link_merge="merge_flattened") - tally.scatter_on(tally.inputs.group) - - return Workflow([*groups.values(), tally, _report(tallies=tally.outputs.tally)], "tallies") - - -# Modelled on Matthew's repo, quality.nf. -def flags_workflow() -> Workflow: - """Three boolean flags, the params file setting strict and verbose and clearing fast.""" - flags = Step(_sh("flags", 'printf "%s\\n" "$@"', "report", strict=Input(cwl.boolean, position=1, flag="--strict"), - verbose=Input(cwl.boolean, position=2, flag="--verbose"), - fast=Input(cwl.boolean, position=3, flag="--fast")), step_name="flags") - flags.inputs.strict, flags.inputs.verbose, flags.inputs.fast = True, True, False - return Workflow([flags], "flags") diff --git a/tests/core/nextflow/test_reference_differential.py b/tests/core/nextflow/test_reference_differential.py index 1280dbb73..3f91bb978 100644 --- a/tests/core/nextflow/test_reference_differential.py +++ b/tests/core/nextflow/test_reference_differential.py @@ -14,6 +14,7 @@ import pytest +from sophios.api.python.nextflow import NotLowered from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl from sophios.api.python.workflow import Step, Workflow from sophios.backends import recorded_outputs @@ -180,7 +181,10 @@ def _run_cwltool(main: Callable[..., int], workflow: Workflow, directory: Path) @pytest.mark.needs_cwltool def test_a_path_inputs_references_mean_under_nextflow_what_they_mean_under_cwltool(tmp_path: Path) -> None: """Plain File and Directory inputs, an entry linked and a writable one copied, and scattered elements of - both, each referenced plainly, by path and by basename, as an argument, the stdout target and a glob.""" + both, each referenced plainly, by path and by basename, as an argument, the stdout target and a glob. The one + cell left out, an entry under its own basename globbed by its plain reference, neither runner takes: CWL reads + `$(inputs.x)` as the Directory object, and a glob must be a string, so cwltool fails the step, and the Nextflow + target refuses it when compiling instead of running what CWL does not (design §6).""" import cwltool.main # pylint: disable=import-outside-toplevel observed, problems = {}, [] @@ -199,29 +203,21 @@ def test_a_path_inputs_references_mean_under_nextflow_what_they_mean_under_cwlto ] assert not problems, "\n".join(problems) + _neither_globs_an_entrys_object(cwltool.main.main, tmp_path / "object_glob") -@pytest.mark.needs_cwltool -def test_neither_runner_takes_an_entrys_object_as_a_glob(tmp_path: Path) -> None: - """The one cell the workflow above leaves out: an entry under its own basename globbed by its plain reference. - CWL reads `$(inputs.x)` as the Directory object, and a glob must be a string, so cwltool fails the step; the - Nextflow target refuses it when compiling instead of running what CWL does not (design §6).""" - import cwltool.main # pylint: disable=import-outside-toplevel +def _neither_globs_an_entrys_object(main: Callable[..., int], directory: Path) -> None: + """A writable entry globbed by its plain reference: refused by the Nextflow target, failed by cwltool.""" fill = CommandLineTool("fill", Inputs(x=Input(cwl.directory, position=1)), Outputs(o=Output(cwl.directory, glob="$(inputs.x)"))).base_command("touch") step = Step(fill.stage(fill.inputs.x, writable=True), step_name="fill") - (tmp_path / "in.d").mkdir() - step.inputs.x = tmp_path / "in.d" + (directory / "in.d").mkdir(parents=True) + step.inputs.x = directory / "in.d" workflow = Workflow([step], "object_glob") workflow.outputs.o = step.outputs.o - with pytest.raises(ValueError, match=r"\$\(inputs\.x\) is the File or Directory object, which CWL does not"): + with pytest.raises(NotLowered) as refused: workflow.compile(target="nextflow") - compiled = workflow.compile() - document, job = compiled.write_cwl(tmp_path / "cwl"), compiled.write_job_inputs(tmp_path / "cwl") - stderr = io.StringIO() - code = cwltool.main.main( - ["--quiet", "--outdir", str(tmp_path / "out"), "--tmpdir-prefix", f"{tmp_path}/tmp/", - "--tmp-outdir-prefix", f"{tmp_path}/tmp_out/", str(document), str(job)], - stdout=io.StringIO(), stderr=stderr, - ) - assert code != 0 and "Resolved glob patterns must be strings" in stderr.getvalue(), stderr.getvalue() + assert [(refusal.code.value, refusal.subject) for refusal in refused.value.refusals] == [ + ("nf-s046", "fill.cwl: outputs.o.outputBinding.glob")] + code, _, messages = _cwltool(main, workflow, directory) + assert code != 0 and "Resolved glob patterns must be strings" in messages, messages diff --git a/tests/core/nextflow/test_safe_subset.py b/tests/core/nextflow/test_safe_subset.py index efbf9c335..dc2b5afab 100644 --- a/tests/core/nextflow/test_safe_subset.py +++ b/tests/core/nextflow/test_safe_subset.py @@ -1,146 +1,57 @@ -"""The safe JavaScript subset, admitted only in a step's when (design §6, Expressions).""" +"""The safe JavaScript subset, admitted only in a step's when (design §6, Expressions). What a when decides is the +subset differential's; here, which texts the subset admits and how it reads them.""" # pylint: disable=missing-function-docstring -from dataclasses import replace -import re -from typing import Any - +from hypothesis import example, given, strategies as st import pytest -from sophios.lang.subset import Expr, check, parse +from sophios.lang.subset import canonical, check, parse, source_text from sophios.nf_expr import render_groovy -from sophios.nf_types import ExecutableNextflowWorkflow, NfTemplate - -from .test_conditions import _when_workflow -from .testkit import lowered_case, step, tool - -TYPES = { - "a": "int", "b": "float", "s": "string", "flag": "boolean", "maybe": ["null", "int"], "n": "long", "d": "double", -} - - -def _calc_workflow(arguments: list[Any], params: dict[str, Any], **inputs: Any) -> ExecutableNextflowWorkflow: - declared = { - name: cwl_type if isinstance(cwl_type, dict) else {"type": cwl_type} - for name, cwl_type in inputs.items() - } - calc = tool( - "CALC", - inputs=declared, - arguments=arguments, - baseCommand="echo", - stdout="out.txt", - outputs={"out": {"type": "File", "outputBinding": {"glob": "out.txt"}}}, - ) - workflow = { - "steps": [step("CALC", **{"in": {name: name for name in inputs}, "out": ["out"]})], - "inputs": {name: definition["type"] for name, definition in declared.items()}, - "outputs": {"out": {"type": "File", "outputSource": "CALC/out"}}, - } - return lowered_case({"workflow": workflow, "tools": [calc], "job": params})[0] - - -@pytest.mark.fast -@pytest.mark.parametrize(("text", "expected"), [ - ("$(1 + 2 * 3)", "number"), - ("$((inputs.a + 1) / 4 % 2)", "number"), - ("$(-inputs.b + +1e3)", "number"), - ("$(Math.min(inputs.a, inputs.b, 3))", "number"), - ("$(Math.round(Math.pow(inputs.b, 2)))", "number"), - ("$(inputs.a > 1 && !inputs.flag || inputs.s === 'x')", "boolean"), - ("$(inputs.maybe === null)", "boolean"), - ("$(inputs.a == 2.0)", "boolean"), -]) -def test_admitted_expressions_type_check(text: str, expected: str) -> None: - assert check(parse(text), TYPES) == expected - - -@pytest.mark.fast -@pytest.mark.parametrize(("text", "message"), [ - ("$(inputs.a ** 2)", "unsupported construct '**'"), - ("$(--inputs.a)", "unsupported construct '--'"), - ("$(1 ++ 2)", "unsupported construct '++'"), - ("$(inputs.a ? 1 : 2)", "unsupported construct '?'"), - ("$(inputs.a & 1)", "unsupported construct '&'"), - ("$(Math.PI)", "unsupported construct 'Math.PI'"), - ("$(inputs.s.length)", "unsupported construct 'inputs.s.length'"), - ("$(self)", "unsupported construct 'self'"), - ("$(runtime.cores)", "unsupported construct 'runtime.cores'"), - ("$(inputs.s + 1)", "+ requires number operands, not string"), - ("$(inputs.a == 'x')", "== requires two operands of the same type, not number and string"), - ("$(inputs.maybe + 1)", "optional inputs.maybe may only be compared with null"), - ("$(inputs.a === null)", "=== with null requires an optional input on the other side"), - ("$(!inputs.a)", "! requires boolean operands, not number"), - ("$(Math.pow(1))", "Math.pow takes 2 arguments"), - ("$(Math.min(1))", "Math.min takes 2 or more arguments"), - ("$(1e999)", "number literal 1e999 is not finite"), - ("$(010 + 1)", "number literal '010' is not a strict-mode decimal"), - ("$(08)", "number literal '08' is not a strict-mode decimal"), - ("$(\u0663)", "unsupported character"), - ("$(inputs.nope)", "inputs.nope is not an input of this tool"), - ("$(inputs.n > 1)", "inputs.n has type 'long'; only scalar inputs are admitted"), - ("$(inputs.d > 1)", "inputs.d has type 'double'; only scalar inputs are admitted"), - ("$(\"a\\\"b\")", "unsupported character"), -]) -def test_constructs_outside_the_subset_are_rejected_by_name(text: str, message: str) -> None: - with pytest.raises(ValueError, match=f"^{re.escape(message)}"): - check(parse(text), TYPES) - - -@pytest.mark.fast -def test_precedence_follows_javascript() -> None: - node = parse("$(1 + 2 * 3 - -4 < 5 || true && false)") - assert node.op == "||" - assert node.args[0].op == "<" - assert node.args[0].args[0].op == "-" - assert node.args[1].op == "&&" - -@pytest.mark.fast -def test_a_control_character_in_where_never_reaches_the_groovy_source() -> None: - rendered = render_groovy(parse("$(inputs.a * 2)"), where="CALC\narguments[0]\t", inputs="[a: a]") - assert "\n" not in rendered and "\t" not in rendered - assert "'CALC\\u000aarguments[0]\\u0009'" in rendered - - -COMPUTED = ["$(inputs.a * 2 + 1)", "$(inputs.a > 1)", "$(Math.round(inputs.b))", "$(runtime.cores)", "${return 1}"] - - -@pytest.mark.fast -@pytest.mark.parametrize("value_from", COMPUTED) -def test_a_computed_argument_valuefrom_is_rejected_by_name(value_from: str) -> None: - with pytest.raises(ValueError, match=re.escape( - "tool 'CALC.cwl: arguments[0].valueFrom': a computed valueFrom is not supported")): - _calc_workflow([{"prefix": "-n", "valueFrom": value_from}], {"a": 3, "b": 1.5}, a="int", b="float") - - -@pytest.mark.fast -@pytest.mark.parametrize("value_from", COMPUTED) -def test_a_computed_input_binding_valuefrom_is_rejected_by_name(value_from: str) -> None: - binding = {"type": "int", "inputBinding": {"position": 1, "valueFrom": value_from}} - with pytest.raises(ValueError, match=re.escape( - "tool 'CALC.cwl: inputs.a.inputBinding.valueFrom': a computed valueFrom")): - _calc_workflow([], {"a": 3, "b": 1.5}, a=binding, b="float") - - -@pytest.mark.fast -@pytest.mark.parametrize("value_from", ["7", "--n=$(inputs.a)", "$(inputs.a)", "$(inputs.a)-$(inputs.b)", - "$(inputs.a).$(inputs.b)"]) -def test_a_valuefrom_of_text_and_projections_stays_a_template(value_from: str) -> None: - workflow = _calc_workflow([{"valueFrom": value_from}], {"a": 1, "b": 2}, a="int", b="int") - assert isinstance(workflow.processes[0].command.tokens[-1], NfTemplate) - - -@pytest.mark.fast -@pytest.mark.parametrize(("node", "message"), [ - (Expr("Runtime.getRuntime().exec", (Expr("ref", value="a"),)), - "unsupported construct 'Runtime.getRuntime\\(\\)\\.exec'"), - (Expr("number", value="010"), "not a strict-mode decimal"), -]) -def test_a_condition_built_outside_the_closed_grammar_is_rejected(node: Expr, message: str) -> None: - """A tree built without parsing, as the reader builds one, is checked when its process is built.""" - process = _when_workflow("$(Math.pow(inputs.a, 2) > 1)", {"a": 3}, a="int").processes[0] - assert process.condition is not None - with pytest.raises(ValueError, match=message): - replace(process, condition=replace(process.condition, args=(node, *process.condition.args[1:]))) +from ..budgets import budget +from .test_subset_differential import _BOOLEAN, _NUMBER, TYPES + +#: Each input an expression here may read, by its CWL type; `w` and `d` are not scalar inputs. +_TYPES = {**TYPES, "a": "int", "w": "long", "d": "double"} + + +@pytest.mark.fast +@budget(200) +@given(st.one_of(_NUMBER.map(lambda text: (text, "number")), _BOOLEAN.map(lambda text: (text, "boolean"))), + st.text(st.characters(codec="utf-8"), max_size=8)) +@example(("1 + 2 * 3 - -4 < 5 || true && false", "boolean"), "CALC\narguments[0]\t") +@example(("Math.round(Math.pow(inputs.x, 2)) + Math.sqrt(4)", "number"), "") +@example(("inputs.maybe === null && null != inputs.maybe", "boolean"), "") +def test_an_admitted_expression_reads_back_as_written(admitted: tuple[str, str], where: str) -> None: + """An expression of the subset's grammar types as its grammar says; its canonical text parses to the same tree, + precedence and all; and its Groovy names where it stands without a raw control character.""" + text, kind = admitted + node = parse(f"$({text})") + assert check(node, _TYPES) == kind + assert canonical(parse(f"$({source_text(node)})")) == canonical(node) + rendered = render_groovy(node, where=where, inputs="[:]") + assert not any(ord(character) < 0x20 for character in rendered) + + +#: Text the subset does not read, each where an operand stands: an operator, a property, a name, a literal, a +#: character, or an operand of the wrong type. +_OUTSIDE = ["inputs.a ** 2", "--inputs.a", "1 ++ 2", "inputs.a ? 1 : 2", "inputs.a & 1", "Math.PI", "inputs.s.length", + "self", "runtime.cores", "inputs.s + 1", "inputs.a == 'x'", "inputs.maybe + 1", "inputs.a === null", + "!inputs.a", "Math.pow(1)", "Math.min(1)", "1e999", "010 + 1", "08", "Ù£", "inputs.nope", + "inputs.w", "inputs.d", '"a\\"b"'] + + +@pytest.mark.fast +@budget(200) +@given(_NUMBER, st.sampled_from(_OUTSIDE)) +@example("inputs.i", "inputs.a === null") +def test_an_expression_with_text_outside_the_subset_is_refused(admitted: str, outside: str) -> None: + """Text outside the subset is refused, alone and beside an admitted number, by parsing or by type, never read as + something else; beside a number it is admitted, so the text is what is refused.""" + with pytest.raises(ValueError): + check(parse(f"$({outside})"), _TYPES) + frame = "$(({}) + ({}) > 0)" + assert check(parse(frame.format(admitted, "1")), _TYPES) == "boolean" + with pytest.raises(ValueError): + check(parse(frame.format(admitted, outside)), _TYPES) diff --git a/tests/core/nextflow/test_step_inputs.py b/tests/core/nextflow/test_step_inputs.py deleted file mode 100644 index 2c252b957..000000000 --- a/tests/core/nextflow/test_step_inputs.py +++ /dev/null @@ -1,198 +0,0 @@ -"""Step-input default, linkMerge and pickValue lowering (design §6, Topology); their runs are the example -tests/core/data/nextflow/runs/step_inputs and the pickValue stops beside it.""" - -# pylint: disable=missing-function-docstring - -from typing import Any - -import pytest - -from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl -from sophios.api.python.workflow import Step, StepInput, Workflow -from sophios.input_output_nf import render_nextflow -from sophios.ir.resolved import NotLowered -from sophios.nf_types import ( - ExecutableNextflowWorkflow, NfPort, NfProcess, NfProcessConnection, NfStepInputConnection, - NfWorkflowInputConnection, -) -from sophios.wic_types import Yaml - -from .test_channels import _lower -from .testkit import command, lowered_case, output_port, refusal_lines, step, tool - -_STRINGS = {"type": "array", "items": "string"} - - -def _echo(name: str, port: Any) -> CommandLineTool: - """``echo`` its one input, an array per item, into out.txt.""" - return CommandLineTool( - name, Inputs(words=Input(port, position=1)), Outputs(line=Output(cwl.file, glob="out.txt")) - ).base_command("echo").stdout("out.txt") - - -def _say(name: str, port: Any, value: Any) -> Step: - step = Step(_echo(name, port), step_name=name) - step.inputs.words = value - return step - - -def _joined(step_input: Any, port_type: Any, inputs: dict[str, Any], *, scatter: bool = False) -> Any: - """A source workflow whose JOIN step binds ``step_input`` to its ``words``, of ``port_type``.""" - join = tool("JOIN", inputs={"words": {"type": port_type, "inputBinding": {"position": 1}}}, - outputs={"out": {"type": "File", "outputBinding": {"glob": "out.txt"}}}, stdout="out.txt") - fields = {"scatter": "words"} if scatter else {} - workflow = { - "steps": [step("JOIN", **{"in": {"words": {"wic_raw_cwl": step_input}}, "out": ["out"]}, **fields)], - "inputs": {name: {"type": declared} for name, (declared, _) in inputs.items()}, - "outputs": {"out": {"type": "File", "outputSource": "JOIN/out"}}, - } - return {"workflow": workflow, "tools": [join], "job": {name: value for name, (_, value) in inputs.items()}} - - -def _findings(case: Yaml) -> list[str]: - """The refusals of the case's lowering, as they print, less their spans.""" - with pytest.raises(NotLowered) as error: - lowered_case(case) - return refusal_lines(error.value) - - -_A, _B = ("string", "a"), ("string", "b") -#: How a refusal of the joined step input begins. -_WORDS = "step 'JOIN': input 'words': " - - -@pytest.mark.fast -@pytest.mark.parametrize(("step_input", "port_type", "inputs", "finding"), [ - ({"source": ["a", "b"], "linkMerge": "merge_deep"}, _STRINGS, {"a": _A, "b": _B}, - _WORDS + "linkMerge: unsupported linkMerge 'merge_deep'"), - ({"source": ["a", "b"], "pickValue": "any_non_null"}, "string", {"a": _A, "b": _B}, - _WORDS + "pickValue: unsupported pickValue 'any_non_null'"), - ({"source": "a", "pickValue": "first_non_null"}, "string", {"a": _A}, - _WORDS + "pickValue picks from a list; one source with no linkMerge is not one"), - ({"source": ["a", "b"], "default": "d"}, _STRINGS, {"a": _A, "b": _B}, - _WORDS + "default: a default never applies beside a linkMerge or a pickValue: the joined value " - "is not null"), - ({"default": ["d"]}, _STRINGS, {}, - _WORDS + "default: the Nextflow target supports a JSON scalar default of the tool input's type"), - ({"default": 1}, "string", {}, - _WORDS + "default: the Nextflow target supports a JSON scalar default of the tool input's type"), - ({"source": ["xs", "b"], "pickValue": "first_non_null"}, "string", {"xs": (_STRINGS, ["x"]), "b": _B}, - _WORDS + "'xs' is an array, and [] stands for both a null and an empty array, so pickValue " - "cannot take it"), - ({"source": "xs", "default": ["d"]}, _STRINGS, {"xs": (_STRINGS, ["x"])}, - _WORDS + "default: the Nextflow target supports a JSON scalar default of the tool input's type"), - ({"source": ["xs", "b"]}, _STRINGS, {"xs": (_STRINGS, ["x"]), "b": _B}, - _WORDS + "merge_nested over the array 'xs' makes a nested array, which is not supported"), - ({"source": ["maybe", "b"]}, _STRINGS, {"maybe": ("string?", "m"), "b": _B}, - _WORDS + "'maybe' may be null, and a joined list has no lowering of a null element; pick from " - "it with pickValue"), - ({"source": ["a", "b"]}, "string", {"a": _A, "b": _B}, - _WORDS + "the step input gives a list, but its tool input declares 'string'"), - ({"source": ["a", "b"], "pickValue": "first_non_null"}, _STRINGS, {"a": _A, "b": _B}, - _WORDS + "the step input gives one value, but its tool input declares " - "{'type': 'array', 'items': 'string'}"), - ({"source": ["a", "b"], "pickValue": "first_non_null"}, "File", {"a": ("File?", None), "b": ("File", "b.txt")}, - "workflow 'wf': workflow: workflow input 'a' is an absent optional File?, which has no lowering; give it a value"), - ({"source": "a", "default": "b.txt"}, "File", {"a": ("File?", "a.txt")}, - _WORDS + "default: a step-input default of a File or Directory input is not supported; give the " - "path as a workflow input"), -], ids=["link-merge", "pick-value", "pick-one-source", "default-beside-merge", "array-default", "mistyped-default", - "pick-over-array", "default-over-array", "nested-array", "null-element", "list-to-scalar", "one-to-list", - "pick-over-absent-path", "path-default"]) -def test_each_step_input_the_idioms_cannot_take_is_rejected_by_name( - step_input: Any, port_type: Any, inputs: dict[str, Any], finding: str -) -> None: - assert _findings(_joined(step_input, port_type, inputs)) == [finding] - - -@pytest.mark.fast -def test_a_scattered_input_takes_its_one_source_as_it_is() -> None: - rose = _joined({"source": ["xs"], "linkMerge": "merge_flattened"}, "string", {"xs": (_STRINGS, ["x"])}, - scatter=True) - assert "step 'JOIN': input 'words': a scattered input takes its one source as it is" in _findings(rose) - - -@pytest.mark.fast -def test_a_label_is_documentation() -> None: - plain = _joined({"source": ["a", "b"]}, _STRINGS, {"a": _A, "b": _B}) - labelled = _joined({"source": ["a", "b"], "label": "two words"}, _STRINGS, {"a": _A, "b": _B}) - assert render_nextflow(lowered_case(labelled)[0]) == render_nextflow(lowered_case(plain)[0]) - - -@pytest.mark.fast -def test_the_idioms_lower_to_one_step_input_connection() -> None: - lowered, _notes = lowered_case(_joined({"source": ["a", "b"]}, _STRINGS, {"a": _A, "b": _B})) - assert NfStepInputConnection( - (NfWorkflowInputConnection("a", "_JOIN", "words"), NfWorkflowInputConnection("b", "_JOIN", "words")), - "merge_nested", - ) in lowered.connections - defaulted, _notes = lowered_case( - _joined({"source": "maybe", "default": "d"}, "string", {"maybe": ("string?", None)}) - ) - assert defaulted.params == {"maybe": [], "_JOIN_words": "d"} - sources = (NfWorkflowInputConnection("maybe", "_JOIN", "words"), - NfWorkflowInputConnection("_JOIN_words", "_JOIN", "words")) - assert NfStepInputConnection(sources, "merge_nested", "first_non_null") in defaulted.connections - - -def _merged(*sources: Any, link_merge: str = "merge_flattened", pick_value: str | None = None, - port: NfPort | None = None) -> ExecutableNextflowWorkflow: - """PAIR gathers into, and A and the parameter xs join at, JOIN's input.""" - pair = NfProcess("PAIR", [NfPort("item", "val")], [output_port("f", "f.txt")], command("true")) - produce = NfProcess("A", [], [output_port("f", "a.txt")], command("true")) - join = NfProcess("JOIN", [port or NfPort("files", "path", is_array=True)], [], command("true")) - return ExecutableNextflowWorkflow( - "WF", [pair, produce, join], - [NfWorkflowInputConnection("items", "PAIR", "item", "dotproduct"), - NfStepInputConnection(sources, link_merge, pick_value)], - {"items": ["x"], "xs": ["x.txt"], "one": "o.txt"}, {"items": "string[]", "xs": "File[]", "one": "File"}, - ) - - -_GATHERED = NfProcessConnection("PAIR", "f", "JOIN", "files", "gather") -_ONE = NfProcessConnection("A", "f", "JOIN", "files") -_XS = NfWorkflowInputConnection("xs", "JOIN", "files") - - -@pytest.mark.fast -@pytest.mark.parametrize(("build", "message"), [ - (lambda: _merged(_ONE, pick_value="first_non_null"), "gives one value to a port that is array-typed"), - (lambda: _merged(_ONE, link_merge="merge_nested", port=NfPort("files", "path")), - "gives a list to a port that is not array-typed"), - (lambda: _merged(_GATHERED, _ONE, link_merge="merge_nested"), - "an array source joins only by merge_flattened with no pickValue"), - (lambda: _merged(_XS, _ONE, pick_value="all_non_null"), - "an array source joins only by merge_flattened with no pickValue"), - (lambda: _merged(NfWorkflowInputConnection("items", "JOIN", "files")), - "workflow input 'items' is val\\[\\], which its port's path cannot take"), - (lambda: _merged(_ONE, NfProcessConnection("A", "f", "PAIR", "item")), "must all reach one process input"), - (lambda: _merged(NfWorkflowInputConnection("xs", "JOIN", "files", "dotproduct")), - "a step input's sources cannot be scattered"), - (lambda: _merged(_ONE, link_merge="merge_deep"), "linkMerge must be one of"), -]) -def test_a_step_input_connection_keeps_the_idioms_invariants(build: Any, message: str) -> None: - with pytest.raises(ValueError, match=message): - build() - - -@pytest.mark.fast -def test_a_step_input_connection_renders_as_one_helper_call() -> None: - assert "__sophios_step_input_9f72e('JOIN.files', __values, [true, false, true], 'merge_flattened', null)" in ( - render_nextflow(_merged(_GATHERED, _ONE, _XS)) - ) - - -@pytest.mark.fast -def test_a_nested_steps_record_takes_its_sources_through_the_workflow_that_calls_it() -> None: - """Each source of a record on a step two workflows down resolves to what feeds it, in the order written.""" - inner = _say("inner", cwl.array(cwl.string), None) - middle = Workflow([inner], "middle") - inner.inputs.words = StepInput( - source=[middle.inputs.y.as_type("string"), middle.inputs.x.as_type("string")], link_merge="merge_nested" - ) - outer = Workflow([middle], "outer") - middle.inputs.x, middle.inputs.y = outer.inputs.x.as_type("string"), "y" - outer.inputs.x = "x" - lowered = _lower(Workflow([outer], "root")) - joined = next(connection for connection in lowered.connections if isinstance(connection, NfStepInputConnection)) - assert [lowered.params[source.from_port] for source in joined.sources] == ["y", "x"] diff --git a/tests/core/nextflow/test_support_table.py b/tests/core/nextflow/test_support_table.py index 09fc4765f..301914e8b 100644 --- a/tests/core/nextflow/test_support_table.py +++ b/tests/core/nextflow/test_support_table.py @@ -19,12 +19,6 @@ from .testkit import lowered_case, step, tool -@pytest.mark.fast -@pytest.mark.parametrize("cwl_class", sorted(SUPPORT_MATRIX)) -def test_the_sophios_classes_have_the_support_matrix_fields(cwl_class: str) -> None: - assert set(FIELDS[cwl_class]) == set(SUPPORT_MATRIX[cwl_class]) - - def _declared_fields(cwl_class: str) -> set[str]: """The fields cwl_utils declares for a CWL class, or cwltool's extension schema for a `cwltool:` one.""" if cwl_class.startswith("cwltool:"): @@ -34,44 +28,31 @@ def _declared_fields(cwl_class: str) -> set[str]: return set(getattr(cwl_v1_2, cwl_class).attrs) -@pytest.mark.fast -@pytest.mark.parametrize("cwl_class", sorted(FIELDS)) -def test_every_field_cwl_utils_or_cwltool_declares_is_classified(cwl_class: str) -> None: - assert set(FIELDS[cwl_class]) == _declared_fields(cwl_class) +# Design §3 names the compile-time fields: these wherever CWL declares them, and NetworkAccess. +COMPILE_TIME = {"doc", "format", "intent", "label", "streamable"} @pytest.mark.fast -def test_every_requirement_class_is_a_cwl_class_and_an_admitted_one_has_its_fields() -> None: +def test_the_table_classifies_every_field_cwl_declares_under_a_construct() -> None: + """Each class's rows are the fields cwl_utils or cwltool declares, Sophios's own classes' as the support matrix + has them; each requirement class is a CWL class, with its fields unless it is refused; every field stands under a + construct a refusal names (resolved-view §7); and the compile-time fields are the ones design §3 names.""" + assert {cwl_class: set(FIELDS[cwl_class]) for cwl_class in SUPPORT_MATRIX} == { + cwl_class: set(fields) for cwl_class, fields in SUPPORT_MATRIX.items()} + assert {cwl_class: set(rows) for cwl_class, rows in FIELDS.items()} == { + cwl_class: _declared_fields(cwl_class) for cwl_class in FIELDS} for classes in REQUIREMENT_CLASSES.values(): for name, row in classes.items(): - assert _declared_fields(name), name - assert row.state is State.REJECTED or name in FIELDS, name - - -@pytest.mark.fast -def test_every_field_stands_under_a_construct_a_refusal_names() -> None: - """A refusal names a construct of the view; the join says which fields each stands for (resolved-view §7).""" + assert _declared_fields(name) and (row.state is State.REJECTED or name in FIELDS), name assert set(CONSTRUCTS) == {construct.value for construct in Construct} rows = {row for joined in CONSTRUCTS.values() for row in joined} assert {cwl_class for cwl_class, _name in rows} <= set(FIELDS) assert [(cwl_class, name) for cwl_class, fields in FIELDS.items() for name in fields if (cwl_class, None) not in rows and (cwl_class, name) not in rows] == [] - - -# Design §3 names the compile-time fields: these wherever CWL declares them, and NetworkAccess. -COMPILE_TIME = {"doc", "format", "intent", "label", "streamable"} - - -@pytest.mark.fast -def test_the_compile_time_fields_are_the_ones_the_design_names() -> None: - compile_time = { - (cwl_class, name) for cwl_class, rows in FIELDS.items() for name, row in rows.items() - if row.state is State.COMPILE_TIME - } - assert compile_time == { - (cwl_class, name) for cwl_class, rows in FIELDS.items() for name in rows - if name in COMPILE_TIME or cwl_class == "NetworkAccess" - } + assert {(cwl_class, name) for cwl_class, fields in FIELDS.items() for name, row in fields.items() + if row.state is State.COMPILE_TIME} == { + (cwl_class, name) for cwl_class, fields in FIELDS.items() for name in fields + if name in COMPILE_TIME or cwl_class == "NetworkAccess"} def _strings() -> Yaml: @@ -171,17 +152,6 @@ def _lower(workflow: Yaml, run: Yaml, **values: Any) -> Any: ] -@pytest.mark.fast -@pytest.mark.parametrize(("cwl_class", "name"), REJECTED, ids=[f"{c}.{n}" for c, n in REJECTED]) -def test_a_rejected_field_is_a_finding_whose_message_is_its_note(cwl_class: str, name: str) -> None: - """One refusal carries the row's note, is of a construct the join gives the row, and names the field's place.""" - workflow, run = _documents() - _position(cwl_class)(workflow, run)[name] = "x" - refused = _refused(workflow, run, FIELDS[cwl_class][name].note) - assert [(refusal.construct in _constructs(cwl_class, name), refusal.subject) - for refusal in refused] == [(True, _subject(cwl_class, name))], refused - - SAMPLES = { "doc": "documentation", "label": "a label", "intent": ["http://edamontology.org/operation_0004"], "format": "http://edamontology.org/format_1929", "streamable": True, @@ -205,28 +175,54 @@ def test_compile_time_fields_leave_the_executable_model_unchanged() -> None: assert _lower(workflow, run, f=value) == plain -@pytest.mark.fast -@pytest.mark.parametrize("section", ["requirements", "hints"]) -@pytest.mark.parametrize("value", [False, "$(inputs.x)", None]) -def test_network_access_other_than_the_literal_true_is_rejected_by_name(section: str, value: Any) -> None: - workflow, run = _documents() - run[section] = {"NetworkAccess": {} if value is None else {"networkAccess": value}} - assert [(refusal.construct, refusal.subject) for refusal in _refused(workflow, run, "only the literal true is " - "supported: a Nextflow task has network access, and the generated pipeline cannot withhold it")] == [ - (Construct.TOOL, f"T.cwl: {section}.NetworkAccess.networkAccess")] - - REJECTED_CLASSES = sorted( name for name, row in REQUIREMENT_CLASSES["CommandLineTool"].items() if row.state is State.REJECTED ) +_WITHHELD = "only the literal true is supported: a Nextflow task has network access, and the generated pipeline " \ + "cannot withhold it" -@pytest.mark.fast -@pytest.mark.parametrize("section", ["requirements", "hints"]) -@pytest.mark.parametrize("name", REJECTED_CLASSES) -def test_a_rejected_requirement_class_is_a_finding_whose_message_is_its_note(section: str, name: str) -> None: +def _refused_as_its_row_says(place: Callable[[Yaml, Yaml], None], note: str, + constructs: set[str]) -> list[tuple[bool, str | None]]: + """The construct and subject of each refusal carrying `note`, when `place` puts a value in `_documents()`.""" workflow, run = _documents() - run[section] = {name: {}} - refused = _refused(workflow, run, REQUIREMENT_CLASSES["CommandLineTool"][name].note) - expected = [(Construct.TOOL, f"T.cwl: {section}.{name}")] - assert [(refusal.construct, refusal.subject) for refusal in refused] == expected + place(workflow, run) + return [(refusal.construct in constructs, refusal.subject) for refusal in _refused(workflow, run, note)] + + +def _field(cwl_class: str, name: str) -> Callable[[Yaml, Yaml], None]: + """Set the field `name` of `cwl_class` where `_documents()` holds it.""" + def place(workflow: Yaml, run: Yaml) -> None: + _position(cwl_class)(workflow, run)[name] = "x" + return place + + +def _section(section: str, requirements: Yaml) -> Callable[[Yaml, Yaml], None]: + """Give the tool `requirements` as its `section`.""" + def place(_workflow: Yaml, run: Yaml) -> None: + run[section] = requirements + return place + + +@pytest.mark.fast +def test_a_refused_row_is_refused_with_its_note_naming_its_place() -> None: + """Each refused field, refused requirement class and NetworkAccess other than the literal true, set in a workflow + that lowers without it, is one refusal carrying its row's note, of a construct the join gives the row, naming the + place it was set: the port it sits on, or in the tool the path to it.""" + expected: dict[str, list[tuple[bool, str | None]]] = {} + found: dict[str, list[tuple[bool, str | None]]] = {} + for cwl_class, name in REJECTED: + expected[f"{cwl_class}.{name}"] = [(True, _subject(cwl_class, name))] + found[f"{cwl_class}.{name}"] = _refused_as_its_row_says( + _field(cwl_class, name), FIELDS[cwl_class][name].note, _constructs(cwl_class, name)) + for section in ("requirements", "hints"): + for name in REJECTED_CLASSES: + expected[f"{section}.{name}"] = [(True, f"T.cwl: {section}.{name}")] + found[f"{section}.{name}"] = _refused_as_its_row_says( + _section(section, {name: {}}), REQUIREMENT_CLASSES["CommandLineTool"][name].note, {Construct.TOOL}) + for value in (False, "$(inputs.x)", None): + expected[f"{section}.NetworkAccess={value!r}"] = [(True, f"T.cwl: {section}.NetworkAccess.networkAccess")] + found[f"{section}.NetworkAccess={value!r}"] = _refused_as_its_row_says( + _section(section, {"NetworkAccess": {} if value is None else {"networkAccess": value}}), _WITHHELD, + {Construct.TOOL}) + assert found == expected diff --git a/tests/core/nextflow/testkit.py b/tests/core/nextflow/testkit.py index e0680ebc6..c42197a66 100644 --- a/tests/core/nextflow/testkit.py +++ b/tests/core/nextflow/testkit.py @@ -17,12 +17,12 @@ from sophios.compiler import compile_source, resolved_view from sophios.input_output_nf import write_nextflow_artifacts from sophios.ir.artifacts import CompilationResult +from sophios.ir.frontdoor import bundle_from_disk from sophios.ir.resolved import NotLowered from sophios.lang.diagnostics import Diagnostic from sophios.nf_types import ( ExecutableNextflowWorkflow, NfCommand, - NfFlag, NfInputReference, NfLiteral, NfPort, @@ -155,6 +155,20 @@ def lowered_case(data: Yaml) -> tuple[ExecutableNextflowWorkflow, tuple[Diagnost outputs=list(document.get("outputs", {})))) +def refusal_of(root: Path) -> NotLowered: + """What the Nextflow target refuses of the `.wic` file `root`, read as the command line reads a file, with the + tools and the other workflows of its directory, given the values of the `.yml` of its name beside it, if any.""" + tools = get_tools_cwl({"search_paths_cwl": {"global": [str(root.parent)]}}) + others = {"global": {path.stem: path for path in root.parent.glob("*.wic") if path != root}} + result = compile_source(bundle_from_disk(root, others, tools), default_compilation_settings(), quiet=True) + job = root.with_suffix(".yml") + try: + lowered(result, yaml.safe_load(job.read_text(encoding="utf-8")) if job.exists() else None) + except NotLowered as refused: + return refused + raise AssertionError(f"{root} is lowered: the Nextflow target refuses nothing of it") + + def refusal_lines(refused: NotLowered) -> list[str]: """Each refusal's owner and message: `step '': `, or `workflow '': `. Its span, which the line the document is written at decides, and its code, which a case names as its `codes`, are left @@ -189,49 +203,6 @@ def runtime_workflow() -> ExecutableNextflowWorkflow: ) -def flag_workflow() -> ExecutableNextflowWorkflow: - """A one-process pipeline whose command carries a conditional flag token.""" - process = NfProcess( - "SORT", - [NfPort("reverse", "val"), NfPort("source", "path")], - [output_port("result", "sorted.txt")], - NfCommand( - ( - template("sort"), - NfFlag("reverse", "-r"), - template(ref("source")), - ), - stdout=template("sorted.txt"), - ), - ) - return ExecutableNextflowWorkflow( - "PIPELINE", - [process], - [ - NfWorkflowInputConnection("reverse", "SORT", "reverse"), - NfWorkflowInputConnection("source", "SORT", "source"), - NfWorkflowOutputConnection("SORT", "result", "result"), - ], - {"reverse": True, "source": "lines.txt"}, {"reverse": "boolean", "source": "File"}, - ) - - -def single_process_workflow( - process: NfProcess, - *, - params: dict[str, Any], - param_types: dict[str, str], - output_port_name: str, -) -> ExecutableNextflowWorkflow: - """Wire every process input to a same-named workflow input plus one emit.""" - connections = [ - NfWorkflowInputConnection(port.name, process.name, port.name) - for port in process.inputs - ] - output_connection = NfWorkflowOutputConnection(process.name, output_port_name, "result") - return ExecutableNextflowWorkflow("PIPELINE", [process], [*connections, output_connection], params, param_types) - - def assert_succeeded(result: "subprocess.CompletedProcess[str]") -> None: """Fail with the process's whole output unless it exited 0.""" assert result.returncode == 0, f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}" diff --git a/tests/core/provocations.py b/tests/core/provocations.py index 89cfb106d..a7f7a7fe5 100644 --- a/tests/core/provocations.py +++ b/tests/core/provocations.py @@ -416,20 +416,31 @@ def _provoke_partial_failure() -> None: def _provoke_nextflow_refusal(code: SophiosErrorCode) -> None: - """The first case of tests/core/data/nextflow/rejected whose refusals name `code`, lowered to Nextflow; the - refusals raised as Sophios raises any error.""" + """The first root of tests/core/data/nextflow/refused whose refusals name `code`, lowered to Nextflow, or for the + one code no file can provoke, a NaN written in Python; the refusals raised as Sophios raises any error.""" # pylint: disable=import-outside-toplevel - from sophios.ir.resolved import NotLowered - from sophios.lang.diagnostics import SophiosError + from .cases import case_dirs + from .nextflow.testkit import refusal_of + + for family in case_dirs('nextflow/refused', 'roots'): + directory, expected = family.values + for root, refusals in expected['roots'].items(): + if any(refusal[0] == str(code) for refusal in refusals): + raise SophiosError(refusal_of(directory / root).diagnostics) + _provoke_not_a_number() + - from .cases import cases - from .nextflow.testkit import lowered_case +def _provoke_not_a_number() -> None: + """A float given NaN in Python, which no file can write and the parameters' JSON cannot hold.""" + # pylint: disable=import-outside-toplevel + from sophios.api.python.nextflow import NotLowered + from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Outputs, cwl + from sophios.api.python.workflow import Step, Workflow - case = next(param.values[0] for param in cases( - 'nextflow/rejected', 'tool', 'out', 'job', 'workflow', 'tools', 'error', 'findings', 'codes') - if str(code) in param.values[0].get('codes', ())) + ratio = Step(CommandLineTool('ratio', Inputs(x=Input(cwl.float, position=1)), Outputs()).base_command('echo')) + ratio.inputs.x = float('nan') try: - lowered_case(case) + Workflow([ratio], 'provoke').compile(target='nextflow') except NotLowered as refused: raise SophiosError(refused.diagnostics) from None diff --git a/tests/core/test_ci_coverage.py b/tests/core/test_ci_coverage.py index 85db6d553..02720f78f 100644 --- a/tests/core/test_ci_coverage.py +++ b/tests/core/test_ci_coverage.py @@ -409,14 +409,11 @@ def _tests_importing(module: str, path: Path) -> set[str]: # runner is checked on every leg by the file's other tests. 'tests/core/test_quiet.py::test_a_failing_step_is_named_with_its_status_below_its_own_messages', 'tests/core/test_quiet.py::test_a_quiet_run_keeps_a_file_the_tool_names_as_its_stdout', - # One six-step workflow run under Nextflow and under cwltool, in about four seconds. Only Lint And Test's - # Linux Nextflow step collects it, so the Windows leg gives up nothing it ran; what the references render - # is checked on every leg by the renderer's tests. + # One six-step workflow run under Nextflow and under cwltool, and one one-step tool cwltool fails, in about six + # seconds. Only Lint And Test's Linux Nextflow step collects it, so the Windows leg gives up nothing it ran; which + # references the target refuses is checked on every leg by the staging family of test_capabilities.py. 'tests/core/nextflow/test_reference_differential.py::' 'test_a_path_inputs_references_mean_under_nextflow_what_they_mean_under_cwltool', - # One cwltool run of a one-step tool that fails, in about two seconds. That the Nextflow target refuses the - # glob is checked on every leg by test_capabilities.py; only cwltool shows CWL refuses it too. - 'tests/core/nextflow/test_reference_differential.py::test_neither_runner_takes_an_entrys_object_as_a_glob', # Seven example workflows run under Nextflow, six of them under cwltool too, and nine that stop, in about # forty-five seconds together. Lint And Test's Linux Nextflow step collects them, so the Windows leg gives up # nothing it ran. @@ -426,7 +423,7 @@ def _tests_importing(module: str, path: Path) -> set[str]: # Four batches of up to twelve small workflows, each run under Nextflow and under cwltool, in about ten # seconds; and one batch of four, whose tools run in containers, in about ten more. Lint And Test's Linux # Nextflow step collects them, so the Windows leg gives up nothing it ran; what each lowers to is checked on - # every leg by the lowering's data cases and the import's fixed point. + # every leg by the import's fixed point. 'tests/core/nextflow/test_step_only_differential.py::' 'test_inherited_docker_requirements_and_greeting_if_run_as_under_cwltool', 'tests/core/nextflow/test_step_only_differential.py::' diff --git a/tests/core/test_run_local.py b/tests/core/test_run_local.py index f09c3c700..382bb9f5a 100644 --- a/tests/core/test_run_local.py +++ b/tests/core/test_run_local.py @@ -685,10 +685,11 @@ async def run_async() -> None: result = gpu_workflow().run(target='nextflow') gpu_workflow().start(target='nextflow').wait() asyncio.run(run_async()) - assert [line for line in capsys.readouterr().err.splitlines() if '[wic046]' in line] == CUDA_NOTES * 3 + printed = [line for line in capsys.readouterr().err.splitlines() if '[wic046]' in line] assert result is not None cuda = [note for note in result.diagnostics if note.code is SophiosErrorCode.UNCHECKED_CUDA_FIELD] - assert [str(note) for note in cuda] == CUDA_NOTES + assert [(str(note.severity), str(note.code), note.locator and note.locator.step) for note in cuda] == CUDA_NOTES + assert [str(note) for note in cuda] * 3 == printed @pytest.mark.fast From 8ba8450e6de96d2288e1ab5f8cdd1b50220548b9 Mon Sep 17 00:00:00 2001 From: Vasu Jaganath Date: Thu, 12 Nov 2026 15:33:10 -0500 Subject: [PATCH 3/7] test(lang): parse documents by family, laws kept The parse case tables and accepted shapes are seven families of .wic documents, each stated by code, line, column and reading; one census loops the code table, and the schema keeps its laws but no pins on how it is built. --- .github/workflows/property_weekly.yml | 2 +- docs/dev/codingstandards.md | 6 +- docs/dev/language_spec.md | 61 +- docs/validation.md | 5 +- src/sophios/lang/support.py | 12 +- tests/core/data/lang_version/calls_a_pin.wic | 6 + .../data/lang_version/implementation_pins.wic | 12 + tests/core/data/lang_version/mistyped.wic | 7 + tests/core/data/lang_version/pinned.wic | 7 + tests/core/data/lang_version/pins_none.wic | 7 + tests/core/data/lang_version/unpinned.wic | 5 + tests/core/data/parse/aliases/blocks.wic | 9 + tests/core/data/parse/aliases/cycles.wic | 16 + tests/core/data/parse/aliases/expected.yaml | 26 + tests/core/data/parse/aliases/laughs.wic | 9 + tests/core/data/parse/document/expected.yaml | 55 + tests/core/data/parse/document/imports.wic | 26 + .../core/data/parse/document/invalid_yaml.wic | 2 + tests/core/data/parse/document/list_forms.wic | 25 + .../data/parse/document/not_a_mapping.wic | 3 + tests/core/data/parse/document/top_level.wic | 20 + tests/core/data/parse/edges.yaml | 61 - tests/core/data/parse/edges/defined.wic | 19 + tests/core/data/parse/edges/expected.yaml | 42 + tests/core/data/parse/edges/misplaced.wic | 24 + tests/core/data/parse/list_forms.yaml | 83 -- tests/core/data/parse/records.yaml | 36 - tests/core/data/parse/records/expected.yaml | 36 + tests/core/data/parse/records/inputs.wic | 18 + tests/core/data/parse/records/refused.wic | 17 + tests/core/data/parse/steps.yaml | 53 - tests/core/data/parse/steps/by_name.wic | 7 + tests/core/data/parse/steps/expected.yaml | 43 + tests/core/data/parse/steps/in_a_sequence.wic | 39 + tests/core/data/parse/steps/keys.wic | 14 + tests/core/data/parse/tags.yaml | 110 -- tests/core/data/parse/tags/blocks.wic | 3 + tests/core/data/parse/tags/expected.yaml | 46 + tests/core/data/parse/tags/sidecar.wic | 11 + tests/core/data/parse/tags/unclaimed.wic | 12 + tests/core/data/parse/tags/unknown.wic | 29 + tests/core/data/parse/tags/wic_steps.wic | 4 + tests/core/data/parse/wic_block.yaml | 15 - tests/core/data/parse/wic_block/empty.wic | 6 + tests/core/data/parse/wic_block/every_key.wic | 53 + tests/core/data/parse/wic_block/expected.yaml | 68 ++ tests/core/data/parse/wic_block/root.wic | 16 + tests/core/data/parse/wic_block/steps.wic | 18 + tests/core/data/parse/wic_values.yaml | 29 - tests/core/data/provoke/empty_name.wic | 5 + tests/core/data/provoke/top_level_hints.wic | 11 + tests/core/data/provoke/undeclared_port.wic | 6 + tests/core/data/render/rendered.wic | 53 + tests/core/data/render/written.wic | 43 + tests/core/provocations.py | 62 +- tests/core/test_cwl_version.py | 59 - tests/core/test_hermeticity.py | 1 - tests/core/test_lang_parser.py | 1031 +++++------------ tests/core/test_lang_render.py | 272 +---- tests/core/test_lang_schema.py | 305 ++--- tests/core/test_lang_version.py | 169 +-- tests/core/test_namespacing.py | 45 - 62 files changed, 1350 insertions(+), 1945 deletions(-) create mode 100644 tests/core/data/lang_version/calls_a_pin.wic create mode 100644 tests/core/data/lang_version/implementation_pins.wic create mode 100644 tests/core/data/lang_version/mistyped.wic create mode 100644 tests/core/data/lang_version/pinned.wic create mode 100644 tests/core/data/lang_version/pins_none.wic create mode 100644 tests/core/data/lang_version/unpinned.wic create mode 100644 tests/core/data/parse/aliases/blocks.wic create mode 100644 tests/core/data/parse/aliases/cycles.wic create mode 100644 tests/core/data/parse/aliases/expected.yaml create mode 100644 tests/core/data/parse/aliases/laughs.wic create mode 100644 tests/core/data/parse/document/expected.yaml create mode 100644 tests/core/data/parse/document/imports.wic create mode 100644 tests/core/data/parse/document/invalid_yaml.wic create mode 100644 tests/core/data/parse/document/list_forms.wic create mode 100644 tests/core/data/parse/document/not_a_mapping.wic create mode 100644 tests/core/data/parse/document/top_level.wic delete mode 100644 tests/core/data/parse/edges.yaml create mode 100644 tests/core/data/parse/edges/defined.wic create mode 100644 tests/core/data/parse/edges/expected.yaml create mode 100644 tests/core/data/parse/edges/misplaced.wic delete mode 100644 tests/core/data/parse/list_forms.yaml delete mode 100644 tests/core/data/parse/records.yaml create mode 100644 tests/core/data/parse/records/expected.yaml create mode 100644 tests/core/data/parse/records/inputs.wic create mode 100644 tests/core/data/parse/records/refused.wic delete mode 100644 tests/core/data/parse/steps.yaml create mode 100644 tests/core/data/parse/steps/by_name.wic create mode 100644 tests/core/data/parse/steps/expected.yaml create mode 100644 tests/core/data/parse/steps/in_a_sequence.wic create mode 100644 tests/core/data/parse/steps/keys.wic delete mode 100644 tests/core/data/parse/tags.yaml create mode 100644 tests/core/data/parse/tags/blocks.wic create mode 100644 tests/core/data/parse/tags/expected.yaml create mode 100644 tests/core/data/parse/tags/sidecar.wic create mode 100644 tests/core/data/parse/tags/unclaimed.wic create mode 100644 tests/core/data/parse/tags/unknown.wic create mode 100644 tests/core/data/parse/tags/wic_steps.wic delete mode 100644 tests/core/data/parse/wic_block.yaml create mode 100644 tests/core/data/parse/wic_block/empty.wic create mode 100644 tests/core/data/parse/wic_block/every_key.wic create mode 100644 tests/core/data/parse/wic_block/expected.yaml create mode 100644 tests/core/data/parse/wic_block/root.wic create mode 100644 tests/core/data/parse/wic_block/steps.wic delete mode 100644 tests/core/data/parse/wic_values.yaml create mode 100644 tests/core/data/provoke/empty_name.wic create mode 100644 tests/core/data/provoke/top_level_hints.wic create mode 100644 tests/core/data/provoke/undeclared_port.wic create mode 100644 tests/core/data/render/rendered.wic create mode 100644 tests/core/data/render/written.wic delete mode 100644 tests/core/test_cwl_version.py delete mode 100644 tests/core/test_namespacing.py diff --git a/.github/workflows/property_weekly.yml b/.github/workflows/property_weekly.yml index d0fcf6dcf..ba7a7f4b2 100644 --- a/.github/workflows/property_weekly.yml +++ b/.github/workflows/property_weekly.yml @@ -88,7 +88,7 @@ jobs: if: ${{ !cancelled() && steps.setup.outcome == 'success' }} timeout-minutes: 180 run: >- - pytest tests/core/test_generators.py tests/core/test_equivalence.py tests/core/test_equivalences.py tests/core/test_predicates.py tests/core/test_reference_compatibility.py tests/core/test_canonical_path.py tests/core/test_emit.py tests/core/test_resolve.py tests/core/test_link.py tests/core/test_infer_phase.py tests/core/test_cwl_version.py tests/core/test_names_emitted.py tests/core/test_edge_binding.py tests/core/test_lower.py tests/core/test_pipeline.py + pytest tests/core/test_generators.py tests/core/test_equivalence.py tests/core/test_equivalences.py tests/core/test_predicates.py tests/core/test_reference_compatibility.py tests/core/test_canonical_path.py tests/core/test_emit.py tests/core/test_resolve.py tests/core/test_link.py tests/core/test_infer_phase.py tests/core/test_names_emitted.py tests/core/test_edge_binding.py tests/core/test_lower.py tests/core/test_pipeline.py tests/core/test_leak_boundary.py::test_step_passthrough_is_byte_identical tests/core/test_leak_boundary.py::test_top_level_passthrough_is_byte_identical tests/core/test_leak_boundary.py::test_hints_survive_on_the_document_and_the_step_and_change_nothing_else diff --git a/docs/dev/codingstandards.md b/docs/dev/codingstandards.md index 87348036b..3ea5fdf2f 100644 --- a/docs/dev/codingstandards.md +++ b/docs/dev/codingstandards.md @@ -65,9 +65,9 @@ command line, `Workflow`, `Step`, `CommandLineTool`, or `compile_source`. A test that pins existing behaviour should fail under a plausible mutation of it. Markers are listed in [Validation and testing](../validation.md); a test that pulls images or runs a container is marked so that the quick lanes skip -it. Every new error code lands with its provocation in -`tests/core/provocations.py` and its explanation in `EXPLANATIONS`, or the -suite fails. +it. Every new error code lands with its provocation, a document under +`tests/core/data/parse` or a callable in `tests/core/provocations.py`, and its +explanation in `EXPLANATIONS`, or the suite fails. ## Before pushing diff --git a/docs/dev/language_spec.md b/docs/dev/language_spec.md index c7a76bbc3..330a0788c 100644 --- a/docs/dev/language_spec.md +++ b/docs/dev/language_spec.md @@ -73,7 +73,7 @@ step's tool is passthrough wholesale: Sophios does not classify | `label` | passthrough | | `test_top_level_passthrough_is_byte_identical` | | `outputs` | native | read: `outputSource` is resolved; merged into | `test_class_is_written_while_inputs_outputs_and_version_are_not` | | `requirements` | native | merged into | `test_user_requirements_are_merged_into_not_copied` | -| `steps` | native | | `test_well_formed_documents_parse` (`test_lang_parser.py`) | +| `steps` | native | | `test_a_well_formed_document_is_read_whole` (`test_lang_parser.py`) | **`WorkflowStep`** @@ -81,10 +81,10 @@ step's tool is passthrough wholesale: Sophios does not classify |---|---|---|---| | `doc` | passthrough | | `test_step_passthrough_is_byte_identical` | | `hints` | passthrough | | `test_step_passthrough_is_byte_identical` | -| `id` | native | `[A-Za-z0-9_-][A-Za-z0-9_.-]*`, else `wic045`, as for workflow input and output names and the root's name | `test_sequence_and_mapping_steps_agree` (`test_lang_parser.py`), `test_a_step_id_outside_the_allowed_characters_is_refused_at_its_line` (`test_diagnostics.py`) | -| `in` | native | | `test_input_values_are_closed` (`test_lang_parser.py`) | +| `id` | native | `[A-Za-z0-9_-][A-Za-z0-9_.-]*`, else `wic045`, as for workflow input and output names and the root's name | `test_a_well_formed_document_is_read_whole` (`test_lang_parser.py`), `test_a_step_id_outside_the_allowed_characters_is_refused_at_its_line` (`test_diagnostics.py`) | +| `in` | native | | `test_a_well_formed_document_is_read_whole` (`test_lang_parser.py`) | | `label` | passthrough | | `test_step_passthrough_is_byte_identical` | -| `out` | native | | `test_the_two_spellings_of_an_edge_definition_agree_on_an_output` (`test_lang_parser.py`) | +| `out` | native | | `test_a_construct_reads_alike_in_either_spelling_and_position` (`test_lang_parser.py`) | | `requirements` | passthrough | | `test_step_passthrough_is_byte_identical` | | `run` | native | a registry stem, a path relative to the document, or an inline body | `test_each_step_runs_the_tool_its_run_names` (`test_frontdoor.py`) | | `scatter` | native | | `test_every_declared_key_is_interpreted` | @@ -95,8 +95,8 @@ step's tool is passthrough wholesale: Sophios does not classify | Field | Support | Note | Pinned by | |---|---|---|---| -| `id` | native | the `in:` key | `test_input_values_are_closed` (`test_lang_parser.py`) | -| `source` | native | `!*`, a bare workflow-input name, or a list of them inside `!cwl {source: [...]}` | `test_input_values_are_closed` (`test_lang_parser.py`) | +| `id` | native | the `in:` key | `test_a_document_reads_as_its_family_states` (`test_lang_parser.py`) | +| `source` | native | `!*`, a bare workflow-input name, or a list of them inside `!cwl {source: [...]}` | `test_a_document_reads_as_its_family_states` (`test_lang_parser.py`) | | `default` | native | through `!cwl {...}`; a relative File or Directory `location`/`path` is written absolute against the `.wic`'s directory | `test_a_cwl_record_emits_the_fields_it_carries` (`test_emit.py`), `test_a_wic_file_default_is_written_absolute_against_the_wic` (`test_wic_defaults.py`) | | `label` | native | through `!cwl {...}` | `test_a_cwl_record_emits_the_fields_it_carries` (`test_emit.py`) | | `linkMerge` | native | through `!cwl {...}` | `test_a_cwl_record_emits_the_fields_it_carries` (`test_emit.py`) | @@ -258,7 +258,7 @@ passthrough keys. `sophios.lang.render`, which emits the tagged one; the two are inverses, the round-trip property in `tests/core/test_lang_render.py`. A nested step entry keeps its `wic:` wrapper through a render, and an empty `wic:` block renders -as `{}`, never as a null (`test_empty_sidecar_renders_as_mapping_not_null`). +as `{}`, never as a null (`tests/core/data/render`). **The Python API** (`Workflow`, `Step`) is the second surface of the same language. It builds a `sophios.lang.Document` directly, compiles it through @@ -278,8 +278,7 @@ Two obligations follow, both enforced by tests: 1. Whatever the Python API writes as a `.wic` file must parse, for every workflow, nested or not - (`test_python_api_emits_documents_this_parser_accepts` in - `tests/core/test_lang_parser.py`). + (`tests/core/test_python_api_workflow.py`). 2. Both spellings must produce the same result: `!ii x` and `{wic_inline_input: x}` are the same input, checked as a property over generated inputs in `tests/core/test_lang_parser.py`. And both surfaces @@ -363,11 +362,11 @@ is never renumbered, and a code that shipped in a release is never reused; `wic040`, `wic041` and `wic042` are unassigned. `wic043` is a note, an error under `--inference_strict`. -Every member is provoked in `tests/core/provocations.py`, in one of two -tiers: `PARSE` (source text through `parse()` alone) or `COMPILED` (a -callable that drives the compiler or its helpers). -`test_every_code_has_a_registered_provocation` fails for a member with no -provocation, so a new code lands with its provocation in the same commit. +Every member is provoked, in one of two ways: a document under +`tests/core/data/parse` reports it (`data/parse`), or a callable in +`tests/core/provocations.py` that drives the compiler or its helpers raises it +(`COMPILED`). `tests/core/test_lang_parser.py` fails for a member neither +provokes, so a new code lands with its provocation in the same commit. Every member has an `Explanation` in `EXPLANATIONS` (kind, meaning, fix); `test_every_code_is_explained` fails for one without, and `test_the_error_codes_page_says_what_the_code_says` keeps the @@ -375,16 +374,16 @@ Every member has an `Explanation` in `EXPLANATIONS` (kind, meaning, fix); | Code | Member | Provoked in | |---|---|---| -| `wic001` | `INVALID_YAML` | `PARSE` | -| `wic002` | `NOT_A_MAPPING` | `PARSE` | -| `wic003` | `EXPECTED_MAPPING` | `PARSE` | -| `wic004` | `EXPECTED_SEQUENCE` | `PARSE` | -| `wic005` | `EXPECTED_SCALAR` | `PARSE` | -| `wic006` | `MISSING_STEP_ID` | `PARSE` | -| `wic007` | `EMPTY_STEP_ID` | `PARSE` | -| `wic008` | `MALFORMED_WIC_STEP_KEY` | `PARSE` | -| `wic009` | `UNKNOWN_TAG` | `PARSE` | -| `wic010` | `DUPLICATE_KEY` | `PARSE` | +| `wic001` | `INVALID_YAML` | `data/parse` | +| `wic002` | `NOT_A_MAPPING` | `data/parse` | +| `wic003` | `EXPECTED_MAPPING` | `data/parse` | +| `wic004` | `EXPECTED_SEQUENCE` | `data/parse` | +| `wic005` | `EXPECTED_SCALAR` | `data/parse` | +| `wic006` | `MISSING_STEP_ID` | `data/parse` | +| `wic007` | `EMPTY_STEP_ID` | `data/parse` | +| `wic008` | `MALFORMED_WIC_STEP_KEY` | `data/parse` | +| `wic009` | `UNKNOWN_TAG` | `data/parse` | +| `wic010` | `DUPLICATE_KEY` | `data/parse` | | `wic011` | `UNRESOLVED_INPUT` | `COMPILED` | | `wic012` | `MISSING_REQUIRED_INPUT` | `COMPILED` | | `wic013` | `SUBWORKFLOW_INVALID` | `COMPILED` | @@ -393,26 +392,26 @@ Every member has an `Explanation` in `EXPLANATIONS` (kind, meaning, fix); | `wic016` | `MISSING_INPUT_FILE` | `COMPILED` | | `wic017` | `UNKNOWN_LANG_VERSION` | `COMPILED` | | `wic018` | `LANG_VERSION_CONFLICT` | `COMPILED` | -| `wic019` | `MISPLACED_EDGE_DEF` | `PARSE` | +| `wic019` | `MISPLACED_EDGE_DEF` | `data/parse` | | `wic020` | `LITERAL_TYPE_MISMATCH` | `COMPILED` | | `wic021` | `DIRECTORY_NOT_WRITABLE` | `COMPILED` | | `wic022` | `FIXED_POINT_NOT_REACHED` | `COMPILED` | | `wic023` | `INCOMPATIBLE_INPUT_REFERENCE` | `COMPILED` | -| `wic024` | `RESERVED_KEY` | `PARSE` | +| `wic024` | `RESERVED_KEY` | `data/parse` | | `wic025` | `UNDEFINED_EDGE` | `COMPILED` | | `wic026` | `DUPLICATE_EDGE_DEF` | `COMPILED` | | `wic027` | `EMPTY_NAME` | `COMPILED` | | `wic028` | `UNDECLARED_PORT` | `COMPILED` | | `wic029` | `PROGRAM_MISSING` | `COMPILED` | -| `wic030` | `RECURSIVE_ALIAS` | `PARSE` | +| `wic030` | `RECURSIVE_ALIAS` | `data/parse` | | `wic031` | `DUPLICATE_DOCUMENT_NAME` | `COMPILED` | | `wic032` | `UNKNOWN_SCATTER_PORT` | `COMPILED` | -| `wic033` | `UNKNOWN_WIC_KEY` | `PARSE` | -| `wic034` | `MALFORMED_WIC_VALUE` | `PARSE` | -| `wic035` | `UNSUPPORTED_CWL_VERSION` | `PARSE` | +| `wic033` | `UNKNOWN_WIC_KEY` | `data/parse` | +| `wic034` | `MALFORMED_WIC_VALUE` | `data/parse` | +| `wic035` | `UNSUPPORTED_CWL_VERSION` | `data/parse` | | `wic036` | `UNTYPED_OUTPUT` | `COMPILED` | | `wic037` | `IMAGE_UNAVAILABLE` | `COMPILED` | -| `wic038` | `STEP_INPUT_RECORD` | `PARSE` | +| `wic038` | `STEP_INPUT_RECORD` | `data/parse` | | `wic039` | `POSITIONAL_OUTPUT_SOURCE` | `COMPILED` | | `wic043` | `INFERENCE_GUESS` | `COMPILED` | | `wic044` | `REALTIME_DECLARATION` | `COMPILED` | diff --git a/docs/validation.md b/docs/validation.md index c17225e75..de1795e12 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -56,8 +56,9 @@ Three kinds of test carry the promises the documentation makes: edge a parent supplies) or `intensive` (the weekly lane runs those); those named `run_partial_failures` run with `--partial_failure_enable`. `tests/core/test_examples.py` drives it. - **The catalog.** `test_the_error_codes_page_says_what_the_code_says` keeps - `docs/error_codes.md` equal to `EXPLANATIONS`; every code has a provocation - in `tests/core/provocations.py` and an explanation, or the suite fails. + `docs/error_codes.md` equal to `EXPLANATIONS`; every code has a provocation, + a document under `tests/core/data/parse` or a callable in `tests/core/provocations.py`, and an + explanation, or the suite fails. ## Property-Based Testing diff --git a/src/sophios/lang/support.py b/src/sophios/lang/support.py index a0f5221a7..d6cac7368 100644 --- a/src/sophios/lang/support.py +++ b/src/sophios/lang/support.py @@ -55,16 +55,16 @@ class Row: 'label': Row(_P, _TOP_LEVEL), 'outputs': Row(_N, _WRITTEN, 'read: outputSource is resolved; merged into'), 'requirements': Row(_N, 'test_user_requirements_are_merged_into_not_copied', 'merged into'), - 'steps': Row(_N, 'test_well_formed_documents_parse'), + 'steps': Row(_N, 'test_a_well_formed_document_is_read_whole'), }) WORKFLOW_STEP: Final[Mapping[str, Row]] = MappingProxyType({ 'doc': Row(_P, _STEP), 'hints': Row(_P, _STEP), - 'id': Row(_N, 'test_sequence_and_mapping_steps_agree'), - 'in': Row(_N, 'test_input_values_are_closed'), + 'id': Row(_N, 'test_a_well_formed_document_is_read_whole'), + 'in': Row(_N, 'test_a_well_formed_document_is_read_whole'), 'label': Row(_P, _STEP), - 'out': Row(_N, 'test_the_two_spellings_of_an_edge_definition_agree_on_an_output'), + 'out': Row(_N, 'test_a_construct_reads_alike_in_either_spelling_and_position'), 'requirements': Row(_P, _STEP), 'run': Row(_N, 'test_each_step_runs_the_tool_its_run_names', 'a registry stem, a path relative to the document, or an inline body'), @@ -74,8 +74,8 @@ class Row: }) WORKFLOW_STEP_INPUT: Final[Mapping[str, Row]] = MappingProxyType({ - 'id': Row(_N, 'test_input_values_are_closed', 'the in: key'), - 'source': Row(_N, 'test_input_values_are_closed', + 'id': Row(_N, 'test_a_document_reads_as_its_family_states', 'the in: key'), + 'source': Row(_N, 'test_a_document_reads_as_its_family_states', '!*, a bare workflow-input name, or a list of them inside !cwl {source: [...]}'), 'default': Row(_N, _RECORD, 'through !cwl {...}'), 'label': Row(_N, _RECORD, 'through !cwl {...}'), diff --git a/tests/core/data/lang_version/calls_a_pin.wic b/tests/core/data/lang_version/calls_a_pin.wic new file mode 100644 index 000000000..dfb48d123 --- /dev/null +++ b/tests/core/data/lang_version/calls_a_pin.wic @@ -0,0 +1,6 @@ +# Pinned to a version that exists, calling a workflow pinned to one that does not: every document's pin counts. +wic: + lang_version: 0.0.1 +steps: +- id: child + run: pins_none.wic diff --git a/tests/core/data/lang_version/implementation_pins.wic b/tests/core/data/lang_version/implementation_pins.wic new file mode 100644 index 000000000..29084eeae --- /dev/null +++ b/tests/core/data/lang_version/implementation_pins.wic @@ -0,0 +1,12 @@ +# Its one implementation pins a language version that does not exist; the body selected decides the version too. +wic: + default_implementation: fast + implementations: + fast: + wic: + lang_version: 9.9.9 + steps: + - id: touch + in: + filename: !ii empty.txt +steps: [] diff --git a/tests/core/data/lang_version/mistyped.wic b/tests/core/data/lang_version/mistyped.wic new file mode 100644 index 000000000..e1f93cf1c --- /dev/null +++ b/tests/core/data/lang_version/mistyped.wic @@ -0,0 +1,7 @@ +# A pin YAML reads as the number 1.0, not as a version. +wic: + lang_version: 1.0 +steps: +- id: touch + in: + filename: !ii empty.txt diff --git a/tests/core/data/lang_version/pinned.wic b/tests/core/data/lang_version/pinned.wic new file mode 100644 index 000000000..26102d493 --- /dev/null +++ b/tests/core/data/lang_version/pinned.wic @@ -0,0 +1,7 @@ +# A document pinned to the language version it is written in. +wic: + lang_version: 0.0.1 +steps: +- id: touch + in: + filename: !ii empty.txt diff --git a/tests/core/data/lang_version/pins_none.wic b/tests/core/data/lang_version/pins_none.wic new file mode 100644 index 000000000..c12d1f531 --- /dev/null +++ b/tests/core/data/lang_version/pins_none.wic @@ -0,0 +1,7 @@ +# Pinned to a language version that does not exist. +wic: + lang_version: 9.9.9 +steps: +- id: touch + in: + filename: !ii empty.txt diff --git a/tests/core/data/lang_version/unpinned.wic b/tests/core/data/lang_version/unpinned.wic new file mode 100644 index 000000000..e9352d3f6 --- /dev/null +++ b/tests/core/data/lang_version/unpinned.wic @@ -0,0 +1,5 @@ +# A document that pins no language version, so it compiles at the newest. +steps: +- id: touch + in: + filename: !ii empty.txt diff --git a/tests/core/data/parse/aliases/blocks.wic b/tests/core/data/parse/aliases/blocks.wic new file mode 100644 index 000000000..bd37ef306 --- /dev/null +++ b/tests/core/data/parse/aliases/blocks.wic @@ -0,0 +1,9 @@ +# The wic: block and the steps reached through their own aliases. +wic: &w + steps: + (1, a): + wic: *w +steps: &s +- id: s + in: + x: *s diff --git a/tests/core/data/parse/aliases/cycles.wic b/tests/core/data/parse/aliases/cycles.wic new file mode 100644 index 000000000..6512ddacb --- /dev/null +++ b/tests/core/data/parse/aliases/cycles.wic @@ -0,0 +1,16 @@ +# A node that contains itself, through an alias, is reported once, wherever it is reached from: a !cwl record +# reached through its own alias is the cycle every other alias cycle is. +top: &a [*a] +direct: &x1 !cwl {default: *x1} +through_a_merge: &x2 !cwl {<<: {default: *x2}} +beside_a_merge: &x3 !cwl {default: *x3, <<: {label: x}} +nested: &x4 !cwl {default: !cwl {default: *x4}} # a record in a field, besides +desugared: &x5 {wic_raw_cwl: {default: *x5}} +steps: + s: + in: + a: &y1 !cwl {default: *y1} + b: &y2 !cwl {<<: {default: *y2}} + c: &y3 !cwl {default: *y3, <<: {label: x}} + d: &y4 !cwl {default: !cwl {default: *y4}} + e: &y5 {wic_raw_cwl: {default: *y5}} diff --git a/tests/core/data/parse/aliases/expected.yaml b/tests/core/data/parse/aliases/expected.yaml new file mode 100644 index 000000000..725de4237 --- /dev/null +++ b/tests/core/data/parse/aliases/expected.yaml @@ -0,0 +1,26 @@ +why: An alias that leads back to the node it is in is a cycle, and one that widens past a budget a bomb. Either is + reported where it is reached, never followed, so reading neither raises nor hangs. +# Each document's diagnostics, by code, line and column in reading order. +documents: + blocks.wic: + - [RECURSIVE_ALIAS, 2, 6] + - [RECURSIVE_ALIAS, 6, 8] + cycles.wic: + - [RECURSIVE_ALIAS, 3, 6] + - [RECURSIVE_ALIAS, 4, 9] + - [RECURSIVE_ALIAS, 5, 18] + - [RECURSIVE_ALIAS, 6, 17] + - [RECURSIVE_ALIAS, 7, 9] + - [STEP_INPUT_RECORD, 7, 9] + - [RECURSIVE_ALIAS, 8, 12] + - [RECURSIVE_ALIAS, 12, 10] + - [RECURSIVE_ALIAS, 13, 10] + - [RECURSIVE_ALIAS, 14, 10] + - [RECURSIVE_ALIAS, 15, 10] + - [STEP_INPUT_RECORD, 15, 10] + - [RECURSIVE_ALIAS, 16, 10] + - [STEP_INPUT_RECORD, 16, 10] + laughs.wic: + - [RECURSIVE_ALIAS, 2, 10] + - [RECURSIVE_ALIAS, 2, 13] + - [RECURSIVE_ALIAS, 2, 16] diff --git a/tests/core/data/parse/aliases/laughs.wic b/tests/core/data/parse/aliases/laughs.wic new file mode 100644 index 000000000..7af777521 --- /dev/null +++ b/tests/core/data/parse/aliases/laughs.wic @@ -0,0 +1,9 @@ +# A chain of aliases, each nine times as wide as the one before: reading it is cut off, not expanded. +a0: &a0 [x, x, x, x, x, x, x, x, x] +a1: &a1 [*a0, *a0, *a0, *a0, *a0, *a0, *a0, *a0, *a0] +a2: &a2 [*a1, *a1, *a1, *a1, *a1, *a1, *a1, *a1, *a1] +a3: &a3 [*a2, *a2, *a2, *a2, *a2, *a2, *a2, *a2, *a2] +a4: &a4 [*a3, *a3, *a3, *a3, *a3, *a3, *a3, *a3, *a3] +a5: &a5 [*a4, *a4, *a4, *a4, *a4, *a4, *a4, *a4, *a4] +a6: &a6 [*a5, *a5, *a5, *a5, *a5, *a5, *a5, *a5, *a5] +a7: &a7 [*a6, *a6, *a6, *a6, *a6, *a6, *a6, *a6, *a6] diff --git a/tests/core/data/parse/document/expected.yaml b/tests/core/data/parse/document/expected.yaml new file mode 100644 index 000000000..0f059a45a --- /dev/null +++ b/tests/core/data/parse/document/expected.yaml @@ -0,0 +1,55 @@ +why: A document is a mapping YAML can read; anything less leaves nothing to read on. Top-level keys the language + does not read are CWL, kept as written, except that list-form inputs, outputs, requirements and hints are keyed. +# Each document's diagnostics, by code, line and column in reading order; an accepted document reports none. +documents: + invalid_yaml.wic: + - [INVALID_YAML, 3, 1] + not_a_mapping.wic: + - [NOT_A_MAPPING, 2, 1] + - [UNKNOWN_TAG, 2, 3] + top_level.wic: + - [UNKNOWN_TAG, 1, 5] + - [UNSUPPORTED_CWL_VERSION, 3, 13] + - [EXPECTED_MAPPING, 4, 8] + - [EXPECTED_MAPPING, 5, 6] + - [EXPECTED_MAPPING, 7, 3] + - [EXPECTED_MAPPING, 8, 3] + - [EXPECTED_MAPPING, 9, 3] + - [EXPECTED_MAPPING, 10, 3] + - [DUPLICATE_KEY, 12, 3] + - [EXPECTED_MAPPING, 14, 3] + - [EXPECTED_MAPPING, 15, 3] + - [EXPECTED_MAPPING, 17, 3] + - [DUPLICATE_KEY, 20, 3] + list_forms.wic: [] + imports.wic: [] +# What a document reads as: each node by its fields, a construct as its tag around what it carries. A document +# not listed here is read too. +reads: + invalid_yaml.wic: null + not_a_mapping.wic: null + list_forms.wic: + steps: + - id: s + passthrough: + requirements: {InlineJavascriptRequirement: {}} + hints: {InlineJavascriptRequirement: {}} + passthrough: + inputs: {a: {type: string}, nm: {type: string}} + outputs: {o: {type: File, outputSource: s/f}, p: {type: File}} + requirements: {ScatterFeatureRequirement: {}, '': {}} + hints: {DockerRequirement: {dockerPull: x}} + imports.wic: + steps: + - id: s + passthrough: + label: a human label + requirements: [{$import: foo.yml}, {class: X}] + hints: [{$include: foo.yml}, {class: X}] + passthrough: + inputs: [{$import: foo.yml}, {id: a}] + outputs: [{$include: foo.yml}, {id: a}] + requirements: [{$include: foo.yml}, {class: a}] + hints: [{$import: foo.yml}, {class: a}] + $namespaces: {edam: 'http://example'} + top: {'!ii': {k: v}} diff --git a/tests/core/data/parse/document/imports.wic b/tests/core/data/parse/document/imports.wic new file mode 100644 index 000000000..b958b4bf5 --- /dev/null +++ b/tests/core/data/parse/document/imports.wic @@ -0,0 +1,26 @@ +# A list that holds an $import or an $include is kept as written, since cwltool reads the file it names. Every other +# top-level key is CWL the parser keeps as written, a literal in it included. +inputs: +- $import: foo.yml +- id: a +outputs: +- $include: foo.yml +- id: a +requirements: +- $include: foo.yml +- class: a +hints: +- $import: foo.yml +- class: a +$namespaces: + edam: http://example +top: !ii {k: v} +steps: + s: + label: a human label + requirements: + - $import: foo.yml + - class: X + hints: + - $include: foo.yml + - class: X diff --git a/tests/core/data/parse/document/invalid_yaml.wic b/tests/core/data/parse/document/invalid_yaml.wic new file mode 100644 index 000000000..9737ee0ae --- /dev/null +++ b/tests/core/data/parse/document/invalid_yaml.wic @@ -0,0 +1,2 @@ +steps: + - [unclosed diff --git a/tests/core/data/parse/document/list_forms.wic b/tests/core/data/parse/document/list_forms.wic new file mode 100644 index 000000000..d12f0a405 --- /dev/null +++ b/tests/core/data/parse/document/list_forms.wic @@ -0,0 +1,25 @@ +# Inputs, outputs, requirements and hints written as lists are read as mappings keyed by id or class, an id by +# what follows its last #; a step's requirements and hints the same way. +inputs: +- id: a + type: string +- id: '#nm' + type: string +outputs: +- id: o + type: File + outputSource: s/f +- id: 'wf.cwl#p' + type: File +requirements: +- class: ScatterFeatureRequirement +- class: '' +hints: +- class: DockerRequirement + dockerPull: x +steps: + s: + requirements: + - class: InlineJavascriptRequirement + hints: + - class: InlineJavascriptRequirement diff --git a/tests/core/data/parse/document/not_a_mapping.wic b/tests/core/data/parse/document/not_a_mapping.wic new file mode 100644 index 000000000..e17dd8deb --- /dev/null +++ b/tests/core/data/parse/document/not_a_mapping.wic @@ -0,0 +1,3 @@ +# A document is a mapping. This one is a list, and holds an unknown tag besides. +- !foo a +- a list diff --git a/tests/core/data/parse/document/top_level.wic b/tests/core/data/parse/document/top_level.wic new file mode 100644 index 000000000..7542ef336 --- /dev/null +++ b/tests/core/data/parse/document/top_level.wic @@ -0,0 +1,20 @@ +--- !foo # an unknown tag on the document itself +# Top-level keys whose values have the wrong shape. +cwlVersion: draft-3 # a CWL version cwltool does not run +steps: nope # steps is a mapping or a sequence +wic: 3 # wic is a mapping +inputs: # list-form entries with no name to key them by +- type: string # no id +- id: [a] # an id that is no string +- {id: '#', type: string} # an id naming no port: the name is what follows the last # +- {id: '', type: string} +- {id: a, type: string} +- {id: '#a', type: int} # a, again +outputs: +- just-a-name # no mapping +- {id: 'wf.cwl#', type: string} +requirements: +- coresMin: 1 # no class +hints: +- {class: A} +- {class: A} # the same class twice diff --git a/tests/core/data/parse/edges.yaml b/tests/core/data/parse/edges.yaml deleted file mode 100644 index c365d842a..000000000 --- a/tests/core/data/parse/edges.yaml +++ /dev/null @@ -1,61 +0,0 @@ -- {id: "an edge definition in input position names the position (.wic reference §3.6)", - source: "steps:\n- id: s\n in:\n f: !& e\n", - report: [{code: MISPLACED_EDGE_DEF, line: 4, message: {contains: ["out:"]}}], recovers: true, - why: &w0 "Each diagnosed shape reports exactly one diagnostic, at its line, and a document survives beside it: - recovery is the norm, and only unparsable YAML leaves nothing to return."} -- {id: the desugared spelling is reported the same way, source: "steps:\n- id: s\n in:\n f: {wic_anchor: e}\n", - report: [{code: MISPLACED_EDGE_DEF, line: 4, message: {contains: ["out:"]}}], recovers: true, why: *w0} -- {id: an anchor nested in a literal payload is reported too, source: "steps:\n- id: s\n in:\n f: !ii {k: !& e}\n", - report: [{code: MISPLACED_EDGE_DEF, line: 4, message: {contains: ["out:"]}}], recovers: true, why: *w0} -- {id: "the rule is positional: an anchor at the top level is reported", source: "top: !& e\n", - report: [{code: MISPLACED_EDGE_DEF, line: 1, message: {contains: ["out:"]}}], recovers: true, why: *w0} -- {id: "and inside the wic: block, which is not a step at all", source: "wic:\n graphviz:\n label: !& e\n", - report: [{code: MISPLACED_EDGE_DEF, line: 3, message: {contains: ["out:"]}}], recovers: true, why: *w0} -- {id: "the desugared spelling is reported in the same positions (language spec §2)", source: "top: {wic_anchor: e}\n", - report: [{code: MISPLACED_EDGE_DEF, line: 1, message: {contains: ["out:"]}}], recovers: true, why: *w0} -- {id: a malformed name does not earn spelling advice for a construct that may not appear here at all, - source: "steps:\n- id: s\n in:\n f: !& [a]\n", - report: [{code: MISPLACED_EDGE_DEF, line: 4, message: {contains: ["out:"]}}], recovers: true, why: *w0} -- {id: "an out: entry that is neither name nor single-key mapping", source: "steps:\n s:\n out: [[a, b]]\n", - report: [{code: EXPECTED_SCALAR, line: 3, message: {contains: ["each out: entry must be"]}}], recovers: true, - why: *w0} -- {id: a sidecar steps out accepts an edge definition, - source: "wic:\n steps:\n (1, s):\n out:\n - output_tpr_path: !& min.tpr\nsteps:\n- id: s\n", ok: true, - why: &w1 "`!&` is legal under `wic.steps.(N, name).out`, exactly as on a step's own `out:` (.wic reference §3.6) — a - sidecar `(N, name): out:` block *is* a step's `out:` entry, just written at a distance (see `basic.wic`, which - places the corpus's only definition of `min.tpr` here rather than in the nested file, precisely to avoid a - `wic026 DUPLICATE_EDGE_DEF`)."} -- {id: a sidecar steps out accepts a desugared edge definition, - source: "wic:\n steps:\n (1, s):\n out:\n - output_tpr_path: {wic_anchor: min.tpr}\nsteps:\n- id: s\n", - ok: true, why: *w1} -- {id: "!& e is refused in input", source: "steps:\n- id: s\n in:\n f: !& e\n", - report: {contains: [{code: MISPLACED_EDGE_DEF}]}, - why: &w2 "One construct, one verdict, in both spellings and every position. The narrower unknown-tag version above - quantifies only over `SophiosErrorCode.UNKNOWN_TAG`, so it cannot see a `wic019` divergence — and there was one: - `_opaque` routed on the tag, so `{wic_anchor: e}` was plain data exactly where `!& e` was refused."} -- {id: "{wic_anchor: e} is refused in input", source: "steps:\n- id: s\n in:\n f: {wic_anchor: e}\n", - report: {contains: [{code: MISPLACED_EDGE_DEF}]}, why: *w2} -- {id: "!& e is refused in nested in a literal", source: "steps:\n- id: s\n in:\n f: !ii {k: !& e}\n", - report: {contains: [{code: MISPLACED_EDGE_DEF}]}, why: *w2} -- {id: "{wic_anchor: e} is refused in nested in a literal", - source: "steps:\n- id: s\n in:\n f: !ii {k: {wic_anchor: e}}\n", - report: {contains: [{code: MISPLACED_EDGE_DEF}]}, why: *w2} -- {id: "!& e is refused in step passthrough", source: "steps:\n- id: s\n label: !& e\n", - report: {contains: [{code: MISPLACED_EDGE_DEF}]}, why: *w2} -- {id: "{wic_anchor: e} is refused in step passthrough", source: "steps:\n- id: s\n label: {wic_anchor: e}\n", - report: {contains: [{code: MISPLACED_EDGE_DEF}]}, why: *w2} -- {id: "!& e is refused in top level", source: "top: !& e\n", report: {contains: [{code: MISPLACED_EDGE_DEF}]}, - why: *w2} -- {id: "{wic_anchor: e} is refused in top level", source: "top: {wic_anchor: e}\n", - report: {contains: [{code: MISPLACED_EDGE_DEF}]}, why: *w2} -- {id: "!& e is refused in wic block", source: "wic:\n graphviz:\n label: !& e\n", - report: {contains: [{code: MISPLACED_EDGE_DEF}]}, why: *w2} -- {id: "{wic_anchor: e} is refused in wic block", source: "wic:\n graphviz:\n label: {wic_anchor: e}\n", - report: {contains: [{code: MISPLACED_EDGE_DEF}]}, why: *w2} -- {id: the tagged edge definition on out, source: "steps:\n- id: s\n out:\n - f: !& e\n", report: [], recovers: true, - why: &w3 "The other half: refusing everywhere would satisfy the test above."} -- {id: the desugared edge definition on out, source: "steps:\n- id: s\n out:\n - f:\n wic_anchor: e\n", - report: [], recovers: true, why: *w3} -- {id: an out value that is no edge definition is reported, source: "steps:\n- id: s\n out:\n - file: something\n", - ok: false, report: {contains: [{message: {contains: [file]}}]}, - why: 'A non-!& out value is reported, never silently dropped.'} diff --git a/tests/core/data/parse/edges/defined.wic b/tests/core/data/parse/edges/defined.wic new file mode 100644 index 000000000..3c60f7a31 --- /dev/null +++ b/tests/core/data/parse/edges/defined.wic @@ -0,0 +1,19 @@ +# An output defines an edge in either spelling, on the step or in the wic: block for it. +wic: + steps: + (1, s): + out: + - output_tpr_path: !& min.tpr + (2, t): + out: + - output_tpr_path: {wic_anchor: min.tpr} +steps: +- id: s + out: + - f: !& e + - g: + wic_anchor: e2 + - h: {wic_anchor: e3} + - plain + - '' +- id: t diff --git a/tests/core/data/parse/edges/expected.yaml b/tests/core/data/parse/edges/expected.yaml new file mode 100644 index 000000000..bc3cce92e --- /dev/null +++ b/tests/core/data/parse/edges/expected.yaml @@ -0,0 +1,42 @@ +why: "One construct, one verdict, in both spellings and every position. An edge is defined on an output, on the step + or in the wic: block for it; anywhere else the definition is reported, and the name it gave is kept, never dropped." +# Each document's diagnostics, by code, line and column in reading order; an accepted document reports none. +documents: + misplaced.wic: + - [MISPLACED_EDGE_DEF, 3, 6] + - [MISPLACED_EDGE_DEF, 4, 16] + - [UNKNOWN_TAG, 5, 7] + - [MISPLACED_EDGE_DEF, 5, 7] + - [MISPLACED_EDGE_DEF, 8, 12] + - [MISPLACED_EDGE_DEF, 13, 18] + - [MISPLACED_EDGE_DEF, 17, 8] + - [MISPLACED_EDGE_DEF, 18, 8] + - [MISPLACED_EDGE_DEF, 19, 16] + - [MISPLACED_EDGE_DEF, 20, 16] + - [MISPLACED_EDGE_DEF, 21, 8] + - [UNKNOWN_TAG, 22, 8] + - [MISPLACED_EDGE_DEF, 22, 8] + - [MISPLACED_EDGE_DEF, 23, 10] + - [MISPLACED_EDGE_DEF, 24, 8] + defined.wic: [] +# What a document reads as: each node by its fields, a construct as its tag around what it carries, a wic: step key +# as [index, name]. +reads: + misplaced.wic: + steps: + - id: s + inputs: {a: e, b: e, c: {'!ii': {k: e}}, d: {'!ii': {k: e}}, f: '', g: x} + passthrough: {label: e, doc: e} + wic: + steps: [[1, s, {entries: {graphviz: {label: e}}}]] + entries: {graphviz: {label: e}} + passthrough: {top: x, top_desugared: x, both: x} + defined.wic: + steps: + - id: s + outputs: [f: {'!&': e}, g: {'!&': e2}, h: {'!&': e3}, plain, ''] + - id: t + wic: + steps: + - [1, s, {entries: {out: [output_tpr_path: {wic_anchor: min.tpr}]}}] + - [2, t, {entries: {out: [output_tpr_path: {wic_anchor: min.tpr}]}}] diff --git a/tests/core/data/parse/edges/misplaced.wic b/tests/core/data/parse/edges/misplaced.wic new file mode 100644 index 000000000..b997354b2 --- /dev/null +++ b/tests/core/data/parse/edges/misplaced.wic @@ -0,0 +1,24 @@ +# An edge is defined where its value comes into being: on a step's output. Anywhere else !& is reported, in either +# spelling, and the name it gave is kept as a name. +top: !& x # at the top level +top_desugared: {wic_anchor: x} +both: !foo {wic_anchor: x} # under an unknown tag as well +wic: + graphviz: + label: !& e # in the wic: block + steps: + (1, s): + wic: + graphviz: + label: {wic_anchor: e} +steps: +- id: s + in: + a: !& e # in input position + b: {wic_anchor: e} + c: !ii {k: !& e} # inside a literal + d: !ii {k: {wic_anchor: e}} + f: !& [a] # on a collection, which has no name to keep + g: !foo {wic_anchor: x} # under an unknown tag as well + label: !& e # in a step's own CWL + doc: {wic_anchor: e} diff --git a/tests/core/data/parse/list_forms.yaml b/tests/core/data/parse/list_forms.yaml deleted file mode 100644 index 6e3e1320d..000000000 --- a/tests/core/data/parse/list_forms.yaml +++ /dev/null @@ -1,83 +0,0 @@ -- {id: a list-form inputs, source: "inputs:\n- id: a\n type: string\n", ok: true, - passthrough: {inputs: {a: {type: string}}}, - why: &w0 "`inputs`, `outputs`, `requirements` and `hints` written as lists are keyed by `id` or `class`."} -- {id: a list-form outputs, source: "outputs:\n- id: o\n type: File\n outputSource: s/f\n", ok: true, - passthrough: {outputs: {o: {type: File, outputSource: s/f}}}, why: *w0} -- {id: a list-form requirements, source: "requirements:\n- class: ScatterFeatureRequirement\n", ok: true, - passthrough: {requirements: {ScatterFeatureRequirement: {}}}, why: *w0} -- {id: a list-form hints, source: "hints:\n- class: DockerRequirement\n dockerPull: x\n", ok: true, - passthrough: {hints: {DockerRequirement: {dockerPull: x}}}, why: *w0} -- {id: a list-form empty, source: "inputs: []\n", ok: true, passthrough: {inputs: {}}, why: *w0} -- {id: a list-form empty-class, source: "requirements:\n- class: ''\n", ok: true, passthrough: {requirements: {"": {}}}, - why: *w0} -- {id: a list-form fragment-id, source: "inputs:\n- id: '#nm'\n type: string\n", ok: true, - passthrough: {inputs: {nm: {type: string}}}, why: *w0} -- {id: a list-form path-fragment-id, source: "outputs:\n- id: 'wf.cwl#o'\n type: File\n", ok: true, - passthrough: {outputs: {o: {type: File}}}, why: *w0} -- {id: a step's list-form requirements, - source: "steps:\n s:\n requirements:\n - class: InlineJavascriptRequirement\n", ok: true, - step_passthrough: {requirements: {InlineJavascriptRequirement: {}}}, - why: &w1 "A step's `requirements` and `hints` are lifted the same way."} -- {id: a step's list-form hints, source: "steps:\n s:\n hints:\n - class: InlineJavascriptRequirement\n", - ok: true, step_passthrough: {hints: {InlineJavascriptRequirement: {}}}, why: *w1} -- {id: "an unkeyable list-form entry: no-id", source: "inputs:\n- type: string\n", - report: [{code: EXPECTED_MAPPING, message: "a list-form inputs: entry must be a mapping with a string id:"}], - why: &w2 "An entry with no usable `id` or `class`, or a name taken twice, has no place in the mapping. Each unkeyable - entry is told the rule it broke: a string name, or an `id:` with a name after the last #."} -- {id: "an unkeyable list-form entry: no-class", source: "requirements:\n- coresMin: 1\n", - report: [{code: EXPECTED_MAPPING, message: "a list-form requirements: entry must be a mapping with a string - class:"}], - why: *w2} -- {id: "an unkeyable list-form entry: not-a-mapping", source: "outputs:\n- just-a-name\n", - report: [{code: EXPECTED_MAPPING}], why: *w2} -- {id: "an unkeyable list-form entry: id-not-a-string", source: "inputs:\n- id: [a]\n", - report: [{code: EXPECTED_MAPPING, message: "a list-form inputs: entry must be a mapping with a string id:"}], - why: *w2} -- {id: "an unkeyable list-form entry: duplicate", source: "inputs:\n- {id: a, type: string}\n- {id: a, type: int}\n", - report: [{code: DUPLICATE_KEY}], why: *w2} -- {id: "an unkeyable list-form entry: duplicate-after-fragment", - source: "inputs:\n- {id: a, type: string}\n- {id: '#a', type: int}\n", report: [{code: DUPLICATE_KEY}], why: *w2} -- {id: "an unkeyable list-form entry: bare-fragment", source: "inputs:\n- {id: '#', type: string}\n", - report: [{code: EXPECTED_MAPPING}], why: *w2} -- {id: "an unkeyable list-form entry: empty-after-file-fragment", source: "outputs:\n- {id: 'wf.cwl#', type: string}\n", - report: [{code: EXPECTED_MAPPING}], why: *w2} -- {id: "an unkeyable list-form entry: empty-id", source: "inputs:\n- {id: '', type: string}\n", - report: [{code: EXPECTED_MAPPING}], why: *w2} -- {id: "an unkeyable list-form entry is told the rule: inputs: - just-a-name", source: "inputs:\n- just-a-name\n", - report: [{message: "a list-form inputs: entry must be a mapping with a string id:"}], why: *w2} -- {id: "an unkeyable list-form entry is told the rule: inputs: - id: '#'", source: "inputs:\n- id: '#'\n", - report: [{message: "a list-form inputs: entry id: '#' names no port: the name is the part after the last #, and it - must not be empty"}], - why: *w2} -- {id: "an unkeyable list-form entry is told the rule: outputs: - id: 'wf.cwl#'", source: "outputs:\n- id: 'wf.cwl#'\n", - report: [{message: "a list-form outputs: entry id: 'wf.cwl#' names no port: the name is the part after the last #, - and it must not be empty"}], - why: *w2} -- {id: "an unkeyable list-form entry is told the rule: inputs: - id: ''", source: "inputs:\n- id: ''\n", - report: [{message: "a list-form inputs: entry id: '' names no port: the name is the part after the last #, and it - must not be empty"}], - why: *w2} -- {id: "a list-form inputs holding an $import", source: "inputs:\n- $import: foo.yml\n- id: a\n", ok: true, - passthrough: {inputs: [{"$import": foo.yml}, {id: a}]}, - why: &w3 "cwltool reads the file such an entry names, so the list is neither keyed nor mapped here."} -- {id: "a list-form outputs holding an $import", source: "outputs:\n- $import: foo.yml\n- id: a\n", ok: true, - passthrough: {outputs: [{"$import": foo.yml}, {id: a}]}, why: *w3} -- {id: "a list-form requirements holding an $import", source: "requirements:\n- $import: foo.yml\n- class: a\n", - ok: true, passthrough: {requirements: [{"$import": foo.yml}, {class: a}]}, why: *w3} -- {id: "a list-form hints holding an $import", source: "hints:\n- $import: foo.yml\n- class: a\n", ok: true, - passthrough: {hints: [{"$import": foo.yml}, {class: a}]}, why: *w3} -- {id: "a list-form inputs holding an $include", source: "inputs:\n- $include: foo.yml\n- id: a\n", ok: true, - passthrough: {inputs: [{"$include": foo.yml}, {id: a}]}, why: *w3} -- {id: "a list-form outputs holding an $include", source: "outputs:\n- $include: foo.yml\n- id: a\n", ok: true, - passthrough: {outputs: [{"$include": foo.yml}, {id: a}]}, why: *w3} -- {id: "a list-form requirements holding an $include", source: "requirements:\n- $include: foo.yml\n- class: a\n", - ok: true, passthrough: {requirements: [{"$include": foo.yml}, {class: a}]}, why: *w3} -- {id: "a list-form hints holding an $include", source: "hints:\n- $include: foo.yml\n- class: a\n", ok: true, - passthrough: {hints: [{"$include": foo.yml}, {class: a}]}, why: *w3} -- {id: "a step's list-form requirements holding an $import", - source: "steps:\n s:\n requirements:\n - $import: foo.yml\n - class: X\n", ok: true, - step_passthrough: {requirements: [{"$import": foo.yml}, {class: X}]}, - why: &w4 "A step's `requirements` and `hints` are left alone the same way."} -- {id: "a step's list-form hints holding an $import", - source: "steps:\n s:\n hints:\n - $import: foo.yml\n - class: X\n", ok: true, - step_passthrough: {hints: [{"$import": foo.yml}, {class: X}]}, why: *w4} diff --git a/tests/core/data/parse/records.yaml b/tests/core/data/parse/records.yaml deleted file mode 100644 index 470b1797d..000000000 --- a/tests/core/data/parse/records.yaml +++ /dev/null @@ -1,36 +0,0 @@ -- {id: "an untagged record: {source: x}", source: "steps:\n mk_file:\n in:\n name: {source: x}\n", - report: [{code: STEP_INPUT_RECORD}], - why: &w0 "A mapping made of WorkflowStepInput fields is not a literal, whatever the reference used to say; reading it - as one sent `{\"source\": \"x\"}` to a tool."} -- {id: "an untagged record: {default: 20}", source: "steps:\n mk_file:\n in:\n name: {default: 20}\n", - report: [{code: STEP_INPUT_RECORD}], why: *w0} -- {id: "an untagged record: {source: x, linkMerge: merge_flattened}", - source: "steps:\n mk_file:\n in:\n name: {source: x, linkMerge: merge_flattened}\n", - report: [{code: STEP_INPUT_RECORD}], why: *w0} -- {id: "an untagged record: {valueFrom: $(1)}", source: "steps:\n mk_file:\n in:\n name: {valueFrom: $(1)}\n", - report: [{code: STEP_INPUT_RECORD}], why: *w0} -- {id: "a record field CWL has no name for: {source: a, nope: 1}", - source: "steps:\n s:\n in:\n f: !cwl {source: a, nope: 1}\n", report: [{code: STEP_INPUT_RECORD}], - why: &w1 "A key outside WorkflowStepInput, a source that is not a reference, and a Sophios construct inside a field - CWL reads verbatim are each refused."} -- {id: "a record field CWL has no name for: {source: !ii 3}", - source: "steps:\n s:\n in:\n f: !cwl {source: !ii 3}\n", report: [{code: STEP_INPUT_RECORD}], why: *w1} -- {id: "a record field CWL has no name for: {source: [a, !cwl x]}", - source: "steps:\n s:\n in:\n f: !cwl {source: [a, !cwl x]}\n", report: [{code: STEP_INPUT_RECORD}], - why: *w1} -- {id: "a record field CWL has no name for: {default: !ii 3}", - source: "steps:\n s:\n in:\n f: !cwl {default: !ii 3}\n", report: [{code: STEP_INPUT_RECORD}], why: *w1} -- {id: "a record field CWL has no name for: {valueFrom: !* e}", - source: "steps:\n s:\n in:\n f: !cwl {valueFrom: !* e}\n", report: [{code: STEP_INPUT_RECORD}], why: *w1} -- {id: "a record that gives no value: {}", source: "steps:\n s:\n in:\n f: !cwl {}\n", - report: [{code: STEP_INPUT_RECORD}], - why: &w2 "Without a source, a default or a valueFrom the input would be bound to nothing, and the binding would stop - Sophios connecting it."} -- {id: "a record that gives no value: {source: []}", source: "steps:\n s:\n in:\n f: !cwl {source: []}\n", - report: [{code: STEP_INPUT_RECORD}], why: *w2} -- {id: "a record that gives no value: {loadContents: true}", - source: "steps:\n s:\n in:\n f: !cwl {loadContents: true}\n", report: [{code: STEP_INPUT_RECORD}], why: *w2} -- {id: "a record {default: 3} needs no source", source: "steps:\n s:\n in:\n f: !cwl {default: 3}\n", ok: true, - why: &w3 "Either gives the input a value, so the record stands without a source."} -- {id: "a record {valueFrom: $(1)} needs no source", source: "steps:\n s:\n in:\n f: !cwl {valueFrom: $(1)}\n", - ok: true, why: *w3} diff --git a/tests/core/data/parse/records/expected.yaml b/tests/core/data/parse/records/expected.yaml new file mode 100644 index 000000000..ab3f29a96 --- /dev/null +++ b/tests/core/data/parse/records/expected.yaml @@ -0,0 +1,36 @@ +why: "An input's value is a name, a literal, an edge, a raw CWL reference or a record. A mapping of WorkflowStepInput + fields alone is a record, never a literal, which sent {\"source\": \"x\"} to a tool once; written untagged, or with a + field CWL has no name for, a source that is no reference, a construct in a field or no value at all, it is reported." +# Each document's diagnostics, by code, line and column in reading order; an accepted document reports none. +documents: + inputs.wic: [] + refused.wic: + - [STEP_INPUT_RECORD, 6, 10] + - [STEP_INPUT_RECORD, 7, 10] + - [STEP_INPUT_RECORD, 8, 10] + - [STEP_INPUT_RECORD, 9, 10] + - [STEP_INPUT_RECORD, 10, 10] + - [STEP_INPUT_RECORD, 11, 10] + - [STEP_INPUT_RECORD, 12, 10] + - [STEP_INPUT_RECORD, 13, 10] + - [STEP_INPUT_RECORD, 14, 10] + - [STEP_INPUT_RECORD, 15, 10] + - [STEP_INPUT_RECORD, 16, 10] + - [STEP_INPUT_RECORD, 17, 10] +# What a document reads as: each node by its fields, a construct as its tag around what it carries. +reads: + inputs.wic: + steps: + - id: s + inputs: + a: plain + b: {'!ii': {some: mapping}} + c: {'!ii': '{unclosed'} + d: {'!ii': {k: v}} + e: {'!ii': {source: x, pdb_code: 1aki}} + f: {'!*': edge} + g: {'!cwl': a/b} + h: {'!cwl': {source: [{'!*': a}, wf_in], linkMerge: merge_flattened}} + i: {'!cwl': {source: [{'!*': a}, wf_in], linkMerge: merge_flattened}} + j: {'!cwl': {source: [], default: 3}} + k: {'!cwl': {source: [], valueFrom: $(1)}} diff --git a/tests/core/data/parse/records/inputs.wic b/tests/core/data/parse/records/inputs.wic new file mode 100644 index 000000000..d153530c6 --- /dev/null +++ b/tests/core/data/parse/records/inputs.wic @@ -0,0 +1,18 @@ +# Each form an input's value takes: a name, a literal, an edge, a raw CWL reference and a record. +steps: + s: + in: + a: plain + b: {some: mapping} # untagged, a literal + c: !ii "{unclosed" # text YAML cannot load stays text + d: !ii {k: v} # a collection, wrapped once + e: {source: x, pdb_code: 1aki} # not all fields of a record: a literal + f: !* edge + g: !cwl a/b + h: !cwl {source: [!* a, wf_in], linkMerge: merge_flattened} + i: + wic_raw_cwl: + source: [{wic_alias: a}, wf_in] + linkMerge: merge_flattened + j: !cwl {default: 3} # a default needs no source + k: !cwl {valueFrom: $(1)} # nor does a valueFrom diff --git a/tests/core/data/parse/records/refused.wic b/tests/core/data/parse/records/refused.wic new file mode 100644 index 000000000..5151881b4 --- /dev/null +++ b/tests/core/data/parse/records/refused.wic @@ -0,0 +1,17 @@ +# A mapping of WorkflowStepInput fields is a record, which is written !cwl, carries only those fields, takes its +# sources as references and its other fields as CWL, and gives the input a value. Each record here breaks one of these. +steps: + s: + in: + a: {source: x} # untagged + b: {default: 20} + c: {source: x, linkMerge: merge_flattened} + d: {valueFrom: $(1)} + e: !cwl {source: a, nope: 1} # a field CWL has no name for + f: !cwl {source: !ii 3} # a source that is no reference + g: !cwl {source: [a, !cwl x]} + h: !cwl {default: !ii 3} # a construct in a field CWL reads as written + i: !cwl {valueFrom: !* e} + j: !cwl {} # no value at all + k: !cwl {source: []} + l: !cwl {loadContents: true} diff --git a/tests/core/data/parse/steps.yaml b/tests/core/data/parse/steps.yaml deleted file mode 100644 index aa3286a4c..000000000 --- a/tests/core/data/parse/steps.yaml +++ /dev/null @@ -1,53 +0,0 @@ -- {id: "a sequence step without an id: names both forms that exist (.wic reference §2.1)", - source: "steps:\n- touch:\n in: {f: !ii x}\n", - report: [{code: MISSING_STEP_ID, line: 2, message: {contains: ["- id: touch"]}}], recovers: true, - why: &w0 "Each diagnosed shape reports exactly one diagnostic, at its line, and a document survives beside it: - recovery is the norm, and only unparsable YAML leaves nothing to return."} -- {id: "and with no body either, which is the shape insertion used to write", source: "steps:\n- sub.wic:\n", - report: [{code: MISSING_STEP_ID, line: 2, message: {contains: ["- id: sub.wic"]}}], recovers: true, why: *w0} -- {id: "a collection step key is reported, not stringified", source: "steps:\n ? [a, b]\n : {}\n", - report: [{code: EXPECTED_SCALAR, line: 2, message: {contains: [mapping keys must be scalars]}}], recovers: true, - why: *w0} -- {id: "an input bound twice names the input (.wic reference §3.8)", - source: "steps:\n- id: s\n in:\n f: !ii a\n f: !ii b\n", - report: [{code: DUPLICATE_KEY, line: 5, message: {contains: ["'f'"]}}], recovers: true, why: *w0} -- {id: a step that is not a mapping is reported, source: "steps:\n - 42\n", - report: [{code: EXPECTED_MAPPING, line: 2, message: {contains: [each step must be a mapping]}}], recovers: true, - why: *w0} -- {id: a step body key repeated names the key, source: "steps:\n- id: s\n in: {a: !ii 1}\n in: {b: !ii 2}\n", - report: [{code: DUPLICATE_KEY, line: 4, message: {contains: [step key 'in']}}], recovers: true, why: *w0} -- {id: "a second id: inside a step body is contradictory, not a tiebreak", source: "steps:\n s:\n id: other\n", - report: [{code: DUPLICATE_KEY, line: 3, message: {contains: [already has its identity]}}], recovers: true, why: *w0} -- {id: "a rejected step entry, a single-key mapping, still reports its body", - source: "steps:\n- touch:\n in:\n f: !bogus x\n g: !& e\n", - report: [{code: MISSING_STEP_ID, line: 2}, {code: UNKNOWN_TAG, line: 4}, {code: MISPLACED_EDGE_DEF, line: 5}], - why: &w1 "A step with no identity is still walked, so one pass sees everything. Both rejected shapes must report the - same body problems the `id:` form does; otherwise fixing the entry's form hands back a fresh round of errors from - contents that were there all along."} -- {id: "a rejected step entry, an entry with keys but no id:, still reports its body", - source: "steps:\n- name: touch\n in:\n f: !bogus x\n g: !& e\n", - report: [{code: MISSING_STEP_ID, line: 2}, {code: UNKNOWN_TAG, line: 4}, {code: MISPLACED_EDGE_DEF, line: 5}], - why: *w1} -- {id: the id form reports the same body problems, source: "steps:\n- id: touch\n in:\n f: !bogus x\n g: !& e\n", - report: [{code: UNKNOWN_TAG, line: 4}, {code: MISPLACED_EDGE_DEF, line: 5}], - why: &w2 "The `id:` form is the baseline the two rejected shapes are held to."} -- {id: a collection key is not quoted back, source: "steps:\n- ? [a]\n : 1\n", - report: [{code: MISSING_STEP_ID, message: "a step in a sequence needs an id:"}, {code: EXPECTED_SCALAR}], - why: &w3 "Only a scalar key is a name the message can offer back. `_key_text` stringifies a collection key so parsing - can continue after wic005; that recovery value is not a name, and quoting it puts a node repr in front of the - user three times. A non-scalar key falls through to the plain message instead."} -- {id: a repeated step id is reported, source: "steps:\n- id: first\n id: second\n", ok: false, - report: [{code: DUPLICATE_KEY, line: 3}], - why: &w4 "Two `id:` keys on one step describe two different programs. This reader keeps the first and an ordinary - YAML load keeps the last, so resolving it either way hands the compiler a step the document does not - unambiguously name. Every other language-owned mapping reports a repeated key; identity is the one that can least - afford an exception."} -- {id: a single-key step without an id, source: "steps:\n- touch:\n in: {f: !ii x}\n", - report: [{code: MISSING_STEP_ID, message: "a step in a sequence carries its name in an id: key — write '- id: touch' - if 'touch' is the step's name; add the '- id:' line above if 'touch' is one of the step's own keys. Keying the - whole steps: block by name is the other form (.wic reference §2.1)"}], - why: &w5 "A sequence step with no `id:` is one code, wic006, whatever else is on it. Only the entry with a single key - has a name to quote, so only that arm can say more; the text is all that distinguishes the two, which is why both - are pinned whole here."} -- {id: a step of several keys without an id, source: "steps:\n- in: {f: !ii x}\n out: [g]\n", - report: [{code: MISSING_STEP_ID, message: "a step in a sequence needs an id:"}], why: *w5} diff --git a/tests/core/data/parse/steps/by_name.wic b/tests/core/data/parse/steps/by_name.wic new file mode 100644 index 000000000..c87fff8fe --- /dev/null +++ b/tests/core/data/parse/steps/by_name.wic @@ -0,0 +1,7 @@ +# Faults in steps keyed by name. +steps: + ? [a, b] # a key that is a collection is no name + : {} + named: + id: other # the key is the step's id already + body: 3 # a step's body is a mapping, or nothing diff --git a/tests/core/data/parse/steps/expected.yaml b/tests/core/data/parse/steps/expected.yaml new file mode 100644 index 000000000..1d414f2d7 --- /dev/null +++ b/tests/core/data/parse/steps/expected.yaml @@ -0,0 +1,43 @@ +why: A step that cannot be read is reported once, where it is written, and the reading goes on, so one pass over a + file reports every fault in it and still returns a document. A step with no id is read through like any other, + so naming it does not bring a second round of faults from what was under it all along. +# Each document's diagnostics, by code, line and column in reading order; an accepted document reports none. +documents: + by_name.wic: + - [EXPECTED_SCALAR, 3, 5] + - [DUPLICATE_KEY, 6, 5] + - [EXPECTED_MAPPING, 7, 3] + in_a_sequence.wic: + - [MISSING_STEP_ID, 3, 3] + - [MISSING_STEP_ID, 5, 3] + - [DUPLICATE_KEY, 9, 5] + - [EXPECTED_MAPPING, 10, 3] + - [DUPLICATE_KEY, 13, 3] + - [MISSING_STEP_ID, 14, 3] + - [UNKNOWN_TAG, 16, 10] + - [MISPLACED_EDGE_DEF, 17, 10] + - [MISSING_STEP_ID, 18, 3] + - [UNKNOWN_TAG, 20, 8] + - [MISPLACED_EDGE_DEF, 21, 8] + - [UNKNOWN_TAG, 24, 8] + - [MISPLACED_EDGE_DEF, 25, 8] + - [MISSING_STEP_ID, 26, 3] + - [EXPECTED_SCALAR, 26, 5] + - [DUPLICATE_KEY, 29, 3] + - [MISSING_STEP_ID, 30, 3] + - [EMPTY_STEP_ID, 32, 7] + - [EXPECTED_MAPPING, 34, 7] + - [EXPECTED_SEQUENCE, 35, 8] + - [EXPECTED_SCALAR, 38, 5] + - [EXPECTED_SCALAR, 39, 11] + keys.wic: [] +# What a document reads as: each node by its fields. A step's own keys are read by name or as the CWL Sophios acts +# on; any other key is CWL, kept as written. +reads: + keys.wic: + steps: + - id: s + outputs: [f] + interpreted: {run: tool.cwl, scatter: [x], scatterMethod: dotproduct, when: $(true)} + passthrough: {doc: a step, label: a human label, touch: {}} + - {id: some_step.wic} diff --git a/tests/core/data/parse/steps/in_a_sequence.wic b/tests/core/data/parse/steps/in_a_sequence.wic new file mode 100644 index 000000000..85dfc466f --- /dev/null +++ b/tests/core/data/parse/steps/in_a_sequence.wic @@ -0,0 +1,39 @@ +# Faults in a sequence of steps. The parser reports each one where it is written and reads on to the next. +steps: +- touch: # a step in a sequence carries its name in an id: key + in: {f: !ii x} +- sub.wic: # the same, with no body +- id: bound_twice + in: + f: !ii a + f: !ii b # an input bound twice +- 42 # a step that is not a mapping +- id: two_ins + in: {a: !ii 1} + in: {b: !ii 2} # a step key written twice +- touch: # no id, and what is under it is still read + in: + f: !bogus x + g: !& e +- name: touch # several keys and no id, likewise + in: + f: !bogus x + g: !& e +- id: touch # with an id, the same two faults and no more + in: + f: !bogus x + g: !& e +- ? [a] # a key that is a collection is no name + : 1 +- id: first + id: second # a second id +- in: {f: !ii x} # no id among several keys + out: [g] +- id: '' # an empty id +- id: shapes + in: 3 # in: is a mapping + out: 3 # out: is a sequence +- id: outs + out: + - [a, b] # an out: entry is a name, or a mapping of one name + - file: something # to an edge definition diff --git a/tests/core/data/parse/steps/keys.wic b/tests/core/data/parse/steps/keys.wic new file mode 100644 index 000000000..890cd8e09 --- /dev/null +++ b/tests/core/data/parse/steps/keys.wic @@ -0,0 +1,14 @@ +# A step's own keys are read, each by name or as CWL Sophios acts on; any other key is CWL, kept as written. A step +# keyed by name may have no body at all. +steps: + s: + in: {} + out: [f] + run: tool.cwl + scatter: [x] + scatterMethod: dotproduct + when: $(true) + doc: a step + label: a human label + touch: {} + some_step.wic: diff --git a/tests/core/data/parse/tags.yaml b/tests/core/data/parse/tags.yaml deleted file mode 100644 index 3d5eebf4f..000000000 --- a/tests/core/data/parse/tags.yaml +++ /dev/null @@ -1,110 +0,0 @@ -- {id: "malformed YAML is located, not raised", source: "steps:\n - [unclosed\n", - report: [{code: INVALID_YAML, line: 3}], recovers: false, - why: &w0 "Each diagnosed shape reports exactly one diagnostic, at its line, and a document survives beside it: - recovery is the norm, and only unparsable YAML leaves nothing to return."} -- {id: an unknown tag on the root document, source: "--- !foo\nsteps: []\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, - why: &w1 "Every tag the language does not own is reported, structure included. A call at each position that consumes - a node is how a position gets missed: each pass over that form found positions the previous one had left - uncovered. One walk over the composed graph has no positions to track, so a shape added later is covered by - default. Each case asserts both halves — the parser reports and `yaml.SafeLoader` raises — since the failure here - is the parser being more permissive than the YAML it is written in."} -- {id: "an unknown tag on the steps: node", source: "steps: !foo {}\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: an unknown tag on one sequence entry, source: "steps:\n- !foo {id: s}\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: an unknown tag on a step body in mapping form, source: "steps:\n touch: !foo {in: {}}\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: "an unknown tag on the in: mapping", source: "steps:\n- id: s\n in: !foo {f: !ii 1}\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: "an unknown tag on the out: node", source: "steps:\n- id: s\n out: !foo [a]\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: "an unknown tag on a scalar out: entry", source: "steps:\n- id: s\n out: [!foo a]\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: "an unknown tag on a mapping out: entry", source: "steps:\n- id: s\n out:\n - !foo {a: !& e}\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: "an unknown tag on the wic: node", source: "wic: !foo {}\nsteps: []\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: "an unknown tag on wic: steps:", source: "wic:\n steps: !foo {}\nsteps: []\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: an unknown tag on a sidecar step value, - source: "wic:\n steps:\n '(1, s)': !foo {wic: {}}\nsteps:\n- id: s\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: "an unknown tag on the nested wic: wrapper", - source: "wic:\n steps:\n '(1, s)':\n wic: !foo {}\nsteps:\n- id: s\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, yaml: raises, why: *w1} -- {id: a misspelled desugared inline literal, source: "steps:\n- id: s\n in: {f: {wic_inline_inpt: 1}}\n", ok: false, - report: {contains: [{code: RESERVED_KEY}]}, - why: &w2 "A single-key mapping beginning `wic_` is read as a construct attempt. Without this the two spellings are - equally *accepted* and unequally *safe*: `!iii` is `wic009` at once, while `wic_inline_inpt` was a mapping like - any other, so the construct vanished and the typo rode into the emitted document. Both spellings are authorable, - so it is a hand-written mistake as much as a generated one."} -- {id: a misspelled desugared edge reference, source: "steps:\n- id: s\n in: {f: {wic_alis: e}}\n", ok: false, - report: {contains: [{code: RESERVED_KEY}]}, why: *w2} -- {id: a misspelled desugared raw CWL reference, source: "steps:\n- id: s\n in: {f: {wic_raw_cwll: e}}\n", ok: false, - report: {contains: [{code: RESERVED_KEY}]}, why: *w2} -- {id: a misspelled desugared the bare prefix, source: "steps:\n- id: s\n in: {f: {wic_: 1}}\n", ok: false, - report: {contains: [{code: RESERVED_KEY}]}, why: *w2} -- {id: the prefix is unclaimed in an input port called wic_, source: "steps:\n s:\n in:\n wic_: !* e\n", - excludes: [RESERVED_KEY], - why: &w3 "A name may carry the prefix; only a construct attempt may not. The first version of this rule walked every - mapping key and reserved the prefix everywhere, which made `in: {wic_: !* e}` — a port someone may legitimately - call `wic_` — an error. The generators found it immediately. Reserving a prefix in *name* position narrows the - language well past the defect being closed, and passthrough must stay open (language spec §1)."} -- {id: the prefix is unclaimed in a port whose name has the prefix, - source: "steps:\n- id: s\n in: {wic_port: {wic_inline_input: 1}}\n", excludes: [RESERVED_KEY], why: *w3} -- {id: the prefix is unclaimed in a passthrough key, source: "steps:\n- id: s\n hints: {wic_hint: 1}\n", - excludes: [RESERVED_KEY], why: *w3} -- {id: the prefix is unclaimed in a key merely containing wic, source: "steps:\n- id: s\n hints: {wicked: 1}\n", - excludes: [RESERVED_KEY], why: *w3} -- {id: the prefix is unclaimed in the sidecar block itself, source: "wic:\n graphviz: {}\nsteps: []\n", - excludes: [RESERVED_KEY], why: *w3} -- {id: an unknown tag reports wic009 in input-pos position, source: "steps:\n- id: s\n in:\n a: !foo bar\n", - ok: false, report: {contains: [{code: UNKNOWN_TAG}]}, - why: &w4 "The code contract: an unknown tag reports wic009, in every position. *Detection* is the adversarial - property's job (with @example pins for determinism); this asserts only the stable code the .wic reference - documents."} -- {id: an unknown tag reports wic009 in scalar position, source: "top: !foo bar\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, why: *w4} -- {id: an unknown tag reports wic009 in mapping position, source: "top: !foo {a: 1}\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, why: *w4} -- {id: an unknown tag reports wic009 in sequence position, source: "top: !foo [1, 2]\n", ok: false, - report: {contains: [{code: UNKNOWN_TAG}]}, why: *w4} -- {id: an unknown tag reports wic009 in over-desugared position, - source: "steps:\n- id: s\n in:\n a: !foo {wic_alias: x}\n", ok: false, report: {contains: [{code: UNKNOWN_TAG}]}, - why: *w4} -- {id: an alias cycle through passthrough, source: "top: &a [*a]\n", ok: false, - report: {contains: [{code: RECURSIVE_ALIAS}]}, - why: &w5 "The contract: a cycle is a diagnosed error, never a quiet success. Totality (no raise) is the adversarial - property's job, with these shapes pinned on it as @example; this asserts the report the .wic reference promises. - The sidecar shape has to actually recurse through `_sidecar` to test that contract — a self-referential `steps:` - value one level up hits an unrelated malformed-key check first and never reaches the cycle guard."} -- {id: an alias cycle through steps, source: "steps: &a\n- id: s\n in:\n x: *a\n", ok: false, - report: {contains: [{code: RECURSIVE_ALIAS}]}, why: *w5} -- {id: "!ii on a key in top position", source: "!ii a: b\n", yaml: loads, - report: [{code: EXPECTED_SCALAR, message: "a mapping key is a name and takes no tag; !ii belongs on the value, as in - `a: !ii `"}], - why: &w6 "YAML admits a tagged key; a key in the language is a name, so the tag belongs on the value."} -- {id: "!ii on a key in input position", source: "steps:\n s:\n in:\n !ii a: b\n", yaml: loads, - report: [{code: EXPECTED_SCALAR, message: "a mapping key is a name and takes no tag; !ii belongs on the value, as in - `a: !ii `"}], - why: *w6} -- {id: "!* on a key in edge position", source: "steps:\n s:\n in:\n !* a: x\n", yaml: loads, - report: [{code: EXPECTED_SCALAR, message: "a mapping key is a name and takes no tag; !* belongs on the value, as in - `a: !* `"}], - why: *w6} -- {id: "!cwl on a key in passthrough position", source: "requirements:\n !cwl a: b\n", yaml: loads, - report: [{code: EXPECTED_SCALAR, message: "a mapping key is a name and takes no tag; !cwl belongs on the value, as in - `a: !cwl `"}], - why: *w6} -- {id: "reading order: a non-mapping root, which returns early", source: "- !foo a\n", - report: {contains: [{code: NOT_A_MAPPING}, {code: UNKNOWN_TAG}]}, - why: &w7 "However many passes produced them, the reader works down the file once: tags are reported in one walk and - everything else in the structural pass, so pass order is not reading order, the non-mapping root included."} -- {id: "reading order: a tag above a structural error", source: "wic: !foo {}\nsteps:\n- in: {}\n", - report: {contains: [{code: UNKNOWN_TAG}, {code: MISSING_STEP_ID}]}, why: *w7} -- {id: "reading order: a tag below a structural error", source: "steps:\n- in: {}\n- id: s\n in: !foo {}\n", - report: {contains: [{code: MISSING_STEP_ID}, {code: UNKNOWN_TAG}]}, why: *w7} -- {id: an undefined core tag is named as unknown, source: "a: !!foo 1\n", - report: [{code: UNKNOWN_TAG, message: "unknown tag 'tag:yaml.org,2002:foo'; YAML cannot construct it"}], - why: "A tag YAML does not define is reported as the tag, not as a bad value."} diff --git a/tests/core/data/parse/tags/blocks.wic b/tests/core/data/parse/tags/blocks.wic new file mode 100644 index 000000000..e365d376b --- /dev/null +++ b/tests/core/data/parse/tags/blocks.wic @@ -0,0 +1,3 @@ +# An unknown tag on the wic: block, and on steps: in its two forms. +wic: !foo {} +steps: !foo {} diff --git a/tests/core/data/parse/tags/expected.yaml b/tests/core/data/parse/tags/expected.yaml new file mode 100644 index 000000000..8e3487480 --- /dev/null +++ b/tests/core/data/parse/tags/expected.yaml @@ -0,0 +1,46 @@ +why: Every tag the language does not own is reported, wherever it is written, and so is any tag on a key, which is a + name. A single-key mapping beginning wic_ is a construct, so a misspelled one is reported, but a name may carry the + prefix freely. +# Each document's diagnostics, by code, line and column in reading order; an accepted document reports none. +documents: + blocks.wic: + - [UNKNOWN_TAG, 2, 6] + - [UNKNOWN_TAG, 3, 8] + sidecar.wic: + - [UNKNOWN_TAG, 4, 13] + - [UNKNOWN_TAG, 6, 12] + - [UNKNOWN_TAG, 8, 10] + - [EXPECTED_SCALAR, 11, 7] + unclaimed.wic: [] + unknown.wic: + - [UNKNOWN_TAG, 2, 6] + - [UNKNOWN_TAG, 3, 10] + - [UNKNOWN_TAG, 4, 11] + - [UNKNOWN_TAG, 5, 8] + - [UNKNOWN_TAG, 6, 9] + - [EXPECTED_SCALAR, 7, 1] + - [EXPECTED_SCALAR, 9, 3] + - [UNKNOWN_TAG, 11, 3] + - [UNKNOWN_TAG, 13, 7] + - [UNKNOWN_TAG, 16, 8] + - [UNKNOWN_TAG, 17, 8] + - [EXPECTED_SCALAR, 18, 5] + - [EXPECTED_SCALAR, 19, 5] + - [RESERVED_KEY, 20, 9] + - [RESERVED_KEY, 21, 9] + - [RESERVED_KEY, 22, 9] + - [RESERVED_KEY, 23, 9] + - [UNKNOWN_TAG, 24, 8] + - [UNKNOWN_TAG, 26, 9] + - [UNKNOWN_TAG, 29, 5] + wic_steps.wic: + - [UNKNOWN_TAG, 3, 10] +# What a document reads as: each node by its fields, a construct as its tag around what it carries. +reads: + unclaimed.wic: + steps: + - id: s + inputs: {wic_: {'!*': e}, wic_port: {'!ii': 1}, a: {'!ii': e}, b: {'!*': e}, c: {'!cwl': e}} + passthrough: {hints: {wic_hint: 1, wicked: 1}} + wic: + entries: {graphviz: {}} diff --git a/tests/core/data/parse/tags/sidecar.wic b/tests/core/data/parse/tags/sidecar.wic new file mode 100644 index 000000000..896b2d462 --- /dev/null +++ b/tests/core/data/parse/tags/sidecar.wic @@ -0,0 +1,11 @@ +# An unknown tag on what the wic: block says about a step, and on a step keyed by name. +wic: + steps: + (1, s): !foo {wic: {}} + (2, t): + wic: !foo {} +steps: + touch: !foo {in: {}} + s: + in: + !ii a: b diff --git a/tests/core/data/parse/tags/unclaimed.wic b/tests/core/data/parse/tags/unclaimed.wic new file mode 100644 index 000000000..c531a285b --- /dev/null +++ b/tests/core/data/parse/tags/unclaimed.wic @@ -0,0 +1,12 @@ +# The wic_ prefix is claimed only where a construct may be written: a name may carry it. +wic: + graphviz: {} +steps: +- id: s + in: + wic_: !* e + wic_port: {wic_inline_input: 1} + a: {wic_inline_input: e} + b: {wic_alias: e} + c: {wic_raw_cwl: e} + hints: {wic_hint: 1, wicked: 1} diff --git a/tests/core/data/parse/tags/unknown.wic b/tests/core/data/parse/tags/unknown.wic new file mode 100644 index 000000000..4d06384e6 --- /dev/null +++ b/tests/core/data/parse/tags/unknown.wic @@ -0,0 +1,29 @@ +# A tag the language does not own is reported wherever it is written, and so is any tag on a key: a key is a name. +top: !foo bar +mapping: !foo {a: 1} +sequence: !foo [1, 2] +alias: !foo {wic_alias: x} +number: !!foo 1 # a core tag YAML does not define +!ii key: b +requirements: + !cwl a: b +steps: +- !foo {id: s} +- id: t + in: !foo {f: !ii 1} +- id: u + in: + a: !foo bar + b: !foo {wic_alias: x} + !ii c: b + !* d: x + e: {wic_inline_inpt: 1} # a construct misspelled + f: {wic_alis: e} + g: {wic_raw_cwll: e} + h: {wic_: 1} + out: !foo [a] +- id: v + out: [!foo a] +- id: w + out: + - !foo {a: !& e} diff --git a/tests/core/data/parse/tags/wic_steps.wic b/tests/core/data/parse/tags/wic_steps.wic new file mode 100644 index 000000000..40bf48a26 --- /dev/null +++ b/tests/core/data/parse/tags/wic_steps.wic @@ -0,0 +1,4 @@ +# An unknown tag on the steps of the wic: block. +wic: + steps: !foo {} +steps: [] diff --git a/tests/core/data/parse/wic_block.yaml b/tests/core/data/parse/wic_block.yaml deleted file mode 100644 index 53fab0713..000000000 --- a/tests/core/data/parse/wic_block.yaml +++ /dev/null @@ -1,15 +0,0 @@ -- {id: "a wic: block reached through its own alias", source: "wic: &w\n steps:\n (1, a):\n wic: *w\n", - report: [{code: RECURSIVE_ALIAS, line: 1, message: {contains: [contains itself]}}], recovers: true, - why: &w0 "Each diagnosed shape reports exactly one diagnostic, at its line, and a document survives beside it: - recovery is the norm, and only unparsable YAML leaves nothing to return."} -- {id: "a repeated wic: step key names the key", source: "wic:\n steps:\n (1, a): {}\n (1, a): {}\n", - report: [{code: DUPLICATE_KEY, line: 4, message: {contains: ["wic: step key '(1, a)'"]}}], recovers: true, why: *w0} -- {id: an alias cycle through sidecar, source: "wic: &w\n steps:\n (1, a):\n wic: *w\n", ok: false, - report: {contains: [{code: RECURSIVE_ALIAS}]}, - why: &w1 "The contract: a cycle is a diagnosed error, never a quiet success. Totality (no raise) is the adversarial - property's job, with these shapes pinned on it as @example; this asserts the report the .wic reference promises. - The sidecar shape has to actually recurse through `_sidecar` to test that contract — a self-referential `steps:` - value one level up hits an unrelated malformed-key check first and never reaches the cycle guard."} -- {id: a sidecar key that is neither form, source: "wic:\n steps:\n \"not a key\": {}\n", - report: [{code: MALFORMED_WIC_STEP_KEY}], - why: &w2 "A key that is neither a bare id nor (index, id) is still wic008."} diff --git a/tests/core/data/parse/wic_block/empty.wic b/tests/core/data/parse/wic_block/empty.wic new file mode 100644 index 000000000..896293eff --- /dev/null +++ b/tests/core/data/parse/wic_block/empty.wic @@ -0,0 +1,6 @@ +# A wic: block with nothing in it. +wic: +steps: + s: + in: + a: x diff --git a/tests/core/data/parse/wic_block/every_key.wic b/tests/core/data/parse/wic_block/every_key.wic new file mode 100644 index 000000000..a24ea05f5 --- /dev/null +++ b/tests/core/data/parse/wic_block/every_key.wic @@ -0,0 +1,53 @@ +# Every key the wic: block has, at the top and for a step, and steps nested three deep: the step keys are read at +# every depth, through the wic: each one wraps, a sibling of which is read beside it. +wic: + graphviz: {label: x, style: dashed, ranksame: ["(1, s)"]} + implementations: {} + driver: slurm + inlineable: true + implementation: x + default_implementation: x + version: x + lang_version: x + namespace: x + steps: + (1, outer): + wic: + steps: + (1, inner): + wic: + steps: + (1, innermost): + namespace: global + (2, s): + graphviz: {label: x} + implementations: {} + driver: slurm + inlineable: true + implementation: x + default_implementation: x + version: x + lang_version: x + namespace: x + scatterMethod: dotproduct + in: {} + scatter: [x] + inference: {} + out: + - value: {wic_anchor: e} + (3, gpu): + wic: + namespace: gpu + out: + - value: {wic_anchor: f} + (4, empty): + wic: + in: {x: 1} + echo: + wic: {} +steps: +- id: outer +- id: s +- id: gpu +- id: empty +- id: echo diff --git a/tests/core/data/parse/wic_block/expected.yaml b/tests/core/data/parse/wic_block/expected.yaml new file mode 100644 index 000000000..51d27528d --- /dev/null +++ b/tests/core/data/parse/wic_block/expected.yaml @@ -0,0 +1,68 @@ +why: "The wic: block is closed at every depth, each key taking a value of its declared shape, and refuses any other + key or shape at the node that is wrong. Its steps are keyed (index, name) or by id, and read at every depth through + the wic: each one wraps, a sibling of which is read beside it." +# Each document's diagnostics, by code, line and column in reading order; an accepted document reports none. +documents: + empty.wic: [] + every_key.wic: [] + root.wic: + - [UNKNOWN_WIC_KEY, 3, 3] + - [UNKNOWN_WIC_KEY, 4, 3] + - [MALFORMED_WIC_VALUE, 5, 15] + - [MALFORMED_WIC_VALUE, 6, 11] + - [MALFORMED_WIC_VALUE, 7, 14] + - [MALFORMED_WIC_VALUE, 8, 17] + - [MALFORMED_WIC_VALUE, 9, 20] + - [MALFORMED_WIC_VALUE, 11, 12] + - [MALFORMED_WIC_VALUE, 12, 12] + - [MALFORMED_WIC_VALUE, 13, 5] + - [MALFORMED_WIC_VALUE, 14, 26] + steps.wic: + - [MALFORMED_WIC_STEP_KEY, 5, 5] + - [DUPLICATE_KEY, 7, 5] + - [MALFORMED_WIC_VALUE, 9, 22] + - [UNKNOWN_WIC_KEY, 10, 7] + - [MALFORMED_WIC_VALUE, 13, 21] + - [UNKNOWN_WIC_KEY, 14, 9] + - [MALFORMED_WIC_VALUE, 15, 19] + - [EXPECTED_MAPPING, 16, 13] +# What a document reads as: each node by its fields, a wic: step key as [index, name]. +reads: + every_key.wic: + steps: [id: outer, id: s, id: gpu, id: empty, id: echo] + wic: + steps: + - [1, outer, {steps: [[1, inner, {steps: [[1, innermost, {entries: {namespace: global}}]]}]]}] + - - 2 + - s + - entries: + graphviz: {label: x} + implementations: {} + driver: slurm + inlineable: true + implementation: x + default_implementation: x + version: x + lang_version: x + namespace: x + scatterMethod: dotproduct + in: {} + scatter: [x] + inference: {} + out: [value: {wic_anchor: e}] + - [3, gpu, {entries: {namespace: gpu, out: [value: {wic_anchor: f}]}}] + - [4, empty, {entries: {in: {x: 1}}}] + - [null, echo, {}] + entries: + graphviz: {label: x, style: dashed, ranksame: ['(1, s)']} + implementations: {} + driver: slurm + inlineable: true + implementation: x + default_implementation: x + version: x + lang_version: x + namespace: x + empty.wic: + steps: [{id: s, inputs: {a: x}}] + wic: {} diff --git a/tests/core/data/parse/wic_block/root.wic b/tests/core/data/parse/wic_block/root.wic new file mode 100644 index 000000000..ac88928ba --- /dev/null +++ b/tests/core/data/parse/wic_block/root.wic @@ -0,0 +1,16 @@ +# Keys the wic: block does not have, and values of the wrong shape, each reported at the node that is wrong. +wic: + nonsense_key: 1 + scatter: [x] # a step's key, not the document's + inlineable: sometimes + driver: pbs + namespace: "" + lang_version: 1.0 + implementations: [a] + graphviz: + label: "" + style: bogus + color: red + ranksame: ["(1, a)", zz] +steps: +- id: s diff --git a/tests/core/data/parse/wic_block/steps.wic b/tests/core/data/parse/wic_block/steps.wic new file mode 100644 index 000000000..788245a9a --- /dev/null +++ b/tests/core/data/parse/wic_block/steps.wic @@ -0,0 +1,18 @@ +# What the wic: block says about steps: each key names a step, as (index, name) or by its id, once, and holds only +# what the block may say about a step. +wic: + steps: + not a key: {} + (1, a): {} + (1, a): {} + (2, s): + scatterMethod: dot + nonsense_key: 1 + (3, t): + wic: + inlineable: 1 + nonsense_key: 1 + graphviz: x + (4, u): 3 # what is said about a step is a mapping +steps: +- id: s diff --git a/tests/core/data/parse/wic_values.yaml b/tests/core/data/parse/wic_values.yaml deleted file mode 100644 index 584123c1f..000000000 --- a/tests/core/data/parse/wic_values.yaml +++ /dev/null @@ -1,29 +0,0 @@ -- {id: "a wrong-shaped wic value: inlineable: sometimes", source: "wic:\n inlineable: sometimes\n", - report: [{code: MALFORMED_WIC_VALUE, line: 2, column: 15}], - why: &w0 "Each declared value shape refuses what the generated jsonschema used to refuse, as `wic034`, at the node - that is wrong -- a nested one included."} -- {id: "a wrong-shaped wic value: driver: pbs", source: "wic:\n driver: pbs\n", - report: [{code: MALFORMED_WIC_VALUE, line: 2, column: 11}], why: *w0} -- {id: "a wrong-shaped wic value: namespace: \"\"", source: "wic:\n namespace: \"\"\n", - report: [{code: MALFORMED_WIC_VALUE, line: 2, column: 14}], why: *w0} -- {id: "a wrong-shaped wic value: lang_version: 1.0", source: "wic:\n lang_version: 1.0\n", - report: [{code: MALFORMED_WIC_VALUE, line: 2, column: 17}], why: *w0} -- {id: "a wrong-shaped wic value: implementations: [a]", source: "wic:\n implementations: [a]\n", - report: [{code: MALFORMED_WIC_VALUE, line: 2, column: 20}], why: *w0} -- {id: "a wrong-shaped wic value: graphviz: x", source: "wic:\n graphviz: x\n", - report: [{code: MALFORMED_WIC_VALUE, line: 2, column: 13}], why: *w0} -- {id: "a wrong-shaped wic value: graphviz: label: \"\"", source: "wic:\n graphviz:\n label: \"\"\n", - report: [{code: MALFORMED_WIC_VALUE, line: 3, column: 12}], why: *w0} -- {id: "a wrong-shaped wic value: graphviz: style: bogus", source: "wic:\n graphviz:\n style: bogus\n", - report: [{code: MALFORMED_WIC_VALUE, line: 3, column: 12}], why: *w0} -- {id: "a wrong-shaped wic value: graphviz: color: red", source: "wic:\n graphviz:\n color: red\n", - report: [{code: MALFORMED_WIC_VALUE, line: 3, column: 5}], why: *w0} -- {id: "a wrong-shaped wic value: graphviz: ranksame: [\"(1, a)\", zz]", - source: "wic:\n graphviz:\n ranksame: [\"(1, a)\", zz]\n", - report: [{code: MALFORMED_WIC_VALUE, line: 3, column: 26}], why: *w0} -- {id: "a wrong-shaped wic value: steps: (1, s): scatterMethod: dot", - source: "wic:\n steps:\n (1, s):\n scatterMethod: dot\n", - report: [{code: MALFORMED_WIC_VALUE, line: 4, column: 22}], why: *w0} -- {id: "a wrong-shaped wic value: steps: (1, s): wic: inlineable: 1", - source: "wic:\n steps:\n (1, s):\n wic:\n inlineable: 1\n", - report: [{code: MALFORMED_WIC_VALUE, line: 5, column: 21}], why: *w0} diff --git a/tests/core/data/provoke/empty_name.wic b/tests/core/data/provoke/empty_name.wic new file mode 100644 index 000000000..9adc3b1c0 --- /dev/null +++ b/tests/core/data/provoke/empty_name.wic @@ -0,0 +1,5 @@ +# An input with an empty name, which parses and which lowering cannot represent. +steps: +- id: s + in: + "": !* e diff --git a/tests/core/data/provoke/top_level_hints.wic b/tests/core/data/provoke/top_level_hints.wic new file mode 100644 index 000000000..2f3d0b16e --- /dev/null +++ b/tests/core/data/provoke/top_level_hints.wic @@ -0,0 +1,11 @@ +# Top-level hints, which no Python Workflow carries. +hints: + ResourceRequirement: + coresMin: 1 +steps: +- id: say + run: + class: CommandLineTool + baseCommand: "true" + inputs: {} + outputs: {} diff --git a/tests/core/data/provoke/undeclared_port.wic b/tests/core/data/provoke/undeclared_port.wic new file mode 100644 index 000000000..3367e5efe --- /dev/null +++ b/tests/core/data/provoke/undeclared_port.wic @@ -0,0 +1,6 @@ +# Binds an input mk_file does not declare. +steps: +- id: mk_file + in: + name: !ii a + ghost: !ii x diff --git a/tests/core/data/render/rendered.wic b/tests/core/data/render/rendered.wic new file mode 100644 index 000000000..b4b927a59 --- /dev/null +++ b/tests/core/data/render/rendered.wic @@ -0,0 +1,53 @@ +wic: + steps: + (1, s): + wic: + namespace: dna + (2, t): + wic: {} +steps: +- id: s + in: + a: !ii x + b: !* e + c: !cwl a/b + d: !cwl + source: !* a + valueFrom: $(self) + e: !cwl + source: + - !* a + - b + linkMerge: merge_flattened + default: + - 1 + f: !cwl + source: + - a + linkMerge: merge_nested + g: !ii '0' + h: !ii 'true' + i: !ii + a: !* e + j: !ii 0777 + k: !ii 1.50 + l: !ii yes + m: !ii 0x1f + n: !ii 1:30 + o: !ii +5 + p: !ii 00 + q: !ii 1.0e+300 + r: !ii .inf + s: !ii .nan + t: !ii on + u: !ii 2020-01-01 + v: !ii null + w: !ii '0' + x: !ii '' + y: !ii a b + out: + - f: !& e + - g +- id: t +meta: !ii + a: 1 diff --git a/tests/core/data/render/written.wic b/tests/core/data/render/written.wic new file mode 100644 index 000000000..b167298e5 --- /dev/null +++ b/tests/core/data/render/written.wic @@ -0,0 +1,43 @@ +# A document in every spelling, which the renderer writes as rendered.wic: each construct tagged, each literal +# spelled as it was written, every step's wic: block in the wrapper it was read through, and an empty one as {}. +wic: + steps: + (1, s): + wic: + namespace: dna + (2, t): + wic: {} +steps: +- id: s + in: + a: {wic_inline_input: x} + b: {wic_alias: e} + c: {wic_raw_cwl: a/b} + d: {wic_raw_cwl: {source: {wic_alias: a}, valueFrom: $(self)}} + e: !cwl {source: [!* a, b], linkMerge: merge_flattened, default: [1]} + f: !cwl {source: [a], linkMerge: merge_nested} + g: {wic_inline_input: '0'} + h: {wic_inline_input: 'true'} + i: !ii {a: !* e} + j: !ii 0777 + k: !ii 1.50 + l: !ii yes + m: !ii 0x1f + n: !ii 1:30 + o: !ii +5 + p: !ii 00 + q: !ii 1.0e+300 + r: !ii .inf + s: !ii .nan + t: !ii on + u: !ii 2020-01-01 + v: !ii null + w: !ii '0' + x: !ii '' + y: !ii 'a b' + out: + - f: + wic_anchor: e + - g +- id: t +meta: !ii {a: 1} diff --git a/tests/core/provocations.py b/tests/core/provocations.py index a7f7a7fe5..3541ecd83 100644 --- a/tests/core/provocations.py +++ b/tests/core/provocations.py @@ -1,5 +1,5 @@ -"""One attack per diagnostic code, as a code nothing provokes is dead on arrival: each SophiosErrorCode is in exactly -one tier (PARSE: source text; COMPILED: callables raising it), or test_lang_parser's meta-test fails.""" +"""One attack per diagnostic code no document under tests/core/data/parse reports, as a code nothing provokes is dead +on arrival: each callable of COMPILED raises a SophiosError carrying its code, or test_lang_parser's census fails.""" # pylint: disable=import-outside-toplevel # the compiler and API load lazily, so enumerating codes stays cheap import asyncio import subprocess @@ -14,26 +14,8 @@ from sophios.lang import SophiosError, SophiosErrorCode, parse, resolve_lang_version from sophios.wic_types import Yaml -#: Codes provoked through `parse()` alone: source text in, diagnostic out. -PARSE: Final[dict[SophiosErrorCode, str]] = { - SophiosErrorCode.INVALID_YAML: 'steps:\n - [unclosed\n', - SophiosErrorCode.NOT_A_MAPPING: '- just\n- a list\n', - SophiosErrorCode.EXPECTED_MAPPING: 'steps: 3\n', - SophiosErrorCode.EXPECTED_SEQUENCE: 'steps:\n- id: s\n out: 3\n', - SophiosErrorCode.EXPECTED_SCALAR: 'steps:\n ? [a, b]\n : {}\n', - SophiosErrorCode.MISSING_STEP_ID: 'steps:\n- {a: 1, b: 2}\n', - SophiosErrorCode.EMPTY_STEP_ID: "steps:\n- id: ''\n", - SophiosErrorCode.MALFORMED_WIC_STEP_KEY: 'wic:\n steps:\n "not a key":\n x: 1\n', - SophiosErrorCode.UNKNOWN_TAG: 'top: !foo bar\n', - SophiosErrorCode.DUPLICATE_KEY: 'steps:\n- id: s\n in:\n f: !ii a\n f: !ii b\n', - SophiosErrorCode.RECURSIVE_ALIAS: 'top: &a [*a]\n', - SophiosErrorCode.MISPLACED_EDGE_DEF: 'top: !& e\n', - SophiosErrorCode.RESERVED_KEY: 'steps:\n- id: s\n in:\n f:\n wic_inline_inpt: 1\n', - SophiosErrorCode.UNKNOWN_WIC_KEY: 'wic:\n nonsense_key: 1\n', - SophiosErrorCode.MALFORMED_WIC_VALUE: 'wic:\n inlineable: sometimes\n', - SophiosErrorCode.UNSUPPORTED_CWL_VERSION: 'cwlVersion: draft-3\n', - SophiosErrorCode.STEP_INPUT_RECORD: 'steps:\n- id: s\n in:\n f: {source: x}\n', -} +#: Documents a provocation reads. +DOCUMENTS: Final = Path(__file__).resolve().parent / 'data' / 'provoke' def _provoke_undefined_edge() -> None: @@ -58,6 +40,16 @@ def _hermetic(yml: Yaml, **options: Any) -> None: compile_hermetic(yml, 'provoke', **options) +def _provoke_subworkflow_invalid() -> None: + """Compile a workflow with no step at all, then, once that is wic013, one whose step runs a file that is neither + beside the document nor in the registry, which raises.""" + try: + _compile_minimal({'steps': []}) + except SophiosError as empty: + if any(found.code is SophiosErrorCode.SUBWORKFLOW_INVALID for found in empty.diagnostics): + _hermetic({'steps': [{'id': 's', 'run': 'nowhere.cwl'}]}) + + def _provoke_script_argument_mismatch() -> None: from sophios.python_cwl_adapter import check_args_match_inputs @@ -69,13 +61,10 @@ def _provoke_script_argument_mismatch() -> None: def _provoke_container_engine_unavailable() -> None: from sophios import preflight - with tempfile.TemporaryDirectory() as root: - tool = Path(root) / 'tool.cwl' - tool.write_text('cwlVersion: v1.2\nclass: CommandLineTool\nrequirements:\n DockerRequirement:\n' - ' dockerPull: docker.io/bash:4.4\nbaseCommand: [echo]\ninputs: {}\noutputs: {}\n', - encoding='utf-8') - with mock.patch.object(preflight.sub, 'run', side_effect=FileNotFoundError('docker')): - preflight.check(preflight.needs([tool]), preflight.RunSettings('docker', root)) + tool = Path(__file__).resolve().parents[2] / 'cwl_adapters' / 'touch.cwl' + with tempfile.TemporaryDirectory() as root, \ + mock.patch.object(preflight.sub, 'run', side_effect=FileNotFoundError('docker')): + preflight.check(preflight.needs([tool]), preflight.RunSettings('docker', root)) def _provoke_missing_input_file() -> None: @@ -119,7 +108,7 @@ def _provoke_empty_name() -> None: from sophios.ir.lower import lower from sophios.ir.resolve import RegistryKey, ResolvedDocument, ResolvedPort, ResolvedProcess, ResolvedStep - document = parse('steps:\n- id: s\n in:\n "": !* e\n', 'provoke.wic').document + document = parse((DOCUMENTS / 'empty_name.wic').read_text(encoding='utf-8'), 'provoke.wic').document assert document is not None step = document.steps[0] process = ResolvedProcess( @@ -140,8 +129,7 @@ def _provoke_undeclared_port() -> None: from .synthetic_tools import SYNTHETIC_TOOLS - document = parse('steps:\n- id: mk_file\n in: {name: !ii a, ghost: !ii x}\n', - 'provoke.wic').document + document = parse((DOCUMENTS / 'undeclared_port.wic').read_text(encoding='utf-8'), 'provoke.wic').document assert document is not None resolved = resolve(document, RegistrySnapshot.from_tools(SYNTHETIC_TOOLS), name='provoke') assert resolved.document is not None @@ -224,12 +212,7 @@ def _provoke_no_python_spelling() -> None: """Read into Python objects a `.wic` that declares top-level `hints:`, which no Python `Workflow` carries.""" from sophios.api.python.workflow import Workflow - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) / 'provoke.wic' - root.write_text('hints:\n ResourceRequirement:\n coresMin: 1\n' - 'steps:\n- id: say\n run:\n class: CommandLineTool\n baseCommand: "true"\n' - ' inputs: {}\n outputs: {}\n', encoding='utf-8') - Workflow.from_wic(root) + Workflow.from_wic(DOCUMENTS / 'top_level_hints.wic') def _provoke_program_missing() -> None: @@ -336,8 +319,7 @@ def _import_edited(code: SophiosErrorCode) -> None: # A null !ii on a non-nullable input. SophiosErrorCode.MISSING_REQUIRED_INPUT: partial( _compile_minimal, {'steps': [{'id': 'touch', 'in': {'filename': {'wic_inline_input': None}}}]}), - # A workflow with no step at all: nothing to run. - SophiosErrorCode.SUBWORKFLOW_INVALID: partial(_compile_minimal, {'steps': []}), + SophiosErrorCode.SUBWORKFLOW_INVALID: _provoke_subworkflow_invalid, SophiosErrorCode.SCRIPT_ARGUMENT_MISMATCH: _provoke_script_argument_mismatch, SophiosErrorCode.CONTAINER_ENGINE_UNAVAILABLE: _provoke_container_engine_unavailable, SophiosErrorCode.MISSING_INPUT_FILE: _provoke_missing_input_file, diff --git a/tests/core/test_cwl_version.py b/tests/core/test_cwl_version.py deleted file mode 100644 index 3375f2422..000000000 --- a/tests/core/test_cwl_version.py +++ /dev/null @@ -1,59 +0,0 @@ -"""The CWL substrate version: one declared value, enforced at every emitting path; the compiler, a tool generator and -the schema once disagreed (v1.2, v1.0, any string).""" -import json -from typing import Final - -import pytest -import yaml -from cwltool.update import ALLUPDATES, UPDATES -from hypothesis import given, strategies as st -from jsonschema import Draft202012Validator - -from sophios.lang import SophiosErrorCode, parse, wic_schema -from sophios.lang.cwl import CWL_VERSION - -from .budgets import budget -from .strategies import pinned - - -@pytest.mark.fast -def test_the_version_serialises_as_a_plain_string() -> None: - """`CWL_VERSION` must survive a YAML dump unchanged. - - This is the check that matters, and the one that `isinstance(x, str)` does - not make. PyYAML picks a representer by exact type, so a `StrEnum` member - compares equal to `'v1.2'`, formats as `v1.2`, and still raises - `RepresenterError` the moment a generated document is written to disk. - """ - assert type(CWL_VERSION) is str # pylint: disable=unidiomatic-typecheck - assert yaml.safe_dump({'cwlVersion': CWL_VERSION}) == "cwlVersion: v1.2\n" - - -#: The main schema, built once; these tests only read it. -_SCHEMA_VALIDATOR: Final = Draft202012Validator(wic_schema()) - - -@pytest.mark.fast -@given(st.one_of(st.sampled_from(sorted(ALLUPDATES)), st.text('v1.023-dev ', max_size=8), st.floats(0, 2), st.none(), - st.lists(st.just('v1.2'), max_size=1))) -@pinned('draft-2', 'draft-3', 'v1.0.dev4', 'v1.2.0-dev5', 'v1.3', '', *sorted(UPDATES)) -@budget(100) -def test_a_version_is_accepted_by_the_parser_and_the_schema_exactly_when_cwltool_runs_it(version: object) -> None: - """A version the toolchain cannot run is refused where it is written, not - later inside the runner with a worse error. - - Accepting a version is a promise to process it. The CWL spec's full - enumeration includes drafts cwltool dropped years ago and `*-dev*` - snapshots gated behind `--enable-dev`; a `.wic` file declaring one used - to sail through an any-non-empty-string schema and die downstream. - `v1.3` and the empty string stand in for plain typos. - - Both readers of `Grammar.CWL_VERSION_VALUE` are checked against what cwltool - runs without `--enable-dev`, not against this module's own tuple: asserting - membership in it is a tautology, and would pass with the check reverted in either place. - """ - runs = version in tuple(UPDATES) - reported = [(d.code, d.span.start_line if d.span else None) - for d in parse(f'cwlVersion: {json.dumps(version)}\n', 'version.wic').diagnostics] - assert reported == ([] if runs else [(SophiosErrorCode.UNSUPPORTED_CWL_VERSION, 1)]) - assert _SCHEMA_VALIDATOR.is_valid({'cwlVersion': version}) is runs diff --git a/tests/core/test_hermeticity.py b/tests/core/test_hermeticity.py index af165709f..52a963879 100644 --- a/tests/core/test_hermeticity.py +++ b/tests/core/test_hermeticity.py @@ -93,7 +93,6 @@ def test_the_registry_reaches_the_branches_it_claims_to() -> None: 'tests/core/test_resolve.py', 'tests/core/test_link.py', 'tests/core/test_infer_phase.py', - 'tests/core/test_cwl_version.py', 'tests/core/test_names_emitted.py', 'tests/core/test_edge_binding.py', ) diff --git a/tests/core/test_lang_parser.py b/tests/core/test_lang_parser.py index 3cf8a3deb..f68b53a72 100644 --- a/tests/core/test_lang_parser.py +++ b/tests/core/test_lang_parser.py @@ -1,13 +1,15 @@ -"""Properties of the Sophios syntax layer, the unit tests at the end only sanity-checking wiring: every AST node has a -span, parsing never raises, InputValue has five forms, diagnostic spans index real text, the corpus parses.""" +"""The Sophios syntax layer. Each family of documents under tests/core/data/parse reads as its expected.yaml states; +properties over generated text and documents show that parsing is total, spans its text, reads YAML as YAML does and +reads a construct alike in either spelling; and every diagnostic code is provoked somewhere.""" +import json +import math import re -import time -from collections.abc import Callable -from contextlib import nullcontext +from concurrent.futures import ThreadPoolExecutor from dataclasses import replace from pathlib import Path -from typing import Any, Final, NamedTuple, cast, get_args +from typing import Any, Final, cast, get_args +import jsonschema import pytest import yaml from hypothesis import example, given @@ -20,7 +22,6 @@ Document, EdgeDef, EdgeRef, - Grammar, InlineLiteral, InputValue, RawCwlRef, @@ -30,387 +31,229 @@ parse, render, to_json, + wic_schema, ) from sophios.lang.spans import SourceSpan from sophios.utils_yaml import Key from . import provocations from .budgets import budget -from .cases import cases, diagnostic as as_written, match -from .wic_corpus import CORPUS, corpus_id -from .strategies import WIC_VALUES, documents, identifiers, input_lines, pinned, scalar_spellings +from .cases import DATA, case_dirs, diagnostic as as_written +from .wic_corpus import CORPUS +from .strategies import documents, identifiers, input_lines, pinned, scalar_spellings from .wic_reading import YamlWithSophiosTagsOpaque FAST = budget(200) +#: The exported schema, as an editor validates a document's JSON projection with it. +SCHEMA_VALIDATOR: Final = jsonschema.Draft202012Validator(wic_schema()) -def _spans(node: Any) -> list[SourceSpan]: - """Collect every span reachable from an AST node.""" - found: list[SourceSpan] = [] + +def reading(node: Any) -> Any: # pylint: disable=too-many-return-statements # one per node kind + """`node` as plain data, the form a family's expected.yaml states it in: each node its AST fields by name, empty + ones left out; a construct its tag around what it carries; a name itself; a `wic:` step key [index, name]; and a + NaN, which equals nothing, the text NaN.""" match node: case Document(): - found += _opt(node.span) - for step in node.steps: - found += _spans(step) - if node.sidecar is not None: - found += _spans(node.sidecar) + return _fields(steps=[reading(step) for step in node.steps], wic=node.sidecar and reading(node.sidecar), + passthrough=node.passthrough) case Step(): - found += _opt(node.span) - for _, value in node.inputs: - found += _spans(value) - for binding in node.outputs: - found.append(_parsed(binding.span)) - if binding.edge_def is not None: - found.append(_parsed(binding.edge_def.span)) + return _fields(id=node.id, inputs=node.inputs, + outputs=[out.name if out.edge_def is None else {out.name: reading(out.edge_def)} + for out in node.outputs], + interpreted=node.interpreted, passthrough=node.passthrough) case WicSidecar(): - found += _opt(node.span) - for _, child in node.steps: - found += _spans(child) - case InlineLiteral() | EdgeDef() | EdgeRef() | RawCwlRef() | UnresolvedName(): - found.append(_parsed(node.span)) - return found - - -def _opt(span: SourceSpan | None) -> list[SourceSpan]: - return [span] if span is not None else [] + return _fields(steps=[[key.index, key.name, reading(child)] for key, child in node.steps], + entries=node.entries) + case InlineLiteral(): + return {'!ii': reading(node.value)} + case EdgeRef(): + return {'!*': node.name} + case EdgeDef(): + return {'!&': node.name} + case RawCwlRef(): + return {'!cwl': node.expression} + case CwlRecord(): + return {'!cwl': {'source': [reading(source) for source in node.sources], **reading(dict(node.fields))}} + case UnresolvedName(): + return node.name + case dict(): + return {key: reading(value) for key, value in node.items()} + case list(): + return [reading(value) for value in node] + case float() if math.isnan(node): + return 'NaN' + return node + + +def _fields(**named: Any) -> dict[str, Any]: + """Each field that holds something, its (key, value) pairs read as a mapping.""" + return {name: reading(dict(value)) if isinstance(value, tuple) else value + for name, value in named.items() if value not in (None, (), [])} + + +@pytest.mark.fast +@pytest.mark.parametrize('family, expected', case_dirs('parse', 'documents', 'reads')) +def test_a_document_reads_as_its_family_states(family: Path, expected: dict[str, Any]) -> None: + """Each `.wic` document of a family under tests/core/data/parse, one per form, holds many faults or none. One + reading of it reports exactly the diagnostics its expected.yaml lists, each an error, by code, line and column in + reading order, so no fault hides the next; and it reads as `reads` states, or else returns a document regardless.""" + assert sorted(expected['documents']) == sorted(path.name for path in family.glob('*.wic')) + for name, report in expected['documents'].items(): + result = parse((family / name).read_text(encoding='utf-8'), name) + found = [as_written(d) for d in result.diagnostics] + assert [[d['code'], d['line'], d['column']] for d in found] == report, name + assert {d['severity'] for d in found} <= {'error'}, name + if name in expected.get('reads', {}): + assert reading(result.document) == expected['reads'][name], name + else: + assert result.document is not None, name -def _parsed(span: SourceSpan | None) -> SourceSpan: - """A value node's span, which may be absent only on a document built in memory.""" - assert span is not None, 'a parsed value node has no span' - return span +_tag_pool = st.sampled_from(['', '!ii ', '!& ', '!* ', '!cwl ', '!foo ', '!x ']) -def _resolvable(span: SourceSpan, text: str) -> bool: - """Whether a span points at a position that exists in the source.""" - lines = text.splitlines() or [''] - if not 1 <= span.start_line <= len(lines): - return False - return bool(1 <= span.start_column <= len(lines[span.start_line - 1]) + 1) +@st.composite +def adversarial_yaml(draw: st.DrawFn) -> str: + """Structured YAML text with anchors, aliases, tags, and real nesting, which arbitrary text almost never forms.""" + fragments = [] + anchors: list[str] = [] + for i in range(draw(st.integers(min_value=1, max_value=6))): + key = draw(identifiers) + shape = draw(st.sampled_from(['scalar', 'flow_list', 'flow_map', 'anchor', 'alias', 'self_ref', 'nested'])) + tag = draw(_tag_pool) + match shape: + case 'scalar': + fragments.append(f'{key}: {tag}{draw(identifiers)}') + case 'flow_list': + items = ', '.join(draw(st.lists(identifiers, min_size=0, max_size=4))) + fragments.append(f'{key}: {tag}[{items}]') + case 'flow_map': + fragments.append(f'{key}: {tag}{{{draw(identifiers)}: {draw(identifiers)}}}') + case 'anchor': + anchors.append(f'a{i}') + fragments.append(f'{key}: &a{i} [{draw(identifiers)}]') + case 'alias' if anchors: + ref = draw(st.sampled_from(anchors)) + repeats = ', '.join([f'*{ref}'] * draw(st.integers(min_value=1, max_value=6))) + anchors.append(f'a{i}') + fragments.append(f'{key}: &a{i} [{repeats}]') + case 'self_ref': + fragments.append(f'{key}: &s{i} [x, *s{i}]') + case _: + nested = draw(identifiers) + for _ in range(draw(st.integers(min_value=1, max_value=5))): + nested = f'{{n: {nested}}}' + fragments.append(f'{key}: {nested}') + return '\n'.join(fragments) + '\n' @pytest.mark.fast -@given(st.text(max_size=400)) -@FAST -def test_parsing_is_total_for_arbitrary_text(text: str) -> None: - """Parsing never raises, whatever it is handed.""" +@given(st.one_of(st.text(max_size=400), st.text('abcdefghijklmnopqrstuvwxyz!&*i {}[]:#-', max_size=120), + adversarial_yaml())) +# Hypothesis's failure database does not travel to CI, so what it once found by luck is pinned. +@example('!: :') # an unknown tag on a mapping key, the position the tag rule first missed +@example('!foo x: y') # the same, spelled legibly +@example('!!: :') # a core tag with an empty suffix, which YAML cannot construct +@example('a: !!int') # a core number tag over an empty value, which raised IndexError +@example('wic: &w\n steps: *w\n') # a malformed key through an alias, not a cycle +@example('_: !& []\n') # a name tag on a collection +@example('a: !cwl b\n') # a tag the language owns, in passthrough +@budget(500) +def test_parsing_is_total(text: str) -> None: + """Parsing never raises, whatever it is handed: any text, or YAML with aliases, cycles, tags and nesting. It + returns a document or diagnostics; each diagnostic sits at a span inside the text, none is reported twice, and + they come in reading order however many passes made them; and what it accepts, YAML loads with the Sophios tags + opaque. The reverse is allowed (`!ii 2020-13-45` is wic009), but the parser is never more permissive than YAML.""" result = parse(text, 'fuzz.wic') - assert result.document is not None or len(result.diagnostics) > 0 + assert result.document is not None or result.diagnostics + reports = [(d.severity, d.code, d.message, d.span) for d in result.diagnostics] + assert len(reports) == len(set(reports)), f'duplicate diagnostics: {reports}' + positions = [] + for found in result.diagnostics: + span = found.span + assert span is not None and span.file == 'fuzz.wic', found + assert 1 <= span.start_line <= max(len(text.splitlines()), 1) + 1 and span.start_column >= 1, found + positions.append((span.start_line, span.start_column)) + assert positions == sorted(positions), reports + if result.ok and result.document is not None: + yaml.load(text, Loader=YamlWithSophiosTagsOpaque) # must not raise -@pytest.mark.fast -@given(documents()) -@FAST -def test_well_formed_documents_parse(source: str) -> None: - """A syntactically valid document yields a document and no errors.""" - result = parse(source, 'gen.wic') - assert result.ok, [str(d) for d in result.diagnostics] +def _spans(node: Any) -> list[SourceSpan | None]: + """Every span reachable from an AST node; a value node's span is never absent on a parsed document.""" + match node: + case Document(): + return [*_present(node.span), *(span for step in node.steps for span in _spans(step)), + *(_spans(node.sidecar) if node.sidecar is not None else [])] + case Step(): + edges = [out.edge_def.span for out in node.outputs if out.edge_def is not None] + return [*_present(node.span), *(span for _, value in node.inputs for span in _spans(value)), + *(out.span for out in node.outputs), *edges] + case WicSidecar(): + return [*_present(node.span), *(span for _, child in node.steps for span in _spans(child))] + case InlineLiteral() | EdgeRef() | RawCwlRef() | UnresolvedName(): + return [node.span] + return [] -@pytest.mark.fast -@given(documents()) -@FAST -def test_every_node_carries_a_resolvable_span(source: str) -> None: - """Every span in the tree points at real source.""" - result = parse(source, 'gen.wic') - assert result.document is not None - spans = _spans(result.document) - assert spans, 'no spans collected; the walk is not reaching the tree' - for span in spans: - assert _resolvable(span, source), f'unresolvable span {span}' +def _present(span: SourceSpan | None) -> list[SourceSpan | None]: + return [span] if span is not None else [] @pytest.mark.fast @given(documents()) +@example('steps:\n touch:\n in:\n f: !ii x\n') +@example('steps:\n- id: touch\n in:\n f: !ii x\n') @FAST -def test_input_values_are_closed(source: str) -> None: - """Every input value is one of the five declared forms.""" - permitted = get_args(InputValue) +def test_a_well_formed_document_is_read_whole(source: str) -> None: + """A well-formed document, in either step form with every input spelling, outputs and nested `wic:` blocks, parses + without a diagnostic. Every node carries a span pointing at real source; every input value is one of the five + forms; written in the other step form, it reads back in that form and is otherwise the same document, so the writer + keeps the form it is given; and its JSON projection is JSON, which the exported schema accepts.""" result = parse(source, 'gen.wic') - assert result.document is not None - for step in result.document.steps: - for name, value in step.inputs: - assert isinstance(value, permitted), f'{name} produced {type(value).__name__}' - - -@pytest.mark.fast -@given(st.text(max_size=400)) -@FAST -def test_diagnostic_spans_index_real_source(text: str) -> None: - """A parse diagnostic always has a span, inside the document. - - The `Diagnostic` type allows a spanless entry because compile-phase - failures may not know a position — but the *parser* always does, and this - is where that stronger guarantee is enforced. - """ - for diagnostic in parse(text, 'fuzz.wic').diagnostics: - assert diagnostic.span is not None, f'parse diagnostic without a span: {diagnostic}' - assert diagnostic.span.file == 'fuzz.wic' - assert diagnostic.span.start_line >= 1 - assert diagnostic.span.start_column >= 1 - assert diagnostic.span.start_line <= max(len(text.splitlines()), 1) + 1 - - -@pytest.mark.cwl_corpus -@pytest.mark.fast -@pytest.mark.parametrize('path', CORPUS, ids=corpus_id) -def test_corpus_files_parse(path: Path) -> None: - """Every `.wic` in the repository corpus parses without error. - - This is what makes "the specification accepts what exists today" - falsifiable rather than an aspiration. - """ - source = path.read_text(encoding='utf-8') - result = parse(source, str(path)) - assert result.ok, [str(d) for d in result.diagnostics] + assert result.ok and result.document is not None, [str(d) for d in result.diagnostics] + document = result.document + lines = source.splitlines() + spans = _spans(document) + assert spans, 'no spans collected; the walk is not reaching the tree' + for span in spans: + assert span is not None and 1 <= span.start_line <= len(lines), span + assert 1 <= span.start_column <= len(lines[span.start_line - 1]) + 1, span + for step in document.steps: + assert all(isinstance(value, get_args(InputValue)) for _, value in step.inputs), step + other = replace(document, steps_as_mapping=not document.steps_as_mapping) + again = parse(render(other), 'b.wic') + assert again.ok and again.document is not None, [str(d) for d in again.diagnostics] + assert again.document.steps_as_mapping is other.steps_as_mapping + assert to_json(replace(again.document, steps_as_mapping=document.steps_as_mapping)) == to_json(document) + projection = json.loads(json.dumps(to_json(document))) + assert SCHEMA_VALIDATOR.is_valid(projection), list(SCHEMA_VALIDATOR.iter_errors(projection)) -@pytest.mark.cwl_corpus -@pytest.mark.fast -def test_corpus_is_not_empty() -> None: - """Discovery must find workflows, or the corpus property passes vacuously. - - The corpus is whatever `search_paths_wic` reaches — the same discovery the - compiler uses, so there is nothing separate to keep complete. An empty - result does not mean a small corpus; it means discovery itself broke, and - that is a failure, not a skip. CI provisions the config that reaches the - sibling repositories, and CI is the arbiter of full coverage. - """ - assert CORPUS, 'get_yml_paths found no workflows; check search_paths_wic' +#: Each tag and its desugared key. +SPELLINGS: Final = {'!ii': Key.INLINE_INPUT, '!*': Key.ALIAS, '!cwl': Key.RAW_CWL, '!&': Key.ANCHOR} @pytest.mark.fast -@given( - st.sampled_from([('!ii', 'wic_inline_input', InlineLiteral), - ('!*', 'wic_alias', EdgeRef), - ('!cwl', 'wic_raw_cwl', RawCwlRef)]), - identifiers, -) +@given(st.sampled_from(sorted(SPELLINGS)), identifiers, _tag_pool, + st.one_of(identifiers, st.builds(lambda key: f'{{{key}: x}}', identifiers | st.sampled_from(sorted(Key.ALL))))) @FAST -def test_surface_forms_are_equivalent(form: tuple[str, str, type], payload: str) -> None: - """Tagged and desugared spellings of a construct parse to the same node. - - Humans write `!ii x`; the Python API emits `{wic_inline_input: x}`, because - a constructor that re-emitted its own tag would fire again on reload. Both - are the same language, so both must produce the same AST — otherwise the - two surfaces have quietly diverged. - """ - tag, key, expected = form - tagged = parse(f'steps:\n- id: s\n in:\n f: {tag} {payload}\n', 'a.wic') - sugared = parse(f'steps:\n- id: s\n in:\n f:\n {key}: {payload}\n', 'b.wic') - assert tagged.ok and sugared.ok - assert tagged.document is not None and sugared.document is not None - - left = tagged.document.steps[0].inputs[0][1] - right = sugared.document.steps[0].inputs[0][1] - assert isinstance(left, expected) and isinstance(right, expected) - assert _payload(left) == _payload(right) - - -@pytest.mark.fast -@given(identifiers) -@FAST -def test_the_two_spellings_of_an_edge_definition_agree_on_an_output(payload: str) -> None: - """`!&` has the same two spellings as its siblings, in the one position it - is legal (.wic reference §3.6). Tested separately rather than as a fourth row above, - because that table quantifies over *input* position and an anchor there is - now `wic019` — the case does not disappear, it moves to where it belongs. - """ - tagged = parse(f'steps:\n- id: s\n out:\n - f: !& {payload}\n', 'a.wic') - sugared = parse(f'steps:\n- id: s\n out:\n - f:\n wic_anchor: {payload}\n', 'b.wic') - assert tagged.ok and sugared.ok - assert tagged.document is not None and sugared.document is not None - - left = tagged.document.steps[0].outputs[0].edge_def - right = sugared.document.steps[0].outputs[0].edge_def - assert isinstance(left, EdgeDef) and isinstance(right, EdgeDef) - assert left.name == right.name == payload - - -def _payload(value: InputValue) -> Any: - """The carried value of an input node, whatever its form.""" - match value: - case InlineLiteral(): - return value.value - case RawCwlRef(): - return value.expression - case EdgeDef() | EdgeRef() | UnresolvedName(): - return value.name - - -# Every row is the same three steps — parse, check the verdict, inspect one -# thing — so only the source and the claim are worth reading. Each row is -# still a named case in the test report. - - -class Accepted(NamedTuple): - """Source the language admits, and what the document must then hold.""" - - claim: str - source: str - holds: Callable[[Document], bool] - - -def _first_keys(sidecar: WicSidecar | None) -> list[tuple[int | None, str]]: - """The (index, name) of each step key, following the first `wic: steps:` entry down while there is one.""" - keys = [] - while sidecar is not None and sidecar.steps: - key, sidecar = sidecar.steps[0] - keys.append((key.index, key.name)) - return keys - - -def _merged_record(document: Document) -> bool: - """Whether step 0's input f is a CwlRecord: typed sources, verbatim fields.""" - record = document.steps[0].input('f') - return (isinstance(record, CwlRecord) - and [(type(source).__name__, source.name) for source in record.sources] - == [('EdgeRef', 'a'), ('UnresolvedName', 'wf_in')] - and dict(record.fields) == {'linkMerge': 'merge_flattened'}) - - -def _defines_e(document: Document) -> bool: - edge = document.steps[0].outputs[0].edge_def - return edge is not None and edge.name == 'e' - - -def _is_kv(value: Any) -> bool: - """`!ii {k: v}` is one InlineLiteral around plain data: the passthrough walk and the input's caller both wrap - tagged collections, and uncoordinated the same node was wrapped twice.""" - return isinstance(value, InlineLiteral) and value.value == {'k': 'v'} - - -ACCEPTED: Final[tuple[Accepted, ...]] = ( - Accepted('a bare name is an unresolved name', - 'steps:\n s:\n in:\n e: plain\n', - lambda d: isinstance(d.steps[0].input('e'), UnresolvedName)), - Accepted('an untagged mapping input is an inline literal (.wic reference §3.2)', - 'steps:\n- id: s\n in:\n a: {some: mapping}\n', - lambda d: isinstance(d.steps[0].inputs[0][1], InlineLiteral) - and d.steps[0].inputs[0][1].value == {'some': 'mapping'}), - Accepted('sidecar step keys are structured, not strings', - 'wic:\n steps:\n (1, alpha):\n wic:\n graphviz: {}\n', - lambda d: d.sidecar is not None - and (d.sidecar.steps[0][0].index, d.sidecar.steps[0][0].name) == (1, 'alpha')), - Accepted('a bare wic: is an empty sidecar, not an error', - 'wic:\nsteps:\n s:\n in:\n a: !ii 1\n', - lambda d: d.sidecar is not None), - Accepted('a step with no body at all is well-formed', - 'steps:\n some_step.wic:\n', - lambda d: d.steps[0].id == 'some_step.wic' and d.steps[0].inputs == ()), - Accepted('uninterpreted step keys survive too', - 'steps:\n s:\n label: a human label\n', - lambda d: dict(d.steps[0].passthrough)['label'] == 'a human label'), - Accepted('a scalar YAML cannot load keeps its literal text', - 'steps:\n s:\n in:\n a: !ii "{unclosed"\n', - lambda d: isinstance(d.steps[0].inputs[0][1], InlineLiteral) - and d.steps[0].inputs[0][1].value == '{unclosed'), - Accepted('uninterpreted top-level keys survive', - '$namespaces:\n edam: http://example\nsteps:\n s: {}\n', - lambda d: dict(d.passthrough)['$namespaces'] == {'edam': 'http://example'}), - # `(index, name)` keys are StepKeys at every depth, not opaque strings: the child sidecar arrives wrapped in a - # `wic:` key, and the parser descends through it, or StepKey's "nothing downstream parses that string again" - # is false past the first depth. - Accepted('sidecar nesting is normalised at every depth', - 'wic:\n steps:\n (1, outer):\n wic:\n steps:\n' - ' (1, inner):\n wic:\n steps:\n' - ' (1, innermost):\n namespace: global\n', - lambda d: _first_keys(d.sidecar) == [(1, 'outer'), (1, 'inner'), (1, 'innermost')]), - # A merged parent contribution lands beside a step's own `wic:` metadata once ast.py::merge_yml_trees combines - # a distant ancestor's unwrapped `out:` with this step's wrapped sidecar (`cg.wic`'s `mdrun`, through - # `basic.wic`). Both survive: the metadata is not stranded opaque under `wic:`, and `!&` under `out:` is accepted. - Accepted('a sidecar steps out sibling to wic: still unwraps', - 'wic:\n steps:\n (1, s):\n wic:\n namespace: gpu\n' - ' out:\n - value: !& e\nsteps:\n- id: s\n', - lambda d: d.sidecar is not None - and (entries := dict(d.sidecar.steps[0][1].entries))['namespace'] == 'gpu' - and entries['out'] == [{'value': {Key.ANCHOR: 'e'}}]), - # The siblings alone, rather than a wic033 naming the wrapper as an unknown key; the schema reads it the same way. - Accepted('an empty sidecar wrapper beside siblings is an empty mapping', - 'wic:\n steps:\n (1, a):\n wic:\n in: {x: 1}\nsteps:\n- id: a\n', - lambda d: d.sidecar is not None and dict(d.sidecar.steps[0][1].entries) == {'in': {'x': 1}}), - # Both edge spellings are honoured, in each of three layouts; a non-!& value is the case in edges.yaml. - Accepted('an out value tagged !& defines an edge', 'steps:\n- id: s\n out:\n - file: !& e\n', _defines_e), - Accepted('an out value desugared to wic_anchor defines an edge', - 'steps:\n- id: s\n out:\n - file: {wic_anchor: e}\n', _defines_e), - Accepted('an out value with a block wic_anchor defines an edge', - 'steps:\n- id: s\n out:\n - f:\n wic_anchor: e\n', _defines_e), - Accepted('an inline literal collection in input is wrapped exactly once', - 'steps:\n- id: s\n in:\n a: !ii {k: v}\n', lambda d: _is_kv(d.steps[0].inputs[0][1])), - Accepted('an inline literal collection in passthrough is wrapped exactly once', - 'top: !ii {k: v}\n', lambda d: _is_kv(dict(d.passthrough)['top'])), - Accepted('only a mapping made of record fields alone is read as one; any other key keeps it a literal', - 'steps:\n mk_file:\n in:\n name: {source: x, pdb_code: 1aki}\n', - lambda d: isinstance(d.steps[0].input('name'), InlineLiteral)), - Accepted('a bare step id is a sidecar step key with no index', - 'wic:\n steps:\n echo:\n wic:\n graphviz:\n label: x\nsteps:\n echo:\n', - lambda d: d.sidecar is not None and _first_keys(d.sidecar) == [(None, 'echo')] - and str(d.sidecar.steps[0][0]) == 'echo'), - Accepted('!cwl builds a record: typed sources, verbatim fields', - 'steps:\n s:\n in:\n f: !cwl {source: [!* a, wf_in], linkMerge: merge_flattened}\n', - _merged_record), - Accepted('wic_raw_cwl builds the same record', - 'steps:\n s:\n in:\n f:\n wic_raw_cwl:\n' - ' source: [{wic_alias: a}, wf_in]\n linkMerge: merge_flattened\n', _merged_record), -) - - -PARSE_KEYS: Final = ('source', 'report', 'excludes', 'ok', 'recovers', 'passthrough', 'step_passthrough', 'yaml') - - -@pytest.mark.fast -@pytest.mark.parametrize('case', cases('parse', *PARSE_KEYS)) -def test_parse_case(case: dict[str, Any]) -> None: - """`source` parses as the case says, each expectation optional: `report`, its diagnostics in reading order, each - as `--diagnostics json` writes it with the code by name; `excludes`, codes it never reports; `ok`; `recovers`, a - document returned; `passthrough` and `step_passthrough`, keys of the document's or its first step's passthrough - and exactly what each holds; `yaml`, whether YAML with the Sophios tags opaque `loads` the text or `raises`. - - Whatever the case, every diagnostic has a span and they come back in reading order: tags are reported in one walk - and everything else in the structural pass, so pass order is not reading order. - """ - result = parse(case['source'], 'case.wic') - found = [as_written(d) for d in result.diagnostics] - assert all(d['line'] is not None for d in found), found - assert [(d['line'], d['column']) for d in found] == sorted((d['line'], d['column']) for d in found), found - assert match(case.get('report', found), found), found - assert not {d['code'] for d in found} & set(case.get('excludes', ())), found - recovered = result.document is not None - assert result.ok is case.get('ok', result.ok) and recovered is case.get('recovers', recovered) - for key, held in case.get('passthrough', {}).items(): - assert result.document is not None and dict(result.document.passthrough)[key] == held - for key, held in case.get('step_passthrough', {}).items(): - assert result.document is not None and dict(result.document.steps[0].passthrough)[key] == held - if 'yaml' in case: - with pytest.raises(yaml.YAMLError) if case['yaml'] == 'raises' else nullcontext(): - yaml.load(case['source'], Loader=YamlWithSophiosTagsOpaque) - - -@pytest.mark.fast -@pytest.mark.parametrize('case', ACCEPTED, ids=[case.claim for case in ACCEPTED]) -def test_accepted_shapes(case: Accepted) -> None: - """Each admitted shape parses, and the AST carries what it should.""" - result = parse(case.source, 'accepted.wic') - assert result.ok, [str(d) for d in result.diagnostics] - assert result.document is not None - assert case.holds(result.document), case.claim - - -@pytest.mark.fast -@given(documents()) -@example('steps:\n touch:\n in:\n f: !ii x\n') -@example('steps:\n- id: touch\n in:\n f: !ii x\n') -@budget(50) -def test_sequence_and_mapping_steps_agree(source: str) -> None: - """Both `steps:` surface forms produce the same AST shape: a document written out in the other form reads back - in that form, and is otherwise the same document. So the writer keeps the form it is given, either way.""" - document = parse(source, 'a.wic').document - assert document is not None - other = replace(document, steps_as_mapping=not document.steps_as_mapping) - result = parse(render(other), 'b.wic') - assert result.ok and result.document is not None, [str(d) for d in result.diagnostics] - assert result.document.steps_as_mapping is other.steps_as_mapping - assert to_json(replace(result.document, steps_as_mapping=document.steps_as_mapping)) == to_json(document) +def test_a_construct_reads_alike_in_either_spelling_and_position(tag: str, payload: str, other: str, + value: str) -> None: + """One construct, one reading. Its tagged spelling, as people write it, and its desugared one, as the Python API + emits it, parse to the same document: an input for `!ii`, `!*` and `!cwl`, and an output's edge for `!&`, which + defines one only there. And a value makes the same unknown-tag call in input position as in passthrough, over each + tag and each construct key, `!foo {wic_anchor: x}` among them, where the two positions once disagreed.""" + place = ' out:\n - f:' if tag == '!&' else ' in:\n f:' + tagged, desugared = (parse(f'steps:\n- id: s\n{place} {spelled}\n', 'spelled.wic') + for spelled in (f'{tag} {payload}', f'{{{SPELLINGS[tag]}: {payload}}}')) + assert tagged.ok and desugared.ok, [str(d) for d in (*tagged.diagnostics, *desugared.diagnostics)] + assert reading(tagged.document) == reading(desugared.document) + in_position = parse(f'steps:\n- id: s\n in:\n a: {other}{value}\n', 'position.wic') + passthrough = parse(f'top: {other}{value}\n', 'position.wic') + assert ({d.code for d in in_position.diagnostics} & {SophiosErrorCode.UNKNOWN_TAG} + == {d.code for d in passthrough.diagnostics} & {SophiosErrorCode.UNKNOWN_TAG}), f'{other}{value}' #: A step's own keys but `id`, written out rather than read off `Grammar.STEP_KEYS`, which they are held to. @@ -423,15 +266,9 @@ def test_sequence_and_mapping_steps_agree(source: str) -> None: min_size=1, max_size=3, unique=True).map(lambda keys: ''.join(f'\n {key}' for key in keys))) -def _placed_alike(body: str) -> bool: - """Whether both spellings place a body's diagnostics alike: not so for an unknown tag on a whole non-mapping - body, whose wic003 the mapping form reports at the key and the sequence form at the value, whatever the key.""" - return not body.startswith(' !bogus') - - @pytest.mark.fast -@given(st.one_of(identifiers, st.sampled_from(_STEP_KEYS)).filter(lambda key: key != 'id'), - _ENTRY_BODIES.filter(_placed_alike)) +@given(st.one_of(identifiers, st.sampled_from([*_STEP_KEYS, 'doc', 'label'])).filter(lambda key: key != 'id'), + _ENTRY_BODIES.filter(lambda body: not body.startswith(' !bogus'))) @example('in', ' [a, b]') # a forgotten id:, its body a non-mapping in: @example('out', ' {a: 1}') # a forgotten id:, its body a non-sequence out: @example('in', ' {id: !ii 1}') # a forgotten id:, an input legitimately named id @@ -447,140 +284,17 @@ def test_a_step_entry_without_an_id_reports_what_its_fix_reports(key: str, body: """Taking the wic006 message's advice must not hand back a fresh error: `- K: V` owes exactly the diagnostics of the spelling that message recommends, plus its own wic006, or the user re-runs and is handed one the sequence spelling never mentioned. A step key `K` is a forgotten `- id:` line, so the entry is the body and the `id:` form - holding it is the fix; any other `K` names the step, as `K: V` in the mapping form does. Walking the key's value - instead would lose the body's own shape errors, and report an input named `id` as a second identity.""" + holding it is the fix; any other `K` names the step, as `K: V` in the mapping form does. An unknown tag on a whole + non-mapping body is not drawn: the mapping form reports its wic003 at the key, the sequence form at the value.""" fix = f'steps:\n- id: s\n {key}:{body}\n' if key in _STEP_KEYS else f'steps:\n {key}:{body}\n' rejected = [d.code for d in parse(f'steps:\n- {key}:{body}\n', 'rejected.wic').diagnostics] assert rejected == [SophiosErrorCode.MISSING_STEP_ID, *(d.code for d in parse(fix, 'fix.wic').diagnostics)] -@pytest.mark.fast -@pytest.mark.parametrize('spelling', sorted(Key.ALL)) -def test_the_desugared_spellings_are_not_reported_against_themselves(spelling: str) -> None: - """The rule names a prefix, so the constructs it exists for must pass it.""" - result = parse(f'steps:\n- id: s\n in:\n f:\n {spelling}: e\n', 'spelled.wic') - assert SophiosErrorCode.RESERVED_KEY not in [d.code for d in result.diagnostics], spelling - - -@pytest.mark.fast -@pytest.mark.parametrize(('name', 'leads'), [('touch', "write '- id: touch'"), ('in', "add the '- id:' line")]) -def test_the_single_key_message_leads_with_the_likelier_reading(name: str, leads: str) -> None: - """`- in:` is almost certainly a forgotten id:; `- touch:` almost certainly a name.""" - diagnostics = parse(f'steps:\n- {name}:\n a: !ii 1\n', 'reading.wic').diagnostics - message = next(d.message for d in diagnostics if d.code is SophiosErrorCode.MISSING_STEP_ID) - assert message.startswith(f'a step in a sequence carries its name in an id: key — {leads}') - assert f"write '- id: {name}'" in message and "add the '- id:' line" in message - - -#: Keys offered to a step body: every one `Grammar.STEP_KEYS` claims, plus -#: three it must not claim. Written out rather than read off `STEP_KEYS`, -#: because a probe derived from the set under test moves with it and a member -#: could then be dropped from both sides unnoticed. -_PROBE_KEYS: Final = ('id', 'in', 'out', 'run', 'scatter', 'scatterMethod', 'when', 'doc', 'label', 'touch') - - -@pytest.mark.fast -def test_step_keys_is_exactly_the_set_step_body_acts_on() -> None: - """`Grammar.STEP_KEYS` is exactly the set `_step_body` acts on. - - The two sides must agree for wic006's reading to be right: a key that falls - through to passthrough is a step name, not a step key. `_step_body` names - `id`, `in` and `out` itself, so those three are spelled in two places and - this is what stops them drifting. - """ - body = ''.join(f' {key}: {{}}\n' for key in _PROBE_KEYS if key != 'id') - document = parse(f'steps:\n- id: s\n{body}', 'keys.wic').document - assert document is not None - passed_through = {key for key, _ in document.steps[0].passthrough} - assert passed_through == {'doc', 'label', 'touch'} - assert set(_PROBE_KEYS) - passed_through == set(Grammar.STEP_KEYS) - - -@pytest.mark.fast -def test_python_api_emits_documents_this_parser_accepts(tmp_path: Path) -> None: - """The Python API is the second surface of the same language. - - Whatever it emits must parse, or the two surfaces have diverged and the - language spec is describing something that does not exist. See - docs/dev/language_spec.md, section 3. - """ - # Imported here: the API pulls in the whole compiler, which the syntax - # layer deliberately does not depend on. - # pylint: disable=import-outside-toplevel - from sophios.api.python.workflow import Workflow - - from .helpers import adapter_step - - touch = adapter_step('touch', filename='empty.txt') - workflow = Workflow([touch], 'adherence') - - result = parse(workflow.write_wic(tmp_path).read_text(encoding='utf-8'), 'api_emitted.wic') - - assert result.ok, [str(d) for d in result.diagnostics] - assert result.document is not None - emitted = result.document.steps[0].input('filename') - assert isinstance(emitted, InlineLiteral) - assert emitted.value == 'empty.txt' - - -def _nested_api_workflow() -> Any: - """A parent calling one nested workflow whose steps share an edge.""" - # pylint: disable=import-outside-toplevel - from sophios.api.python.workflow import Workflow - - from .helpers import adapter_step - - touch = adapter_step('touch', filename='empty.txt') - append = adapter_step('append', file=touch.outputs.file, str='Hello') - child = Workflow([touch, append], 'adherence_child') - return Workflow([child], 'adherence_parent') - - -@pytest.mark.fast -def test_python_api_writes_nested_workflows_this_parser_accepts(tmp_path: Path) -> None: - """Every `.wic` file of a written nested workflow parses: the parent calls - the child by name, and the child's edge is an ordinary `!&`/`!*` pair in - its own document (language spec §3). Each tool is written beside them.""" - root = _nested_api_workflow().write_wic(tmp_path) - - written = sorted(tmp_path.glob('*.wic')) - assert root in written and len(written) == 2, written - assert [path.name for path in sorted(tmp_path.glob('*.cwl'))] == ['append.cwl', 'touch.cwl'] - for path in written: - result = parse(path.read_text(), path.name) - assert result.ok, (path.name, [str(d) for d in result.diagnostics]) - -# `yaml.SafeLoader` rejects unknown tags with ConstructorError; a syntax layer -# that silently accepted them would specify a superset of the language. Both -# escapes found so far are pinned, plus the agreement property. - - -@pytest.mark.fast -@given(st.text('abcdefghijklmnopqrstuvwxyz!&*i {}[]:#-', max_size=120)) -@FAST -@example('!: :') # unknown tag on a mapping *key* — the position that was missed -@example('!foo x: y') # the same, spelled legibly -@example('!!: :') # a core tag with an empty suffix, which YAML cannot construct -@example('a: !!str [a]') # a core tag on the wrong node kind -@example('a: !!int') # a core number tag over an empty value, which raises IndexError -@example('a: !!int abc') # a core tag over a value its constructor cannot read -def test_parser_is_not_more_permissive_than_yaml(text: str) -> None: - """Any document the parser accepts without diagnostics, `yaml.SafeLoader` - loads with the Sophios tags opaque. - - The reverse is allowed — the parser reports what YAML accepts as an opaque - tag's text (`!ii 2020-13-45` is wic009) — but this direction is the - specification's half of the bargain. - - The pinned cases are tags in key position. The property found `!: :` on - its own, months after the tag rule was written, because the alphabet only - rarely composes a tagged key — which is exactly why it is pinned now: - Hypothesis's failure database does not travel to CI, so a find that came - from one lucky seed would otherwise be re-discovered by luck or not at all. - """ - result = parse(text, 'agree.wic') - if result.ok and result.document is not None: - yaml.load(text, Loader=YamlWithSophiosTagsOpaque) # must not raise +def _payload(value: Any) -> Any: + """The value an `!ii` input carries.""" + assert isinstance(value, InlineLiteral), value + return value.value @st.composite @@ -614,8 +328,8 @@ def node(depth: int) -> str: @FAST def test_what_yaml_cannot_construct_is_one_wic009(document: tuple[str, bool]) -> None: """A tag YAML cannot construct, or a node its tag cannot build, is one wic009, and in passthrough nothing else; the - parser never raises. A failed merge is worded as a merge, an undefined tag is named, and a value YAML cannot read - says so. What YAML builds is no wic009.""" + parser never raises. The diagnostic names its subject: a failed merge as a merge, an undefined tag by name, a value + YAML cannot read as such. What YAML builds is no wic009.""" source, passthrough = document diagnostics = parse(source, 't.wic').diagnostics messages = [d.message for d in diagnostics if d.code is SophiosErrorCode.UNKNOWN_TAG] @@ -657,270 +371,6 @@ def test_a_scalar_is_read_as_yaml_reads_it(spelled: tuple[str, str | None]) -> N assert (repr(value), type(value)) == (repr(read), type(read)), text -@pytest.mark.fast -def test_the_wic_block_is_closed_at_every_depth() -> None: - """Each `wic:` key the language has parses clean; any other is `wic033`, - positioned at the key itself. - - The generated jsonschema used to refuse such a key as the file was read. - The parser is the gate now, so it is the parser that must refuse it -- at - the root, and on a `steps:` entry, whose vocabulary is the root's plus - what it says about the step it names. - """ - for key in sorted(Grammar.SIDECAR_KEYS - {'steps'}): - root = parse(f'wic:\n {key}: {WIC_VALUES[key]}\nsteps:\n- id: s\n', 'root.wic') - assert not root.diagnostics.has_errors, (key, [str(d) for d in root.diagnostics]) - for key in sorted(Grammar.SIDECAR_STEP_KEYS - {'steps', 'out'}): - entry = parse(f'wic:\n steps:\n (1, s):\n {key}: {WIC_VALUES[key]}\nsteps:\n- id: s\n', - 'entry.wic') - assert not entry.diagnostics.has_errors, (key, [str(d) for d in entry.diagnostics]) - - for source, line, column in [ - ('wic:\n nonsense_key: 1\nsteps:\n- id: s\n', 2, 3), - ('wic:\n steps:\n (1, s):\n wic:\n nonsense_key: 1\nsteps:\n- id: s\n', 5, 9), - ('wic:\n steps:\n (1, s):\n nonsense_key: 1\nsteps:\n- id: s\n', 4, 7), - # A step-only key is not a root key. - ('wic:\n scatter: [x]\nsteps:\n- id: s\n', 2, 3)]: - reported = [(d.code, d.span.start_line, d.span.start_column) - for d in parse(source, 'closed.wic').diagnostics if d.span is not None] - assert reported == [(SophiosErrorCode.UNKNOWN_WIC_KEY, line, column)], source - - -@pytest.mark.fast -def test_alias_expansion_is_bounded() -> None: - """A widening alias chain is cut off by budget, quickly, once.""" - laughs = 'a0: &a0 [x, x, x, x, x, x, x, x, x]\n' - for i in range(1, 8): - refs = ', '.join([f'*a{i-1}'] * 9) - laughs += f'a{i}: &a{i} [{refs}]\n' - - started = time.perf_counter() - result = parse(laughs, 'laughs.wic') # must not raise or hang - assert time.perf_counter() - started < 5.0 - assert not result.ok - assert any(d.code is SophiosErrorCode.RECURSIVE_ALIAS for d in result.diagnostics) - - -# `st.text()` almost never forms valid YAML with aliases, so quantifying -# totality over it left the entire anchor/alias class untested: cycles raised -# RecursionError and widening chains exhausted memory while the totality -# property stayed green. -# These strategies generate *structured* YAML — anchors, aliases (including -# self-referential ones), tags known and unknown, deep nesting — so the -# property covers the inputs that actually break parsers. - - -_tag_pool = st.sampled_from(['', '!ii ', '!& ', '!* ', '!cwl ', '!foo ', '!x ']) - - -@st.composite -def adversarial_yaml(draw: st.DrawFn) -> str: - """Structured YAML text with anchors, aliases, tags, and real nesting.""" - fragments = [] - anchors: list[str] = [] - for i in range(draw(st.integers(min_value=1, max_value=6))): - key = draw(identifiers) - shape = draw(st.sampled_from(['scalar', 'flow_list', 'flow_map', 'anchor', 'alias', 'self_ref', 'nested'])) - tag = draw(_tag_pool) - match shape: - case 'scalar': - fragments.append(f'{key}: {tag}{draw(identifiers)}') - case 'flow_list': - items = ', '.join(draw(st.lists(identifiers, min_size=0, max_size=4))) - fragments.append(f'{key}: {tag}[{items}]') - case 'flow_map': - inner = draw(identifiers) - fragments.append(f'{key}: {tag}{{{inner}: {draw(identifiers)}}}') - case 'anchor': - anchors.append(f'a{i}') - fragments.append(f'{key}: &a{i} [{draw(identifiers)}]') - case 'alias' if anchors: - ref = draw(st.sampled_from(anchors)) - repeats = ', '.join([f'*{ref}'] * draw(st.integers(min_value=1, max_value=6))) - anchors.append(f'a{i}') - fragments.append(f'{key}: &a{i} [{repeats}]') - case 'self_ref': - # A node that contains itself — legal YAML, lethal to naive walks. - fragments.append(f'{key}: &s{i} [x, *s{i}]') - case _: - depth = draw(st.integers(min_value=1, max_value=5)) - nested = draw(identifiers) - for _ in range(depth): - nested = f'{{n: {nested}}}' - fragments.append(f'{key}: {nested}') - return '\n'.join(fragments) + '\n' - - -@pytest.mark.fast -@given(adversarial_yaml()) -# Deterministic pins: Hypothesis is randomised and its failure database does -# not travel to CI, so every counterexample this property has caught (or was -# built to catch) is an @example — same coverage, no separate test functions. -@example('top: &a [*a]\n') # alias cycle -@example('steps: &a\n- id: s\n in:\n x: *a\n') # cycle via steps -@example('wic: &w\n steps: *w\n') # malformed key via alias, not a cycle -@example('wic: &w\n steps:\n (1, a):\n wic: *w\n') # cycle via sidecar -@example('_: !& []\n') # name tag on a collection -@example('_: !foo bar\n') # unknown tag, passthrough -@example('a: !cwl b\n') # an owned tag on passthrough -@example('_: !ii {k: v}\n') # collection literal, single wrap -@example('- !foo a\n') # reading order, a non-mapping root -@example('wic: !foo {}\nsteps:\n- in: {}\n') # reading order, a tag above a structural error -@example('steps:\n- in: {}\n- id: s\n in: !foo {}\n') # reading order, a tag below one -@FAST -def test_parsing_is_total_for_adversarial_structure(text: str) -> None: - """The other half of totality: over real YAML structure — aliases, cycles, - unknown tags, nesting — and not over text alone. - - Never raises; never accepts silently what YAML rejects; never reports the - same problem twice — several parse paths legitimately visit the same node, - and duplicate (code, span, message) reports were a measured regression once - already; and reports in reading order, each at a span, however many passes - produced them. - """ - result = parse(text, 'adversarial.wic') # must not raise - assert result.document is not None or len(result.diagnostics) > 0 - - reports = [(d.severity, d.code, d.message, d.span) for d in result.diagnostics] - assert len(reports) == len(set(reports)), f'duplicate diagnostics: {reports}' - positions = [(d.span.start_line, d.span.start_column) for d in result.diagnostics if d.span] - assert len(positions) == len(reports) and positions == sorted(positions), reports - - if result.ok and result.document is not None: - yaml.load(text, Loader=YamlWithSophiosTagsOpaque) # agreement holds here too - - -@pytest.mark.fast -@given(_tag_pool, st.sampled_from(['scalar', 'flow_map']), st.data()) -@FAST -def test_tag_decisions_agree_across_positions(tag: str, shape: str, data: st.DataObject) -> None: - """Input position and passthrough position make the same unknown-tag call. - - `!foo {wic_anchor: x}` was reported in passthrough but - swallowed in input position — two paths, one language, two answers. This - pins the agreement for every tag and payload shape the generator makes. - """ - # The mapping key is drawn from the construct keys as well as arbitrary - # identifiers. `identifiers` caps at eight characters and every desugared - # key is longer, so without this union the generator could not produce - # `!foo {wic_anchor: x}` — the one payload where the two positions once - # disagreed — and the property was green over a space missing its own - # motivating case. - key = data.draw(st.one_of(identifiers, st.sampled_from(sorted(Key.ALL)))) - payload = data.draw(identifiers) if shape == 'scalar' else f'{{{key}: x}}' - value = f'{tag}{payload}' - - in_position = parse(f'steps:\n- id: s\n in:\n a: {value}\n', 'pos.wic') - passthrough = parse(f'top: {value}\n', 'pos.wic') - - # Only the unknown-tag verdict, which is what this property is about. - # Subtracting the codes that legitimately differ by position instead -- - # `wic024` is one, since a single-key `wic_` mapping is a construct attempt - # where a construct may appear and ordinary CWL where one may not -- makes - # every future position-specific diagnostic another exemption here. - unknown_in = any(d.code is SophiosErrorCode.UNKNOWN_TAG for d in in_position.diagnostics) - unknown_through = any(d.code is SophiosErrorCode.UNKNOWN_TAG for d in passthrough.diagnostics) - assert unknown_in == unknown_through, ( - f'{value!r}: input reported unknown-tag={unknown_in}, ' - f'passthrough={unknown_through}') - - -@pytest.mark.fast -def test_every_code_has_a_registered_provocation() -> None: - """Each declared SophiosErrorCode appears in exactly one tier of the registry. - - Adding a SophiosErrorCode without its attack fails here, in the same commit.""" - registered = set(provocations.PARSE) | set(provocations.COMPILED) - missing = set(SophiosErrorCode) - registered - doubled = set(provocations.PARSE) & set(provocations.COMPILED) - assert not missing, f'codes with no registered provocation: {sorted(map(str, missing))}' - assert not doubled, f'codes registered in both tiers: {sorted(map(str, doubled))}' - - -@pytest.mark.fast -@pytest.mark.parametrize('code', sorted(provocations.PARSE), ids=lambda c: c.name) -def test_parse_provocations_fire(code: SophiosErrorCode) -> None: - """Every parse-tier provocation actually fires its code.""" - result = parse(provocations.PARSE[code], 'provoke.wic') - assert any(d.code is code for d in result.diagnostics), f'{code.name} did not fire' - - -@pytest.mark.skip_pypi_ci -@pytest.mark.parametrize('code', sorted(provocations.COMPILED), ids=lambda c: c.name) -def test_compiled_provocations_fire(code: SophiosErrorCode) -> None: - """Every compiled-tier provocation raises SophiosError carrying its code. - - `SophiosError` is looked up dynamically: it arrives with the diagnostics - branch, and on branches before it the COMPILED tier is empty so this test - has no instances — the lookup keeps the file importable stack-wide. - """ - from sophios.lang import diagnostics as diagnostics_module - sophios_error: type[Exception] = getattr(diagnostics_module, 'SophiosError', AssertionError) - with pytest.raises(sophios_error) as caught: - provocations.COMPILED[code]() - fired = getattr(caught.value, 'diagnostics', ()) - assert any(d.code is code for d in fired), f'{code.name} did not fire' - - -@pytest.mark.fast -@pytest.mark.parametrize('source, expected', [ - ('steps:\n- id: s\n in:\n f: !& e\n', 'e'), - ('steps:\n- id: s\n in:\n f: {wic_anchor: e}\n', 'e'), - ('top: !& x\n', 'x'), - ('steps:\n- id: s\n in:\n f: !& [a]\n', ''), -], ids=['tagged', 'desugared', 'passthrough', 'collection has no name']) -def test_a_misplaced_edge_definition_keeps_the_name_it_was_given( - source: str, expected: str) -> None: - """Recovery preserves the name, in both spellings and every position. - - `_output_binding` states the rule this follows: the AST preserves what it - was given, and a silent drop is the one thing a total parser must never - do. Reporting the construct is not a licence to discard the name it - carried — a caller rendering the recovered AST would otherwise emit `''` - where the source said `e`. A collection genuinely has no name to keep, so - the empty string is honest there rather than invented. - """ - result = parse(source, 'keep.wic') - assert result.document is not None - step = result.document.steps[0] if result.document.steps else None - value = step.inputs[0][1] if step else result.document.passthrough[0][1] - assert isinstance(value, UnresolvedName) - assert value.name == expected - - -@pytest.mark.fast -@pytest.mark.parametrize('payload, expected', [ - ('{wic_anchor: x}', {SophiosErrorCode.UNKNOWN_TAG, SophiosErrorCode.MISPLACED_EDGE_DEF}), - ('{wic_alias: x}', {SophiosErrorCode.UNKNOWN_TAG}), - ('bar', {SophiosErrorCode.UNKNOWN_TAG}), -], ids=['anchor payload', 'alias payload', 'scalar payload']) -def test_an_unknown_tag_and_a_misplaced_anchor_are_both_reported_in_both_positions( - payload: str, expected: set) -> None: - """A node can be two things wrong at once, and both positions must say so. - - `!foo {wic_anchor: x}` is an unknown tag *and* a misplaced edge - definition. `_input_value` used to return on the anchor before reaching - the tag check while `_opaque` checked the tag first, so input position - reported one code and passthrough reported two — the same construct, two - verdicts. The property above cannot be relied on alone to catch this: - until its payload keys were widened it could not spell `wic_anchor`. - """ - in_position = parse(f'steps:\n- id: s\n in:\n a: !foo {payload}\n', 'both.wic') - passthrough = parse(f'top: !foo {payload}\n', 'both.wic') - - assert {d.code for d in in_position.diagnostics} == expected - assert {d.code for d in passthrough.diagnostics} == expected - - -@pytest.mark.fast -def test_a_run_stem_nowhere_is_reported() -> None: - """A `run:` path with no file beside the document and no registry entry is wic013.""" - from .hermetic import compile_hermetic # pylint: disable=import-outside-toplevel - with pytest.raises(SophiosError) as caught: - compile_hermetic({'steps': [{'id': 's', 'run': 'nowhere.cwl'}]}) - assert caught.value.diagnostics[0].code is SophiosErrorCode.SUBWORKFLOW_INVALID - - _MERGE_TARGETS: Final = { 'passthrough': ('a:', 2, '{n}'), 'cwl': ('a: !cwl', 2, '{n}'), 'steps': ('steps:', 2, '{{in: {{x: !ii {n}}}}}'), 'literal': ('steps:\n s:\n in:\n f: !ii', 8, '{n}'), 'in': ('steps:\n s:\n in:', 6, '!ii {n}'), @@ -994,18 +444,67 @@ def test_a_merge_builds_what_yaml_builds(merged: tuple[str, str]) -> None: assert list(built.items()) == list(read.items()), source +def _fires(code: SophiosErrorCode) -> bool: + """Whether the provocation registered for `code` raises a SophiosError carrying it.""" + try: + provocations.COMPILED[code]() + except SophiosError as raised: + return any(found.code is code for found in raised.diagnostics) + return False + + +@pytest.mark.skip_pypi_ci +def test_every_code_is_provoked() -> None: + """Every SophiosErrorCode is provoked, as a code nothing provokes is dead on arrival: a document under + tests/core/data/parse reports it, or else the provocation tests/core/provocations.py registers for it raises it. + So a new code lands with its provocation in the same commit.""" + parsed = {SophiosErrorCode[report[0]] for path in sorted((DATA / 'parse').glob('*/expected.yaml')) + for reports in yaml.safe_load(path.read_text(encoding='utf-8'))['documents'].values() + for report in reports} + assert not parsed & set(provocations.COMPILED), sorted(map(str, parsed & set(provocations.COMPILED))) + unprovoked = [str(code) for code in SophiosErrorCode + if code not in parsed and (code not in provocations.COMPILED or not _fires(code))] + assert not unprovoked, f'codes nothing provokes: {unprovoked}' + + +@pytest.mark.cwl_corpus @pytest.mark.fast -@pytest.mark.parametrize('value', [ - '&x !cwl {q: *x}', - '&x !cwl {<<: {q: *x}}', - '&x !cwl {q: *x, <<: {r: 1}}', - '&x !cwl {q: !cwl {r: *x}}', - '&x {wic_raw_cwl: {q: *x}}', -], ids=['direct', 'through-merge', 'beside-merge', 'nested', 'desugared']) -@pytest.mark.parametrize('where', ['passthrough', 'step-input']) -def test_a_raw_cwl_record_that_contains_itself_is_an_alias_cycle(value: str, where: str) -> None: - """A `!cwl` record reached through its own alias is the cycle every other alias cycle is.""" - source = f'a: {value}\n' if where == 'passthrough' else f'steps:\n s:\n in:\n a: {value}\n' - result = parse(source, 'c.wic') - cycles = [d.message for d in result.diagnostics if d.code is SophiosErrorCode.RECURSIVE_ALIAS] - assert cycles == ['alias cycle: a node contains itself'], [str(d) for d in result.diagnostics] +def test_the_corpus_parses_validates_and_round_trips() -> None: + """Every `.wic` the compiler's own discovery reaches parses without a diagnostic, its JSON projection is a document + the exported schema accepts, and it reads the same once rendered: "the language accepts what exists today" is a + falsifiable claim. Discovery reaching nothing is a failure, not a small corpus: discovery itself broke.""" + assert CORPUS, 'get_yml_paths found no workflows; check search_paths_wic' + failed = [] + for path in CORPUS: + first = parse(path.read_text(encoding='utf-8'), str(path)) + second = parse(render(first.document), str(path)) if first.document is not None else first + if not (first.ok and second.ok and SCHEMA_VALIDATOR.is_valid(to_json(cast(Document, first.document))) + and reading(second.document) == reading(first.document)): + failed.append((str(path), [str(d) for d in (*first.diagnostics, *second.diagnostics)])) + assert not failed, failed + + +@pytest.mark.package +@pytest.mark.fast +def test_reading_writing_and_the_schema_share_no_state() -> None: + """Parsing, rendering and the schema export keep nothing between calls. A parse leaves `yaml.safe_load` blind to + `!ii`, which registering on `yaml.SafeLoader` would teach every later load in the process, in any library. One + source parsed and rendered from many threads at once gives every thread the same answer. And editing an exported + schema three levels down, where a shallow copy once shared its interior, leaves the next export as it was.""" + source = (DATA / 'parse' / 'records' / 'inputs.wic').read_text(encoding='utf-8') + assert parse(source, 'tags.wic').ok + with pytest.raises(yaml.YAMLError): + yaml.safe_load(source) + + def once(_: int) -> tuple[str, int]: + document = parse(source, 'concurrent.wic').document + assert document is not None + return render(document), len(wic_schema()['$defs']) + + with ThreadPoolExecutor(max_workers=8) as pool: + assert len(set(pool.map(once, range(64)))) == 1, 'concurrent parses disagreed' + + edited, pristine = wic_schema(), wic_schema() + edited['$defs']['stepBody']['properties']['in']['additionalProperties']['$ref'] = 'CORRUPTED' + edited['$defs']['outputEntry']['oneOf'][0]['type'] = 'CORRUPTED' + assert wic_schema() == pristine diff --git a/tests/core/test_lang_render.py b/tests/core/test_lang_render.py index 3f03f9e80..f7b5a6027 100644 --- a/tests/core/test_lang_render.py +++ b/tests/core/test_lang_render.py @@ -1,7 +1,6 @@ -"""Properties of the Sophios renderer: it inverts parsing, so a round trip, parse(render(ast)) == ast, proves one of the -two wrong.""" +"""The Sophios renderer inverts parsing: a document reads the same once rendered, rendering settles at once, a value +built in Python gets a spelling that reads back as itself, and a document renders as tests/core/data/render states.""" import math -from pathlib import Path from typing import Any import pytest @@ -9,113 +8,33 @@ from hypothesis import example, given from hypothesis import strategies as st -from sophios.lang import ( - CwlRecord, - Document, - EdgeDef, - EdgeRef, - InlineLiteral, - OutputBinding, - RawCwlRef, - Step, - UnresolvedName, - WicSidecar, - parse, -) +from sophios.lang import Document, InlineLiteral, Step, parse from sophios.lang.render import render from sophios.lang.spans import SourceSpan from .budgets import budget -from .strategies import documents, pinned, scalar_payload_texts - -from .wic_corpus import CORPUS, corpus_id +from .cases import DATA +from .strategies import documents, identifiers, pinned +from .test_lang_parser import reading from .wic_reading import YamlWithSophiosTagsOpaque FAST = budget(200) -#: The spellings whose source text IS the scalar's content — every payload -#: above except the quoted ones, where the quotes belong to the YAML syntax -#: rather than to the scalar: `!ii '0'` is the text 0, which the writer -#: spells from the value, quotes and all. -unquoted_spellings = scalar_payload_texts.filter(lambda text: not text.startswith("'")) - - -# A round-tripped document cannot carry the original spans: rendering produces -# new text, so positions legitimately move. The property is therefore about -# structure, and comparison strips spans rather than pretending they survive. - - -def _shape(node: Any) -> Any: # pylint: disable=too-many-return-statements,too-many-branches - """Reduce an AST to its structure, discarding source positions; one return per node kind, so each kind's fields stay - visible.""" - match node: - case Document(): - return ('doc', - tuple(_shape(s) for s in node.steps), - _shape(node.sidecar) if node.sidecar is not None else None, - tuple((k, _shape(v)) for k, v in node.passthrough)) - case Step(): - return ('step', node.id, - tuple((k, _shape(v)) for k, v in node.inputs), - tuple(_shape(o) for o in node.outputs), - tuple((k, _shape(v)) for k, v in node.interpreted), - tuple((k, _shape(v)) for k, v in node.passthrough)) - case OutputBinding(): - return ('out', node.name, _shape(node.edge_def) if node.edge_def else None) - case WicSidecar(): - return ('wic', - tuple(((k.index, k.name), _shape(v)) for k, v in node.steps), - tuple((k, _shape(v)) for k, v in node.entries)) - case InlineLiteral(): - return ('lit', _shape(node.value)) - case EdgeDef(): - return ('def', node.name) - case EdgeRef(): - return ('ref', node.name) - case RawCwlRef(): - return ('raw', node.expression) - case UnresolvedName(): - return ('name', node.name) - case CwlRecord(): - return ('record', tuple(_shape(source) for source in node.sources), - tuple((k, _shape(v)) for k, v in node.fields)) - case dict(): - return tuple((k, _shape(v)) for k, v in node.items()) - case list(): - return tuple(_shape(v) for v in node) - case float() if math.isnan(node): - # NaN != NaN would fail the comparison exactly when the round - # trip is correct; normalise to a sentinel before comparing. - return 'NaN' - case _: - return node - - -identifiers = st.text('abcdefghijklmnopqrstuvwxyz_', min_size=1, max_size=8) - -# Literals are drawn as YAML source text rather than converted from Python -# values: writing the spelling out keeps the awkward cases visible, and leaves -# the test with no quoting logic of its own to agree with the renderer's. -# Included on purpose: the falsy values a naive `x or ''` would destroy, and -# the characters that force the renderer off plain style. +# Literals are drawn as YAML source text rather than converted from Python values: writing the spelling out keeps +# the awkward cases visible, and leaves the test no quoting logic of its own to agree with the renderer's. Included on +# purpose: the falsy values a naive `x or ''` would destroy, and the characters that force the renderer off plain style. literal_texts = st.sampled_from([ - '0', '1', '-42', '3.5', - 'true', 'false', 'null', - 'plain_word', 'a/path/to.txt', - "''", "'0'", "'false'", - "'hello world'", "'has: colon'", "'#hash'", "'-dash'", "'{brace}'", - "'has ''quote'''", "'trailing '''", + '0', '1', '-42', '3.5', 'true', 'false', 'null', 'plain_word', 'a/path/to.txt', "''", "'0'", "'false'", + "'hello world'", "'has: colon'", "'#hash'", "'-dash'", "'{brace}'", "'has ''quote'''", "'trailing '''", ]) @st.composite def awkward_literal_documents(draw: st.DrawFn) -> str: - """Documents whose `!ii` payloads are the renderer's hard cases, to hammer quoting; the structural round trip uses - the parser suite's `documents()`, as a second narrower one once made outputs and nested sidecars invisible to it.""" + """Documents whose `!ii` payloads are the renderer's hard cases, to hammer quoting.""" lines = ['steps:'] for _ in range(draw(st.integers(min_value=1, max_value=3))): - lines.append(f'- id: {draw(identifiers)}') - lines.append(' in:') + lines += [f'- id: {draw(identifiers)}', ' in:'] for name in draw(st.lists(identifiers, min_size=1, max_size=3, unique=True)): lines.append(f' {name}: !ii {draw(literal_texts)}') return '\n'.join(lines) + '\n' @@ -123,89 +42,29 @@ def awkward_literal_documents(draw: st.DrawFn) -> str: @pytest.mark.fast @given(st.one_of(documents(), awkward_literal_documents())) -# Counterexamples, pinned deterministically (Hypothesis's -# failure database does not travel to CI). Duplicate-key cases are absent -# because they are parse errors now, pinned on the parser's provocations. -@example('steps:\n- id: t\n in:\n f: !ii {a: !* e}\n') # construct inside collection literal -@example('steps:\n- id: t\nmeta: !ii {a: 1}\n') # collection literal in passthrough -@example("steps:\n- id: t\n in:\n f: {wic_inline_input: '0'}\n") # string that spells an int -@example("steps:\n- id: t\n in:\n f: {wic_inline_input: 'true'}\n") # string that spells a bool -@example('steps:\n- id: t\n in:\n f: !ii 1.0e+300\n') # exponent float -@example('steps:\n- id: t\n in:\n f: !ii .inf\n') # YAML float special -@example('steps:\n- id: t\n in:\n f: !ii .nan\n') # NaN, comparator-normalised -@example('steps:\n- id: t\n in:\n f: !cwl {source: [!* a, b], linkMerge: merge_flattened, default: [1]}\n') +# Hypothesis's failure database does not travel to CI, so what it once found is pinned. +@example('') # nothing at all +@example('steps:\n- id: t\n in:\n f: !ii {a: !* e}\n') # a construct inside a collection literal +@example("steps:\n- id: t\n in:\n f: {wic_inline_input: '0'}\n") # text that spells a number +@example('steps:\n- id: t\n in:\n f: !ii .nan\n') # NaN, which equals nothing @example('steps:\n- id: t\n in:\n f: !cwl {source: [a], linkMerge: merge_nested}\n') # one source, still a list -@example('steps:\n- id: t\n in:\n f: {wic_raw_cwl: {source: {wic_alias: a}, valueFrom: $(self)}}\n') -@example('wic:\n steps:\n (1, o):\n wic:\n namespace: dna\n') # nested wrapper -@example('wic:\n steps:\n (1, o):\n wic: {}\n') # empty child sidecar: {} not null @FAST -def test_round_trip_preserves_structure(source: str) -> None: - """Parsing a rendered document reproduces the document. - - Quantified over the shared full-language generator (both step forms, - both spellings, outputs, nested sidecars) plus the quoting-hostile - literals — and the rendered text must also be YAML that `yaml.SafeLoader` - loads with the Sophios tags opaque, since a renderer that emits what YAML - rejects would be writing a dialect — a differential oracle, not - self-consistency. - """ +def test_a_rendered_document_reads_the_same_and_renders_the_same(source: str) -> None: + """Parsing a rendered document reproduces the document, and rendering it again reproduces the text: a formatter + that never settled would churn every file it touched. The rendered text is also YAML that `yaml.SafeLoader` loads + with the Sophios tags opaque, since a renderer writing what YAML rejects would be writing a dialect.""" first = parse(source, 'a.wic') assert first.ok and first.document is not None - rendered = render(first.document) second = parse(rendered, 'b.wic') - assert second.ok, [str(d) for d in second.diagnostics] - assert second.document is not None - - assert _shape(second.document) == _shape(first.document) - if rendered: - yaml.load(rendered, Loader=YamlWithSophiosTagsOpaque) # YAML agrees too - - -@pytest.mark.fast -@given(st.one_of(documents(), awkward_literal_documents())) -@FAST -def test_rendering_is_idempotent(source: str) -> None: - """Rendering a round-tripped document produces identical text. - - Round-trip stability matters more than matching the original byte for byte: - a formatter that never settles would churn every file it touched. - """ - document = parse(source, 'a.wic').document - assert document is not None - - once = render(document) - reparsed = parse(once, 'b.wic').document - assert reparsed is not None - assert once == render(reparsed) - - -@pytest.mark.cwl_corpus -@pytest.mark.fast -@pytest.mark.parametrize('path', CORPUS, ids=corpus_id) -def test_corpus_round_trips(path: Path) -> None: - """Every corpus file survives a render/parse cycle unchanged in structure.""" - source = path.read_text(encoding='utf-8') - first = parse(source, str(path)) - assert first.ok and first.document is not None - - second = parse(render(first.document), str(path)) - assert second.ok, [str(d) for d in second.diagnostics] - assert _shape(second.document) == _shape(first.document) - - -@pytest.mark.fast -def test_render_emits_the_tagged_spelling() -> None: - """Output uses the spelling the .wic reference tells people to write.""" - document = parse('steps:\n- id: s\n in:\n f:\n wic_inline_input: x\n', 'a.wic').document - assert document is not None - text = render(document) - assert '!ii' in text - assert 'wic_inline_input' not in text + assert second.ok and second.document is not None, [str(d) for d in second.diagnostics] + assert reading(second.document) == reading(first.document) + assert render(second.document) == rendered + yaml.load(rendered, Loader=YamlWithSophiosTagsOpaque) #: A value the renderer must spell as an `!ii` payload, as the Python API hands it over: no source text behind it. -#: A parsed literal remembers how it was written and is transcribed verbatim, so the round-trip properties never reach +#: A parsed literal remembers how it was written and is transcribed verbatim, so the round trip above never reaches #: the code that has to *choose* a spelling. synthesized = st.recursive(st.none() | st.booleans() | st.integers() | st.floats() | st.text(), lambda inner: st.lists(inner, max_size=3) | st.dictionaries(st.text(), inner, max_size=3), @@ -233,66 +92,17 @@ def test_a_synthesized_literal_gets_a_spelling_that_survives(value: Any) -> None @pytest.mark.fast -def test_empty_document_renders_empty() -> None: - """A document carrying nothing renders to nothing, and reparses.""" - document = parse('', 'e.wic').document - assert document is not None - assert render(document) == '' - assert parse(render(document), 'e.wic').ok - - -@pytest.mark.fast -def test_nested_sidecar_wrapper_survives_rendering() -> None: - """The renderer re-wraps what the parser unwraps — asymmetry test. - - The round-trip property is structurally blind here: the parser tolerates - the missing wrapper - in the renderer's own output, so the round-trip holds even when rendering - is a semantic edit. Every downstream consumer reads through the wrapper - explicitly, which is why its loss changes what a workflow means. - """ - source = 'wic:\n steps:\n (1, o):\n wic:\n namespace: dna\n' - document = parse(source, 'x.wic').document - assert document is not None - rendered = render(document) - assert rendered == source # byte-exact, wrapper included - - -@pytest.mark.fast -def test_empty_sidecar_renders_as_mapping_not_null() -> None: - """`{}` — a present-None sails past every `.get(key, {})` downstream.""" - document = parse('wic:\n steps:\n (1, o):\n wic: {}\n', 'x.wic').document - assert document is not None - rendered = render(document) - assert 'null' not in rendered and '~' not in rendered - - -@pytest.mark.fast -@given(unquoted_spellings) -@FAST -@example('0777') # octal: value 511 knows nothing of how it was spelled -@example('1.50') # trailing zero -@example('yes') # YAML 1.1 boolean -@example('0x1f') # hexadecimal -@example('1:30') # sexagesimal -def test_a_tagged_literal_keeps_its_source_spelling(spelling: str) -> None: - """`!ii ` renders back as `!ii `, character for - character. - - This is the renderer's founding claim — transcription, not - reconstruction — and the only claim that distinguishes the two. The - round-trip property cannot: it compares parsed values, and every spelling - here parses to a value that re-serialises to *some* valid spelling, just - not the one the author wrote. So when the parser silently stopped - recording the source text, every property stayed green while `!ii 0777` - began compiling as `!ii 511`. - """ - source = f'steps:\n- id: s\n in:\n f: !ii {spelling}\n' - result = parse(source, 'transcribe.wic') - assert result.ok, [str(d) for d in result.diagnostics] - assert result.document is not None - - payload = render(result.document).split('!ii ', 1)[1].rstrip('\n') - # Exactly, quotes included: a plain spelling must come back plain, since - # `!ii '1:30'` is the text 1:30 where `!ii 1:30` is the number 90. - assert payload == spelling, f'{spelling!r} came back as {payload!r}' +def test_a_document_renders_as_stated() -> None: + """tests/core/data/render/written.wic, in every spelling, renders as rendered.wic, byte for byte: each construct + in the tagged spelling the .wic reference tells people to write; each literal transcribed as it was spelled, since + `!ii 0777` is 511 and `!ii '1:30'` text where `!ii 1:30` is the number 90; each step's `wic:` block in the wrapper + it was read through, which the parser tolerates the loss of, so no round trip sees it go; and an empty one as `{}`, + since a null sails past every `.get(key, {})` downstream. rendered.wic reads as written.wic and renders as itself; + and nothing renders as nothing.""" + rendered = (DATA / 'render' / 'rendered.wic').read_text(encoding='utf-8') + written, again = (parse((DATA / 'render' / name).read_text(encoding='utf-8'), name).document + for name in ('written.wic', 'rendered.wic')) + assert written is not None and again is not None + assert render(written) == rendered and render(again) == rendered and reading(again) == reading(written) + nothing = parse('', 'empty.wic').document + assert nothing is not None and render(nothing) == '' diff --git a/tests/core/test_lang_schema.py b/tests/core/test_lang_schema.py index 928ac69fb..6875bec87 100644 --- a/tests/core/test_lang_schema.py +++ b/tests/core/test_lang_schema.py @@ -1,179 +1,60 @@ -"""The exported JSON Schema accepts what the AST accepts: exactly on the shapes the parser diagnoses, one way -elsewhere, since JSON has no tags and passthrough CWL cannot be closed (language spec §1).""" +"""The exported JSON Schema and the parser are two readers of one declaration: the schema refuses a document exactly +when the parser reports its shape or its CWL version, and `sophios --generate_schemas` writes it and nothing else.""" import json -from dataclasses import fields from pathlib import Path from typing import Any, Final import jsonschema import pytest import yaml +from cwltool.update import ALLUPDATES, UPDATES from hypothesis import example, given +from hypothesis import strategies as st -from sophios.lang import SophiosErrorCode, Forms, Grammar, parse, to_json, wic_schema -from sophios.lang.nodes import Shape, Step, WicSidecar, surface_of +from sophios.lang import SophiosErrorCode, parse, to_json, wic_schema from .budgets import budget -from .cases import cases -from .strategies import WIC_VALUES, documents, pinned, shapes -from .test_lang_parser import PARSE_KEYS -from .wic_corpus import CORPUS, corpus_id +from .cases import DATA +from .strategies import pinned, shapes -FAST = budget(200) +VALIDATOR: Final = jsonschema.Draft202012Validator(wic_schema()) -SCHEMA = wic_schema() -VALIDATOR = jsonschema.Draft202012Validator(SCHEMA) - - -def _accepts(data: Any) -> bool: - """Whether the exported schema accepts this document.""" - return VALIDATOR.is_valid(data) - - -@pytest.mark.fast -def test_schema_is_itself_valid() -> None: - """The exported schema is a legal JSON Schema of the dialect it claims.""" - jsonschema.Draft202012Validator.check_schema(SCHEMA) - - -@pytest.mark.fast -def test_schema_is_derived_from_the_parser() -> None: - """Every construct and interpreted key comes from the parser's own tables. - - This is the acceptance criterion "derived from the AST, never - hand-maintained": adding a construct to the parser must move the schema - without anyone remembering to edit it. - """ - construct = SCHEMA['$defs']['construct'] - assert set(construct['properties']) == set(Forms.DESUGARED_KEYS) - - step_keys = set(SCHEMA['$defs']['stepBody']['properties']) - assert Grammar.INTERPRETED_STEP_KEYS <= step_keys - - steps = SCHEMA['$defs']['wicBlock']['properties']['steps'] - assert set(steps['patternProperties']) == {Grammar.WIC_STEP_KEY_PATTERN, Grammar.WIC_STEP_ID_PATTERN} - - -@pytest.mark.fast -def test_generate_schemas_writes_the_ast_schema_and_nothing_else( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """`sophios --generate_schemas` writes `wic_schema()`, and compiles nothing. - - The schema it replaced compiled each discovered workflow and read the - compiled inputs back, so a subworkflow with an unbound inner input - advertised the compiler's generated name for it as something a caller may - bind. A caller may name only what the callee declares (wic032). The - control shows such a name exists; the file written must not carry it, or - any other, and discovery and compilation are forbidden while it is written. - """ - import sophios.compiler # pylint: disable=import-outside-toplevel - import sophios.main # pylint: disable=import-outside-toplevel - import sophios.plugins # pylint: disable=import-outside-toplevel - - from .hermetic import compile_hermetic, subworkflow_step # pylint: disable=import-outside-toplevel - - compiled = compile_hermetic({'steps': [subworkflow_step('child.wic', {'steps': [{'id': 'mk_file'}]})]}) - generated = 'mk_file~name' - assert any(generated in child.cwl['inputs'] for child in compiled.artifact.children) - - def forbidden(*_args: Any, **_kwargs: Any) -> None: - raise AssertionError('--generate_schemas reached discovery or compilation') - - for module, name in [(sophios.compiler, 'compile_source'), (sophios.plugins, 'get_tools_cwl'), - (sophios.plugins, 'get_yml_paths'), (sophios.main.io, 'get_config')]: - monkeypatch.setattr(module, name, forbidden) - monkeypatch.chdir(tmp_path) - monkeypatch.setattr('sys.argv', ['sophios', '--generate_schemas', '--homedir', str(tmp_path)]) - with pytest.raises(SystemExit) as caught: - sophios.main._main(*sophios.cli.parser.parse_known_args()) # pylint: disable=protected-access - assert caught.value.code == 0 - - written = (tmp_path / 'autogenerated' / 'schemas' / 'wic.json').read_text(encoding='utf-8') - assert json.loads(written) == wic_schema() - assert '__step__' not in written - - -@pytest.mark.fast -@given(documents()) -@FAST -def test_accepts_every_document_the_parser_accepts(source: str) -> None: - """A parsed document's JSON projection validates — and IS JSON. - - Both halves matter, and only together are they the claim: `jsonschema` - is duck-typed and will happily "validate" live Python objects that - `json.dumps` refuses, which is precisely how a broken `to_json` stayed - green under this property. - """ - result = parse(source, 'gen.wic') - assert result.document is not None - projection = to_json(result.document) - json.dumps(projection) # serialisability is the claim, not an assumption - assert _accepts(projection), list(VALIDATOR.iter_errors(projection)) - - -@pytest.mark.cwl_corpus -@pytest.mark.fast -@pytest.mark.parametrize('path', CORPUS, ids=corpus_id) -def test_accepts_the_whole_corpus(path: Path) -> None: - """Every real `.wic` in the repository validates against the schema.""" - result = parse(path.read_text(encoding='utf-8'), str(path)) - assert result.document is not None - data = to_json(result.document) - assert _accepts(data), list(VALIDATOR.iter_errors(data)) - - -#: What the parser reports about a document's shape, as distinct from what it says about names, tags and edges. +#: What the parser reports about a document's shape and its CWL version, as distinct from what it says about names, +#: tags and edges, which JSON cannot spell. _SHAPE_CODES: Final = frozenset({ SophiosErrorCode.EXPECTED_MAPPING, SophiosErrorCode.EXPECTED_SEQUENCE, SophiosErrorCode.EXPECTED_SCALAR, SophiosErrorCode.MISSING_STEP_ID, SophiosErrorCode.EMPTY_STEP_ID, SophiosErrorCode.MALFORMED_WIC_STEP_KEY, - SophiosErrorCode.UNKNOWN_WIC_KEY, SophiosErrorCode.MALFORMED_WIC_VALUE}) + SophiosErrorCode.UNKNOWN_WIC_KEY, SophiosErrorCode.MALFORMED_WIC_VALUE, SophiosErrorCode.UNSUPPORTED_CWL_VERSION}) -#: Shapes the parser reports, each with what the language says there. -REFUSED: Final = { - 'steps must be a mapping or sequence': {'steps': 'nope'}, - 'step body must be a mapping or null': {'steps': {'s': 3}}, - 'in must be a mapping': {'steps': {'s': {'in': 3}}}, - 'out must be a sequence': {'steps': {'s': {'out': 3}}}, - 'an out: entry is a name or a single-key mapping': {'steps': {'s': {'out': [['s']]}}}, - 'wic must be a mapping': {'wic': 3}, - 'wic steps must be a mapping': {'wic': {'steps': 3}}, - 'wic step keys have the form (index, name) or are a step id': {'wic': {'steps': {'not a key': {'x': 1}}}}, - 'a sequence step carries its name in an id: key': {'steps': [{'touch': {'in': {'f': 'x'}}}]}, - 'a sequence step with a null body still needs an id:': {'steps': [{'touch': None}]}, - 'a sequence entry keyed by a step key is not an identity': {'steps': [{'in': {'value': 'something'}}]}, - 'an empty step id is wic007': {'steps': [{'id': ''}]}, - **{f'{key} is not a top-level wic: key': {'wic': {key: yaml.safe_load(value)}} - for key, value in WIC_VALUES.items() if key not in Grammar.SIDECAR_KEYS}, -} +#: A `cwlVersion` value: each version CWL ever named, drafts and snapshots among them, and anything else. +_VERSIONS = st.one_of(st.sampled_from(sorted(ALLUPDATES)), st.text('v1.023-dev ', max_size=8), st.floats(0, 2), + st.none(), st.lists(st.just('v1.2'), max_size=1)) -#: Shapes the language admits, each with why. -ADMITTED: Final = { - 'a step may have no body (.wic reference §2.1)': {'steps': {'sub.wic': None}}, - 'nor a wic: block': {'wic': None}, - 'unknown keys are passthrough CWL, not errors (language spec §1)': { - '$namespaces': {'edam': 'http://edamontology.org/'}, - 'steps': {'s': {'in': {'f': 'name'}, 'hints': [{'class': 'X'}]}}}, - **{f'{key} is an input value': {'steps': {'s': {'in': {'f': {key: 'x'}}}}} for key in sorted(Forms.DESUGARED_KEYS)}, - # Both Step.id and OutputBinding.name are IDENTITY-shaped: a non-empty constraint written onto the shape made the - # schema stricter than the language for outputs, invisible while the generator's names were all non-empty. - "out: [''] parses without a diagnostic": {'steps': [{'id': 's', 'out': ['']}]}, - # The parser's reading of `(1, a): {wic: , in: ...}`: wicStepBlock admits null, so both take the siblings alone. - 'an empty sidecar wrapper beside siblings': {'wic': {'steps': {'(1, a)': {'wic': None, 'in': {'x': 1}}}}, - 'steps': [{'id': 'a'}]}, - **{f'{key} is a wic: steps: key': {'wic': {'steps': {'(1, s)': {key: yaml.safe_load(value)}}}} - for key, value in WIC_VALUES.items()}, - **{f'{key} is a top-level wic: key': {'wic': {key: yaml.safe_load(value)}} - for key, value in WIC_VALUES.items() if key in Grammar.SIDECAR_KEYS}, -} -#: Each row's outcome, by the JSON text of its document: `True` and `1` are equal in Python, not as the parser reads. -_ACCEPTS: Final = {json.dumps(document): accepted for accepted, table in ((False, REFUSED), (True, ADMITTED)) - for document in table.values()} + +#: Shapes the parser reports, each alone, as a drawn document seldom holds one fault without another. +_ALONE: Final = ( + {'steps': 'nope'}, {'steps': {'s': 3}}, {'steps': {'s': {'in': 3}}}, {'steps': {'s': {'out': 3}}}, + {'steps': {'s': {'out': [['s']]}}}, {'wic': 3}, {'wic': {'steps': 3}}, {'wic': {'steps': {'not a key': {'x': 1}}}}, + {'wic': {'scatter': ['x']}}, {'steps': [{'touch': {'in': {'f': 'x'}}}]}, {'steps': [{'touch': None}]}, + {'steps': [{'in': {'value': 'something'}}]}, {'steps': [{'id': ''}]}) + + +def _tag_free(path: Path) -> Any: + """The mapping the document at `path` is, as YAML loads it, where it holds no tag and no alias; else None.""" + text = path.read_text(encoding='utf-8') + try: + loaded = None if '!' in text or '&' in text else yaml.safe_load(text) + except yaml.YAMLError: + return None + return loaded if isinstance(loaded, dict) else None @pytest.mark.fast -@given(shapes()) -@pinned(*REFUSED.values(), *ADMITTED.values(), - *(yaml.safe_load(case.values[0]['source']) for case in cases('parse/wic_values.yaml', *PARSE_KEYS))) +@given(st.builds(lambda shape, version: {**shape, **version}, shapes(), + st.fixed_dictionaries({}, optional={'cwlVersion': _VERSIONS}))) +@pinned(*_ALONE, *filter(None, map(_tag_free, sorted((DATA / 'parse').glob('*/*.wic')))), + *({'cwlVersion': version} for version in ['draft-2', 'draft-3', 'v1.0.dev4', 'v1.2.0-dev5', 'v1.3', '', + *sorted(UPDATES)])) @example({'steps': [{'id': 1}]}).xfail(raises=AssertionError, reason="the parser reads the id as the name '1', the " 'schema wants a string') @example({'steps': {'s': {'out': [{'f': 'x'}]}}}).xfail(raises=AssertionError, reason='wic005: an out: entry binds ' @@ -183,92 +64,46 @@ def test_accepts_the_whole_corpus(path: Path) -> None: @example({'steps': {'s': {'in': {'f': {'wic_alias': ['x']}}}}}).xfail(raises=AssertionError, reason='wic005: the ' 'schema leaves a construct open') @budget(100) -def test_the_schema_refuses_exactly_the_shapes_the_parser_reports(document: dict[str, Any]) -> None: - """Two readers of one declaration, over tag-free documents, where loading one is its projection: the schema - refuses a document, as an editor loads it, exactly when the parser reports its shape, and a row as its table - says. And what the parser accepts projects to JSON the schema accepts, as for `documents()` above.""" +def test_the_schema_refuses_exactly_what_the_parser_reports(document: dict[str, Any]) -> None: + """Over tag-free documents, where loading one is its projection: the schema refuses a document, as an editor loads + it, exactly when the parser reports its shape or its CWL version; the parser reports a `cwlVersion` exactly when + cwltool cannot run it without `--enable-dev`, where it is written rather than later inside the runner; and what the + parser accepts projects to JSON the schema accepts.""" result = parse(json.dumps(document), 'shape.wic') reported = [str(d) for d in result.diagnostics if d.code in _SHAPE_CODES] - assert _accepts(document) == (not reported), ([str(d) for d in result.diagnostics], - list(VALIDATOR.iter_errors(document))) - assert _ACCEPTS.get(json.dumps(document), not reported) == (not reported) + assert VALIDATOR.is_valid(document) == (not reported), ([str(d) for d in result.diagnostics], + list(VALIDATOR.iter_errors(document))) + if 'cwlVersion' in document: + assert ((SophiosErrorCode.UNSUPPORTED_CWL_VERSION in {d.code for d in result.diagnostics}) + == (document['cwlVersion'] not in tuple(UPDATES))) if result.ok and result.document is not None: - projection = to_json(result.document) - json.dumps(projection) - assert _accepts(projection), list(VALIDATOR.iter_errors(projection)) - - -@pytest.mark.fast -def test_the_wic_block_is_closed_and_complete_for_editors() -> None: - """Each `wic:` form offers exactly the keys the parser admits there, and - no other, so an editor completes them and flags the rest (.wic reference §7).""" - forms = {'wicBlock': Grammar.SIDECAR_KEYS, 'wicStepBlock': Grammar.SIDECAR_STEP_KEYS, - 'wicStepEntry': Grammar.SIDECAR_STEP_KEYS | {'wic'}} - for form, keys in forms.items(): - assert set(SCHEMA['$defs'][form]['properties']) == keys, form - assert SCHEMA['$defs'][form]['additionalProperties'] is False, form - - -# The schema is generated from the `Surface` declarations in `nodes.py`. These -# check that the generation is total — that no field can be added, and no key -# invented, without one of these failing. - - -@pytest.mark.fast -def test_schema_keys_come_only_from_the_ast() -> None: - """Every key the schema describes traces back to a declared field. - - The schema is not allowed to invent syntax. `id` is expected on the - sequence form and absent from the mapping form, where the step's name is - the mapping key rather than a key inside it. - """ - declared = {surface_of(Step, f.name).key for f in fields(Step)} - {None} - declared |= set(Grammar.INTERPRETED_STEP_KEYS) - - for form in ('sequenceStep', 'stepBody'): - keys = set(SCHEMA['$defs'][form]['properties']) - assert keys <= declared, f'{form} invented {keys - declared}' - - assert 'id' in SCHEMA['$defs']['sequenceStep']['properties'] - assert 'id' not in SCHEMA['$defs']['stepBody']['properties'] + projection = json.loads(json.dumps(to_json(result.document))) + assert VALIDATOR.is_valid(projection), list(VALIDATOR.iter_errors(projection)) @pytest.mark.fast -@pytest.mark.parametrize('node_type,form', [(Step, 'sequenceStep'), (WicSidecar, 'wicBlock')], - ids=['Step', 'WicSidecar']) -def test_every_keyed_field_reaches_the_schema(node_type: type, form: str) -> None: - """A field that occupies a surface key is described by the schema.""" - properties = SCHEMA['$defs'][form]['properties'] - for declared in fields(node_type): - shape = surface_of(node_type, declared.name) - if shape.key is not None and shape.shape is not Shape.INTERNAL: - assert shape.key in properties, f'{node_type.__name__}.{declared.name} is not in the schema' - - -@pytest.mark.fast -def test_passthrough_declarations_open_their_objects() -> None: - """A node declaring PASSTHROUGH produces an open object, and one without - it does not. Openness is the AST's statement, not the generator's.""" - assert any(surface_of(Step, f.name).shape is Shape.PASSTHROUGH for f in fields(Step)) - assert SCHEMA['$defs']['sequenceStep']['additionalProperties'] is True - assert SCHEMA['$defs']['construct']['additionalProperties'] is False - +def test_generate_schemas_writes_the_schema_and_compiles_nothing(monkeypatch: pytest.MonkeyPatch, + tmp_path: Path) -> None: + """`sophios --generate_schemas` writes `wic_schema()`, a legal JSON Schema of the dialect it claims, and compiles + nothing. The schema it replaced compiled each discovered workflow and read the compiled inputs back, so a + subworkflow with an unbound inner input advertised the compiler's generated name for it (`mk_file~name`, `__step__`) + as something a caller may bind, where a caller may name only what the callee declares (wic032).""" + import sophios.compiler # pylint: disable=import-outside-toplevel + import sophios.main # pylint: disable=import-outside-toplevel + import sophios.plugins # pylint: disable=import-outside-toplevel -@pytest.mark.fast -def test_editing_an_export_cannot_affect_a_later_one() -> None: - """Freshness is deep, not one level down. + def forbidden(*_args: Any, **_kwargs: Any) -> None: + raise AssertionError('--generate_schemas reached discovery or compilation') - The generator builds from shared fragments, and those fragments are - nested; a shallow copy of one hands out its interior. Reaching three - levels into an export and writing there must not change what the next - call produces — that is the whole of what "returned fresh each call" - claims, and it is checked at the depth where the claim used to fail. - """ - first = wic_schema() - first['$defs']['stepBody']['properties']['in']['additionalProperties']['$ref'] = 'CORRUPTED' - first['$defs']['outputEntry']['oneOf'][0]['type'] = 'CORRUPTED' + for module, name in [(sophios.compiler, 'compile_source'), (sophios.plugins, 'get_tools_cwl'), + (sophios.plugins, 'get_yml_paths'), (sophios.main.io, 'get_config')]: + monkeypatch.setattr(module, name, forbidden) + monkeypatch.chdir(tmp_path) + monkeypatch.setattr('sys.argv', ['sophios', '--generate_schemas', '--homedir', str(tmp_path)]) + with pytest.raises(SystemExit) as caught: + sophios.main._main(*sophios.cli.parser.parse_known_args()) # pylint: disable=protected-access + assert caught.value.code == 0 - second = wic_schema() - assert second['$defs']['stepBody']['properties']['in']['additionalProperties']['$ref'] \ - == '#/$defs/inputValue' - assert second['$defs']['outputEntry']['oneOf'][0]['type'] == 'string' + written = json.loads((tmp_path / 'autogenerated' / 'schemas' / 'wic.json').read_text(encoding='utf-8')) + jsonschema.Draft202012Validator.check_schema(written) + assert written == wic_schema() diff --git a/tests/core/test_lang_version.py b/tests/core/test_lang_version.py index a5bdf7580..28811f50b 100644 --- a/tests/core/test_lang_version.py +++ b/tests/core/test_lang_version.py @@ -1,5 +1,5 @@ -"""Language-version resolution over fabricated histories (spec §6): the highest satisfying version, an explicit setting -beating a file tag, one version per compile, reported on success and absent from the compiled CWL.""" +"""Language-version resolution (spec §6) over fabricated histories: the highest satisfying version, an explicit setting +beating a file tag, one version per compile; and through the compiler, reported on success and absent from the CWL.""" import sys from pathlib import Path import pytest @@ -7,16 +7,14 @@ from hypothesis import example, given from hypothesis import strategies as st -from sophios.ir.frontdoor import bundle_from_disk from sophios.lang import KNOWN_VERSIONS, LANG_VERSION, resolve_lang_version from sophios.lang.diagnostics import SophiosError from sophios.lang.error_codes import SophiosErrorCode import sophios.cli import sophios.main -from sophios.wic_types import Yaml -from .compile_harness import FAST, TOUCH, compile_cwl, compile_info -from .hermetic import subworkflow_step +from .cases import DATA +from .compile_harness import FAST from .test_setup import load_test_registry #: The key earlier Sophios versions annotated compiled CWL with. @@ -29,11 +27,6 @@ ).map(lambda vs: tuple(sorted(vs, key=lambda v: int(v.rsplit('.', 1)[1])))) -def _compile(yml: Yaml, lang_version: str | None = None) -> Yaml: - """Compile one in-memory workflow and return the emitted CWL.""" - return compile_cwl(yml, 'lang_version', lang_version=lang_version) - - @pytest.mark.fast @given(histories.flatmap(lambda known: st.tuples( st.just(known), st.none() | st.sampled_from(known) | st.just('9.9.9'), @@ -65,138 +58,38 @@ def test_resolution_follows_the_rule_the_spec_states(case: tuple[tuple[str, ...] @pytest.mark.skip_pypi_ci @pytest.mark.fast -def test_conflicting_pins_across_a_tree_are_caught_at_the_root() -> None: - """The same, through the compiler: a subworkflow pin that disagrees with the root's is a - conflict at compile time — every reachable document's pin is collected.""" - tree: Yaml = { - 'wic': {'lang_version': '0.0.1'}, - 'steps': [subworkflow_step('child.wic', {'wic': {'lang_version': '9.9.9'}, **TOUCH})], - } - with pytest.raises(SophiosError) as caught: - _compile(tree) - assert caught.value.diagnostics[0].code is SophiosErrorCode.UNKNOWN_LANG_VERSION - - -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -def test_an_inline_implementation_body_pin_is_collected() -> None: - """A pin that lives only on the selected implementation body still decides the version.""" - body = {'wic': {'lang_version': '9.9.9'}, **TOUCH} - tree: Yaml = { - 'wic': {'default_implementation': 'fast', 'implementations': {'fast': body}}, - 'steps': [], - } - with pytest.raises(SophiosError) as caught: - _compile(tree) - assert caught.value.diagnostics[0].code is SophiosErrorCode.UNKNOWN_LANG_VERSION - - -# The resolved version is never a secret: every compile reports -# it (CLI, Python API), and the compiled CWL stays plain CWL - - -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -def test_every_compile_reports_its_version() -> None: - """The result names the resolved version, untagged, tagged and explicitly - pinned alike, and the CWL it carries has no annotation of its own.""" - tagged = {'wic': {'lang_version': '0.0.1'}, **TOUCH} - for yml, explicit, expected in ((TOUCH, None, LANG_VERSION), (tagged, None, '0.0.1'), (TOUCH, '0.0.1', '0.0.1')): - result = compile_info(yml, 'lang_version', lang_version=explicit) - assert result.lang_version == expected - assert ANNOTATION_KEY not in result.artifact.cwl - assert 'sophios' not in result.artifact.cwl.get('$namespaces', {}) - - -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -def test_the_python_api_surfaces_the_version() -> None: - """`CompiledWorkflow.lang_version` names the version, no digging.""" - from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl - from sophios.api.python.workflow import Step, Workflow - - emit = (CommandLineTool('emit_text', - Inputs(message=Input(cwl.string, position=1)), - Outputs(file=Output(cwl.file, glob='stdout.txt'))) - .base_command('echo') - .stdout('stdout.txt')) - step = Step(emit) - step.inputs.message = 'hello' - compiled = Workflow([step], 'p18_version').compile() - assert compiled.lang_version == LANG_VERSION - assert ANNOTATION_KEY not in compiled.cwl_workflow - - -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -def test_a_pinned_file_reports_its_version_and_writes_plain_cwl( +def test_a_compile_resolves_its_version_reports_it_and_writes_none( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: - """A `wic: lang_version:` pin still compiles and the command line prints the - version; a Python workflow, which pins per compile, names it in - `CompiledWorkflow.lang_version`; neither CWL carries a `sophios` key or prefix.""" - from sophios.api.python.workflow import Workflow # pylint: disable=import-outside-toplevel - - source = tmp_path / 'pinned.wic' - source.write_text(f'wic:\n lang_version: {LANG_VERSION}\n' - 'steps:\n- id: touch\n in:\n filename: !ii empty.txt\n', encoding='utf-8') + """The rule through the compiler, each document of tests/core/data/lang_version through the command line. Every + reachable pin counts: one on a called workflow, one on the implementation body selected, and a pin YAML reads as a + number, never ignored; so 9.9.9 or 1.0, which no version is, is wic017, as are `--lang_version 9.9.9`, the flag + reaching the compiler past every pin, and `compile(lang_version='9.9.9')`. A compile that succeeds names its + version, on the command line and as `CompiledWorkflow.lang_version`, and the CWL it writes, through either door, + has no `sophios` key or prefix.""" monkeypatch.chdir(tmp_path) - monkeypatch.setattr(sys, 'argv', ['sophios', '--yaml', str(source), '--generate_cwl_workflow']) - sophios.main._main(*sophios.cli.parser.parse_known_args()) # pylint: disable=protected-access - assert f'Sophios lang_version: {LANG_VERSION}' in capsys.readouterr().out + + def compile_file(name: str, *flags: str) -> None: + monkeypatch.setattr(sys, 'argv', ['sophios', '--yaml', str(DATA / 'lang_version' / name), + '--generate_cwl_workflow', *flags]) + sophios.main._main(*sophios.cli.parser.parse_known_args()) # pylint: disable=protected-access + + for name, flags, unknown in [('calls_a_pin.wic', (), '9.9.9'), ('implementation_pins.wic', (), '9.9.9'), + ('mistyped.wic', (), '1.0'), ('unpinned.wic', ('--lang_version', '9.9.9'), '9.9.9')]: + with pytest.raises(SophiosError) as caught: + compile_file(name, *flags) + first = caught.value.diagnostics[0] + assert first.code is SophiosErrorCode.UNKNOWN_LANG_VERSION and f"'{unknown}'" in first.message, name + compile_file('pinned.wic') + assert 'Sophios lang_version: 0.0.1' in capsys.readouterr().out written = yaml.safe_load((tmp_path / 'autogenerated' / 'pinned.cwl').read_text(encoding='utf-8')) assert ANNOTATION_KEY not in written and 'sophios' not in written.get('$namespaces', {}) - unpinned = tmp_path / 'unpinned.wic' - unpinned.write_text('steps:\n- id: touch\n in:\n filename: !ii empty.txt\n', encoding='utf-8') + from sophios.api.python.workflow import Workflow # pylint: disable=import-outside-toplevel tools = load_test_registry().tools - compiled = Workflow.from_wic(unpinned, tool_registry=tools).compile(tool_registry=tools, lang_version=LANG_VERSION) - assert compiled.lang_version == LANG_VERSION - assert ANNOTATION_KEY not in compiled.cwl_workflow - - -@pytest.mark.fast -def test_the_cli_flag_and_the_library_defaults_reach_the_compiler() -> None: - """`--lang_version` survives the trip from argv to compiler options. - - The flag's entire contract is precedence — an explicit setting beats a - file pin — and it could not keep it: `main` parsed the real argv, then - `_build_and_compile_workflow` threw those arguments away and called - `get_dicts_for_compilation()`, which re-parses a patched - `sys.argv` of `['sophios', '--yaml', '']`. Every flag arrived at the - compiler as its default, so `--lang_version 9.9.9` compiled at the newest - version instead of reporting an unknown one. - - Tested at the seam because that is where the value was being dropped. The - caller side needs no test of its own any more: `get_dicts_for_compilation` - requires its argument, so a `main` that forgets to pass what it parsed is - a TypeError and a mypy failure rather than a silent compile with defaults. - The guarantee moved from a test into the signature. - """ - supplied = sophios.cli.get_args('wf.wic', ['--lang_version', '9.9.9']) - options, _graph_settings = sophios.cli.get_dicts_for_compilation(supplied) - assert options['lang_version'] == '9.9.9', 'the flag never reached the compiler' - - # A library caller asking for defaults by name (the Python API, the schema generator and a real-time analysis - # compile with them) gets the documented ones, and no pin. - defaults = sophios.cli.default_compilation_settings() - assert defaults['lang_version'] is None - assert defaults['allow_raw_cwl'] is False - assert defaults['inference_use_naming_conventions'] is True - - -@pytest.mark.fast -def test_a_mistyped_pin_is_reported_not_ignored(tmp_path: Path) -> None: - """`lang_version: 1.0` is a YAML float, not a string. A walk that only - collected strings made it vanish — silently inferred over, when the - author plainly asked for something, and by the no-silent-selection rule - above, silence is the one wrong answer. Any value under the key is a pin - claim; a non-version is reported as unknown, naming what was written.""" - written = tmp_path / 'mistyped.wic' - written.write_text('wic: {lang_version: 1.0}\nsteps:\n- id: s\n', encoding='utf-8') - pins = bundle_from_disk(written, {'global': {}}, {}).lang_version_pins - assert pins == ('1.0',) - + workflow = Workflow.from_wic(DATA / 'lang_version' / 'unpinned.wic', tool_registry=tools) with pytest.raises(SophiosError) as caught: - resolve_lang_version(None, pins) + workflow.compile(tool_registry=tools, lang_version='9.9.9') assert caught.value.diagnostics[0].code is SophiosErrorCode.UNKNOWN_LANG_VERSION - assert "'1.0'" in caught.value.diagnostics[0].message + compiled = workflow.compile(tool_registry=tools) + assert compiled.lang_version == LANG_VERSION + assert ANNOTATION_KEY not in compiled.cwl_workflow and 'sophios' not in compiled.cwl_workflow.get('$namespaces', {}) diff --git a/tests/core/test_namespacing.py b/tests/core/test_namespacing.py deleted file mode 100644 index 996840756..000000000 --- a/tests/core/test_namespacing.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Parsing leaves global YAML state alone, and gives the same answer from many threads.""" -from concurrent.futures import ThreadPoolExecutor - -import pytest -import yaml - -from sophios.lang import parse, wic_schema -from sophios.lang.render import render - -pytestmark = pytest.mark.package - -SOURCE = 'steps:\n- id: touch\n in:\n f: !ii empty.txt\n out:\n - file: !& out\n' - - -@pytest.mark.fast -def test_parsing_does_not_touch_the_global_safeloader() -> None: - """Parsing a `.wic` leaves `yaml.safe_load` alone. - - The parser builds YAML with `yaml.SafeLoader`; registering on it would make - every later `safe_load` in the process interpret `!ii`, anywhere, including - in unrelated libraries. - """ - assert parse(SOURCE, 'tags.wic').ok - - with pytest.raises(yaml.YAMLError): - yaml.safe_load('x: !ii 5') - - -@pytest.mark.fast -def test_parsing_and_rendering_are_safe_from_many_threads() -> None: - """The same source parsed concurrently gives every thread the same answer. - - Not a proof of thread safety — no test is — but it exercises the shared - tables, the parser's YAML loading, and the schema export from several threads at once, - which is where per-module mutable state would show up as divergence. - """ - def once(_: int) -> tuple[str, int]: - document = parse(SOURCE, 'concurrent.wic').document - assert document is not None - return render(document), len(wic_schema()['$defs']) - - with ThreadPoolExecutor(max_workers=8) as pool: - results = list(pool.map(once, range(64))) - - assert len(set(results)) == 1, 'concurrent parses disagreed' From 89486cd3ab84f58ea3665233606dc67bf98a9c72 Mon Sep 17 00:00:00 2001 From: Vasu Jaganath Date: Thu, 12 Nov 2026 23:38:48 -0500 Subject: [PATCH 4/7] test(compiler): judge the compiler on example files Run examples move to data/examples with a compile leg and a cwltool leg; the compiler, inference, contributions, lowering and inline flags are judged on example directories, and the workflows() laws share one compile. --- .github/workflows/lint_and_test.yml | 30 +- .github/workflows/property_weekly.yml | 12 +- design_docs/one-target-table-design.md | 2 +- docs/dev/architecture.md | 4 +- docs/dev/language_spec.md | 81 ++- src/sophios/lang/support.py | 22 +- tests/core/ast_strategies.py | 122 +--- tests/core/cases.py | 5 +- .../boundary/a_class_with_no_body.wic | 4 + .../core/data/compiler/boundary/authored.wic | 7 + tests/core/data/compiler/boundary/both.wic | 3 + .../core/data/compiler/boundary/bystander.cwl | 6 + tests/core/data/compiler/boundary/called.wic | 2 + .../data/compiler/boundary/clash_beneath.wic | 3 + .../data/compiler/boundary/clash_document.wic | 4 + .../data/compiler/boundary/clash_inside.wic | 2 + .../data/compiler/boundary/clash_tools.wic | 4 + .../data/compiler/boundary/edam_authored.wic | 6 + .../data/compiler/boundary/edam_default.wic | 5 + .../core/data/compiler/boundary/edam_job.wic | 3 + .../data/compiler/boundary/edam_promoted.wic | 2 + .../compiler/boundary/edam_step_default.wic | 3 + .../core/data/compiler/boundary/elsewhere.cwl | 6 + .../core/data/compiler/boundary/expected.yaml | 62 ++ .../compiler/boundary/format_expression.wic | 4 + .../core/data/compiler/boundary/formatted.cwl | 9 + tests/core/data/compiler/boundary/grand.wic | 3 + .../data/compiler/boundary/imported_ports.wic | 8 + tests/core/data/compiler/boundary/maker.cwl | 6 + tests/core/data/compiler/boundary/no_edam.wic | 3 + tests/core/data/compiler/boundary/owned.wic | 25 + .../core/data/compiler/boundary/prefixes.wic | 13 + tests/core/data/compiler/boundary/probe.cwl | 6 + tests/core/data/compiler/boundary/rival.cwl | 6 + tests/core/data/compiler/boundary/through.wic | 2 + tests/core/data/compiler/boundary/twin.cwl | 6 + tests/core/data/compiler/names/a/echo.cwl | 5 + tests/core/data/compiler/names/b/echo.cwl | 5 + tests/core/data/compiler/names/child.wic | 8 + tests/core/data/compiler/names/expected.yaml | 56 ++ tests/core/data/compiler/names/greeting.wic | 34 + tests/core/data/compiler/names/inner.wic | 2 + tests/core/data/compiler/names/other.wic | 5 + tests/core/data/compiler/names/probe.cwl | 6 + tests/core/data/compiler/refused/deep.wic | 3 + tests/core/data/compiler/refused/disjoint.wic | 5 + .../core/data/compiler/refused/expected.yaml | 37 ++ tests/core/data/compiler/refused/imports.wic | 7 + .../data/compiler/refused/inputs_imported.wic | 5 + .../data/compiler/refused/inputs_included.wic | 5 + .../core/data/compiler/refused/int_source.cwl | 5 + tests/core/data/compiler/refused/kid.wic | 5 + .../compiler/refused/outputs_imported.wic | 5 + .../compiler/refused/outputs_included.wic | 5 + tests/core/data/compiler/refused/records.wic | 13 + .../core/data/compiler/refused/undeclared.wic | 12 + .../core/data/compiler/refused/unresolved.wic | 5 + .../compiler/refused/untyped_derived_name.wic | 7 + .../compiler/refused/untyped_misspelled.wic | 7 + .../compiler/refused/untyped_no_source.wic | 7 + .../refused/untyped_nothing_close.wic | 7 + .../refused/untyped_old_generated.wic | 7 + .../refused/untyped_without_extension.wic | 7 + tests/core/data/compiler/refused/wrapper.wic | 2 + .../data/compiler/sources/alt/mk_file.cwl | 5 + tests/core/data/compiler/sources/calls.wic | 18 + tests/core/data/compiler/sources/choice.wic | 7 + tests/core/data/compiler/sources/consumer.wic | 5 + tests/core/data/compiler/sources/deep.wic | 3 + tests/core/data/compiler/sources/deferred.wic | 5 + .../core/data/compiler/sources/expected.yaml | 74 +++ tests/core/data/compiler/sources/fast.wic | 2 + tests/core/data/compiler/sources/kid.wic | 7 + tests/core/data/compiler/sources/listed.wic | 15 + tests/core/data/compiler/sources/made.wic | 5 + tests/core/data/compiler/sources/make.cwl | 5 + .../core/data/compiler/sources/namespaced.wic | 8 + .../core/data/compiler/sources/positions.wic | 28 + tests/core/data/compiler/sources/producer.wic | 6 + .../core/data/compiler/sources/raw_names.wic | 5 + tests/core/data/compiler/sources/records.wic | 21 + tests/core/data/compiler/sources/relayed.wic | 3 + .../data/compiler/sources/string_source.cwl | 5 + tests/core/data/compiler/sources/take.cwl | 5 + tests/core/data/compiler/sources/unbound.wic | 5 + tests/core/data/compiler/sources/untyped.wic | 22 + tests/core/data/compiler/sources/wrapper.wic | 2 + tests/core/data/compiler/when/child.wic | 5 + tests/core/data/compiler/when/expected.yaml | 54 ++ tests/core/data/compiler/when/gated.cwl | 6 + tests/core/data/compiler/when/job.yml | 5 + tests/core/data/compiler/when/lowers.wic | 15 + tests/core/data/compiler/when/maker.wic | 2 + tests/core/data/compiler/when/workflow.wic | 68 ++ tests/core/data/contributions/cases.yaml | 191 ------ .../child.wic | 4 + .../workflow.wic | 12 + .../child.wic | 4 + .../workflow.wic | 11 + .../child.wic | 9 + .../workflow.wic | 14 + .../child.wic | 7 + .../workflow.wic | 11 + .../workflow.wic | 11 + .../workflow.wic | 11 + .../child.wic | 8 + .../workflow.wic | 11 + .../child.wic | 10 + .../workflow.wic | 11 + .../data/contributions/merging/expected.yaml | 25 + .../a.wic | 2 + .../b.wic | 2 + .../c.wic | 2 + .../workflow.wic | 17 + .../child.wic | 2 + .../workflow.wic | 11 + .../cg.wic | 4 + .../min.wic | 2 + .../workflow.wic | 16 + .../child.wic | 2 + .../workflow.wic | 13 + .../child.wic | 2 + .../workflow.wic | 11 + .../data/contributions/reach/expected.yaml | 17 + .../spellings/bare_name/child.wic | 2 + .../spellings/bare_name/workflow.wic | 13 + .../edge_reference_desugared/child.wic | 2 + .../edge_reference_desugared/workflow.wic | 13 + .../spellings/edge_reference_tagged/child.wic | 2 + .../edge_reference_tagged/workflow.wic | 13 + .../contributions/spellings/expected.yaml | 24 + .../spellings/literal_desugared/child.wic | 2 + .../spellings/literal_desugared/workflow.wic | 13 + .../spellings/literal_tagged/child.wic | 2 + .../spellings/literal_tagged/workflow.wic | 13 + .../raw_cwl_reference_desugared/child.wic | 2 + .../raw_cwl_reference_desugared/workflow.wic | 13 + .../raw_cwl_reference_tagged/child.wic | 2 + .../raw_cwl_reference_tagged/workflow.wic | 13 + .../spellings/untagged_mapping/child.wic | 2 + .../spellings/untagged_mapping/workflow.wic | 13 + .../a_bare_id_naming_no_step/workflow.wic | 8 + .../child.wic | 4 + .../workflow.wic | 15 + .../child.wic | 8 + .../workflow.wic | 11 + .../child.wic | 5 + .../workflow.wic | 4 + .../child.wic | 7 + .../workflow.wic | 11 + .../child.wic | 7 + .../workflow.wic | 11 + .../workflow.wic | 9 + .../data/contributions/stale/expected.yaml | 36 ++ tests/core/data/defaults/sub/child.wic | 5 + tests/core/data/defaults/w.wic | 20 + tests/core/data/embedded_tools/cases.yaml | 62 -- tests/core/data/equivalence/cases.yaml | 294 --------- .../runs => examples}/commands/cat_file.cwl | 0 .../runs => examples}/commands/copy_file.cwl | 0 .../commands/count_bytes.cwl | 0 .../runs => examples}/commands/expected.yaml | 20 + .../runs => examples}/commands/greeting.txt | 0 .../commands/print_bindings.cwl | 0 .../runs => examples}/commands/produce.cwl | 0 .../commands/shell_redirect.cwl | 0 .../commands/three_commands.cwl | 0 .../runs => examples}/commands/touch_file.cwl | 0 .../runs => examples}/commands/workflow.wic | 0 .../conditions_and_scatter/cat_pair.cwl | 0 .../conditions_and_scatter/copy_note.cwl | 0 .../conditions_and_scatter/echo_item.cwl | 0 .../conditions_and_scatter/expected.yaml | 72 +++ .../conditions_and_scatter/job.yml | 0 .../conditions_and_scatter/never_runs.cwl | 0 .../conditions_and_scatter/numbers_if.cwl | 0 .../numbers_if_prev_last.cwl | 0 .../conditions_and_scatter/pair.cwl | 0 .../pair_after_sleeping.cwl | 0 .../conditions_and_scatter/ref.txt | 0 .../conditions_and_scatter/say_ok.cwl | 0 .../conditions_and_scatter/touch_done.cwl | 0 .../conditions_and_scatter/workflow.wic | 0 .../conditions_and_scatter/write_note.cwl | 0 .../runs => examples}/nested/child.wic | 0 .../runs => examples}/nested/copy_file.cwl | 0 .../runs => examples}/nested/count_lines.cwl | 0 .../runs => examples}/nested/echo_each.cwl | 0 .../runs => examples}/nested/expected.yaml | 10 + .../runs => examples}/nested/grandchild.wic | 0 .../runs => examples}/nested/sibling.wic | 0 .../runs => examples}/nested/touch_n.cwl | 0 .../runs => examples}/nested/workflow.wic | 0 .../runs => examples}/nested/write_source.cwl | 0 .../outputs/backtick_named.cwl | 0 .../runs => examples}/outputs/brace_named.cwl | 0 .../outputs/dollar_named.cwl | 0 .../runs => examples}/outputs/expected.yaml | 14 + .../outputs/first_of_braces.cwl | 0 .../runs => examples}/outputs/maybe_log.cwl | 0 .../runs => examples}/outputs/maybe_named.cwl | 0 .../runs => examples}/outputs/touch_names.cwl | 0 .../runs => examples}/outputs/workflow.wic | 0 .../runs => examples}/resources/expected.yaml | 6 + .../runs => examples}/resources/make_dir.cwl | 0 .../resources/nextflow.config | 0 .../runs => examples}/resources/workflow.nf | 0 .../runs => examples}/resources/workflow.wic | 0 .../staging/capture_own_entry.cwl | 0 .../staging/capture_renamed_entry.cwl | 0 .../staging/copy_named_after_source.cwl | 0 .../runs => examples}/staging/expected.yaml | 13 + .../runs => examples}/staging/plugin.cwl | 0 .../staging/stage_and_read.cwl | 0 .../staging/stage_own_basename.cwl | 0 .../runs => examples}/staging/workflow.wic | 0 .../staging/write_source.cwl | 0 .../step_inputs/cat_files.cwl | 0 .../data/examples/step_inputs/expected.yaml | 43 ++ .../runs => examples}/step_inputs/job.yml | 0 .../runs => examples}/step_inputs/say_if.cwl | 0 .../step_inputs/say_word.cwl | 0 .../step_inputs/say_words.cwl | 0 .../step_inputs/workflow.wic | 0 .../step_inputs/write_name.cwl | 0 .../a_call_output_is_a_candidate/sub.wic | 3 + .../a_call_output_is_a_candidate/workflow.wic | 4 + .../fan.wic | 3 + .../workflow.wic | 6 + .../a_file_fanned_out_two_calls_down/fan.wic | 12 + .../a_file_fanned_out_two_calls_down/mid.wic | 10 + .../workflow.wic | 6 + .../make.wic | 2 + .../use.wic | 2 + .../workflow.wic | 4 + .../pair.cwl | 11 + .../src.wic | 6 + .../workflow.wic | 7 + .../make.wic | 4 + .../use.wic | 4 + .../workflow.wic | 4 + .../src.wic | 6 + .../workflow.wic | 8 + tests/core/data/infer/calls/expected.yaml | 28 + tests/core/data/infer/calls/multi_file.cwl | 11 + .../make.wic | 2 + .../use.wic | 3 + .../workflow.wic | 4 + .../fan.wic | 12 + .../workflow.wic | 6 + tests/core/data/infer/cases.yaml | 288 --------- .../a_break_stops_the_search/workflow.wic | 10 + .../a_call_output_feeds_a_converter/sub.wic | 2 + .../workflow.wic | 4 + .../core/data/infer/converters/expected.yaml | 11 + .../insert_steps_automatically_conv_1.cwl | 6 + .../insert_steps_automatically_conv_2.cwl | 6 + tests/core/data/infer/converters/mk_1.cwl | 6 + tests/core/data/infer/converters/mk_2.cwl | 6 + .../workflow.wic | 7 + tests/core/data/infer/converters/use_1.cwl | 6 + tests/core/data/infer/converters/use_2.cwl | 6 + .../workflow.wic | 12 + .../core/data/infer/duplicates/expected.yaml | 17 + .../pair.cwl | 14 + .../workflow.wic | 8 + .../pair.cwl | 13 + .../workflow.wic | 8 + .../workflow.wic | 8 + .../workflow.wic | 12 + .../consumer.cwl | 7 + .../producer.cwl | 7 + .../workflow.wic | 4 + .../consumer.cwl | 6 + .../producer.cwl | 6 + .../workflow.wic | 4 + .../file_array_sink.cwl | 5 + .../a_scatter_lifts_both_sides/workflow.wic | 7 + .../consumer.cwl | 9 + .../producer.cwl | 8 + .../workflow.wic | 4 + tests/core/data/infer/formats/expected.yaml | 9 + .../a_log_is_a_file_like_any_other/make.cwl | 8 + .../a_log_is_a_file_like_any_other/reader.cwl | 6 + .../workflow.wic | 5 + .../maker.cwl | 11 + .../reader.cwl | 6 + .../workflow.wic | 4 + .../named.cwl | 11 + .../workflow.wic | 4 + .../maker.cwl | 14 + .../reader.cwl | 6 + .../workflow.wic | 5 + .../reader.cwl | 6 + .../workflow.wic | 5 + tests/core/data/infer/names/consumer.cwl | 8 + tests/core/data/infer/names/expected.yaml | 25 + tests/core/data/infer/names/logger.cwl | 8 + .../workflow.wic | 4 + .../workflow.wic | 4 + tests/core/data/infer/names/producer.cwl | 11 + .../workflow.wic | 9 + .../a_pinned_edge_is_not_noted/workflow.wic | 13 + .../a_strict_compile_refuses/workflow.wic | 9 + .../workflow.wic | 4 + tests/core/data/infer/recency/expected.yaml | 27 + tests/core/data/infer/recency/multi_file.cwl | 11 + .../workflow.wic | 9 + .../workflow.wic | 9 + .../workflow.wic | 7 + .../workflow.wic | 9 + .../workflow.wic | 7 + tests/core/data/infer/values/expected.yaml | 16 + .../defaulted.cwl | 9 + .../workflow.wic | 3 + .../workflow.wic | 3 + tests/core/data/inline/defaulted.wic | 5 + .../data/inline/embedded/cwltool_names.cwl | 9 + .../inline/embedded/cwltool_names_listed.cwl | 8 + tests/core/data/inline/embedded/declared.cwl | 8 + tests/core/data/inline/embedded/expected.yaml | 22 + tests/core/data/inline/embedded/listed.cwl | 8 + tests/core/data/inline/embedded/no_ports.cwl | 4 + .../core/data/inline/embedded/no_version.cwl | 5 + tests/core/data/inline/embedded/v1_0.cwl | 12 + .../inline/embedded/v1_0_without_hints.cwl | 8 + tests/core/data/inline/embedded/v1_1.cwl | 7 + tests/core/data/inline/embedded/v1_3_dev.cwl | 6 + tests/core/data/inline/expected.yaml | 42 ++ tests/core/data/inline/gated.wic | 3 + tests/core/data/inline/inner.wic | 3 + tests/core/data/inline/javascript.wic | 5 + tests/core/data/inline/labelled.wic | 3 + tests/core/data/inline/listed.wic | 5 + tests/core/data/inline/middle.wic | 2 + tests/core/data/inline/moved.wic | 9 + tests/core/data/inline/opted_in.wic | 4 + tests/core/data/inline/opted_out.wic | 4 + tests/core/data/inline/plain.wic | 5 + tests/core/data/inline/required.wic | 3 + tests/core/data/inline/scattered.wic | 5 + tests/core/data/inline/sealed.wic | 4 + tests/core/data/inline/sealing.wic | 2 + tests/core/data/inline/unbound.wic | 5 + tests/core/data/inline/valued.wic | 5 + tests/core/data/inline/workflow.wic | 38 ++ tests/core/data/kept_calls/cases.yaml | 14 - tests/core/data/lower/cases.yaml | 64 -- tests/core/data/lower/edges.wic | 24 + tests/core/data/lower/empty_step_id.wic | 4 + tests/core/data/lower/expected.yaml | 30 + tests/core/data/lower/merged_outputs.wic | 11 + tests/core/data/lower/names.wic | 15 + tests/core/data/lower/outputs.wic | 17 + tests/core/data/lower/record_sources.wic | 8 + tests/core/data/lower/scatter.wic | 18 + .../runs/conditions_and_scatter/expected.yaml | 46 -- .../nextflow/runs/step_inputs/expected.yaml | 21 - tests/core/data/when_boolean.yaml | 92 --- tests/core/helpers.py | 86 ++- tests/core/nextflow/test_import.py | 10 +- tests/core/nextflow/test_phase3_cells.py | 2 +- .../nextflow/test_reference_differential.py | 64 +- tests/core/nextflow/test_runtime.py | 62 +- tests/core/nextflow/testkit.py | 33 - tests/core/reference_model.py | 70 ++- tests/core/test_canonical_path.py | 164 +---- tests/core/test_ci_coverage.py | 22 +- tests/core/test_compiler.py | 229 +++---- tests/core/test_diagnostics.py | 2 +- tests/core/test_emit.py | 580 ++++++------------ tests/core/test_equivalence.py | 174 ------ tests/core/test_equivalences.py | 275 --------- tests/core/test_examples.py | 17 +- tests/core/test_generators.py | 178 ------ tests/core/test_hermeticity.py | 5 - tests/core/test_infer_phase.py | 387 ++---------- tests/core/test_inline_flags.py | 358 ++++------- tests/core/test_leak_boundary.py | 356 ++--------- tests/core/test_link.py | 180 ------ tests/core/test_lower.py | 241 ++------ tests/core/test_manufactured_documents.py | 144 ----- tests/core/test_metadata_emitted.py | 55 -- tests/core/test_names_emitted.py | 259 -------- tests/core/test_nesting_scaling.py | 29 +- tests/core/test_pipeline.py | 97 --- tests/core/test_python_api_from_wic.py | 4 +- tests/core/test_reference_compatibility.py | 200 ++---- tests/core/test_resolve.py | 283 ++------- tests/core/test_support_matrix.py | 22 +- tests/core/test_wic_defaults.py | 20 +- tests/core/transformations.py | 172 ------ 392 files changed, 3736 insertions(+), 5123 deletions(-) create mode 100644 tests/core/data/compiler/boundary/a_class_with_no_body.wic create mode 100644 tests/core/data/compiler/boundary/authored.wic create mode 100644 tests/core/data/compiler/boundary/both.wic create mode 100644 tests/core/data/compiler/boundary/bystander.cwl create mode 100644 tests/core/data/compiler/boundary/called.wic create mode 100644 tests/core/data/compiler/boundary/clash_beneath.wic create mode 100644 tests/core/data/compiler/boundary/clash_document.wic create mode 100644 tests/core/data/compiler/boundary/clash_inside.wic create mode 100644 tests/core/data/compiler/boundary/clash_tools.wic create mode 100644 tests/core/data/compiler/boundary/edam_authored.wic create mode 100644 tests/core/data/compiler/boundary/edam_default.wic create mode 100644 tests/core/data/compiler/boundary/edam_job.wic create mode 100644 tests/core/data/compiler/boundary/edam_promoted.wic create mode 100644 tests/core/data/compiler/boundary/edam_step_default.wic create mode 100644 tests/core/data/compiler/boundary/elsewhere.cwl create mode 100644 tests/core/data/compiler/boundary/expected.yaml create mode 100644 tests/core/data/compiler/boundary/format_expression.wic create mode 100644 tests/core/data/compiler/boundary/formatted.cwl create mode 100644 tests/core/data/compiler/boundary/grand.wic create mode 100644 tests/core/data/compiler/boundary/imported_ports.wic create mode 100644 tests/core/data/compiler/boundary/maker.cwl create mode 100644 tests/core/data/compiler/boundary/no_edam.wic create mode 100644 tests/core/data/compiler/boundary/owned.wic create mode 100644 tests/core/data/compiler/boundary/prefixes.wic create mode 100644 tests/core/data/compiler/boundary/probe.cwl create mode 100644 tests/core/data/compiler/boundary/rival.cwl create mode 100644 tests/core/data/compiler/boundary/through.wic create mode 100644 tests/core/data/compiler/boundary/twin.cwl create mode 100644 tests/core/data/compiler/names/a/echo.cwl create mode 100644 tests/core/data/compiler/names/b/echo.cwl create mode 100644 tests/core/data/compiler/names/child.wic create mode 100644 tests/core/data/compiler/names/expected.yaml create mode 100644 tests/core/data/compiler/names/greeting.wic create mode 100644 tests/core/data/compiler/names/inner.wic create mode 100644 tests/core/data/compiler/names/other.wic create mode 100644 tests/core/data/compiler/names/probe.cwl create mode 100644 tests/core/data/compiler/refused/deep.wic create mode 100644 tests/core/data/compiler/refused/disjoint.wic create mode 100644 tests/core/data/compiler/refused/expected.yaml create mode 100644 tests/core/data/compiler/refused/imports.wic create mode 100644 tests/core/data/compiler/refused/inputs_imported.wic create mode 100644 tests/core/data/compiler/refused/inputs_included.wic create mode 100644 tests/core/data/compiler/refused/int_source.cwl create mode 100644 tests/core/data/compiler/refused/kid.wic create mode 100644 tests/core/data/compiler/refused/outputs_imported.wic create mode 100644 tests/core/data/compiler/refused/outputs_included.wic create mode 100644 tests/core/data/compiler/refused/records.wic create mode 100644 tests/core/data/compiler/refused/undeclared.wic create mode 100644 tests/core/data/compiler/refused/unresolved.wic create mode 100644 tests/core/data/compiler/refused/untyped_derived_name.wic create mode 100644 tests/core/data/compiler/refused/untyped_misspelled.wic create mode 100644 tests/core/data/compiler/refused/untyped_no_source.wic create mode 100644 tests/core/data/compiler/refused/untyped_nothing_close.wic create mode 100644 tests/core/data/compiler/refused/untyped_old_generated.wic create mode 100644 tests/core/data/compiler/refused/untyped_without_extension.wic create mode 100644 tests/core/data/compiler/refused/wrapper.wic create mode 100644 tests/core/data/compiler/sources/alt/mk_file.cwl create mode 100644 tests/core/data/compiler/sources/calls.wic create mode 100644 tests/core/data/compiler/sources/choice.wic create mode 100644 tests/core/data/compiler/sources/consumer.wic create mode 100644 tests/core/data/compiler/sources/deep.wic create mode 100644 tests/core/data/compiler/sources/deferred.wic create mode 100644 tests/core/data/compiler/sources/expected.yaml create mode 100644 tests/core/data/compiler/sources/fast.wic create mode 100644 tests/core/data/compiler/sources/kid.wic create mode 100644 tests/core/data/compiler/sources/listed.wic create mode 100644 tests/core/data/compiler/sources/made.wic create mode 100644 tests/core/data/compiler/sources/make.cwl create mode 100644 tests/core/data/compiler/sources/namespaced.wic create mode 100644 tests/core/data/compiler/sources/positions.wic create mode 100644 tests/core/data/compiler/sources/producer.wic create mode 100644 tests/core/data/compiler/sources/raw_names.wic create mode 100644 tests/core/data/compiler/sources/records.wic create mode 100644 tests/core/data/compiler/sources/relayed.wic create mode 100644 tests/core/data/compiler/sources/string_source.cwl create mode 100644 tests/core/data/compiler/sources/take.cwl create mode 100644 tests/core/data/compiler/sources/unbound.wic create mode 100644 tests/core/data/compiler/sources/untyped.wic create mode 100644 tests/core/data/compiler/sources/wrapper.wic create mode 100644 tests/core/data/compiler/when/child.wic create mode 100644 tests/core/data/compiler/when/expected.yaml create mode 100644 tests/core/data/compiler/when/gated.cwl create mode 100644 tests/core/data/compiler/when/job.yml create mode 100644 tests/core/data/compiler/when/lowers.wic create mode 100644 tests/core/data/compiler/when/maker.wic create mode 100644 tests/core/data/compiler/when/workflow.wic delete mode 100644 tests/core/data/contributions/cases.yaml create mode 100644 tests/core/data/contributions/merging/a_contributed_out_replaces_the_step_s/child.wic create mode 100644 tests/core/data/contributions/merging/a_contributed_out_replaces_the_step_s/workflow.wic create mode 100644 tests/core/data/contributions/merging/a_contributed_value_wins_over_the_child/child.wic create mode 100644 tests/core/data/contributions/merging/a_contributed_value_wins_over_the_child/workflow.wic create mode 100644 tests/core/data/contributions/merging/a_contribution_merges_with_the_child_s/child.wic create mode 100644 tests/core/data/contributions/merging/a_contribution_merges_with_the_child_s/workflow.wic create mode 100644 tests/core/data/contributions/merging/a_positional_key_from_the_parent_merges/child.wic create mode 100644 tests/core/data/contributions/merging/a_positional_key_from_the_parent_merges/workflow.wic create mode 100644 tests/core/data/contributions/merging/a_positional_key_wins_over_an_id_key_for/workflow.wic create mode 100644 tests/core/data/contributions/merging/an_id_key_and_a_positional_key_for_the/workflow.wic create mode 100644 tests/core/data/contributions/merging/an_id_key_from_the_parent_merges_over/child.wic create mode 100644 tests/core/data/contributions/merging/an_id_key_from_the_parent_merges_over/workflow.wic create mode 100644 tests/core/data/contributions/merging/an_id_key_from_the_parent_wins_when_the/child.wic create mode 100644 tests/core/data/contributions/merging/an_id_key_from_the_parent_wins_when_the/workflow.wic create mode 100644 tests/core/data/contributions/merging/expected.yaml create mode 100644 tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/a.wic create mode 100644 tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/b.wic create mode 100644 tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/c.wic create mode 100644 tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/workflow.wic create mode 100644 tests/core/data/contributions/reach/a_contributed_input_reaches_a_step_of_a/child.wic create mode 100644 tests/core/data/contributions/reach/a_contributed_input_reaches_a_step_of_a/workflow.wic create mode 100644 tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/cg.wic create mode 100644 tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/min.wic create mode 100644 tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/workflow.wic create mode 100644 tests/core/data/contributions/reach/a_contribution_to_a_wic_step_addresses/child.wic create mode 100644 tests/core/data/contributions/reach/a_contribution_to_a_wic_step_addresses/workflow.wic create mode 100644 tests/core/data/contributions/reach/an_id_keyed_contribution_reaches_the_one/child.wic create mode 100644 tests/core/data/contributions/reach/an_id_keyed_contribution_reaches_the_one/workflow.wic create mode 100644 tests/core/data/contributions/reach/expected.yaml create mode 100644 tests/core/data/contributions/spellings/bare_name/child.wic create mode 100644 tests/core/data/contributions/spellings/bare_name/workflow.wic create mode 100644 tests/core/data/contributions/spellings/edge_reference_desugared/child.wic create mode 100644 tests/core/data/contributions/spellings/edge_reference_desugared/workflow.wic create mode 100644 tests/core/data/contributions/spellings/edge_reference_tagged/child.wic create mode 100644 tests/core/data/contributions/spellings/edge_reference_tagged/workflow.wic create mode 100644 tests/core/data/contributions/spellings/expected.yaml create mode 100644 tests/core/data/contributions/spellings/literal_desugared/child.wic create mode 100644 tests/core/data/contributions/spellings/literal_desugared/workflow.wic create mode 100644 tests/core/data/contributions/spellings/literal_tagged/child.wic create mode 100644 tests/core/data/contributions/spellings/literal_tagged/workflow.wic create mode 100644 tests/core/data/contributions/spellings/raw_cwl_reference_desugared/child.wic create mode 100644 tests/core/data/contributions/spellings/raw_cwl_reference_desugared/workflow.wic create mode 100644 tests/core/data/contributions/spellings/raw_cwl_reference_tagged/child.wic create mode 100644 tests/core/data/contributions/spellings/raw_cwl_reference_tagged/workflow.wic create mode 100644 tests/core/data/contributions/spellings/untagged_mapping/child.wic create mode 100644 tests/core/data/contributions/spellings/untagged_mapping/workflow.wic create mode 100644 tests/core/data/contributions/stale/a_bare_id_naming_no_step/workflow.wic create mode 100644 tests/core/data/contributions/stale/a_contribution_whose_key_does_not_match/child.wic create mode 100644 tests/core/data/contributions/stale/a_contribution_whose_key_does_not_match/workflow.wic create mode 100644 tests/core/data/contributions/stale/a_stale_child_id_entry_does_not_pair/child.wic create mode 100644 tests/core/data/contributions/stale/a_stale_child_id_entry_does_not_pair/workflow.wic create mode 100644 tests/core/data/contributions/stale/a_stale_key_is_named_once_however_many/child.wic create mode 100644 tests/core/data/contributions/stale/a_stale_key_is_named_once_however_many/workflow.wic create mode 100644 tests/core/data/contributions/stale/a_stale_positional_key_from_the_parent/child.wic create mode 100644 tests/core/data/contributions/stale/a_stale_positional_key_from_the_parent/workflow.wic create mode 100644 tests/core/data/contributions/stale/a_stale_positional_key_in_the_child_does/child.wic create mode 100644 tests/core/data/contributions/stale/a_stale_positional_key_in_the_child_does/workflow.wic create mode 100644 tests/core/data/contributions/stale/an_id_keyed_entry_for_a_repeated_id_is/workflow.wic create mode 100644 tests/core/data/contributions/stale/expected.yaml create mode 100644 tests/core/data/defaults/sub/child.wic create mode 100644 tests/core/data/defaults/w.wic delete mode 100644 tests/core/data/embedded_tools/cases.yaml delete mode 100644 tests/core/data/equivalence/cases.yaml rename tests/core/data/{nextflow/runs => examples}/commands/cat_file.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/commands/copy_file.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/commands/count_bytes.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/commands/expected.yaml (68%) rename tests/core/data/{nextflow/runs => examples}/commands/greeting.txt (100%) rename tests/core/data/{nextflow/runs => examples}/commands/print_bindings.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/commands/produce.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/commands/shell_redirect.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/commands/three_commands.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/commands/touch_file.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/commands/workflow.wic (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/cat_pair.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/copy_note.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/echo_item.cwl (100%) create mode 100644 tests/core/data/examples/conditions_and_scatter/expected.yaml rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/job.yml (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/never_runs.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/numbers_if.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/numbers_if_prev_last.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/pair.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/pair_after_sleeping.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/ref.txt (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/say_ok.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/touch_done.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/workflow.wic (100%) rename tests/core/data/{nextflow/runs => examples}/conditions_and_scatter/write_note.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/nested/child.wic (100%) rename tests/core/data/{nextflow/runs => examples}/nested/copy_file.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/nested/count_lines.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/nested/echo_each.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/nested/expected.yaml (63%) rename tests/core/data/{nextflow/runs => examples}/nested/grandchild.wic (100%) rename tests/core/data/{nextflow/runs => examples}/nested/sibling.wic (100%) rename tests/core/data/{nextflow/runs => examples}/nested/touch_n.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/nested/workflow.wic (100%) rename tests/core/data/{nextflow/runs => examples}/nested/write_source.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/outputs/backtick_named.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/outputs/brace_named.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/outputs/dollar_named.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/outputs/expected.yaml (59%) rename tests/core/data/{nextflow/runs => examples}/outputs/first_of_braces.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/outputs/maybe_log.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/outputs/maybe_named.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/outputs/touch_names.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/outputs/workflow.wic (100%) rename tests/core/data/{nextflow/runs => examples}/resources/expected.yaml (52%) rename tests/core/data/{nextflow/runs => examples}/resources/make_dir.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/resources/nextflow.config (100%) rename tests/core/data/{nextflow/runs => examples}/resources/workflow.nf (100%) rename tests/core/data/{nextflow/runs => examples}/resources/workflow.wic (100%) rename tests/core/data/{nextflow/runs => examples}/staging/capture_own_entry.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/staging/capture_renamed_entry.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/staging/copy_named_after_source.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/staging/expected.yaml (56%) rename tests/core/data/{nextflow/runs => examples}/staging/plugin.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/staging/stage_and_read.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/staging/stage_own_basename.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/staging/workflow.wic (100%) rename tests/core/data/{nextflow/runs => examples}/staging/write_source.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/step_inputs/cat_files.cwl (100%) create mode 100644 tests/core/data/examples/step_inputs/expected.yaml rename tests/core/data/{nextflow/runs => examples}/step_inputs/job.yml (100%) rename tests/core/data/{nextflow/runs => examples}/step_inputs/say_if.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/step_inputs/say_word.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/step_inputs/say_words.cwl (100%) rename tests/core/data/{nextflow/runs => examples}/step_inputs/workflow.wic (100%) rename tests/core/data/{nextflow/runs => examples}/step_inputs/write_name.cwl (100%) create mode 100644 tests/core/data/infer/calls/a_call_output_is_a_candidate/sub.wic create mode 100644 tests/core/data/infer/calls/a_call_output_is_a_candidate/workflow.wic create mode 100644 tests/core/data/infer/calls/a_file_fanned_out_to_two_inner_steps/fan.wic create mode 100644 tests/core/data/infer/calls/a_file_fanned_out_to_two_inner_steps/workflow.wic create mode 100644 tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/fan.wic create mode 100644 tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/mid.wic create mode 100644 tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/workflow.wic create mode 100644 tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/make.wic create mode 100644 tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/use.wic create mode 100644 tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/workflow.wic create mode 100644 tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/pair.cwl create mode 100644 tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/src.wic create mode 100644 tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/workflow.wic create mode 100644 tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/make.wic create mode 100644 tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/use.wic create mode 100644 tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/workflow.wic create mode 100644 tests/core/data/infer/calls/an_output_read_through_its_inner_port/src.wic create mode 100644 tests/core/data/infer/calls/an_output_read_through_its_inner_port/workflow.wic create mode 100644 tests/core/data/infer/calls/expected.yaml create mode 100644 tests/core/data/infer/calls/multi_file.cwl create mode 100644 tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/make.wic create mode 100644 tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/use.wic create mode 100644 tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/workflow.wic create mode 100644 tests/core/data/infer/calls/two_inputs_of_a_call_reading_one_file/fan.wic create mode 100644 tests/core/data/infer/calls/two_inputs_of_a_call_reading_one_file/workflow.wic delete mode 100644 tests/core/data/infer/cases.yaml create mode 100644 tests/core/data/infer/converters/a_break_stops_the_search/workflow.wic create mode 100644 tests/core/data/infer/converters/a_call_output_feeds_a_converter/sub.wic create mode 100644 tests/core/data/infer/converters/a_call_output_feeds_a_converter/workflow.wic create mode 100644 tests/core/data/infer/converters/expected.yaml create mode 100644 tests/core/data/infer/converters/insert_steps_automatically_conv_1.cwl create mode 100644 tests/core/data/infer/converters/insert_steps_automatically_conv_2.cwl create mode 100644 tests/core/data/infer/converters/mk_1.cwl create mode 100644 tests/core/data/infer/converters/mk_2.cwl create mode 100644 tests/core/data/infer/converters/two_insertions_reach_one_fixed_point/workflow.wic create mode 100644 tests/core/data/infer/converters/use_1.cwl create mode 100644 tests/core/data/infer/converters/use_2.cwl create mode 100644 tests/core/data/infer/duplicates/a_written_edge_and_an_inferred_one/workflow.wic create mode 100644 tests/core/data/infer/duplicates/expected.yaml create mode 100644 tests/core/data/infer/duplicates/inputs_that_declare_the_format_may_share_an_output/pair.cwl create mode 100644 tests/core/data/infer/duplicates/inputs_that_declare_the_format_may_share_an_output/workflow.wic create mode 100644 tests/core/data/infer/duplicates/one_input_without_the_evidence_refuses/pair.cwl create mode 100644 tests/core/data/infer/duplicates/one_input_without_the_evidence_refuses/workflow.wic create mode 100644 tests/core/data/infer/duplicates/two_bare_inputs_reading_one_output_refuse/workflow.wic create mode 100644 tests/core/data/infer/duplicates/two_written_edges_reading_one_output_are_meant/workflow.wic create mode 100644 tests/core/data/infer/formats/a_format_substring_is_no_candidate/consumer.cwl create mode 100644 tests/core/data/infer/formats/a_format_substring_is_no_candidate/producer.cwl create mode 100644 tests/core/data/infer/formats/a_format_substring_is_no_candidate/workflow.wic create mode 100644 tests/core/data/infer/formats/a_non_file_output_needs_no_format/consumer.cwl create mode 100644 tests/core/data/infer/formats/a_non_file_output_needs_no_format/producer.cwl create mode 100644 tests/core/data/infer/formats/a_non_file_output_needs_no_format/workflow.wic create mode 100644 tests/core/data/infer/formats/a_scatter_lifts_both_sides/file_array_sink.cwl create mode 100644 tests/core/data/infer/formats/a_scatter_lifts_both_sides/workflow.wic create mode 100644 tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/consumer.cwl create mode 100644 tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/producer.cwl create mode 100644 tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/workflow.wic create mode 100644 tests/core/data/infer/formats/expected.yaml create mode 100644 tests/core/data/infer/names/a_log_is_a_file_like_any_other/make.cwl create mode 100644 tests/core/data/infer/names/a_log_is_a_file_like_any_other/reader.cwl create mode 100644 tests/core/data/infer/names/a_log_is_a_file_like_any_other/workflow.wic create mode 100644 tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/maker.cwl create mode 100644 tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/reader.cwl create mode 100644 tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/workflow.wic create mode 100644 tests/core/data/infer/names/a_tie_settled_by_names_is_not_noted/named.cwl create mode 100644 tests/core/data/infer/names/a_tie_settled_by_names_is_not_noted/workflow.wic create mode 100644 tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/maker.cwl create mode 100644 tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/reader.cwl create mode 100644 tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/workflow.wic create mode 100644 tests/core/data/infer/names/an_output_log_feeds_an_input_log/reader.cwl create mode 100644 tests/core/data/infer/names/an_output_log_feeds_an_input_log/workflow.wic create mode 100644 tests/core/data/infer/names/consumer.cwl create mode 100644 tests/core/data/infer/names/expected.yaml create mode 100644 tests/core/data/infer/names/logger.cwl create mode 100644 tests/core/data/infer/names/naming_conventions_off_take_the_first_output/workflow.wic create mode 100644 tests/core/data/infer/names/naming_conventions_pick_the_matching_name/workflow.wic create mode 100644 tests/core/data/infer/names/producer.cwl create mode 100644 tests/core/data/infer/recency/a_lenient_compile_carries_the_note/workflow.wic create mode 100644 tests/core/data/infer/recency/a_pinned_edge_is_not_noted/workflow.wic create mode 100644 tests/core/data/infer/recency/a_strict_compile_refuses/workflow.wic create mode 100644 tests/core/data/infer/recency/a_tie_within_one_producer_names_every_fit/workflow.wic create mode 100644 tests/core/data/infer/recency/expected.yaml create mode 100644 tests/core/data/infer/recency/multi_file.cwl create mode 100644 tests/core/data/infer/recency/recency_between_producers_is_noted/workflow.wic create mode 100644 tests/core/data/infer/recency/strict_mode_turns_notes_into_errors/workflow.wic create mode 100644 tests/core/data/infer/recency/the_most_recent_step_and_its_first_output_win/workflow.wic create mode 100644 tests/core/data/infer/values/a_list_literal_under_scatter_is_unchanged/workflow.wic create mode 100644 tests/core/data/infer/values/a_scalar_literal_under_scatter_is_refused/workflow.wic create mode 100644 tests/core/data/infer/values/expected.yaml create mode 100644 tests/core/data/infer/values/falsy_defaults_satisfy_inputs/defaulted.cwl create mode 100644 tests/core/data/infer/values/falsy_defaults_satisfy_inputs/workflow.wic create mode 100644 tests/core/data/infer/values/iteration_exhaustion_is_exactly_wic022/workflow.wic create mode 100644 tests/core/data/inline/defaulted.wic create mode 100644 tests/core/data/inline/embedded/cwltool_names.cwl create mode 100644 tests/core/data/inline/embedded/cwltool_names_listed.cwl create mode 100644 tests/core/data/inline/embedded/declared.cwl create mode 100644 tests/core/data/inline/embedded/expected.yaml create mode 100644 tests/core/data/inline/embedded/listed.cwl create mode 100644 tests/core/data/inline/embedded/no_ports.cwl create mode 100644 tests/core/data/inline/embedded/no_version.cwl create mode 100644 tests/core/data/inline/embedded/v1_0.cwl create mode 100644 tests/core/data/inline/embedded/v1_0_without_hints.cwl create mode 100644 tests/core/data/inline/embedded/v1_1.cwl create mode 100644 tests/core/data/inline/embedded/v1_3_dev.cwl create mode 100644 tests/core/data/inline/expected.yaml create mode 100644 tests/core/data/inline/gated.wic create mode 100644 tests/core/data/inline/inner.wic create mode 100644 tests/core/data/inline/javascript.wic create mode 100644 tests/core/data/inline/labelled.wic create mode 100644 tests/core/data/inline/listed.wic create mode 100644 tests/core/data/inline/middle.wic create mode 100644 tests/core/data/inline/moved.wic create mode 100644 tests/core/data/inline/opted_in.wic create mode 100644 tests/core/data/inline/opted_out.wic create mode 100644 tests/core/data/inline/plain.wic create mode 100644 tests/core/data/inline/required.wic create mode 100644 tests/core/data/inline/scattered.wic create mode 100644 tests/core/data/inline/sealed.wic create mode 100644 tests/core/data/inline/sealing.wic create mode 100644 tests/core/data/inline/unbound.wic create mode 100644 tests/core/data/inline/valued.wic create mode 100644 tests/core/data/inline/workflow.wic delete mode 100644 tests/core/data/kept_calls/cases.yaml delete mode 100644 tests/core/data/lower/cases.yaml create mode 100644 tests/core/data/lower/edges.wic create mode 100644 tests/core/data/lower/empty_step_id.wic create mode 100644 tests/core/data/lower/expected.yaml create mode 100644 tests/core/data/lower/merged_outputs.wic create mode 100644 tests/core/data/lower/names.wic create mode 100644 tests/core/data/lower/outputs.wic create mode 100644 tests/core/data/lower/record_sources.wic create mode 100644 tests/core/data/lower/scatter.wic delete mode 100644 tests/core/data/nextflow/runs/conditions_and_scatter/expected.yaml delete mode 100644 tests/core/data/nextflow/runs/step_inputs/expected.yaml delete mode 100644 tests/core/data/when_boolean.yaml delete mode 100644 tests/core/test_equivalence.py delete mode 100644 tests/core/test_equivalences.py delete mode 100644 tests/core/test_generators.py delete mode 100644 tests/core/test_link.py delete mode 100644 tests/core/test_manufactured_documents.py delete mode 100644 tests/core/test_metadata_emitted.py delete mode 100644 tests/core/test_names_emitted.py delete mode 100644 tests/core/test_pipeline.py delete mode 100644 tests/core/transformations.py diff --git a/.github/workflows/lint_and_test.yml b/.github/workflows/lint_and_test.yml index 26539f2ef..ba13e5344 100644 --- a/.github/workflows/lint_and_test.yml +++ b/.github/workflows/lint_and_test.yml @@ -267,33 +267,21 @@ jobs: timeout-minutes: 20 run: cd sophios/ && pytest tests/core/test_predicates.py tests/core/test_leak_boundary.py tests/core/test_lang_version.py tests/core/test_lang_parser.py tests/core/test_hermeticity.py -m "skip_pypi_ci" - # The oracle suite: the generators, the equivalence relation and the - # suite's own hermeticity checks. Its own step, so a red build is - # attributable to a zone without bisecting. It needs nothing this matrix - # lacks: no plugins, no containers, no corpus. - # - # skip_pypi_ci excludes the per-stem `cwltool --validate` cases, for the - # reason the contrib step gives below. + # The suite's own hermeticity checks. Its own step, so a red build is + # attributable to a zone without bisecting. - name: PyTest Oracle if: ${{ !cancelled() && steps.setup.outcome == 'success' }} - run: cd sophios/ && pytest tests/core/test_hermeticity.py tests/core/test_generators.py tests/core/test_equivalence.py tests/core/test_equivalences.py -m "not skip_pypi_ci" - - # The front end's opinion of the documents the - # compiler manufactures. Its own step because a red build here means the - # compiler emitted something the language refuses — a different fact from - # a property failing, and one worth reading without bisecting. ~3s. - - name: PyTest Manufactured Documents - if: ${{ !cancelled() && steps.setup.outcome == 'success' }} - run: cd sophios/ && pytest tests/core/test_manufactured_documents.py + run: cd sophios/ && pytest tests/core/test_hermeticity.py -m "not skip_pypi_ci" - # Phase contracts plus the composed - # pipeline. It does not assert that a retired name has stayed retired -- - # a deleted symbol coming back is a review failure, and a test that - # names one can only ever restate its own deletion. + # Phase contracts, the laws every compile keeps, and the compiler judged on + # example workflows in files: what each compiles to on every leg, and what + # cwltool runs each to on POSIX. It does not assert that a retired name has + # stayed retired -- a deleted symbol coming back is a review failure, and a + # test that names one can only ever restate its own deletion. - name: PyTest IR Phases if: ${{ !cancelled() && steps.setup.outcome == 'success' }} timeout-minutes: 30 - run: cd sophios/ && pytest tests/core/test_lower.py tests/core/test_emit.py tests/core/test_resolve.py tests/core/test_link.py tests/core/test_infer_phase.py tests/core/test_pipeline.py + run: cd sophios/ && pytest tests/core/test_lower.py tests/core/test_emit.py tests/core/test_resolve.py tests/core/test_infer_phase.py tests/core/test_compiler.py # The Python API surfaces that used to be example scripts nothing executed: # `search_paths_wic` reaches the corpus repositories and docs/tutorials, diff --git a/.github/workflows/property_weekly.yml b/.github/workflows/property_weekly.yml index ba7a7f4b2..b46cb5bfd 100644 --- a/.github/workflows/property_weekly.yml +++ b/.github/workflows/property_weekly.yml @@ -82,18 +82,14 @@ jobs: # The oracle suite (tests/core/test_hermeticity.py::ORACLE_FILES) and the # phase properties beside it, slow ones included: the `--validate` # property is slow-marked, and deepening it is the point of this lane. - # test_leak_boundary.py's other tests compile against a discovered - # registry, so its five hermetic properties are named. + # test_leak_boundary.py's other test compiles against a discovered + # registry, so its hermetic property is named. - name: PyTest Oracle and Phase Properties if: ${{ !cancelled() && steps.setup.outcome == 'success' }} timeout-minutes: 180 run: >- - pytest tests/core/test_generators.py tests/core/test_equivalence.py tests/core/test_equivalences.py tests/core/test_predicates.py tests/core/test_reference_compatibility.py tests/core/test_canonical_path.py tests/core/test_emit.py tests/core/test_resolve.py tests/core/test_link.py tests/core/test_infer_phase.py tests/core/test_names_emitted.py tests/core/test_edge_binding.py tests/core/test_lower.py tests/core/test_pipeline.py - tests/core/test_leak_boundary.py::test_step_passthrough_is_byte_identical - tests/core/test_leak_boundary.py::test_top_level_passthrough_is_byte_identical - tests/core/test_leak_boundary.py::test_hints_survive_on_the_document_and_the_step_and_change_nothing_else - tests/core/test_leak_boundary.py::test_unknown_keys_change_nothing_else - tests/core/test_leak_boundary.py::test_no_key_lands_on_both_sides + pytest tests/core/test_predicates.py tests/core/test_reference_compatibility.py tests/core/test_canonical_path.py tests/core/test_emit.py tests/core/test_resolve.py tests/core/test_infer_phase.py tests/core/test_edge_binding.py tests/core/test_lower.py + tests/core/test_leak_boundary.py::test_freight_survives_byte_for_byte_and_changes_nothing_else --hypothesis-seed="$HYPOTHESIS_SEED" --junitxml=property-reports/oracle.xml # The language layer's properties. Its skip_pypi_ci tests compile against diff --git a/design_docs/one-target-table-design.md b/design_docs/one-target-table-design.md index 07b29a452..f32e722dc 100644 --- a/design_docs/one-target-table-design.md +++ b/design_docs/one-target-table-design.md @@ -227,7 +227,7 @@ cases reach each code and each family of §5 no case reached. Other tests pin th - Expectations whose text D changes by design: a workflow input of a type the target does not lower names the type (`scatter_over_an_array_typed_port`, `scatter_over_a_non_array_workflow_input`); a `when` that is text is - `wic056`'s wording (`tests/core/data/when_boolean.yaml`); the made-input test and the no-inputs `when` test read + `wic056`'s wording (`tests/core/data/compiler/when`); the made-input test and the no-inputs `when` test read the diagnostic. **Measured.** The byte harness, taught that from D on only a `NotLowered` is a refusal and any other `ValueError` a diff --git a/docs/dev/architecture.md b/docs/dev/architecture.md index a1f7e204d..c1f6dfd1d 100644 --- a/docs/dev/architecture.md +++ b/docs/dev/architecture.md @@ -42,8 +42,8 @@ real-time declarations. An idempotent completion step, run before Link and again after Infer, materialises emission facts already decided (boundary spellings, source strings); it looks nothing up and decides nothing. The phases are tested one by one (`tests/core/test_resolve.py`, -`test_lower.py`, `test_link.py`, `test_infer_phase.py`, `test_emit.py`) and -together (`test_pipeline.py`). +`test_lower.py`, `test_infer_phase.py`), together by the laws of `test_emit.py`, and +on example workflows in files (`tests/core/data/examples`, `tests/core/data/compiler`). ## Names diff --git a/docs/dev/language_spec.md b/docs/dev/language_spec.md index 330a0788c..c445b07e9 100644 --- a/docs/dev/language_spec.md +++ b/docs/dev/language_spec.md @@ -13,8 +13,8 @@ page and it are meant to agree, and where they disagree, that is a bug in one of them. Every rule here is implemented and pinned by the tests it names. One gap is known: a step input typed by a `SchemaDefRequirement` name is promoted to a workflow input without the requirement that defines the name, so cwltool -rejects the compiled workflow (`test_a_schema_def_typed_input_validates` in -`tests/core/test_emit.py`, a strict xfail). +rejects the compiled workflow (an xfail example of the validation property in +`tests/core/test_emit.py`). ## The language and its two surfaces @@ -63,15 +63,15 @@ step's tool is passthrough wholesale: Sophios does not classify | Field | Support | Note | Pinned by | |---|---|---|---| -| `class` | native | written by the compiler | `test_class_is_written_while_inputs_outputs_and_version_are_not` | -| `cwlVersion` | native | written; `wic035` for an unrunnable value | `test_class_is_written_while_inputs_outputs_and_version_are_not` | -| `doc` | passthrough | | `test_top_level_passthrough_is_byte_identical` | -| `hints` | passthrough | | `test_top_level_passthrough_is_byte_identical` | -| `id` | passthrough | | `test_top_level_passthrough_is_byte_identical` | -| `inputs` | native | merged into; the compiler wins on a collision | `test_class_is_written_while_inputs_outputs_and_version_are_not` | -| `intent` | passthrough | | `test_top_level_passthrough_is_byte_identical` | -| `label` | passthrough | | `test_top_level_passthrough_is_byte_identical` | -| `outputs` | native | read: `outputSource` is resolved; merged into | `test_class_is_written_while_inputs_outputs_and_version_are_not` | +| `class` | native | written by the compiler | `tests/core/data/compiler/boundary` | +| `cwlVersion` | native | written; `wic035` for an unrunnable value | `tests/core/data/compiler/boundary` | +| `doc` | passthrough | | `test_leak_boundary.py` | +| `hints` | passthrough | | `test_leak_boundary.py` | +| `id` | passthrough | | `test_leak_boundary.py` | +| `inputs` | native | merged into; the compiler wins on a collision | `tests/core/data/compiler/boundary` | +| `intent` | passthrough | | `test_leak_boundary.py` | +| `label` | passthrough | | `test_leak_boundary.py` | +| `outputs` | native | read: `outputSource` is resolved; merged into | `tests/core/data/compiler/boundary` | | `requirements` | native | merged into | `test_user_requirements_are_merged_into_not_copied` | | `steps` | native | | `test_a_well_formed_document_is_read_whole` (`test_lang_parser.py`) | @@ -79,17 +79,17 @@ step's tool is passthrough wholesale: Sophios does not classify | Field | Support | Note | Pinned by | |---|---|---|---| -| `doc` | passthrough | | `test_step_passthrough_is_byte_identical` | -| `hints` | passthrough | | `test_step_passthrough_is_byte_identical` | +| `doc` | passthrough | | `test_leak_boundary.py` | +| `hints` | passthrough | | `test_leak_boundary.py` | | `id` | native | `[A-Za-z0-9_-][A-Za-z0-9_.-]*`, else `wic045`, as for workflow input and output names and the root's name | `test_a_well_formed_document_is_read_whole` (`test_lang_parser.py`), `test_a_step_id_outside_the_allowed_characters_is_refused_at_its_line` (`test_diagnostics.py`) | | `in` | native | | `test_a_well_formed_document_is_read_whole` (`test_lang_parser.py`) | -| `label` | passthrough | | `test_step_passthrough_is_byte_identical` | +| `label` | passthrough | | `test_leak_boundary.py` | | `out` | native | | `test_a_construct_reads_alike_in_either_spelling_and_position` (`test_lang_parser.py`) | -| `requirements` | passthrough | | `test_step_passthrough_is_byte_identical` | +| `requirements` | passthrough | | `test_leak_boundary.py` | | `run` | native | a registry stem, a path relative to the document, or an inline body | `test_each_step_runs_the_tool_its_run_names` (`test_frontdoor.py`) | -| `scatter` | native | | `test_every_declared_key_is_interpreted` | -| `scatterMethod` | native | | `test_every_declared_key_is_interpreted` | -| `when` | native | | `test_every_declared_key_is_interpreted` | +| `scatter` | native | | `test_leak_boundary.py` | +| `scatterMethod` | native | | `test_leak_boundary.py` | +| `when` | native | | `test_leak_boundary.py` | **`WorkflowStepInput`** (an entry of a step's `in:`) @@ -109,32 +109,32 @@ step's tool is passthrough wholesale: Sophios does not classify | Field | Support | Note | Pinned by | |---|---|---|---| -| `id` | native | | `test_class_is_written_while_inputs_outputs_and_version_are_not` | -| `type` | native | | `test_an_untyped_authored_output_takes_its_producers_type` (`test_emit.py`) | -| `outputSource` | native | one step/port reference; a list is `wic038` | `test_an_authored_output_source_validates` | -| `format` | passthrough | | `test_class_is_written_while_inputs_outputs_and_version_are_not` | -| `doc` | passthrough | | `test_class_is_written_while_inputs_outputs_and_version_are_not` | -| `label` | passthrough | | `test_class_is_written_while_inputs_outputs_and_version_are_not` | -| `secondaryFiles` | passthrough | | `test_a_promoted_output_keeps_the_fields_a_workflow_output_may_state` (`test_emit.py`) | -| `streamable` | passthrough | | `test_a_promoted_output_keeps_the_fields_a_workflow_output_may_state` (`test_emit.py`) | -| `linkMerge` | rejected | `wic038` | `test_link_merge_and_pick_value_on_an_output_are_wic038` (`test_lower.py`) | -| `pickValue` | rejected | `wic038` | `test_link_merge_and_pick_value_on_an_output_are_wic038` (`test_lower.py`) | +| `id` | native | | `tests/core/data/compiler/boundary` | +| `type` | native | | `tests/core/data/compiler/sources` | +| `outputSource` | native | one step/port reference; a list is `wic038` | `test_leak_boundary.py` | +| `format` | passthrough | | `tests/core/data/compiler/boundary` | +| `doc` | passthrough | | `tests/core/data/compiler/boundary` | +| `label` | passthrough | | `tests/core/data/compiler/boundary` | +| `secondaryFiles` | passthrough | | `test_emit.py` | +| `streamable` | passthrough | | `test_emit.py` | +| `linkMerge` | rejected | `wic038` | `tests/core/data/lower` | +| `pickValue` | rejected | `wic038` | `tests/core/data/lower` | **`WorkflowInputParameter`** (an entry of the workflow's `inputs:`) | Field | Support | Note | Pinned by | |---|---|---|---| -| `id` | native | | `test_class_is_written_while_inputs_outputs_and_version_are_not` | -| `type` | native | read for the reference judgment | `test_only_proven_disjoint_cross_scope_types_are_rejected` (`test_link.py`) | -| `format` | native | read by inference | `test_promoted_input_preserves_a_cwl_format_expression` (`test_infer_phase.py`) | -| `default` | passthrough | a relative File or Directory `location`/`path` is written absolute against the `.wic`'s directory | `test_class_is_written_while_inputs_outputs_and_version_are_not`, `test_a_wic_file_default_is_written_absolute_against_the_wic` (`test_wic_defaults.py`) | +| `id` | native | | `tests/core/data/compiler/boundary` | +| `type` | native | read for the reference judgment | `tests/core/data/compiler/refused` | +| `format` | native | read by inference | `tests/core/data/compiler/boundary` | +| `default` | passthrough | a relative File or Directory `location`/`path` is written absolute against the `.wic`'s directory | `tests/core/data/compiler/boundary`, `test_a_wic_file_default_is_written_absolute_against_the_wic` (`test_wic_defaults.py`) | | `doc` | passthrough | | `test_a_referenced_input_merges_the_documentation_of_the_argument_it_binds` (`test_compiler.py`) | | `label` | passthrough | | `test_a_referenced_input_merges_the_documentation_of_the_argument_it_binds` (`test_compiler.py`) | -| `inputBinding` | passthrough | | `test_class_is_written_while_inputs_outputs_and_version_are_not` | -| `loadContents` | passthrough | | `test_a_promoted_input_keeps_the_fields_a_workflow_input_may_state` (`test_emit.py`) | -| `loadListing` | passthrough | | `test_a_promoted_input_keeps_the_fields_a_workflow_input_may_state` (`test_emit.py`) | -| `secondaryFiles` | passthrough | | `test_a_promoted_input_keeps_the_fields_a_workflow_input_may_state` (`test_emit.py`) | -| `streamable` | passthrough | | `test_a_promoted_input_keeps_the_fields_a_workflow_input_may_state` (`test_emit.py`) | +| `inputBinding` | passthrough | | `tests/core/data/compiler/boundary` | +| `loadContents` | passthrough | | `test_emit.py` | +| `loadListing` | passthrough | | `test_emit.py` | +| `secondaryFiles` | passthrough | | `test_emit.py` | +| `streamable` | passthrough | | `test_emit.py` | ### 1.1 The native rows of `Workflow` @@ -172,12 +172,7 @@ step's tool is passthrough wholesale: Sophios does not classify ports use a prefix do not all bind it to one URI, that is `wic031`; a tool that binds the prefix differently but promotes no port using it conflicts with nothing, so the result does not depend on how the workflow is split - into subworkflows. Pinned by - `test_user_namespaces_survive_and_edam_is_edams_where_a_format_says_it`, the - tests of `test_metadata_emitted.py`, and in `test_emit.py` by - `test_a_prefix_two_promoting_sources_bind_differently_is_reported`, - `test_a_clash_on_a_prefix_no_promoted_format_uses_is_no_error` and - `test_a_step_promoting_no_format_with_a_prefix_is_no_source_for_it_wherever_it_sits`. + into subworkflows. Pinned by the example `tests/core/data/compiler/boundary`. ### 1.3 Passthrough diff --git a/src/sophios/lang/support.py b/src/sophios/lang/support.py index d6cac7368..2d9ec976c 100644 --- a/src/sophios/lang/support.py +++ b/src/sophios/lang/support.py @@ -34,13 +34,13 @@ class Row: _N, _P, _R = Support.NATIVE, Support.PASSTHROUGH, Support.REJECTED -_WRITTEN: Final = 'test_class_is_written_while_inputs_outputs_and_version_are_not' -_TOP_LEVEL: Final = 'test_top_level_passthrough_is_byte_identical' -_STEP: Final = 'test_step_passthrough_is_byte_identical' -_INTERPRETED: Final = 'test_every_declared_key_is_interpreted' -_OUTPUT_MERGE: Final = 'test_link_merge_and_pick_value_on_an_output_are_wic038' -_PROMOTED_INPUT: Final = 'test_a_promoted_input_keeps_the_fields_a_workflow_input_may_state' -_PROMOTED_OUTPUT: Final = 'test_a_promoted_output_keeps_the_fields_a_workflow_output_may_state' +_WRITTEN: Final = 'test_a_compiler_example_compiles_as_it_states' +_TOP_LEVEL: Final = 'test_freight_survives_byte_for_byte_and_changes_nothing_else' +_STEP: Final = 'test_freight_survives_byte_for_byte_and_changes_nothing_else' +_INTERPRETED: Final = 'test_freight_survives_byte_for_byte_and_changes_nothing_else' +_OUTPUT_MERGE: Final = 'test_a_document_lowers_to_the_diagnostics_its_family_states' +_PROMOTED_INPUT: Final = 'test_a_promoted_port_keeps_the_fields_a_workflow_port_may_state' +_PROMOTED_OUTPUT: Final = 'test_a_promoted_port_keeps_the_fields_a_workflow_port_may_state' _DOCUMENTED: Final = 'test_a_referenced_input_merges_the_documentation_of_the_argument_it_binds' _RECORD: Final = 'test_a_cwl_record_emits_the_fields_it_carries' @@ -88,8 +88,8 @@ class Row: WORKFLOW_OUTPUT_PARAMETER: Final[Mapping[str, Row]] = MappingProxyType({ 'id': Row(_N, _WRITTEN), - 'type': Row(_N, 'test_an_untyped_authored_output_takes_its_producers_type'), - 'outputSource': Row(_N, 'test_an_authored_output_source_validates', 'one step/port reference; a list is wic038'), + 'type': Row(_N, 'test_a_compiler_example_compiles_as_it_states'), + 'outputSource': Row(_N, 'test_residue_validates_as_cwl_v1_2', 'one step/port reference; a list is wic038'), 'format': Row(_P, _WRITTEN), 'doc': Row(_P, _WRITTEN), 'label': Row(_P, _WRITTEN), @@ -101,8 +101,8 @@ class Row: WORKFLOW_INPUT_PARAMETER: Final[Mapping[str, Row]] = MappingProxyType({ 'id': Row(_N, _WRITTEN), - 'type': Row(_N, 'test_only_proven_disjoint_cross_scope_types_are_rejected', 'read for the reference judgment'), - 'format': Row(_N, 'test_promoted_input_preserves_a_cwl_format_expression', 'read by inference'), + 'type': Row(_N, 'test_a_compiler_example_compiles_as_it_states', 'read for the reference judgment'), + 'format': Row(_N, 'test_a_compiler_example_compiles_as_it_states', 'read by inference'), 'default': Row(_P, _WRITTEN), 'doc': Row(_P, _DOCUMENTED), 'label': Row(_P, _DOCUMENTED), diff --git a/tests/core/ast_strategies.py b/tests/core/ast_strategies.py index b3578642d..e87f005f9 100644 --- a/tests/core/ast_strategies.py +++ b/tests/core/ast_strategies.py @@ -1,13 +1,13 @@ """Strategies over the language AST, rendered and re-parsed by `parse` before compiling, so writer and reader must agree and a counterexample shrinks to a minimal document; stems and bindings name synthetic_tools' real ports.""" import copy -from typing import Any, Callable, Final, cast +from typing import Any, Final, cast from hypothesis import strategies as st from hypothesis.strategies import SearchStrategy from sophios import utils_cwl -from sophios.lang import (SophiosErrorCode, CwlRecord, Document, EdgeDef, EdgeRef, Grammar, InlineLiteral, InputValue, +from sophios.lang import (CwlRecord, Document, EdgeDef, EdgeRef, Grammar, InlineLiteral, InputValue, OpaqueCwl, OutputBinding, RawCwlRef, Step, StepKey, UnresolvedName, WicSidecar, parse, render, to_json) from sophios.lang.spans import SourceSpan @@ -19,60 +19,6 @@ #: The one span generated nodes carry: they have no source, and nothing downstream reads it. _SPAN: Final = SourceSpan('', 1, 1, 1, 1) -#: Kinds the generator cannot draw, each with its reason; an InputValue member in neither this nor CONSTRUCTS fails -#: test_the_construct_inventory_accounts_for_every_input_kind. -NOT_GENERATED: Final[dict[str, str]] = {} - -#: The construct kinds the coverage property demands, from the .wic reference's tables rather than the strategy, so a -#: kind the strategy stops producing fails instead of narrowing silently. -CONSTRUCTS: Final[tuple[str, ...]] = ( - 'steps_mapping', 'steps_sequence', - 'inline_literal', 'edge_ref', 'raw_cwl_ref', 'unresolved_name', 'cwl_record', - 'output_bare', 'output_edge', - 'interpreted_scatter', 'interpreted_scatterMethod', 'interpreted_when', - 'step_passthrough', 'top_passthrough', - 'sidecar', 'sidecar_steps', - 'subworkflow', 'inferred_input', -) - - -def constructs_in(document: Document) -> frozenset[str]: - """Which construct kinds a document contains: one place, so coverage and the strategy agree on what one is.""" - # pylint: disable=too-many-branches # one branch per construct kind, by design - found = {'steps_mapping' if document.steps_as_mapping else 'steps_sequence'} - if document.passthrough: - found.add('top_passthrough') - if document.sidecar is not None: - found.add('sidecar') - if document.sidecar.steps: - found.add('sidecar_steps') - for step in document.steps: - if step.id.endswith('.wic'): - found.add('subworkflow') - if step.passthrough: - found.add('step_passthrough') - for key, _ in step.interpreted: - found.add(f'interpreted_{key}') - for binding in step.outputs: - found.add('output_edge' if binding.edge_def is not None else 'output_bare') - bound = {name for name, _ in step.inputs} - for _, value in step.inputs: - match value: - case InlineLiteral(): - found.add('inline_literal') - case EdgeRef(): - found.add('edge_ref') - case RawCwlRef(): - found.add('raw_cwl_ref') - case CwlRecord(): - found.add('cwl_record') - case _: - found.add('unresolved_name') - if not step.id.endswith('.wic') and set(required_inputs_of(step.id)) - bound: - found.add('inferred_input') - return frozenset(found) - - literals: Final = st.one_of( st.text('abcxyz_.', min_size=1, max_size=8), st.integers(min_value=-4, max_value=4), @@ -288,8 +234,9 @@ def literal(name: str) -> InlineLiteral: @st.composite def documents(draw: st.DrawFn) -> Document: # pylint: disable=too-many-locals - """A well-formed document over every construct in CONSTRUCTS, well typed where it binds a literal, in both forms. - Mapping-form stems are drawn unique up front: a step drawn then discarded would leave its `!&` names dangling.""" + """A well-formed document over every construct the .wic reference tabulates, well typed where it binds a literal, + in both forms. Mapping-form stems are drawn unique up front: a step drawn then discarded would leave its `!&` names + dangling.""" as_mapping = draw(st.booleans()) stems = draw(st.lists(st.sampled_from(STEMS), min_size=1, max_size=4, unique=as_mapping)) @@ -334,30 +281,6 @@ def documents(draw: st.DrawFn) -> Document: # pylint: disable=too-many-locals steps_as_mapping=as_mapping) -#: Constructs the specification admits and the compiler does not accept yet, each with its finding; -#: test_the_compilable_subset_still_reaches_every_construct_it_does_not_exclude holds the filter to construct coverage. -NOT_YET_COMPILABLE: Final[dict[str, str]] = {} - - -#: One predicate per NOT_YET_COMPILABLE entry, keyed identically, as the assertion below checks. -_EXCLUSION_PREDICATES: Final[dict[str, Callable[[Document], bool]]] = {} -assert NOT_YET_COMPILABLE.keys() == _EXCLUSION_PREDICATES.keys(), ( - 'NOT_YET_COMPILABLE and _EXCLUSION_PREDICATES must name exactly the same exclusions') - - -def compilable_documents() -> SearchStrategy[Document]: - """`documents()` minus what NOT_YET_COMPILABLE names: the compile-driving properties need input that compiles, the - parse-level ones keep the whole language.""" - # pylint: disable=no-member # see workflows()'s identical disable, below - return documents().filter(lambda d: not any(pred(d) for pred in _EXCLUSION_PREDICATES.values())) - - -def excluded_documents(name: str) -> SearchStrategy[Document]: - """Documents that trip the named exclusion, so its predicate's excuse can be shown still true.""" - # pylint: disable=no-member # see workflows()'s identical disable, below - return documents().filter(_EXCLUSION_PREDICATES[name]) - - #: The bodies a subworkflow step's id selects, by its stem less the appended index; each literal is a child job value #: Complete lifts to the caller, and `decl` declares an input its caller binds and may scatter over. SUBWORKFLOW_BODIES: Final[dict[str, Yaml]] = { @@ -389,8 +312,8 @@ def to_yml(document: Document) -> Yaml: def workflows() -> SearchStrategy[Yaml]: - """The strategy the compile-driving properties quantify over: `compilable_documents()` through `to_yml`.""" - return compilable_documents().map(to_yml) + """The strategy the compile-driving properties quantify over: `documents()` through `to_yml`.""" + return documents().map(to_yml) # pylint: disable=no-member #: `join` is absent: its `left` and `right` would be inferred from one output, which inference refuses (wic055). @@ -433,37 +356,6 @@ def to_yml_with_freight(document: Document, step_index: int, freight: dict[str, return loaded -@st.composite -def partitionings(draw: st.DrawFn, steps: int) -> tuple[tuple[int, ...], ...]: - """A contiguous grouping of `range(steps)`: a subworkflow is the steps written in one file, so nothing else is - expressible.""" - if steps <= 1: - return ((0,),) if steps else () - cuts = sorted(draw(st.lists(st.integers(min_value=1, max_value=steps - 1), unique=True, max_size=steps - 1))) - bounds = [0, *cuts, steps] - return tuple(tuple(range(a, b)) for a, b in zip(bounds, bounds[1:])) - - -#: Ill-formed source paired with the code it must provoke: a bare string would accept the wrong diagnostic. -_HOSTILE: Final = ( - ('steps:\n s:\n in:\n f: !ii a\n f: !ii b\n', SophiosErrorCode.DUPLICATE_KEY), - ('steps:\n- id: s\n in:\n f: !foo bar\n', SophiosErrorCode.UNKNOWN_TAG), - ('steps:\n- id: ""\n', SophiosErrorCode.EMPTY_STEP_ID), - # A sequence step names itself in `id:`, so an entry without one earns MISSING_STEP_ID. - ('steps:\n- {}\n', SophiosErrorCode.MISSING_STEP_ID), - ('steps:\n- id: s\n out: {a: b}\n', SophiosErrorCode.EXPECTED_SEQUENCE), - ('steps: 3\n', SophiosErrorCode.EXPECTED_MAPPING), - # A step's own `wic:` key is passthrough: the malformed key must live in the document-level `wic: steps:`. - ('wic:\n steps:\n "not a key": {}\n', SophiosErrorCode.MALFORMED_WIC_STEP_KEY), - ('steps: &a\n- id: s\n wic: {x: *a}\n', SophiosErrorCode.RECURSIVE_ALIAS), -) - - -def hostile_documents() -> SearchStrategy[tuple[str, SophiosErrorCode]]: - """Documents outside the language, each with the code it must earn.""" - return st.sampled_from(_HOSTILE) - - #: Keys and JSON-shaped values the language does not claim and must preserve. #: `requirements` and `hints` are claimed: the parser reads their list form as a mapping. CLAIMED_STEP_KEYS: Final = (frozenset({'id', 'in', 'out', 'wic', 'requirements', 'hints'}) diff --git a/tests/core/cases.py b/tests/core/cases.py index b23c54f0c..d167cc314 100644 --- a/tests/core/cases.py +++ b/tests/core/cases.py @@ -7,10 +7,11 @@ - `{startswith: text}`: text starting with `text` - `{contains: [item, ...]}`: text holding each item, or a list in which each item matches some element - `{exact: value}`: equal to `value`, so a mapping with any other key fails +- `{keys: [key, ...]}`: a mapping with exactly these keys, in this order - any other mapping: a mapping with at least its keys, each value matching - a list: a list of the same length, matching element by element - anything else: an equal value -A mapping whose one key is re, startswith, contains or exact is therefore always a form, never data. +A mapping whose one key is re, startswith, contains, exact or keys is therefore always a form, never data. `contains: []` matches nothing, so an empty list cannot pass for an expectation. The loaders raise ValueError, a collection error of the calling module, for no cases, a repeated id, or a key the @@ -101,6 +102,8 @@ def match(expected: Any, actual: Any) -> bool: # pylint: disable=too-many-retur else any(match(item, each) for each in actual) for item in given) if form == 'exact': return bool(actual == given) + if form == 'keys': + return isinstance(actual, dict) and list(actual) == given if isinstance(expected, dict): return isinstance(actual, dict) and all(key in actual and match(value, actual[key]) for key, value in expected.items()) diff --git a/tests/core/data/compiler/boundary/a_class_with_no_body.wic b/tests/core/data/compiler/boundary/a_class_with_no_body.wic new file mode 100644 index 000000000..7733db2d5 --- /dev/null +++ b/tests/core/data/compiler/boundary/a_class_with_no_body.wic @@ -0,0 +1,4 @@ +# Held today: a requirement written with no body, which nothing needs, stays null in the compiled CWL, which cwltool +# refuses; it should be the empty body {}. +requirements: {ResourceRequirement: null} +steps: [{id: mk_file, in: {name: {wic_inline_input: a}}}] diff --git a/tests/core/data/compiler/boundary/authored.wic b/tests/core/data/compiler/boundary/authored.wic new file mode 100644 index 000000000..630eebc6a --- /dev/null +++ b/tests/core/data/compiler/boundary/authored.wic @@ -0,0 +1,7 @@ +# The author's own binding of a prefix their formats use is theirs: probe's port is bound, so probe promotes none. +$namespaces: {myns: 'http://other.example/'} +inputs: + x: {type: File, format: 'myns:format_1'} +steps: +- id: probe + in: {f: x} diff --git a/tests/core/data/compiler/boundary/both.wic b/tests/core/data/compiler/boundary/both.wic new file mode 100644 index 000000000..14ca72394 --- /dev/null +++ b/tests/core/data/compiler/boundary/both.wic @@ -0,0 +1,3 @@ +steps: +- id: probe +- id: rival diff --git a/tests/core/data/compiler/boundary/bystander.cwl b/tests/core/data/compiler/boundary/bystander.cwl new file mode 100644 index 000000000..42bf3f73d --- /dev/null +++ b/tests/core/data/compiler/boundary/bystander.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {myns: 'http://other.example/', elsens: 'http://else.example/'} +inputs: {g: File} +outputs: {} diff --git a/tests/core/data/compiler/boundary/called.wic b/tests/core/data/compiler/boundary/called.wic new file mode 100644 index 000000000..05445e8d1 --- /dev/null +++ b/tests/core/data/compiler/boundary/called.wic @@ -0,0 +1,2 @@ +steps: +- id: probe diff --git a/tests/core/data/compiler/boundary/clash_beneath.wic b/tests/core/data/compiler/boundary/clash_beneath.wic new file mode 100644 index 000000000..c981233fc --- /dev/null +++ b/tests/core/data/compiler/boundary/clash_beneath.wic @@ -0,0 +1,3 @@ +steps: +- id: called.wic +- id: rival diff --git a/tests/core/data/compiler/boundary/clash_document.wic b/tests/core/data/compiler/boundary/clash_document.wic new file mode 100644 index 000000000..9a60cba01 --- /dev/null +++ b/tests/core/data/compiler/boundary/clash_document.wic @@ -0,0 +1,4 @@ +# probe's myns:format_1 against the document's own myns: neither binding is kept. +$namespaces: {myns: 'http://other.example/'} +steps: +- id: probe diff --git a/tests/core/data/compiler/boundary/clash_inside.wic b/tests/core/data/compiler/boundary/clash_inside.wic new file mode 100644 index 000000000..25baecf9f --- /dev/null +++ b/tests/core/data/compiler/boundary/clash_inside.wic @@ -0,0 +1,2 @@ +steps: +- id: both.wic diff --git a/tests/core/data/compiler/boundary/clash_tools.wic b/tests/core/data/compiler/boundary/clash_tools.wic new file mode 100644 index 000000000..2073709d0 --- /dev/null +++ b/tests/core/data/compiler/boundary/clash_tools.wic @@ -0,0 +1,4 @@ +# probe and rival bind myns differently, and both promote a myns: port. +steps: +- id: probe +- id: rival diff --git a/tests/core/data/compiler/boundary/edam_authored.wic b/tests/core/data/compiler/boundary/edam_authored.wic new file mode 100644 index 000000000..cd5487c46 --- /dev/null +++ b/tests/core/data/compiler/boundary/edam_authored.wic @@ -0,0 +1,6 @@ +# Each File format a runner reads against `$namespaces` needs edam bound; no ontology is added. +inputs: + f: {type: File, format: "edam:format_2330"} +steps: +- id: count + in: {file: f} diff --git a/tests/core/data/compiler/boundary/edam_default.wic b/tests/core/data/compiler/boundary/edam_default.wic new file mode 100644 index 000000000..989a2a140 --- /dev/null +++ b/tests/core/data/compiler/boundary/edam_default.wic @@ -0,0 +1,5 @@ +inputs: + f: {type: File, default: {class: File, location: x.txt, format: "edam:format_2330"}} +steps: +- id: count + in: {file: f} diff --git a/tests/core/data/compiler/boundary/edam_job.wic b/tests/core/data/compiler/boundary/edam_job.wic new file mode 100644 index 000000000..fda3928e5 --- /dev/null +++ b/tests/core/data/compiler/boundary/edam_job.wic @@ -0,0 +1,3 @@ +steps: +- id: count + in: {file: !ii {class: File, location: x.txt, format: "edam:format_2330"}} diff --git a/tests/core/data/compiler/boundary/edam_promoted.wic b/tests/core/data/compiler/boundary/edam_promoted.wic new file mode 100644 index 000000000..583422fc3 --- /dev/null +++ b/tests/core/data/compiler/boundary/edam_promoted.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file # its promoted output says edam:format_2330 diff --git a/tests/core/data/compiler/boundary/edam_step_default.wic b/tests/core/data/compiler/boundary/edam_step_default.wic new file mode 100644 index 000000000..9fb9bac2a --- /dev/null +++ b/tests/core/data/compiler/boundary/edam_step_default.wic @@ -0,0 +1,3 @@ +steps: +- id: count + in: {file: !cwl {default: {class: File, location: x.txt, format: "edam:format_2330"}}} diff --git a/tests/core/data/compiler/boundary/elsewhere.cwl b/tests/core/data/compiler/boundary/elsewhere.cwl new file mode 100644 index 000000000..cc74dcdbf --- /dev/null +++ b/tests/core/data/compiler/boundary/elsewhere.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {myns: 'http://other.example/', elsens: 'http://else.example/'} +inputs: {g: {type: File, format: 'elsens:format_2'}} +outputs: {} diff --git a/tests/core/data/compiler/boundary/expected.yaml b/tests/core/data/compiler/boundary/expected.yaml new file mode 100644 index 000000000..a2d03c95f --- /dev/null +++ b/tests/core/data/compiler/boundary/expected.yaml @@ -0,0 +1,62 @@ +# The keys a compiled document's boundary holds, by hand from each root's comments. +owned.wic: + written: + owned.cwl: + class: Workflow + cwlVersion: v1.2 + $namespaces: {exact: {mine: 'https://mine/', edam: 'https://edamontology.org/'}} + $schemas: [https://example.org/ontologies/mine.owl] + inputs: {mine: string, mk_file~name: {type: {type: array, items: string}}} + outputs: {mine: {type: 'File[]', outputSource: mk_file/file}, mk_file~file: {format: 'edam:format_2330'}} + requirements: [{$import: shared.yml}] + hints: [{$import: shared.yml}, {class: ResourceRequirement, coresMin: 1}] + steps: [{id: mk_file, requirements: [{$import: shared.yml}, {class: ResourceRequirement, coresMin: 1}], + hints: [{$import: shared.yml}]}] +a_class_with_no_body.wic: {written: {a_class_with_no_body.cwl: {requirements: {exact: {ResourceRequirement: null}}}}} +imported_ports.wic: + written: + imported_ports.cwl: + $namespaces: {exact: {mine: 'https://mine/', edam: 'https://not-edam/'}} + inputs: {exact: {count~file: {type: File}}} + outputs: {exact: {count~n: {type: int, outputSource: count/n}}} +no_edam.wic: {files: [no_edam.cwl, no_edam_inputs.yml, no_edam~count.cwl], written: {no_edam.cwl: {keys: [steps, + cwlVersion, class, inputs, outputs]}}} +edam_authored.wic: {written: {edam_authored.cwl: {$namespaces: {exact: {edam: 'https://edamontology.org/'}}}}} +edam_promoted.wic: {written: {edam_promoted.cwl: {$namespaces: {exact: {edam: 'https://edamontology.org/'}}}}} +edam_job.wic: {written: {edam_job.cwl: {$namespaces: {exact: {edam: 'https://edamontology.org/'}}}}} +edam_default.wic: {written: {edam_default.cwl: {$namespaces: {exact: {edam: 'https://edamontology.org/'}}}}} +edam_step_default.wic: {written: {edam_step_default.cwl: {$namespaces: {exact: {edam: 'https://edamontology.org/'}}}}} +prefixes.wic: + written: + prefixes.cwl: + $namespaces: {exact: {myns: 'http://tool.example/', elsens: 'http://else.example/', + edam: 'https://edamontology.org/'}} + inputs: + called~probe~f: {format: 'myns:format_1'} + probe~f: {format: 'myns:format_1'} + twin~f: {format: 'myns:format_1'} + elsewhere~g: {format: 'elsens:format_2'} + outputs: {maker~o: {format: 'myns:format_1'}, mk_file~file: {format: 'edam:format_2330'}} + prefixes~called.cwl: {$namespaces: {exact: {myns: 'http://tool.example/'}}} + prefixes~through.cwl: {$namespaces: {exact: {myns: 'http://tool.example/'}}, inputs: {probe~f: {format: 'myns:format_1'}}} +authored.wic: + written: {authored.cwl: {$namespaces: {exact: {myns: 'http://other.example/'}}}} +# Two sources binding one prefix a promoted format uses differently: neither binding is kept, and wic031 names both. +clash_document.wic: + refused: [{code: DUPLICATE_DOCUMENT_NAME, severity: error, step: probe, + message: {contains: ["'myns'", "'http://other.example/'", this document, "'http://tool.example/'"]}}] +clash_tools.wic: + refused: [{code: DUPLICATE_DOCUMENT_NAME, severity: error, step: rival, + message: {contains: ["'myns'", "step 'probe'", "'http://tool.example/'", "step 'rival'"]}}] +clash_beneath.wic: + refused: [{code: DUPLICATE_DOCUMENT_NAME, severity: error, step: rival, + message: {contains: ["'myns'", "step 'called.wic'", "step 'rival'", "'http://other.example/'"]}}] +clash_inside.wic: + refused: [{code: DUPLICATE_DOCUMENT_NAME, severity: error, step: rival, + message: {contains: ["workflow 'both'", "step 'probe'", "step 'rival'"]}}] +format_expression.wic: + written: + format_expression.cwl: + inputs: + formatted~reference: {format: $(inputs.source.format)} + formatted~body: {format: '${ return inputs.source.format; }'} diff --git a/tests/core/data/compiler/boundary/format_expression.wic b/tests/core/data/compiler/boundary/format_expression.wic new file mode 100644 index 000000000..5e9073667 --- /dev/null +++ b/tests/core/data/compiler/boundary/format_expression.wic @@ -0,0 +1,4 @@ +# A promoted input carries its tool's `format` as written, an expression too, the spelling a rewrite would most +# likely break. +steps: +- id: formatted diff --git a/tests/core/data/compiler/boundary/formatted.cwl b/tests/core/data/compiler/boundary/formatted.cwl new file mode 100644 index 000000000..2fb69d8ec --- /dev/null +++ b/tests/core/data/compiler/boundary/formatted.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +requirements: {InlineJavascriptRequirement: {}} +inputs: + source: File + reference: {type: File, format: $(inputs.source.format)} + body: {type: File, format: '${ return inputs.source.format; }'} +outputs: {} diff --git a/tests/core/data/compiler/boundary/grand.wic b/tests/core/data/compiler/boundary/grand.wic new file mode 100644 index 000000000..730c50a6a --- /dev/null +++ b/tests/core/data/compiler/boundary/grand.wic @@ -0,0 +1,3 @@ +steps: +- id: probe + in: {f: !* shared} diff --git a/tests/core/data/compiler/boundary/imported_ports.wic b/tests/core/data/compiler/boundary/imported_ports.wic new file mode 100644 index 000000000..17ea7ea8a --- /dev/null +++ b/tests/core/data/compiler/boundary/imported_ports.wic @@ -0,0 +1,8 @@ +# `inputs:` and `outputs:` lists holding an `$import` are neither merged nor emitted: the compiler models the mapping. +$namespaces: {mine: 'https://mine/', edam: 'https://not-edam/'} # no format says edam:, so both are the author's +inputs: +- $import: shared.yml +outputs: +- $import: shared.yml +steps: +- id: count diff --git a/tests/core/data/compiler/boundary/maker.cwl b/tests/core/data/compiler/boundary/maker.cwl new file mode 100644 index 000000000..f7da7c342 --- /dev/null +++ b/tests/core/data/compiler/boundary/maker.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {myns: 'http://tool.example/'} +inputs: {} +outputs: {o: {type: File, format: 'myns:format_1', outputBinding: {glob: o}}} diff --git a/tests/core/data/compiler/boundary/no_edam.wic b/tests/core/data/compiler/boundary/no_edam.wic new file mode 100644 index 000000000..0af24f0c9 --- /dev/null +++ b/tests/core/data/compiler/boundary/no_edam.wic @@ -0,0 +1,3 @@ +# Nothing says edam:, so nothing binds a prefix or names an ontology. +steps: +- id: count diff --git a/tests/core/data/compiler/boundary/owned.wic b/tests/core/data/compiler/boundary/owned.wic new file mode 100644 index 000000000..66f92f35d --- /dev/null +++ b/tests/core/data/compiler/boundary/owned.wic @@ -0,0 +1,25 @@ +# The keys the compiler owns, each its own way: `class` and `cwlVersion` are written over what the author wrote, +# `inputs` and `outputs` merged into, `$namespaces` and `$schemas` kept. A `requirements:` or `hints:` list holding +# an `$import`, which only cwltool reads, is emitted as written, not merged into, though a step scatters. +class: ExpressionTool # not what a .wic compiles to +cwlVersion: v1.0 # Sophios writes one CWL version +$namespaces: {mine: 'https://mine/', edam: 'https://not-edam/'} # mine is kept; edam:, which a format says, is EDAM's +$schemas: [https://example.org/ontologies/mine.owl] # the author's ontology, and no other +inputs: + mine: string +outputs: + mine: {type: 'File[]', outputSource: mk_file/file} +requirements: +- $import: shared.yml +hints: +- $import: shared.yml +- {class: ResourceRequirement, coresMin: 1} +steps: +- id: mk_file + in: {name: !ii [a.txt, b.txt]} + scatter: [name] + requirements: + - $import: shared.yml + - {class: ResourceRequirement, coresMin: 1} + hints: + - $import: shared.yml diff --git a/tests/core/data/compiler/boundary/prefixes.wic b/tests/core/data/compiler/boundary/prefixes.wic new file mode 100644 index 000000000..d04827484 --- /dev/null +++ b/tests/core/data/compiler/boundary/prefixes.wic @@ -0,0 +1,13 @@ +# A promoted port keeps its tool's CURIE, so the document promoting it declares the prefix. Tools agreeing on a +# prefix are no conflict; a tool binding a prefix no promoted port uses is no source for it; `edam` is the compiler's. +steps: +- id: called.wic # promotes probe's port from beneath a call +- id: probe # myns: tool.example; also edam over http and s over http +- id: twin # myns: tool.example too; edam over https, s over https +- id: maker # promotes an output in myns: +- id: bystander # binds myns elsewhere, but promotes no myns: port +- id: elsewhere # promotes an elsens: port +- id: mk_file # promotes edam:format_2330 + in: {name: !ii x} + out: [file: !& shared] +- id: through.wic # an edge into a grandchild promotes its port through the child, which declares the prefix diff --git a/tests/core/data/compiler/boundary/probe.cwl b/tests/core/data/compiler/boundary/probe.cwl new file mode 100644 index 000000000..ad029d609 --- /dev/null +++ b/tests/core/data/compiler/boundary/probe.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {myns: 'http://tool.example/', edam: 'http://edamontology.org/', s: 'http://schema.org/'} +inputs: {f: {type: File, format: 'myns:format_1'}} +outputs: {} diff --git a/tests/core/data/compiler/boundary/rival.cwl b/tests/core/data/compiler/boundary/rival.cwl new file mode 100644 index 000000000..ca0b7a7f5 --- /dev/null +++ b/tests/core/data/compiler/boundary/rival.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {myns: 'http://other.example/'} +inputs: {g: {type: File, format: 'myns:format_1'}} +outputs: {} diff --git a/tests/core/data/compiler/boundary/through.wic b/tests/core/data/compiler/boundary/through.wic new file mode 100644 index 000000000..0e12fcc69 --- /dev/null +++ b/tests/core/data/compiler/boundary/through.wic @@ -0,0 +1,2 @@ +steps: +- id: grand.wic diff --git a/tests/core/data/compiler/boundary/twin.cwl b/tests/core/data/compiler/boundary/twin.cwl new file mode 100644 index 000000000..c0c27f22f --- /dev/null +++ b/tests/core/data/compiler/boundary/twin.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {myns: 'http://tool.example/', edam: 'https://edamontology.org/', s: 'https://schema.org/'} +inputs: {f: {type: File, format: 'myns:format_1'}} +outputs: {} diff --git a/tests/core/data/compiler/names/a/echo.cwl b/tests/core/data/compiler/names/a/echo.cwl new file mode 100644 index 000000000..35c29cad6 --- /dev/null +++ b/tests/core/data/compiler/names/a/echo.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: echo +inputs: {a: string} +outputs: {} diff --git a/tests/core/data/compiler/names/b/echo.cwl b/tests/core/data/compiler/names/b/echo.cwl new file mode 100644 index 000000000..a045d243d --- /dev/null +++ b/tests/core/data/compiler/names/b/echo.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: rm +inputs: {a: string} +outputs: {} diff --git a/tests/core/data/compiler/names/child.wic b/tests/core/data/compiler/names/child.wic new file mode 100644 index 000000000..7908a4c5c --- /dev/null +++ b/tests/core/data/compiler/names/child.wic @@ -0,0 +1,8 @@ +inputs: + file: File +steps: +- id: inner.wic +- id: xform + in: {file: file} +outputs: + file: {outputSource: xform/file} diff --git a/tests/core/data/compiler/names/expected.yaml b/tests/core/data/compiler/names/expected.yaml new file mode 100644 index 000000000..3f18dffd2 --- /dev/null +++ b/tests/core/data/compiler/names/expected.yaml @@ -0,0 +1,56 @@ +# Both roots are written into one directory, the second after the first, so a file the second overwrote fails the +# first's statement. A step is `@` exactly when another id, or a workflow input, casefolds to its id; +# a made name is `~`; each document is `~
.cwl`, its address the calls above it. +greeting.wic: + # One file per step, not per tool: the three xform files are three, and none is a device name. + files: [greeting.cwl, greeting_inputs.yml, greeting~Touch@6.cwl, greeting~child@1.cwl, greeting~child@1~inner.cwl, + greeting~child@1~inner~mk_file.cwl, greeting~child@1~xform.cwl, greeting~child@2.cwl, + greeting~child@2~inner.cwl, greeting~child@2~inner~mk_file.cwl, greeting~child@2~xform.cwl, + greeting~child@3.cwl, greeting~con.cwl, greeting~echo@4.cwl, greeting~greeting__step__1__mk_file.cwl, + greeting~hello.cwl, greeting~mk_file.cwl, greeting~probe.cwl, greeting~shout.cwl, greeting~touch@7.cwl, + greeting~xform@10.cwl, greeting~xform@8.cwl, greeting~xform@9.cwl] + notes: # each input inference gave a value, at the step that reads it (the guesses themselves are inference's) + - {code: INFERENCE_GUESS, severity: note, step: child.wic, index: 2, port: file} + - {code: INFERENCE_GUESS, severity: note, step: child, index: 3, port: file} + - {code: INFERENCE_GUESS, severity: note, step: xform, index: 8, port: file} + - {code: INFERENCE_GUESS, severity: note, step: xform, index: 9, port: file} + - {code: INFERENCE_GUESS, severity: note, step: xform, index: 10, port: file} + written: + greeting.cwl: + steps: + - {id: child@1, run: greeting~child@1.cwl} + - {id: child@2, run: greeting~child@2.cwl, in: {file: child@1/xform~file}} + - {id: child@3, run: greeting~child@3.cwl, in: {file: child@2/xform~file}} + - {id: echo@4, run: greeting~echo@4.cwl, in: {name: echo}} + - {id: mk_file, run: greeting~mk_file.cwl} + - {id: Touch@6, run: greeting~Touch@6.cwl} + - {id: touch@7, run: greeting~touch@7.cwl} + - {id: xform@8, run: greeting~xform@8.cwl, in: {file: touch@7/file}} + - {id: xform@9, run: greeting~xform@9.cwl, in: {file: xform@8/file}} + - {id: xform@10, run: greeting~xform@10.cwl, in: {file: xform@9/file}} + - {id: con, run: greeting~con.cwl} + - {id: greeting__step__1__mk_file, run: greeting~greeting__step__1__mk_file.cwl} + - {id: hello, run: greeting~hello.cwl} + - {id: shout, run: greeting~shout.cwl} + - {id: probe, run: greeting~probe.cwl, in: {a~b: probe~a~b}} + inputs: {keys: [echo, mk_file__name, child@1~file, child@1~inner~mk_file~name, child@1~xform~name, + child@2~inner~mk_file~name, child@2~xform~name, mk_file~name, Touch@6~name, touch@7~name, + xform@8~name, xform@9~name, xform@10~name, con~name, greeting__step__1__mk_file~name, + hello~a, shout~a, probe~a~b]} + outputs: + generated: {outputSource: greeting__step__1__mk_file/file} + child@1~inner~mk_file~file: {outputSource: child@1/inner~mk_file~file} + greeting_inputs.yml: {exact: {hello~a: x, shout~a: y}} + greeting~child@1.cwl: + steps: [{id: inner, run: greeting~child@1~inner.cwl}, {id: xform, run: greeting~child@1~xform.cwl}] + inputs: {keys: [file, inner~mk_file~name, xform~name]} + outputs: {keys: [file, inner~mk_file~file, xform~file]} + greeting~child@1~inner.cwl: {steps: [{id: mk_file, run: greeting~child@1~inner~mk_file.cwl}]} + greeting~hello.cwl: {baseCommand: echo} # a/echo.cwl + greeting~shout.cwl: {baseCommand: rm} # b/echo.cwl +other.wic: + files: [other.cwl, other_inputs.yml, other~hello.cwl] + written: + other.cwl: {steps: [{id: hello, run: other~hello.cwl}]} + other~hello.cwl: {baseCommand: rm} + other_inputs.yml: {exact: {hello~a: x}} diff --git a/tests/core/data/compiler/names/greeting.wic b/tests/core/data/compiler/names/greeting.wic new file mode 100644 index 000000000..4ade94b1a --- /dev/null +++ b/tests/core/data/compiler/names/greeting.wic @@ -0,0 +1,34 @@ +# Compiled CWL calls each step what its author wrote and spells nothing of its own (docs/compiling-to-cwl.md). +# mk_file, xform and count are the suite's synthetic tools (tests/core/synthetic_tools.py). +inputs: + echo: string # an input named like a step: CWL keeps inputs and steps in one id space + mk_file__name: string # an input spelled like a name the compiler once made is just an input +steps: +- id: child.wic # a call is called by its stem; called twice, each copy carries its position +- id: child.wic +- id: child # named like the call, so numbered too + run: count +- id: echo # named like the input, so numbered + run: mk_file + in: {name: echo} +- id: mk_file +- id: Touch # ids that differ only in case are one id: one step directory on macOS and Windows + run: mk_file +- id: touch + run: mk_file +- id: xform # one tool run three times is written three times, once per step +- id: xform +- id: xform +- id: con # a Windows device name is a suffix of the file's name, so an ordinary file + run: mk_file +- id: greeting__step__1__mk_file # an id that looks generated is just an id + run: mk_file +- id: hello # two tools with one file name are named by the steps that run them + run: a/echo.cwl + in: {a: !ii x} +- id: shout + run: b/echo.cwl + in: {a: !ii y} +- id: probe # a port named a~b +outputs: + generated: {type: File, outputSource: greeting__step__1__mk_file/file} diff --git a/tests/core/data/compiler/names/inner.wic b/tests/core/data/compiler/names/inner.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/compiler/names/inner.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/compiler/names/other.wic b/tests/core/data/compiler/names/other.wic new file mode 100644 index 000000000..b55edfeb1 --- /dev/null +++ b/tests/core/data/compiler/names/other.wic @@ -0,0 +1,5 @@ +# A second root written beside the first: every file starts with its root's name. +steps: +- id: hello + run: b/echo.cwl + in: {a: !ii x} diff --git a/tests/core/data/compiler/names/probe.cwl b/tests/core/data/compiler/names/probe.cwl new file mode 100644 index 000000000..3874363e6 --- /dev/null +++ b/tests/core/data/compiler/names/probe.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + a~b: {type: string, inputBinding: {position: 1}} +outputs: {} diff --git a/tests/core/data/compiler/refused/deep.wic b/tests/core/data/compiler/refused/deep.wic new file mode 100644 index 000000000..74c8f6c36 --- /dev/null +++ b/tests/core/data/compiler/refused/deep.wic @@ -0,0 +1,3 @@ +steps: +- id: mk_file + in: {name: !* shared} diff --git a/tests/core/data/compiler/refused/disjoint.wic b/tests/core/data/compiler/refused/disjoint.wic new file mode 100644 index 000000000..4eef774b1 --- /dev/null +++ b/tests/core/data/compiler/refused/disjoint.wic @@ -0,0 +1,5 @@ +# An int, defined here, read as the string a step two calls down takes: proven disjoint, so wic023. +steps: +- id: int_source + out: [value: !& shared] +- id: wrapper.wic diff --git a/tests/core/data/compiler/refused/expected.yaml b/tests/core/data/compiler/refused/expected.yaml new file mode 100644 index 000000000..dfde28ffc --- /dev/null +++ b/tests/core/data/compiler/refused/expected.yaml @@ -0,0 +1,37 @@ +# Each root is refused, every diagnostic by code, severity, step and port, and what it names. +untyped_no_source.wic: + refused: [{code: UNTYPED_OUTPUT, severity: error, message: {contains: ["'o'", "has no `outputSource:` to take one"]}}] +untyped_misspelled.wic: + refused: [{code: UNTYPED_OUTPUT, severity: error, message: {contains: ["`outputSource: mk_file/fiel`", # codespell:ignore fiel + "Did you mean 'mk_file/file'?"]}}] +untyped_without_extension.wic: + refused: [{code: UNTYPED_OUTPUT, severity: error, message: {contains: ["`outputSource: kid/res`", + "Did you mean 'kid.wic/res'?"]}}] +untyped_nothing_close.wic: + refused: [{code: UNTYPED_OUTPUT, severity: error, message: {contains: [nothing/at_all, Check the step and output]}}] +untyped_derived_name.wic: + refused: [{code: UNTYPED_OUTPUT, severity: error, message: {contains: [kid.wic/mk_file~file, + "Did you mean 'mk_file/file'?"]}}] +untyped_old_generated.wic: + refused: [{code: UNTYPED_OUTPUT, severity: error, message: {contains: [oracle__step__1__mk_file/file]}}] +undeclared.wic: + refused: + - {code: UNDECLARED_PORT, severity: error, step: kid.wic, index: 1, port: child__step__1__mk_file___file} + - {code: UNDECLARED_PORT, severity: error, step: mk_file, index: 3, port: go} +imports.wic: + refused: + - {code: SUBWORKFLOW_INVALID, severity: error, message: {contains: ["global/inputs_imported lists its inputs:"]}} + - {code: SUBWORKFLOW_INVALID, severity: error, message: {contains: ["global/inputs_included lists its inputs:"]}} + - {code: SUBWORKFLOW_INVALID, severity: error, message: {contains: ["global/outputs_imported lists its outputs:"]}} + - {code: SUBWORKFLOW_INVALID, severity: error, message: {contains: ["global/outputs_included lists its outputs:"]}} +records.wic: + refused: + - {code: STEP_INPUT_RECORD, severity: error, message: {contains: ["'nope'"]}} + - {code: STEP_INPUT_RECORD, severity: error, message: {contains: ["`source` names edges"]}} + - {code: STEP_INPUT_RECORD, severity: error, message: {contains: ["`source` names edges"]}} +disjoint.wic: + refused: [{code: INCOMPATIBLE_INPUT_REFERENCE, severity: error, step: mk_file, index: 1, port: name, + message: {contains: ["'int'", "'string'"]}}] +unresolved.wic: + refused: [{code: UNRESOLVED_INPUT, severity: error, step: mk_file, index: 1, port: name, + message: {contains: ['!ii', not_a_workflow_input]}}] diff --git a/tests/core/data/compiler/refused/imports.wic b/tests/core/data/compiler/refused/imports.wic new file mode 100644 index 000000000..f364567fd --- /dev/null +++ b/tests/core/data/compiler/refused/imports.wic @@ -0,0 +1,7 @@ +# A called workflow listing its ports with an `$import` or `$include` keeps them in a file only cwltool reads, so no +# step can be checked against them: reported at the call, not met with a KeyError. +steps: +- id: inputs_imported.wic +- id: inputs_included.wic +- id: outputs_imported.wic +- id: outputs_included.wic diff --git a/tests/core/data/compiler/refused/inputs_imported.wic b/tests/core/data/compiler/refused/inputs_imported.wic new file mode 100644 index 000000000..445c8b0c2 --- /dev/null +++ b/tests/core/data/compiler/refused/inputs_imported.wic @@ -0,0 +1,5 @@ +inputs: +- $import: shared.yml +steps: +- id: mk_file + in: {name: !ii x} diff --git a/tests/core/data/compiler/refused/inputs_included.wic b/tests/core/data/compiler/refused/inputs_included.wic new file mode 100644 index 000000000..4b75c98ae --- /dev/null +++ b/tests/core/data/compiler/refused/inputs_included.wic @@ -0,0 +1,5 @@ +inputs: +- $include: shared.yml +steps: +- id: mk_file + in: {name: !ii x} diff --git a/tests/core/data/compiler/refused/int_source.cwl b/tests/core/data/compiler/refused/int_source.cwl new file mode 100644 index 000000000..c5074a3c3 --- /dev/null +++ b/tests/core/data/compiler/refused/int_source.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: {value: int} diff --git a/tests/core/data/compiler/refused/kid.wic b/tests/core/data/compiler/refused/kid.wic new file mode 100644 index 000000000..1ed271154 --- /dev/null +++ b/tests/core/data/compiler/refused/kid.wic @@ -0,0 +1,5 @@ +steps: +- id: mk_file + in: {name: !ii x} +outputs: + res: {type: File, outputSource: mk_file/file} diff --git a/tests/core/data/compiler/refused/outputs_imported.wic b/tests/core/data/compiler/refused/outputs_imported.wic new file mode 100644 index 000000000..bff8cfa15 --- /dev/null +++ b/tests/core/data/compiler/refused/outputs_imported.wic @@ -0,0 +1,5 @@ +outputs: +- $import: shared.yml +steps: +- id: mk_file + in: {name: !ii x} diff --git a/tests/core/data/compiler/refused/outputs_included.wic b/tests/core/data/compiler/refused/outputs_included.wic new file mode 100644 index 000000000..56e7d9448 --- /dev/null +++ b/tests/core/data/compiler/refused/outputs_included.wic @@ -0,0 +1,5 @@ +outputs: +- $include: shared.yml +steps: +- id: mk_file + in: {name: !ii x} diff --git a/tests/core/data/compiler/refused/records.wic b/tests/core/data/compiler/refused/records.wic new file mode 100644 index 000000000..1fd511c32 --- /dev/null +++ b/tests/core/data/compiler/refused/records.wic @@ -0,0 +1,13 @@ +# `{wic_raw_cwl: {...}}` contributed through `wic: steps:` is the record `!cwl {...}` spells, so a field it may not +# carry is refused, not dropped. +inputs: + w: File +steps: +- id: count +- id: count +- id: count +wic: + steps: + (1, count): {in: {file: {wic_raw_cwl: {source: w, nope: 1}}}} + (2, count): {in: {file: {wic_raw_cwl: {source: {wic_inline_input: 3}}}}} + (3, count): {in: {file: {wic_raw_cwl: {source: 3}}}} diff --git a/tests/core/data/compiler/refused/undeclared.wic b/tests/core/data/compiler/refused/undeclared.wic new file mode 100644 index 000000000..e9e592e5c --- /dev/null +++ b/tests/core/data/compiler/refused/undeclared.wic @@ -0,0 +1,12 @@ +# An anchor on a name the called workflow never declares, and an input bound plainly that its tool does not +# declare, are wic028; the graph is not built from a document the phase refused. +inputs: + go: boolean +steps: +- id: kid.wic + out: [child__step__1__mk_file___file: !& e] +- id: sink + in: {file: !* e, n: !ii 1} +- id: mk_file + in: {name: !ii a, go: go} + when: $(inputs.go) diff --git a/tests/core/data/compiler/refused/unresolved.wic b/tests/core/data/compiler/refused/unresolved.wic new file mode 100644 index 000000000..993174cf2 --- /dev/null +++ b/tests/core/data/compiler/refused/unresolved.wic @@ -0,0 +1,5 @@ +# A bare name no input declares is reported, with the tag that would make it a literal; --allow_raw_cwl lets it +# through. +steps: +- id: mk_file + in: {name: not_a_workflow_input} diff --git a/tests/core/data/compiler/refused/untyped_derived_name.wic b/tests/core/data/compiler/refused/untyped_derived_name.wic new file mode 100644 index 000000000..a93ff8eda --- /dev/null +++ b/tests/core/data/compiler/refused/untyped_derived_name.wic @@ -0,0 +1,7 @@ +# wic036 says which half of the outputSource: to fix, here a name only the compiler derives. +steps: +- id: mk_file + in: {name: !ii a} +- id: kid.wic +outputs: + o: {outputSource: kid.wic/mk_file~file} diff --git a/tests/core/data/compiler/refused/untyped_misspelled.wic b/tests/core/data/compiler/refused/untyped_misspelled.wic new file mode 100644 index 000000000..b23e780d8 --- /dev/null +++ b/tests/core/data/compiler/refused/untyped_misspelled.wic @@ -0,0 +1,7 @@ +# wic036 says which half of the outputSource: to fix, here the output. +steps: +- id: mk_file + in: {name: !ii a} +- id: kid.wic +outputs: + o: {outputSource: mk_file/fiel} # codespell:ignore fiel diff --git a/tests/core/data/compiler/refused/untyped_no_source.wic b/tests/core/data/compiler/refused/untyped_no_source.wic new file mode 100644 index 000000000..79e707551 --- /dev/null +++ b/tests/core/data/compiler/refused/untyped_no_source.wic @@ -0,0 +1,7 @@ +# wic036 says which half of the outputSource: to fix, not only to add a type:. +steps: +- id: mk_file + in: {name: !ii a} +- id: kid.wic +outputs: + o: {label: no type here} diff --git a/tests/core/data/compiler/refused/untyped_nothing_close.wic b/tests/core/data/compiler/refused/untyped_nothing_close.wic new file mode 100644 index 000000000..300357a6a --- /dev/null +++ b/tests/core/data/compiler/refused/untyped_nothing_close.wic @@ -0,0 +1,7 @@ +# wic036 says which half of the outputSource: to fix, here both, with nothing close. +steps: +- id: mk_file + in: {name: !ii a} +- id: kid.wic +outputs: + o: {outputSource: nothing/at_all} diff --git a/tests/core/data/compiler/refused/untyped_old_generated.wic b/tests/core/data/compiler/refused/untyped_old_generated.wic new file mode 100644 index 000000000..02b76840f --- /dev/null +++ b/tests/core/data/compiler/refused/untyped_old_generated.wic @@ -0,0 +1,7 @@ +# wic036 says which half of the outputSource: to fix, here a spelling the compiler no longer makes. +steps: +- id: mk_file + in: {name: !ii a} +- id: kid.wic +outputs: + o: {outputSource: oracle__step__1__mk_file/file} diff --git a/tests/core/data/compiler/refused/untyped_without_extension.wic b/tests/core/data/compiler/refused/untyped_without_extension.wic new file mode 100644 index 000000000..02bcb101f --- /dev/null +++ b/tests/core/data/compiler/refused/untyped_without_extension.wic @@ -0,0 +1,7 @@ +# wic036 says which half of the outputSource: to fix, here the call's id. +steps: +- id: mk_file + in: {name: !ii a} +- id: kid.wic +outputs: + o: {outputSource: kid/res} diff --git a/tests/core/data/compiler/refused/wrapper.wic b/tests/core/data/compiler/refused/wrapper.wic new file mode 100644 index 000000000..332c41443 --- /dev/null +++ b/tests/core/data/compiler/refused/wrapper.wic @@ -0,0 +1,2 @@ +steps: +- id: deep.wic diff --git a/tests/core/data/compiler/sources/alt/mk_file.cwl b/tests/core/data/compiler/sources/alt/mk_file.cwl new file mode 100644 index 000000000..4039cec30 --- /dev/null +++ b/tests/core/data/compiler/sources/alt/mk_file.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: alt +inputs: {name: string} +outputs: {file: {type: File, outputBinding: {glob: f}}} diff --git a/tests/core/data/compiler/sources/calls.wic b/tests/core/data/compiler/sources/calls.wic new file mode 100644 index 000000000..8038e520d --- /dev/null +++ b/tests/core/data/compiler/sources/calls.wic @@ -0,0 +1,18 @@ +# Edges across calls. `shared`, defined here, is read two documents down; `made` is an output of a call, whose +# producer is the step inside it; `scattered`, defined in a scattered call, feeds a call that threads its declared input to an inner port of +# another name; and an input a call leaves unbound is lifted, not bound by the call. +steps: +- id: string_source + out: [value: !& shared] +- id: wrapper.wic +- id: made.wic + out: [result: !& made] +- id: count + in: {file: !* made} +- id: producer.wic # `scattered` is defined inside it + in: {seed: !ii [a, b]} + scatter: [seed] +- id: consumer.wic + in: {outer_name: !* scattered} + scatter: [outer_name] +- id: unbound.wic diff --git a/tests/core/data/compiler/sources/choice.wic b/tests/core/data/compiler/sources/choice.wic new file mode 100644 index 000000000..1d2695828 --- /dev/null +++ b/tests/core/data/compiler/sources/choice.wic @@ -0,0 +1,7 @@ +# A workflow with implementations runs the one it selects: `implementation` over `default_implementation`. +wic: + implementations: + fast: {steps: [{id: mk_file, in: {name: {wic_inline_input: fast}}}]} + safe: {steps: [{id: mk_text, in: {name: {wic_inline_input: safe}}}]} + default_implementation: safe + implementation: fast diff --git a/tests/core/data/compiler/sources/consumer.wic b/tests/core/data/compiler/sources/consumer.wic new file mode 100644 index 000000000..350acbcd8 --- /dev/null +++ b/tests/core/data/compiler/sources/consumer.wic @@ -0,0 +1,5 @@ +inputs: + outer_name: File # declared as outer_name, read as inner_name +steps: +- id: take + in: {inner_name: outer_name} diff --git a/tests/core/data/compiler/sources/deep.wic b/tests/core/data/compiler/sources/deep.wic new file mode 100644 index 000000000..74c8f6c36 --- /dev/null +++ b/tests/core/data/compiler/sources/deep.wic @@ -0,0 +1,3 @@ +steps: +- id: mk_file + in: {name: !* shared} diff --git a/tests/core/data/compiler/sources/deferred.wic b/tests/core/data/compiler/sources/deferred.wic new file mode 100644 index 000000000..48830475b --- /dev/null +++ b/tests/core/data/compiler/sources/deferred.wic @@ -0,0 +1,5 @@ +# An empty implementation body defers to the registry's workflow of its name: fast.wic, which the command line reads +# because the `safe` body calls it. +wic: + implementations: {fast: {}, safe: {steps: [{id: fast.wic}]}} + implementation: fast diff --git a/tests/core/data/compiler/sources/expected.yaml b/tests/core/data/compiler/sources/expected.yaml new file mode 100644 index 000000000..e8c7fd722 --- /dev/null +++ b/tests/core/data/compiler/sources/expected.yaml @@ -0,0 +1,74 @@ +# What each step reads and each output names, as compiled. Written by hand from each root's comments. +positions.wic: + notes: [{code: INFERENCE_GUESS, severity: note, step: count, index: 4, port: file}] + said: [{contains: ["output 'first'", "2 steps have the id 'mk_file'", "'(1, mk_file)/file'"]}] + written: + positions.cwl: + steps: + - {id: mk_file@1} + - {id: count@2, in: {file: mk_file@1/file}} + - {id: mk_file@3} + - {id: count@4, in: {file: mk_file@3/file}} + - {id: xform, scatter: [name, file], scatterMethod: nested_crossproduct} + outputs: + n: {outputSource: count@4/n} + first: {outputSource: mk_file@1/file} + third: {outputSource: mk_file@3/file} + only: {outputSource: xform/file} + old: {outputSource: positions__step__1__mk_file/file} + mk_file@1~file: {outputSource: mk_file@1/file} # lifted as if nothing had asked for it +records.wic: + written: + records.cwl: + steps: + - {id: sink, in: {file: f, extras: {exact: {source: [f], linkMerge: merge_nested}}}} + - {id: mk_file@2, in: {name: wf_name, go: {exact: {source: go}}}, when: $(inputs.go)} + - {id: mk_file@3} + - {id: relayed, in: {sink~file: {source: mk_file@3/file}}} + - {id: count, in: {file: {exact: {source: w, loadContents: true}}}} + requirements: {keys: [InlineJavascriptRequirement, MultipleInputFeatureRequirement, + SubworkflowFeatureRequirement]} + records~relayed.cwl: + steps: [{id: sink, in: {file: {source: sink~file}}}] # the boundary input the edge is relayed through +untyped.wic: + written: + untyped.cwl: + outputs: + plain: {type: File, outputSource: mk_file@1/file} + scattered: {type: {type: array, items: File}, outputSource: mk_file@2/file} + called: {type: File, outputSource: kid@3/res} + called_scattered: {type: {type: array, items: File}, outputSource: kid@4/res} + untyped~kid@3.cwl: {outputs: {res: {type: File}}} + untyped~kid@4.cwl: {outputs: {res: {type: File}}} +listed.wic: + written: + listed.cwl: + inputs: {keys: [zeta, alpha, mk_file~name, mk_text~name]} + outputs: {o: {type: 'File[]', outputSource: mk_file/file}} + requirements: {exact: {InlineJavascriptRequirement: {}, ScatterFeatureRequirement: {}}} +calls.wic: + written: + calls.cwl: + steps: + - {id: string_source} + - {id: wrapper, in: {mk_file~name: {source: string_source/value}}} + - {id: made} + - {id: count, in: {file: {source: made/result}}} + - {id: producer, scatter: [seed]} + - {id: consumer, in: {outer_name: {source: producer/make~value}}, scatter: [outer_name]} + - {id: unbound, in: {name: string_source/value}} # left unbound by the call, so inference's to give + inputs: {keys: [made~mk_file~name, producer~seed]} + # `shared` is threaded down through one boundary input per level, each reaching the same sink. + calls~wrapper.cwl: {steps: [{id: deep, in: {mk_file~name: {source: mk_file~name}}}], inputs: {keys: [mk_file~name]}} + calls~wrapper~deep.cwl: {steps: [{id: mk_file, in: {name: {source: mk_file~name}}}], + inputs: {keys: [mk_file~name]}} + calls~consumer.cwl: {steps: [{id: take, in: {inner_name: outer_name}}]} +choice.wic: + written: {choice.cwl: {steps: [{id: mk_file}]}, choice_inputs.yml: {exact: {mk_file~name: fast}}} +deferred.wic: + written: {deferred.cwl: {steps: [{id: mk_file}]}, deferred_inputs.yml: {exact: {mk_file~name: deferred}}} +namespaced.wic: + written: {namespaced~mk_file.cwl: {baseCommand: alt}} +raw_names.wic: + options: {allow_raw_cwl: true} + written: {raw_names.cwl: {steps: [{id: mk_file, in: {name: not_a_workflow_input}}]}} diff --git a/tests/core/data/compiler/sources/fast.wic b/tests/core/data/compiler/sources/fast.wic new file mode 100644 index 000000000..55c3f19dc --- /dev/null +++ b/tests/core/data/compiler/sources/fast.wic @@ -0,0 +1,2 @@ +# The workflow deferred.wic runs for its empty `fast` body. +steps: [{id: mk_file, in: {name: {wic_inline_input: deferred}}}] diff --git a/tests/core/data/compiler/sources/kid.wic b/tests/core/data/compiler/sources/kid.wic new file mode 100644 index 000000000..473d4ab0e --- /dev/null +++ b/tests/core/data/compiler/sources/kid.wic @@ -0,0 +1,7 @@ +inputs: + name: string +steps: +- id: mk_file + in: {name: name} +outputs: + res: {outputSource: mk_file/file} diff --git a/tests/core/data/compiler/sources/listed.wic b/tests/core/data/compiler/sources/listed.wic new file mode 100644 index 000000000..e7b7872e0 --- /dev/null +++ b/tests/core/data/compiler/sources/listed.wic @@ -0,0 +1,15 @@ +# CWL's list forms of `outputs:` and `requirements:` compile as their mappings do. Authored inputs keep the order +# written and come first; inputs exposing a step's port follow the steps. +inputs: + zeta: string + alpha: string +requirements: +- class: InlineJavascriptRequirement +steps: +- id: mk_file # its name is lifted, after mk_text's literal already exposed its own + in: {name: !ii [a, b]} + scatter: [name] +- id: mk_text + in: {name: !ii a} +outputs: +- {id: o, type: 'File[]', outputSource: mk_file/file} diff --git a/tests/core/data/compiler/sources/made.wic b/tests/core/data/compiler/sources/made.wic new file mode 100644 index 000000000..9b7ccec7e --- /dev/null +++ b/tests/core/data/compiler/sources/made.wic @@ -0,0 +1,5 @@ +steps: +- id: mk_file + in: {name: !ii child.txt} +outputs: + result: {type: File, outputSource: mk_file/file} diff --git a/tests/core/data/compiler/sources/make.cwl b/tests/core/data/compiler/sources/make.cwl new file mode 100644 index 000000000..56f42cde4 --- /dev/null +++ b/tests/core/data/compiler/sources/make.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {seed: string} +outputs: {value: {type: File, outputBinding: {glob: v}}} diff --git a/tests/core/data/compiler/sources/namespaced.wic b/tests/core/data/compiler/sources/namespaced.wic new file mode 100644 index 000000000..94cf780a4 --- /dev/null +++ b/tests/core/data/compiler/sources/namespaced.wic @@ -0,0 +1,8 @@ +# The closest sidecar namespace selects the process over the default global one. +wic: + steps: + (1, mk_file): + wic: + namespace: alt +steps: +- id: mk_file diff --git a/tests/core/data/compiler/sources/positions.wic b/tests/core/data/compiler/sources/positions.wic new file mode 100644 index 000000000..7e50bfcb1 --- /dev/null +++ b/tests/core/data/compiler/sources/positions.wic @@ -0,0 +1,28 @@ +# Outputs named by position: inference moves no step, so `(4, count)` names the fourth step. +steps: +- id: mk_file + in: {name: !ii x} +- id: count +- id: mk_file + in: {name: !ii y} +- id: count +- id: xform # scattered in the order written: under nested_crossproduct, the nesting of its outputs + in: {name: !ii [a], file: !ii [x.txt]} + scatter: [name, file] + scatterMethod: nested_crossproduct +outputs: + n: + type: int + outputSource: (4, count)/n + first: # a bare id two steps share means the first, and the compile says so + type: File + outputSource: mk_file/file + third: # the spelling that says which is never reported + type: File + outputSource: (3, mk_file)/file + only: # a position at an id no other step has is that plain id + type: File[][] + outputSource: (5, xform)/file + old: # a spelling no step has: written as it is + type: File + outputSource: positions__step__1__mk_file/file diff --git a/tests/core/data/compiler/sources/producer.wic b/tests/core/data/compiler/sources/producer.wic new file mode 100644 index 000000000..cebec9e33 --- /dev/null +++ b/tests/core/data/compiler/sources/producer.wic @@ -0,0 +1,6 @@ +inputs: + seed: string +steps: +- id: make + in: {seed: seed} + out: [value: !& scattered] diff --git a/tests/core/data/compiler/sources/raw_names.wic b/tests/core/data/compiler/sources/raw_names.wic new file mode 100644 index 000000000..6eab59e6f --- /dev/null +++ b/tests/core/data/compiler/sources/raw_names.wic @@ -0,0 +1,5 @@ +# Under --allow_raw_cwl a bare name no input declares reaches CWL as written: the flag is the difference between +# this and refused/unresolved.wic. +steps: +- id: mk_file + in: {name: not_a_workflow_input} diff --git a/tests/core/data/compiler/sources/records.wic b/tests/core/data/compiler/sources/records.wic new file mode 100644 index 000000000..84ddd3536 --- /dev/null +++ b/tests/core/data/compiler/sources/records.wic @@ -0,0 +1,21 @@ +# Records: a step input written as CWL's WorkflowStepInput, `!cwl {...}`, reaches the step as written. +inputs: + f: File + go: boolean + w: File + wf_name: string +steps: +- id: sink # one source beside linkMerge stays a list: CWL merges a list + in: {file: f, n: !ii 1, extras: !cwl {source: [f], linkMerge: merge_nested}} +- id: mk_file # `go` is bound only for `when` to read: the step declares it, so nothing is said + in: {name: !cwl wf_name, go: !cwl {source: go}} + when: $(inputs.go) +- id: mk_file + in: {name: !ii a} + out: [file: !& made] +- id: relayed.wic # its record reads `made`, relayed through the call's boundary input +- id: count # bound through `wic: steps:` in the desugared spelling, as the tagged one binds +wic: + steps: + (5, count): + in: {file: {wic_raw_cwl: {source: w, loadContents: true}}} diff --git a/tests/core/data/compiler/sources/relayed.wic b/tests/core/data/compiler/sources/relayed.wic new file mode 100644 index 000000000..a406f52b6 --- /dev/null +++ b/tests/core/data/compiler/sources/relayed.wic @@ -0,0 +1,3 @@ +steps: +- id: sink + in: {file: !cwl {source: !* made}, n: !ii 1} diff --git a/tests/core/data/compiler/sources/string_source.cwl b/tests/core/data/compiler/sources/string_source.cwl new file mode 100644 index 000000000..a04f11613 --- /dev/null +++ b/tests/core/data/compiler/sources/string_source.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: {value: string} diff --git a/tests/core/data/compiler/sources/take.cwl b/tests/core/data/compiler/sources/take.cwl new file mode 100644 index 000000000..9992209b7 --- /dev/null +++ b/tests/core/data/compiler/sources/take.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {inner_name: File} +outputs: {} diff --git a/tests/core/data/compiler/sources/unbound.wic b/tests/core/data/compiler/sources/unbound.wic new file mode 100644 index 000000000..130503ed0 --- /dev/null +++ b/tests/core/data/compiler/sources/unbound.wic @@ -0,0 +1,5 @@ +inputs: + name: string +steps: +- id: mk_file + in: {name: name} diff --git a/tests/core/data/compiler/sources/untyped.wic b/tests/core/data/compiler/sources/untyped.wic new file mode 100644 index 000000000..004963de8 --- /dev/null +++ b/tests/core/data/compiler/sources/untyped.wic @@ -0,0 +1,22 @@ +# An output with an `outputSource:` and no `type:` takes its producer's type: an array under a scatter; through a +# call, the called workflow's untyped output and the caller's output that names it alike. +steps: +- id: mk_file + in: {name: !ii a} +- id: mk_file + in: {name: !ii [a, b]} + scatter: [name] +- id: kid.wic + in: {name: !ii a} +- id: kid.wic + in: {name: !ii [a, b]} + scatter: [name] +outputs: + plain: + outputSource: (1, mk_file)/file + scattered: + outputSource: (2, mk_file)/file + called: + outputSource: (3, kid.wic)/res + called_scattered: + outputSource: (4, kid.wic)/res diff --git a/tests/core/data/compiler/sources/wrapper.wic b/tests/core/data/compiler/sources/wrapper.wic new file mode 100644 index 000000000..332c41443 --- /dev/null +++ b/tests/core/data/compiler/sources/wrapper.wic @@ -0,0 +1,2 @@ +steps: +- id: deep.wic diff --git a/tests/core/data/compiler/when/child.wic b/tests/core/data/compiler/when/child.wic new file mode 100644 index 000000000..fd26a281d --- /dev/null +++ b/tests/core/data/compiler/when/child.wic @@ -0,0 +1,5 @@ +inputs: + n: int +steps: +- id: gated + in: {n: n} diff --git a/tests/core/data/compiler/when/expected.yaml b/tests/core/data/compiler/when/expected.yaml new file mode 100644 index 000000000..0717bea4d --- /dev/null +++ b/tests/core/data/compiler/when/expected.yaml @@ -0,0 +1,54 @@ +# Expected by hand from design_docs/resolved-view-design.md §10: the CWL target notes each `when` the shared check +# finds gives no boolean, at its step, and refuses nothing; the Nextflow target refuses it, and also each `when` its +# subset cannot read, and a `when` on a call. A `when` that reads an input its step does not declare is a note too, +# naming the input and, for a made name read dotted, the bracket form. +workflow.wic: + notes: + - {code: WHEN_NOT_BOOLEAN, severity: note, step: dotted_absent, message: {contains: [inputs.nope, does not declare]}} + - {code: WHEN_NOT_BOOLEAN, severity: note, step: bracketed_absent, message: {contains: [inputs.nope, does not declare]}} + - {code: WHEN_NOT_BOOLEAN, severity: note, step: maker.wic, + message: {contains: [inputs.mk_file, does not declare, "inputs['mk_file~name']"]}} + - {code: WHEN_NOT_BOOLEAN, severity: note, step: a_number, message: {contains: [not a number]}} + - {code: WHEN_NOT_BOOLEAN, severity: note, step: a_string, message: {contains: [not a string]}} + - {code: WHEN_NOT_BOOLEAN, severity: note, step: a_null, message: {contains: [not a null]}} + - {code: WHEN_NOT_BOOLEAN, severity: note, step: an_element, message: {contains: [not a number]}} + - {code: WHEN_NOT_BOOLEAN, severity: note, step: text, message: {contains: ["not one $(...) or ${...} expression"]}} + - {code: WHEN_NOT_BOOLEAN, severity: note, step: a_template, message: {contains: [not one $(...)]}} + - {code: WHEN_NOT_BOOLEAN, severity: note, step: child, message: {contains: [not a number]}} + nextflow: + - {step: child, says: {contains: [a when on a nested-workflow step]}} + - {step: maker@15, says: {contains: [a when on a nested-workflow step]}} + - {step: maker@16, says: {contains: [a when on a nested-workflow step]}} + - {step: a_number, says: {contains: [not a number]}} + - {step: a_string, says: {contains: [not a string]}} + - {step: a_null, says: {contains: [not a null]}} + - {step: an_element, says: {contains: [not a number]}} + - {step: text, says: {contains: [not one $(...)]}} + - {step: a_template, says: {contains: [not one $(...)]}} + - {step: outside_the_subset, says: {contains: [outside the safe JavaScript subset, "'**'"]}} + - {step: a_body, says: {contains: ["safe JavaScript subset $( … ) expression"]}} + - {step: not_a_string, says: {contains: ["safe JavaScript subset $( … ) expression"]}} + - {step: dotted_absent, says: {contains: [inputs.nope, does not bind]}} + - {step: bracketed_absent, says: {contains: [outside the safe JavaScript subset]}} + - {step: minus, says: {contains: [number operands]}} + written: + workflow.cwl: + steps: + - {id: a_number, when: $(inputs.n + 1)} + - {id: a_string, in: {s: {source: s}}} + - {id: a_null} + - {id: an_element, scatter: [n]} + - {id: text, when: 'true'} + - {id: a_template} + - {id: child, when: $(inputs.n)} + - {id: a_boolean, when: ' $(inputs.n > 0) '} + - {id: outside_the_subset} + - {id: a_body} + - {id: not_a_string, when: true} + - {id: dotted_absent, when: $(inputs.nope != null)} # still compiles, as written + - {id: bracketed_absent} + - {id: minus} + - {id: maker@15, in: {mk_file~name: maker@15~mk_file~name}} + - {id: maker@16} +lowers.wic: + nextflow: [] diff --git a/tests/core/data/compiler/when/gated.cwl b/tests/core/data/compiler/when/gated.cwl new file mode 100644 index 000000000..c1bb15cf1 --- /dev/null +++ b/tests/core/data/compiler/when/gated.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + n: int +outputs: {} diff --git a/tests/core/data/compiler/when/job.yml b/tests/core/data/compiler/when/job.yml new file mode 100644 index 000000000..a99c4a1d7 --- /dev/null +++ b/tests/core/data/compiler/when/job.yml @@ -0,0 +1,5 @@ +n: 1 +s: a +ns: [1] +maker@15~mk_file~name: x +maker@16~mk_file~name: y diff --git a/tests/core/data/compiler/when/lowers.wic b/tests/core/data/compiler/when/lowers.wic new file mode 100644 index 000000000..6387f20ea --- /dev/null +++ b/tests/core/data/compiler/when/lowers.wic @@ -0,0 +1,15 @@ +# The `when` both targets read alike: a comparison gives true or false, so the CWL target notes nothing and the +# Nextflow target lowers it, reading each input the step binds and one only the `when` reads. +inputs: + n: int + s: string + ns: int[] +steps: +- id: gated + in: {n: n, s: !cwl {source: s}} + when: $(inputs.n > 0 && inputs.s === "a") +- id: each + run: gated + in: {n: ns} + scatter: [n] + when: ' $(inputs.n > 0) ' diff --git a/tests/core/data/compiler/when/maker.wic b/tests/core/data/compiler/when/maker.wic new file mode 100644 index 000000000..0a1de9de4 --- /dev/null +++ b/tests/core/data/compiler/when/maker.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file # leaves `name` for its caller diff --git a/tests/core/data/compiler/when/workflow.wic b/tests/core/data/compiler/when/workflow.wic new file mode 100644 index 000000000..145e9ffe0 --- /dev/null +++ b/tests/core/data/compiler/when/workflow.wic @@ -0,0 +1,68 @@ +# A `when` must give true or false (CWL v1.2's WorkflowStep), and cwltool stops the run at one that gives anything +# else: the CWL target notes each one the shared check finds (wic056) and the Nextflow target refuses it. A `when` +# that reads an input its step does not declare reads nothing, and the compile says so. +inputs: + n: int + s: string + ns: int[] +steps: +- id: a_number # 2 is not a boolean + run: gated + in: {n: n} + when: $(inputs.n + 1) +- id: a_string # typed by what each input delivers, a step-only one among them + run: gated + in: {n: n, s: !cwl {source: s}} + when: $(inputs.s) +- id: a_null # null is neither true nor false + run: gated + in: {n: n} + when: $(null) +- id: an_element # evaluated in each job of a scatter, over one element + run: gated + in: {n: ns} + scatter: [n] + when: $(inputs.n) +- id: text # no expression in it, so no CWL Expression + run: gated + in: {n: n} + when: 'true' +- id: a_template # text around an expression is interpolated into a string + run: gated + in: {n: n} + when: $(inputs.n > 0) or not +- id: child.wic # a call's when is a CWL when like any other + in: {n: n} + when: $(inputs.n) +- id: a_boolean # a comparison gives true or false + run: gated + in: {n: n} + when: ' $(inputs.n > 0) ' +- id: outside_the_subset # the shared check cannot read it, so says nothing of it + run: gated + in: {n: n} + when: $(inputs.n ** 2) +- id: a_body # a ${...} body is one expression the check does not read + run: gated + in: {n: n} + when: '${ return inputs.n; }' +- id: not_a_string # cwltool's schema validation refuses it + run: gated + in: {n: n} + when: true +- id: dotted_absent # reads `nope`, which mk_file does not declare + run: mk_file + in: {name: !ii a} + when: $(inputs.nope != null) +- id: bracketed_absent + run: mk_file + in: {name: !ii b} + when: $(inputs["nope"] != null) +- id: minus # `inputs.name - 1`: `name` is declared + run: mk_file + in: {name: !ii c} + when: $(inputs.name-1 > 0) +- id: maker.wic # declares the names its child exposes, read in brackets + when: $(inputs["mk_file~name"] != null) +- id: maker.wic # `inputs.mk_file~name` is `inputs.mk_file`, then `~name` + when: $(inputs.mk_file~name != null) diff --git a/tests/core/data/contributions/cases.yaml b/tests/core/data/contributions/cases.yaml deleted file mode 100644 index 47a436b1d..000000000 --- a/tests/core/data/contributions/cases.yaml +++ /dev/null @@ -1,191 +0,0 @@ -- id: a contributed input reaches a step of a called subworkflow - why: "An `in:` written at a distance binds that step's input in the child." - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: !ii contributed.txt\nsteps:\n- id: child.wic\n" - children: {child: "steps:\n- id: mk_file\n"} - expect: [{depth: 1, inputs: {name: [InlineLiteral, contributed.txt]}}] -- id: a contributed output defines an edge on a nested step - why: "`out:` carries `!&` to a step two subworkflows down, as `basic.wic` does. The definition exists nowhere else: - writing it in the child would define it twice when that child is called from a second root, which is the whole - reason the corpus places it from above." - root: "\nwic:\n steps:\n (1, min.wic):\n wic:\n steps:\n (1, - cg.wic):\n wic:\n steps:\n (1, - mk_file):\n out:\n - file: !& min.tpr\nsteps:\n- id: min.wic\n" - children: {min: "steps:\n- id: cg.wic\n", cg: "steps:\n- id: mk_file\n in:\n name: !ii min.tpr\n"} - expect: [{depth: 2, outputs: [[file, min.tpr]]}] -- id: a bare wic body only recurses until it reaches a payload - why: "Three nested `wic:` bodies carry nothing themselves; the fourth binds." - root: "\nwic:\n steps:\n (1, a.wic):\n wic:\n steps:\n (1, - b.wic):\n wic:\n steps:\n (1, - c.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: !* deep.txt\nsteps:\n- id: a.wic\n" - children: {a: "steps:\n- id: b.wic\n", b: "steps:\n- id: c.wic\n", c: "steps:\n- id: mk_file\n"} - expect: [{depth: 3, inputs: {name: [EdgeRef, deep.txt]}}] -- id: a contributed value wins over the child's own - why: "Overriding is the point of parameter passing: the contributor wins." - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: !ii from_the_parent.txt\nsteps:\n- id: child.wic\n" - children: {child: "steps:\n- id: mk_file\n in:\n name: !ii its_own.txt\n"} - expect: [{depth: 1, inputs: {name: [InlineLiteral, from_the_parent.txt]}}] -- id: a contribution whose key does not match its step is named on stderr - why: "`(N, name)` addresses one step, so half a match is no match: the key is ignored, and each such key is named once - on stderr." - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (2, - mk_file):\n in:\n name: !ii wrong_index.txt\n (1, - mk_text):\n in:\n name: !ii wrong_name.txt\nsteps:\n- id: child.wic\n" - children: {child: "steps:\n- id: mk_file\n in:\n name: !ii its_own.txt\n"} - expect: [{depth: 1, inputs: {name: [InlineLiteral, its_own.txt]}}] - stderr: ["Warning! root.wic: wic: steps: key (2, mk_file) addresses no step of 'child': there is no step 2; the - document has 1 step. The key is ignored.", "Warning! root.wic: wic: steps: key (1, mk_text) addresses no step - of 'child': step 1 is 'mk_file'; write (1, mk_file). The key is ignored."] -- id: a contribution to a wic step addresses the subworkflow not the call - why: "A `.wic` step's body names steps inside it; nothing lands on the call site." - root: "\nwic:\n steps:\n (1, child.wic):\n in:\n name: !ii - never_bound_here.txt\n wic:\n steps:\n (1, mk_file):\n in:\n name: - !ii contributed.txt\nsteps:\n- id: child.wic\n" - children: {child: "steps:\n- id: mk_file\n"} - expect: [{inputs: {exact: {}}}, {depth: 1, inputs: {name: [InlineLiteral, contributed.txt]}}] -- id: "a contributed literal, tagged" - why: &surfaces "A contribution is opaque content, where each construct has two spellings. The tagged one is what a - human writes and the desugared one is what the Python API and `render` emit, so a contribution that only - understood tags would apply to a hand-written document and vanish from a round-tripped one." - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: !ii shared.txt\nsteps:\n- id: child.wic\n" - children: &mk {child: "steps:\n- id: mk_file\n"} - expect: [{depth: 1, inputs: {name: [InlineLiteral, shared.txt]}}] -- id: "a contributed literal, desugared" - why: *surfaces - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: {wic_inline_input: shared.txt}\nsteps:\n- id: child.wic\n" - children: *mk - expect: [{depth: 1, inputs: {name: [InlineLiteral, shared.txt]}}] -- id: "a contributed edge reference, tagged" - why: *surfaces - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: !* shared.txt\nsteps:\n- id: child.wic\n" - children: *mk - expect: [{depth: 1, inputs: {name: [EdgeRef, shared.txt]}}] -- id: "a contributed edge reference, desugared" - why: *surfaces - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: {wic_alias: shared.txt}\nsteps:\n- id: child.wic\n" - children: *mk - expect: [{depth: 1, inputs: {name: [EdgeRef, shared.txt]}}] -- id: "a contributed raw CWL reference, tagged" - why: *surfaces - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: !cwl shared.txt\nsteps:\n- id: child.wic\n" - children: *mk - expect: [{depth: 1, inputs: {name: [RawCwlRef, shared.txt]}}] -- id: "a contributed raw CWL reference, desugared" - why: *surfaces - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: {wic_raw_cwl: shared.txt}\nsteps:\n- id: child.wic\n" - children: *mk - expect: [{depth: 1, inputs: {name: [RawCwlRef, shared.txt]}}] -- id: a contributed bare name - why: *surfaces - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: shared.txt\nsteps:\n- id: child.wic\n" - children: *mk - expect: [{depth: 1, inputs: {name: [UnresolvedName, shared.txt]}}] -- id: a contributed untagged mapping - why: *surfaces - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: {a: 1}\nsteps:\n- id: child.wic\n" - children: *mk - expect: [{depth: 1, inputs: {name: [InlineLiteral, {a: 1}]}}] -- id: a contributed out replaces the step's own sequence - why: "`out:` is a sequence, and a sequence the contributor supplies replaces. Merging the two instead would keep an - edge definition the contributor deliberately removed, and define it twice wherever the contributor put its own - back." - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n out:\n - file\nsteps:\n- id: child.wic\n" - children: {child: "steps:\n- id: mk_file\n out:\n - file: !& its_own_edge\n"} - expect: [{depth: 1, outputs: [[file, null]]}] -- id: a contribution merges with the child's own body for the same step - why: "Both bodies address `(1, xform)`; neither replaces the other wholesale. A subworkflow that already parameterises - one of its own steps is the ordinary case -- `cg.wic` does -- so a contribution that overwrote the whole `(N, - name)` body would delete whatever the child had written there, and one that overwrote the whole `in:` would delete - the bindings it does not itself mention." - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - xform):\n in:\n name: !ii contributed.txt\nsteps:\n- id: child.wic\n" - children: {child: "\nwic:\n steps:\n (1, xform):\n in:\n file: !* upstream\n out:\n - file: - !& its_own_edge\nsteps:\n- id: xform\n"} - expect: [{depth: 1, inputs: {file: [EdgeRef, upstream], name: [InlineLiteral, contributed.txt]}, - outputs: [[file, its_own_edge]]}] -- id: an id-keyed contribution reaches the one step with that id - why: A parent contributes to the one step with that id by its bare id. - root: "\nwic:\n steps:\n (1, - child.wic):\n wic:\n steps:\n mk_file:\n in:\n name: !ii - from_root.txt\nsteps:\n- id: child.wic\n" - children: {child: "steps:\n- id: mk_file\n"} - expect: [{depth: 1, inputs: {name: [InlineLiteral, from_root.txt]}}] - stderr: [] -- id: an id-keyed entry for a repeated id is named on stderr and ignored - why: A bare id naming several steps is reported and ignored. - root: "wic:\n steps:\n mk_file:\n in:\n name: !ii x.txt\nsteps:\n- id: mk_file\n- id: mk_file\n" - expect: [{inputs: {exact: {}}}, {step: 1, inputs: {exact: {}}}] - stderr: ["Warning! root.wic: wic: steps: key mk_file addresses no step of 'root': 'mk_file' names 2 steps; write - (index, mk_file). The key is ignored."] -- id: a positional key wins over an id key for the same step - why: Within one sidecar a positional key wins over a bare id for the same step. - root: "wic:\n steps:\n mk_file:\n in:\n name: !ii by_id.txt\n (1, - mk_file):\n in:\n name: !ii by_position.txt\nsteps:\n- id: mk_file\n" - expect: [{inputs: {name: [InlineLiteral, by_position.txt]}}] -- id: a stale key is named once however many steps call the workflow - why: A stale key is reported once however many steps call the workflow. - root: "steps:\n- id: child.wic\n- id: child.wic\n" - children: {child: "wic:\n steps:\n (2, mk_file): {}\nsteps:\n- id: mk_file\n"} - expect: [] - stderr: [{startswith: "Warning! "}] -- id: an id key from the parent merges over the child's positional entry - why: The calling step's contribution wins whichever spelling each side uses. - root: "\nwic:\n steps:\n (1, - child.wic):\n wic:\n steps:\n mk_file:\n in:\n name: !ii - from_root.txt\nsteps:\n- id: child.wic\n" - children: {child: "\nwic:\n steps:\n (1, mk_file):\n wic:\n graphviz:\n label: a - label\nsteps:\n- id: mk_file\n"} - expect: [{depth: 1, inputs: {name: [InlineLiteral, from_root.txt]}}] - stderr: [] -- id: an id key from the parent wins when the child has both spellings - why: The contribution wins over a child that spells the same step both ways. - root: "\nwic:\n steps:\n (1, - child.wic):\n wic:\n steps:\n mk_file:\n in:\n name: !ii - from_root.txt\nsteps:\n- id: child.wic\n" - children: {child: "wic:\n steps:\n mk_file:\n in:\n other: !ii o\n (1, - mk_file):\n in:\n name: !ii child_pos.txt\nsteps:\n- id: mk_file\n"} - expect: [{depth: 1, inputs: {name: [InlineLiteral, from_root.txt], other: [InlineLiteral, o]}}] -- id: a positional key from the parent merges over the child's id entry - why: "The parent's (index, id) contribution overrides the child's own bare-id entry." - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: !ii from_root.txt\nsteps:\n- id: child.wic\n" - children: {child: "\nwic:\n steps:\n mk_file:\n in:\n name: !ii child_own.txt\nsteps:\n- id: - mk_file\n"} - expect: [{depth: 1, inputs: {name: [InlineLiteral, from_root.txt]}}] -- id: a stale positional key from the parent does not swallow the child's id entry - why: A parent key that addresses no step leaves the child's valid bare-id entry alone. - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (2, - mk_file):\n in:\n name: !ii from_root.txt\nsteps:\n- id: child.wic\n" - children: {child: "wic:\n steps:\n mk_file:\n in:\n name: !ii child_own.txt\nsteps:\n- id: mk_file\n"} - expect: [{depth: 1, inputs: {name: [InlineLiteral, child_own.txt]}}] -- id: a stale positional key in the child does not swallow the parent's id contribution - why: A child key that addresses no step leaves the parent's valid bare-id contribution alone. - root: "\nwic:\n steps:\n (1, - child.wic):\n wic:\n steps:\n mk_file:\n in:\n name: !ii - from_root.txt\nsteps:\n- id: child.wic\n" - children: {child: "wic:\n steps:\n (2, mk_file):\n in:\n name: !ii child_stale.txt\nsteps:\n- id: - mk_file\n"} - expect: [{depth: 1, inputs: {name: [InlineLiteral, from_root.txt]}}] -- id: an id key and a positional key for the same step merge in one sidecar - why: "Fields only the bare entry sets survive; the positional entry wins where both set one." - root: "wic:\n steps:\n mk_file:\n in:\n a: !ii x.txt\n (1, mk_file):\n in:\n b: !ii - y.txt\nsteps:\n- id: mk_file\n" - expect: [{inputs: {a: [InlineLiteral, x.txt], b: [InlineLiteral, y.txt]}}] -- id: a stale child id entry does not pair with the parent's positional key - why: "A child bare id naming two steps addresses none, so it is not merged under the parent's (1, id) key." - root: "\nwic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, - mk_file):\n in:\n name: !ii from_root.txt\nsteps:\n- id: child.wic\n" - children: {child: "wic:\n steps:\n mk_file:\n in:\n extra: !ii stale_child.txt\nsteps:\n- id: - mk_file\n- id: mk_file\n"} - expect: [{depth: 1, inputs: {exact: {name: [InlineLiteral, from_root.txt]}}}] diff --git a/tests/core/data/contributions/merging/a_contributed_out_replaces_the_step_s/child.wic b/tests/core/data/contributions/merging/a_contributed_out_replaces_the_step_s/child.wic new file mode 100644 index 000000000..1920d068b --- /dev/null +++ b/tests/core/data/contributions/merging/a_contributed_out_replaces_the_step_s/child.wic @@ -0,0 +1,4 @@ +steps: +- id: mk_file + out: + - file: !& its_own_edge diff --git a/tests/core/data/contributions/merging/a_contributed_out_replaces_the_step_s/workflow.wic b/tests/core/data/contributions/merging/a_contributed_out_replaces_the_step_s/workflow.wic new file mode 100644 index 000000000..2783dc902 --- /dev/null +++ b/tests/core/data/contributions/merging/a_contributed_out_replaces_the_step_s/workflow.wic @@ -0,0 +1,12 @@ +# `out:` is a sequence, and a sequence the contributor supplies replaces. Merging the two instead would keep an edge +# definition the contributor deliberately removed, and define it twice wherever the contributor put its own back. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + out: + - file +steps: +- id: child.wic diff --git a/tests/core/data/contributions/merging/a_contributed_value_wins_over_the_child/child.wic b/tests/core/data/contributions/merging/a_contributed_value_wins_over_the_child/child.wic new file mode 100644 index 000000000..a6c5ef8f7 --- /dev/null +++ b/tests/core/data/contributions/merging/a_contributed_value_wins_over_the_child/child.wic @@ -0,0 +1,4 @@ +steps: +- id: mk_file + in: + name: !ii its_own.txt diff --git a/tests/core/data/contributions/merging/a_contributed_value_wins_over_the_child/workflow.wic b/tests/core/data/contributions/merging/a_contributed_value_wins_over_the_child/workflow.wic new file mode 100644 index 000000000..333d79af0 --- /dev/null +++ b/tests/core/data/contributions/merging/a_contributed_value_wins_over_the_child/workflow.wic @@ -0,0 +1,11 @@ +# Overriding is the point of parameter passing: the contributor wins. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: !ii from_the_parent.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/merging/a_contribution_merges_with_the_child_s/child.wic b/tests/core/data/contributions/merging/a_contribution_merges_with_the_child_s/child.wic new file mode 100644 index 000000000..ce1e85c9d --- /dev/null +++ b/tests/core/data/contributions/merging/a_contribution_merges_with_the_child_s/child.wic @@ -0,0 +1,9 @@ +wic: + steps: + (1, xform): + in: + file: !* upstream + out: + - file: !& its_own_edge +steps: +- id: xform diff --git a/tests/core/data/contributions/merging/a_contribution_merges_with_the_child_s/workflow.wic b/tests/core/data/contributions/merging/a_contribution_merges_with_the_child_s/workflow.wic new file mode 100644 index 000000000..06fa879b5 --- /dev/null +++ b/tests/core/data/contributions/merging/a_contribution_merges_with_the_child_s/workflow.wic @@ -0,0 +1,14 @@ +# Both bodies address `(1, xform)`; neither replaces the other wholesale. A subworkflow that already parameterises +# one of its own steps is the ordinary case -- `cg.wic` does -- so a contribution that overwrote the whole `(N, +# name)` body would delete whatever the child had written there, and one that overwrote the whole `in:` would delete +# the bindings it does not itself mention. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, xform): + in: + name: !ii contributed.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/merging/a_positional_key_from_the_parent_merges/child.wic b/tests/core/data/contributions/merging/a_positional_key_from_the_parent_merges/child.wic new file mode 100644 index 000000000..a3889b299 --- /dev/null +++ b/tests/core/data/contributions/merging/a_positional_key_from_the_parent_merges/child.wic @@ -0,0 +1,7 @@ +wic: + steps: + mk_file: + in: + name: !ii child_own.txt +steps: +- id: mk_file diff --git a/tests/core/data/contributions/merging/a_positional_key_from_the_parent_merges/workflow.wic b/tests/core/data/contributions/merging/a_positional_key_from_the_parent_merges/workflow.wic new file mode 100644 index 000000000..125857054 --- /dev/null +++ b/tests/core/data/contributions/merging/a_positional_key_from_the_parent_merges/workflow.wic @@ -0,0 +1,11 @@ +# The parent's (index, id) contribution overrides the child's own bare-id entry. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: !ii from_root.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/merging/a_positional_key_wins_over_an_id_key_for/workflow.wic b/tests/core/data/contributions/merging/a_positional_key_wins_over_an_id_key_for/workflow.wic new file mode 100644 index 000000000..9a787ab82 --- /dev/null +++ b/tests/core/data/contributions/merging/a_positional_key_wins_over_an_id_key_for/workflow.wic @@ -0,0 +1,11 @@ +# Within one sidecar a positional key wins over a bare id for the same step. +wic: + steps: + mk_file: + in: + name: !ii by_id.txt + (1, mk_file): + in: + name: !ii by_position.txt +steps: +- id: mk_file diff --git a/tests/core/data/contributions/merging/an_id_key_and_a_positional_key_for_the/workflow.wic b/tests/core/data/contributions/merging/an_id_key_and_a_positional_key_for_the/workflow.wic new file mode 100644 index 000000000..5e08816f0 --- /dev/null +++ b/tests/core/data/contributions/merging/an_id_key_and_a_positional_key_for_the/workflow.wic @@ -0,0 +1,11 @@ +# Fields only the bare entry sets survive; the positional entry wins where both set one. +wic: + steps: + mk_file: + in: + a: !ii x.txt + (1, mk_file): + in: + b: !ii y.txt +steps: +- id: mk_file diff --git a/tests/core/data/contributions/merging/an_id_key_from_the_parent_merges_over/child.wic b/tests/core/data/contributions/merging/an_id_key_from_the_parent_merges_over/child.wic new file mode 100644 index 000000000..5d2a33f30 --- /dev/null +++ b/tests/core/data/contributions/merging/an_id_key_from_the_parent_merges_over/child.wic @@ -0,0 +1,8 @@ +wic: + steps: + (1, mk_file): + wic: + graphviz: + label: a label +steps: +- id: mk_file diff --git a/tests/core/data/contributions/merging/an_id_key_from_the_parent_merges_over/workflow.wic b/tests/core/data/contributions/merging/an_id_key_from_the_parent_merges_over/workflow.wic new file mode 100644 index 000000000..361f07e2d --- /dev/null +++ b/tests/core/data/contributions/merging/an_id_key_from_the_parent_merges_over/workflow.wic @@ -0,0 +1,11 @@ +# The calling step's contribution wins whichever spelling each side uses. +wic: + steps: + (1, child.wic): + wic: + steps: + mk_file: + in: + name: !ii from_root.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/merging/an_id_key_from_the_parent_wins_when_the/child.wic b/tests/core/data/contributions/merging/an_id_key_from_the_parent_wins_when_the/child.wic new file mode 100644 index 000000000..3b98a11a5 --- /dev/null +++ b/tests/core/data/contributions/merging/an_id_key_from_the_parent_wins_when_the/child.wic @@ -0,0 +1,10 @@ +wic: + steps: + mk_file: + in: + other: !ii o + (1, mk_file): + in: + name: !ii child_pos.txt +steps: +- id: mk_file diff --git a/tests/core/data/contributions/merging/an_id_key_from_the_parent_wins_when_the/workflow.wic b/tests/core/data/contributions/merging/an_id_key_from_the_parent_wins_when_the/workflow.wic new file mode 100644 index 000000000..78fcab59b --- /dev/null +++ b/tests/core/data/contributions/merging/an_id_key_from_the_parent_wins_when_the/workflow.wic @@ -0,0 +1,11 @@ +# The contribution wins over a child that spells the same step both ways. +wic: + steps: + (1, child.wic): + wic: + steps: + mk_file: + in: + name: !ii from_root.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/merging/expected.yaml b/tests/core/data/contributions/merging/expected.yaml new file mode 100644 index 000000000..5dcaa1b8b --- /dev/null +++ b/tests/core/data/contributions/merging/expected.yaml @@ -0,0 +1,25 @@ +a_contributed_value_wins_over_the_child: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, from_the_parent.txt]}} +a_contributed_out_replaces_the_step_s: + expect: + - {depth: 1, outputs: [[file, null]]} +a_contribution_merges_with_the_child_s: + expect: + - {depth: 1, inputs: {file: [EdgeRef, upstream], name: [InlineLiteral, contributed.txt]}, outputs: [[file, its_own_edge]]} +a_positional_key_wins_over_an_id_key_for: + expect: + - {inputs: {name: [InlineLiteral, by_position.txt]}} +an_id_key_from_the_parent_merges_over: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, from_root.txt]}} + said: [] +an_id_key_from_the_parent_wins_when_the: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, from_root.txt], other: [InlineLiteral, o]}} +a_positional_key_from_the_parent_merges: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, from_root.txt]}} +an_id_key_and_a_positional_key_for_the: + expect: + - {inputs: {a: [InlineLiteral, x.txt], b: [InlineLiteral, y.txt]}} diff --git a/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/a.wic b/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/a.wic new file mode 100644 index 000000000..06764ef9f --- /dev/null +++ b/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/a.wic @@ -0,0 +1,2 @@ +steps: +- id: b.wic diff --git a/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/b.wic b/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/b.wic new file mode 100644 index 000000000..bbac877b3 --- /dev/null +++ b/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/b.wic @@ -0,0 +1,2 @@ +steps: +- id: c.wic diff --git a/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/c.wic b/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/c.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/c.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/workflow.wic b/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/workflow.wic new file mode 100644 index 000000000..c97b66e4f --- /dev/null +++ b/tests/core/data/contributions/reach/a_bare_wic_body_only_recurses_until_it/workflow.wic @@ -0,0 +1,17 @@ +# Three nested `wic:` bodies carry nothing themselves; the fourth binds. +wic: + steps: + (1, a.wic): + wic: + steps: + (1, b.wic): + wic: + steps: + (1, c.wic): + wic: + steps: + (1, mk_file): + in: + name: !* deep.txt +steps: +- id: a.wic diff --git a/tests/core/data/contributions/reach/a_contributed_input_reaches_a_step_of_a/child.wic b/tests/core/data/contributions/reach/a_contributed_input_reaches_a_step_of_a/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/reach/a_contributed_input_reaches_a_step_of_a/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/reach/a_contributed_input_reaches_a_step_of_a/workflow.wic b/tests/core/data/contributions/reach/a_contributed_input_reaches_a_step_of_a/workflow.wic new file mode 100644 index 000000000..01bfcffbf --- /dev/null +++ b/tests/core/data/contributions/reach/a_contributed_input_reaches_a_step_of_a/workflow.wic @@ -0,0 +1,11 @@ +# An `in:` written at a distance binds that step's input in the child. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: !ii contributed.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/cg.wic b/tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/cg.wic new file mode 100644 index 000000000..687bfc628 --- /dev/null +++ b/tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/cg.wic @@ -0,0 +1,4 @@ +steps: +- id: mk_file + in: + name: !ii min.tpr diff --git a/tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/min.wic b/tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/min.wic new file mode 100644 index 000000000..77eab054f --- /dev/null +++ b/tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/min.wic @@ -0,0 +1,2 @@ +steps: +- id: cg.wic diff --git a/tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/workflow.wic b/tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/workflow.wic new file mode 100644 index 000000000..2a35748aa --- /dev/null +++ b/tests/core/data/contributions/reach/a_contributed_output_defines_an_edge_on/workflow.wic @@ -0,0 +1,16 @@ +# `out:` carries `!&` to a step two subworkflows down, as `basic.wic` does. The definition exists nowhere else: +# writing it in the child would define it twice when that child is called from a second root, which is the whole +# reason the corpus places it from above. +wic: + steps: + (1, min.wic): + wic: + steps: + (1, cg.wic): + wic: + steps: + (1, mk_file): + out: + - file: !& min.tpr +steps: +- id: min.wic diff --git a/tests/core/data/contributions/reach/a_contribution_to_a_wic_step_addresses/child.wic b/tests/core/data/contributions/reach/a_contribution_to_a_wic_step_addresses/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/reach/a_contribution_to_a_wic_step_addresses/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/reach/a_contribution_to_a_wic_step_addresses/workflow.wic b/tests/core/data/contributions/reach/a_contribution_to_a_wic_step_addresses/workflow.wic new file mode 100644 index 000000000..430598f7c --- /dev/null +++ b/tests/core/data/contributions/reach/a_contribution_to_a_wic_step_addresses/workflow.wic @@ -0,0 +1,13 @@ +# A `.wic` step's body names steps inside it; nothing lands on the call site. +wic: + steps: + (1, child.wic): + in: + name: !ii never_bound_here.txt + wic: + steps: + (1, mk_file): + in: + name: !ii contributed.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/reach/an_id_keyed_contribution_reaches_the_one/child.wic b/tests/core/data/contributions/reach/an_id_keyed_contribution_reaches_the_one/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/reach/an_id_keyed_contribution_reaches_the_one/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/reach/an_id_keyed_contribution_reaches_the_one/workflow.wic b/tests/core/data/contributions/reach/an_id_keyed_contribution_reaches_the_one/workflow.wic new file mode 100644 index 000000000..befae163d --- /dev/null +++ b/tests/core/data/contributions/reach/an_id_keyed_contribution_reaches_the_one/workflow.wic @@ -0,0 +1,11 @@ +# A parent contributes to the one step with that id by its bare id. +wic: + steps: + (1, child.wic): + wic: + steps: + mk_file: + in: + name: !ii from_root.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/reach/expected.yaml b/tests/core/data/contributions/reach/expected.yaml new file mode 100644 index 000000000..74a8d95a5 --- /dev/null +++ b/tests/core/data/contributions/reach/expected.yaml @@ -0,0 +1,17 @@ +a_contributed_input_reaches_a_step_of_a: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, contributed.txt]}} +a_contributed_output_defines_an_edge_on: + expect: + - {depth: 2, outputs: [[file, min.tpr]]} +a_bare_wic_body_only_recurses_until_it: + expect: + - {depth: 3, inputs: {name: [EdgeRef, deep.txt]}} +a_contribution_to_a_wic_step_addresses: + expect: + - {inputs: {exact: {}}} + - {depth: 1, inputs: {name: [InlineLiteral, contributed.txt]}} +an_id_keyed_contribution_reaches_the_one: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, from_root.txt]}} + said: [] diff --git a/tests/core/data/contributions/spellings/bare_name/child.wic b/tests/core/data/contributions/spellings/bare_name/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/spellings/bare_name/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/spellings/bare_name/workflow.wic b/tests/core/data/contributions/spellings/bare_name/workflow.wic new file mode 100644 index 000000000..70c86ef8f --- /dev/null +++ b/tests/core/data/contributions/spellings/bare_name/workflow.wic @@ -0,0 +1,13 @@ +# A contribution is opaque content, where each construct has two spellings. The tagged one is what a human writes +# and the desugared one is what the Python API and `render` emit, so a contribution that only understood tags would +# apply to a hand-written document and vanish from a round-tripped one. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: shared.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/spellings/edge_reference_desugared/child.wic b/tests/core/data/contributions/spellings/edge_reference_desugared/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/spellings/edge_reference_desugared/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/spellings/edge_reference_desugared/workflow.wic b/tests/core/data/contributions/spellings/edge_reference_desugared/workflow.wic new file mode 100644 index 000000000..f7d953105 --- /dev/null +++ b/tests/core/data/contributions/spellings/edge_reference_desugared/workflow.wic @@ -0,0 +1,13 @@ +# A contribution is opaque content, where each construct has two spellings. The tagged one is what a human writes +# and the desugared one is what the Python API and `render` emit, so a contribution that only understood tags would +# apply to a hand-written document and vanish from a round-tripped one. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: {wic_alias: shared.txt} +steps: +- id: child.wic diff --git a/tests/core/data/contributions/spellings/edge_reference_tagged/child.wic b/tests/core/data/contributions/spellings/edge_reference_tagged/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/spellings/edge_reference_tagged/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/spellings/edge_reference_tagged/workflow.wic b/tests/core/data/contributions/spellings/edge_reference_tagged/workflow.wic new file mode 100644 index 000000000..b62327529 --- /dev/null +++ b/tests/core/data/contributions/spellings/edge_reference_tagged/workflow.wic @@ -0,0 +1,13 @@ +# A contribution is opaque content, where each construct has two spellings. The tagged one is what a human writes +# and the desugared one is what the Python API and `render` emit, so a contribution that only understood tags would +# apply to a hand-written document and vanish from a round-tripped one. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: !* shared.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/spellings/expected.yaml b/tests/core/data/contributions/spellings/expected.yaml new file mode 100644 index 000000000..8404a4fc4 --- /dev/null +++ b/tests/core/data/contributions/spellings/expected.yaml @@ -0,0 +1,24 @@ +literal_tagged: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, shared.txt]}} +literal_desugared: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, shared.txt]}} +edge_reference_tagged: + expect: + - {depth: 1, inputs: {name: [EdgeRef, shared.txt]}} +edge_reference_desugared: + expect: + - {depth: 1, inputs: {name: [EdgeRef, shared.txt]}} +raw_cwl_reference_tagged: + expect: + - {depth: 1, inputs: {name: [RawCwlRef, shared.txt]}} +raw_cwl_reference_desugared: + expect: + - {depth: 1, inputs: {name: [RawCwlRef, shared.txt]}} +bare_name: + expect: + - {depth: 1, inputs: {name: [UnresolvedName, shared.txt]}} +untagged_mapping: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, {a: 1}]}} diff --git a/tests/core/data/contributions/spellings/literal_desugared/child.wic b/tests/core/data/contributions/spellings/literal_desugared/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/spellings/literal_desugared/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/spellings/literal_desugared/workflow.wic b/tests/core/data/contributions/spellings/literal_desugared/workflow.wic new file mode 100644 index 000000000..a4cda4c99 --- /dev/null +++ b/tests/core/data/contributions/spellings/literal_desugared/workflow.wic @@ -0,0 +1,13 @@ +# A contribution is opaque content, where each construct has two spellings. The tagged one is what a human writes +# and the desugared one is what the Python API and `render` emit, so a contribution that only understood tags would +# apply to a hand-written document and vanish from a round-tripped one. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: {wic_inline_input: shared.txt} +steps: +- id: child.wic diff --git a/tests/core/data/contributions/spellings/literal_tagged/child.wic b/tests/core/data/contributions/spellings/literal_tagged/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/spellings/literal_tagged/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/spellings/literal_tagged/workflow.wic b/tests/core/data/contributions/spellings/literal_tagged/workflow.wic new file mode 100644 index 000000000..f5369d75d --- /dev/null +++ b/tests/core/data/contributions/spellings/literal_tagged/workflow.wic @@ -0,0 +1,13 @@ +# A contribution is opaque content, where each construct has two spellings. The tagged one is what a human writes +# and the desugared one is what the Python API and `render` emit, so a contribution that only understood tags would +# apply to a hand-written document and vanish from a round-tripped one. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: !ii shared.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/spellings/raw_cwl_reference_desugared/child.wic b/tests/core/data/contributions/spellings/raw_cwl_reference_desugared/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/spellings/raw_cwl_reference_desugared/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/spellings/raw_cwl_reference_desugared/workflow.wic b/tests/core/data/contributions/spellings/raw_cwl_reference_desugared/workflow.wic new file mode 100644 index 000000000..502fc443b --- /dev/null +++ b/tests/core/data/contributions/spellings/raw_cwl_reference_desugared/workflow.wic @@ -0,0 +1,13 @@ +# A contribution is opaque content, where each construct has two spellings. The tagged one is what a human writes +# and the desugared one is what the Python API and `render` emit, so a contribution that only understood tags would +# apply to a hand-written document and vanish from a round-tripped one. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: {wic_raw_cwl: shared.txt} +steps: +- id: child.wic diff --git a/tests/core/data/contributions/spellings/raw_cwl_reference_tagged/child.wic b/tests/core/data/contributions/spellings/raw_cwl_reference_tagged/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/spellings/raw_cwl_reference_tagged/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/spellings/raw_cwl_reference_tagged/workflow.wic b/tests/core/data/contributions/spellings/raw_cwl_reference_tagged/workflow.wic new file mode 100644 index 000000000..7425f0743 --- /dev/null +++ b/tests/core/data/contributions/spellings/raw_cwl_reference_tagged/workflow.wic @@ -0,0 +1,13 @@ +# A contribution is opaque content, where each construct has two spellings. The tagged one is what a human writes +# and the desugared one is what the Python API and `render` emit, so a contribution that only understood tags would +# apply to a hand-written document and vanish from a round-tripped one. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: !cwl shared.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/spellings/untagged_mapping/child.wic b/tests/core/data/contributions/spellings/untagged_mapping/child.wic new file mode 100644 index 000000000..243f9fd9a --- /dev/null +++ b/tests/core/data/contributions/spellings/untagged_mapping/child.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_file diff --git a/tests/core/data/contributions/spellings/untagged_mapping/workflow.wic b/tests/core/data/contributions/spellings/untagged_mapping/workflow.wic new file mode 100644 index 000000000..e7960c4b1 --- /dev/null +++ b/tests/core/data/contributions/spellings/untagged_mapping/workflow.wic @@ -0,0 +1,13 @@ +# A contribution is opaque content, where each construct has two spellings. The tagged one is what a human writes +# and the desugared one is what the Python API and `render` emit, so a contribution that only understood tags would +# apply to a hand-written document and vanish from a round-tripped one. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: {a: 1} +steps: +- id: child.wic diff --git a/tests/core/data/contributions/stale/a_bare_id_naming_no_step/workflow.wic b/tests/core/data/contributions/stale/a_bare_id_naming_no_step/workflow.wic new file mode 100644 index 000000000..4d2730bb3 --- /dev/null +++ b/tests/core/data/contributions/stale/a_bare_id_naming_no_step/workflow.wic @@ -0,0 +1,8 @@ +# A bare id no step has addresses nothing: named on stderr and ignored. +wic: + steps: + nothing: + in: + name: !ii x.txt +steps: +- id: mk_file diff --git a/tests/core/data/contributions/stale/a_contribution_whose_key_does_not_match/child.wic b/tests/core/data/contributions/stale/a_contribution_whose_key_does_not_match/child.wic new file mode 100644 index 000000000..a6c5ef8f7 --- /dev/null +++ b/tests/core/data/contributions/stale/a_contribution_whose_key_does_not_match/child.wic @@ -0,0 +1,4 @@ +steps: +- id: mk_file + in: + name: !ii its_own.txt diff --git a/tests/core/data/contributions/stale/a_contribution_whose_key_does_not_match/workflow.wic b/tests/core/data/contributions/stale/a_contribution_whose_key_does_not_match/workflow.wic new file mode 100644 index 000000000..3cd967129 --- /dev/null +++ b/tests/core/data/contributions/stale/a_contribution_whose_key_does_not_match/workflow.wic @@ -0,0 +1,15 @@ +# `(N, name)` addresses one step, so half a match is no match: the key is ignored, and each such key is named once +# on stderr. +wic: + steps: + (1, child.wic): + wic: + steps: + (2, mk_file): + in: + name: !ii wrong_index.txt + (1, mk_text): + in: + name: !ii wrong_name.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/stale/a_stale_child_id_entry_does_not_pair/child.wic b/tests/core/data/contributions/stale/a_stale_child_id_entry_does_not_pair/child.wic new file mode 100644 index 000000000..dcff7686c --- /dev/null +++ b/tests/core/data/contributions/stale/a_stale_child_id_entry_does_not_pair/child.wic @@ -0,0 +1,8 @@ +wic: + steps: + mk_file: + in: + extra: !ii stale_child.txt +steps: +- id: mk_file +- id: mk_file diff --git a/tests/core/data/contributions/stale/a_stale_child_id_entry_does_not_pair/workflow.wic b/tests/core/data/contributions/stale/a_stale_child_id_entry_does_not_pair/workflow.wic new file mode 100644 index 000000000..bbb67d74a --- /dev/null +++ b/tests/core/data/contributions/stale/a_stale_child_id_entry_does_not_pair/workflow.wic @@ -0,0 +1,11 @@ +# A child bare id naming two steps addresses none, so it is not merged under the parent's (1, id) key. +wic: + steps: + (1, child.wic): + wic: + steps: + (1, mk_file): + in: + name: !ii from_root.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/stale/a_stale_key_is_named_once_however_many/child.wic b/tests/core/data/contributions/stale/a_stale_key_is_named_once_however_many/child.wic new file mode 100644 index 000000000..3ffa2352d --- /dev/null +++ b/tests/core/data/contributions/stale/a_stale_key_is_named_once_however_many/child.wic @@ -0,0 +1,5 @@ +wic: + steps: + (2, mk_file): {} +steps: +- id: mk_file diff --git a/tests/core/data/contributions/stale/a_stale_key_is_named_once_however_many/workflow.wic b/tests/core/data/contributions/stale/a_stale_key_is_named_once_however_many/workflow.wic new file mode 100644 index 000000000..9000be1a9 --- /dev/null +++ b/tests/core/data/contributions/stale/a_stale_key_is_named_once_however_many/workflow.wic @@ -0,0 +1,4 @@ +# A stale key is reported once however many steps call the workflow. +steps: +- id: child.wic +- id: child.wic diff --git a/tests/core/data/contributions/stale/a_stale_positional_key_from_the_parent/child.wic b/tests/core/data/contributions/stale/a_stale_positional_key_from_the_parent/child.wic new file mode 100644 index 000000000..a3889b299 --- /dev/null +++ b/tests/core/data/contributions/stale/a_stale_positional_key_from_the_parent/child.wic @@ -0,0 +1,7 @@ +wic: + steps: + mk_file: + in: + name: !ii child_own.txt +steps: +- id: mk_file diff --git a/tests/core/data/contributions/stale/a_stale_positional_key_from_the_parent/workflow.wic b/tests/core/data/contributions/stale/a_stale_positional_key_from_the_parent/workflow.wic new file mode 100644 index 000000000..e5faca3e5 --- /dev/null +++ b/tests/core/data/contributions/stale/a_stale_positional_key_from_the_parent/workflow.wic @@ -0,0 +1,11 @@ +# A parent key that addresses no step leaves the child's valid bare-id entry alone. +wic: + steps: + (1, child.wic): + wic: + steps: + (2, mk_file): + in: + name: !ii from_root.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/stale/a_stale_positional_key_in_the_child_does/child.wic b/tests/core/data/contributions/stale/a_stale_positional_key_in_the_child_does/child.wic new file mode 100644 index 000000000..ab14d40e9 --- /dev/null +++ b/tests/core/data/contributions/stale/a_stale_positional_key_in_the_child_does/child.wic @@ -0,0 +1,7 @@ +wic: + steps: + (2, mk_file): + in: + name: !ii child_stale.txt +steps: +- id: mk_file diff --git a/tests/core/data/contributions/stale/a_stale_positional_key_in_the_child_does/workflow.wic b/tests/core/data/contributions/stale/a_stale_positional_key_in_the_child_does/workflow.wic new file mode 100644 index 000000000..2c3d061b1 --- /dev/null +++ b/tests/core/data/contributions/stale/a_stale_positional_key_in_the_child_does/workflow.wic @@ -0,0 +1,11 @@ +# A child key that addresses no step leaves the parent's valid bare-id contribution alone. +wic: + steps: + (1, child.wic): + wic: + steps: + mk_file: + in: + name: !ii from_root.txt +steps: +- id: child.wic diff --git a/tests/core/data/contributions/stale/an_id_keyed_entry_for_a_repeated_id_is/workflow.wic b/tests/core/data/contributions/stale/an_id_keyed_entry_for_a_repeated_id_is/workflow.wic new file mode 100644 index 000000000..ab5fc0cbf --- /dev/null +++ b/tests/core/data/contributions/stale/an_id_keyed_entry_for_a_repeated_id_is/workflow.wic @@ -0,0 +1,9 @@ +# A bare id naming several steps is reported and ignored. +wic: + steps: + mk_file: + in: + name: !ii x.txt +steps: +- id: mk_file +- id: mk_file diff --git a/tests/core/data/contributions/stale/expected.yaml b/tests/core/data/contributions/stale/expected.yaml new file mode 100644 index 000000000..fb57c6841 --- /dev/null +++ b/tests/core/data/contributions/stale/expected.yaml @@ -0,0 +1,36 @@ +a_contribution_whose_key_does_not_match: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, its_own.txt]}} + said: + - {contains: ['key (2, mk_file) addresses no step of ''child''', there is no step 2; the document has 1 step]} + - {contains: ['key (1, mk_text) addresses no step of ''child''', 'step 1 is ''mk_file''; write (1, mk_file)']} +an_id_keyed_entry_for_a_repeated_id_is: + expect: + - {inputs: {exact: {}}} + - {step: 1, inputs: {exact: {}}} + said: + - {contains: [key mk_file addresses no step of 'workflow', '''mk_file'' names 2 steps; write (index, mk_file)']} +a_stale_key_is_named_once_however_many: + expect: [] + said: + - {startswith: 'Warning! '} +a_stale_positional_key_from_the_parent: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, child_own.txt]}} + said: + - {contains: ["key (2, mk_file) addresses no step of 'child'", there is no step 2]} +a_stale_positional_key_in_the_child_does: + expect: + - {depth: 1, inputs: {name: [InlineLiteral, from_root.txt]}} + said: + - {contains: [child.wic, "key (2, mk_file) addresses no step of 'child'"]} +a_stale_child_id_entry_does_not_pair: + expect: + - {depth: 1, inputs: {exact: {name: [InlineLiteral, from_root.txt]}}} + said: + - {contains: [child.wic, "key mk_file addresses no step of 'child'", "'mk_file' names 2 steps"]} +a_bare_id_naming_no_step: + expect: + - {inputs: {exact: {}}} + said: + - {contains: ["key nothing addresses no step of 'workflow'", "no step is called 'nothing'"]} diff --git a/tests/core/data/defaults/sub/child.wic b/tests/core/data/defaults/sub/child.wic new file mode 100644 index 000000000..6d438e612 --- /dev/null +++ b/tests/core/data/defaults/sub/child.wic @@ -0,0 +1,5 @@ +inputs: + cfg: {type: File, default: {class: File, location: other.txt}} +steps: +- id: xform + in: {file: cfg, name: !ii out.txt} diff --git a/tests/core/data/defaults/w.wic b/tests/core/data/defaults/w.wic new file mode 100644 index 000000000..94551bd37 --- /dev/null +++ b/tests/core/data/defaults/w.wic @@ -0,0 +1,20 @@ +# A `.wic` is read where it is and written elsewhere: a relative location in a `default:` names a file beside the +# `.wic` that wrote it, as a URI for a `location` and a path for a `path`. xform is a synthetic tool. +inputs: + cfg: {type: File, default: {class: File, location: data/config.txt}} + ref: {type: File, default: {class: File, path: data/ref.txt}} + far: {type: File, default: {class: File, location: "file:///elsewhere/far.txt"}} +steps: +- id: xform + in: {file: cfg, name: !ii a.txt} +- id: again + run: xform + in: {file: ref, name: !ii b.txt} +- id: third + run: xform + in: {file: far, name: !ii c.txt} +- id: call + run: sub/child.wic +- id: fourth + run: xform + in: {file: !cwl {default: {class: File, location: data/step.txt}}, name: !ii d.txt} diff --git a/tests/core/data/embedded_tools/cases.yaml b/tests/core/data/embedded_tools/cases.yaml deleted file mode 100644 index 7ab4313ab..000000000 --- a/tests/core/data/embedded_tools/cases.yaml +++ /dev/null @@ -1,62 +0,0 @@ -# A tool, whole, as `--cwl_inline_runtag` embeds it, and the keys of the embedded `run:` it must write, or the refusal. -# Expected by hand from CWL v1.0 -> v1.1 as cwltool's updater (cwltool/update.py, v1_0to1_1) applies it to a file it -# loads. -- {id: v1.0-gets-what-v1.0-implied, tool: {cwlVersion: v1.0, hints: {}}, - why: 'cwltool gives a v1.0 file network access and a deep listing', - embedded: {hints: {LoadListingRequirement: {loadListing: deep_listing}, NetworkAccess: {networkAccess: true}}}} -- {id: v1.0-without-hints, tool: {cwlVersion: v1.0}, why: 'no hints key is the usual case, not an exception', - embedded: {hints: {LoadListingRequirement: {loadListing: deep_listing}, NetworkAccess: {networkAccess: true}}}} -- {id: v1.1-gains-nothing, tool: {cwlVersion: v1.1, hints: {ResourceRequirement: {ramMin: 8}}}, - why: 'only v1.0 implied anything', - embedded: {hints: {ResourceRequirement: {ramMin: 8}}}} -- {id: v1.2-gains-nothing, tool: {cwlVersion: v1.2, hints: {ResourceRequirement: {ramMin: 8}}}, - why: 'only v1.0 implied anything', - embedded: {hints: {ResourceRequirement: {ramMin: 8}}}} -- {id: a-declared-hint-wins, tool: {cwlVersion: v1.0, hints: {NetworkAccess: {networkAccess: false}}}, - why: 'what the tool wrote wins', - embedded: {hints: {LoadListingRequirement: {loadListing: deep_listing}, NetworkAccess: {networkAccess: false}}}} -- {id: a-declared-requirement-wins, why: 'in whichever form it wrote it', tool: {cwlVersion: v1.0, hints: {}, - requirements: {LoadListingRequirement: {loadListing: no_listing}}}, - embedded: {hints: {NetworkAccess: {networkAccess: true}}}} -- {id: a-listed-requirement-wins, why: 'in whichever form it wrote it', tool: {cwlVersion: v1.0, hints: {}, - requirements: [{class: NetworkAccess, networkAccess: false}]}, - embedded: {hints: {LoadListingRequirement: {loadListing: deep_listing}}}} -- {id: hints-as-a-list, why: 'a packed tool writes its hints as a list of {class} entries', tool: {cwlVersion: v1.0, - hints: [{class: ResourceRequirement, ramMin: 8}]}, embedded: {hints: [{class: LoadListingRequirement, - loadListing: deep_listing}, - {class: NetworkAccess, networkAccess: true}, {class: ResourceRequirement, ramMin: 8}]}} -- {id: cwltool-prefix, why: 'cwltool renames the namespaced class; embedded, nothing does', - tool: {cwlVersion: v1.0, hints: { - 'cwltool:LoadListingRequirement': {loadListing: shallow_listing}, 'cwltool:NetworkAccess': {networkAccess: false}}}, - embedded: {hints: {LoadListingRequirement: {loadListing: shallow_listing}, NetworkAccess: {networkAccess: false}}}} -- {id: cwltool-uri, why: 'cwltool renames the namespaced class; embedded, nothing does', - tool: {cwlVersion: v1.0, hints: { - 'http://commonwl.org/cwltool#LoadListingRequirement': {loadListing: shallow_listing}, - 'http://commonwl.org/cwltool#NetworkAccess': {networkAccess: false}}}, - embedded: {hints: {LoadListingRequirement: {loadListing: shallow_listing}, NetworkAccess: {networkAccess: false}}}} -- {id: cwltool-prefix-listed, why: 'renamed in the list form too', tool: {cwlVersion: v1.0, - hints: [{class: 'cwltool:LoadListingRequirement', loadListing: no_listing}], - requirements: [{class: 'cwltool:NetworkAccess', networkAccess: true}]}, - embedded: {hints: [{class: LoadListingRequirement, loadListing: no_listing}], - requirements: [{class: NetworkAccess, networkAccess: true}]}} -- {id: cwltool-uri-listed, why: 'renamed in the list form too', tool: {cwlVersion: v1.0, - hints: [{class: 'http://commonwl.org/cwltool#LoadListingRequirement', loadListing: no_listing}], - requirements: [{class: 'http://commonwl.org/cwltool#NetworkAccess', networkAccess: true}]}, - embedded: {hints: [{class: LoadListingRequirement, loadListing: no_listing}], - requirements: [{class: NetworkAccess, networkAccess: true}]}} -- {id: one-secondary-file-pattern, why: "cwltool's v1.0 updater lists a single pattern, and its checker indexes the - list", - tool: {cwlVersion: v1.0, inputs: {name: {type: File, secondaryFiles: {pattern: .fai}}, - other: {type: File, secondaryFiles: [.crai, .csi]}, - plain: string}, outputs: {file: {type: File, secondaryFiles: .bai}}}, - embedded: {inputs: {name: {type: File, secondaryFiles: [{pattern: .fai}]}, - other: {type: File, secondaryFiles: [.crai, .csi]}, plain: string}, - outputs: {file: {type: File, secondaryFiles: [.bai]}}}} -- {id: one-secondary-file-pattern-on-listed-ports, why: 'the same for ports written as lists', tool: {cwlVersion: v1.0, - inputs: [{id: name, type: File, secondaryFiles: .fai}], outputs: [{id: file, type: File, secondaryFiles: .bai}]}, - embedded: {inputs: [{id: name, type: File, secondaryFiles: [.fai]}], - outputs: [{id: file, type: File, secondaryFiles: [.bai]}]}} -- {id: a-version-sophios-does-not-run, tool: {cwlVersion: v1.3.0-dev1}, says: "declares cwlVersion 'v1.3.0-dev1'", - why: 'embedding would otherwise guess what a version Sophios has never seen implied'} -- {id: no-version, tool: {class: CommandLineTool}, says: declares no cwlVersion, - why: 'the message does not claim it declared one'} diff --git a/tests/core/data/equivalence/cases.yaml b/tests/core/data/equivalence/cases.yaml deleted file mode 100644 index 629dfcb70..000000000 --- a/tests/core/data/equivalence/cases.yaml +++ /dev/null @@ -1,294 +0,0 @@ -- id: a step is missing - why: &differ "Pairs no strength may call equivalent: a relation that accepts any of these would make a differential - harness report zero divergences on a rewrite that changed behaviour." - left: {steps: [{id: a__step__1__mk, out: [file]}]} - right: {steps: []} - verdicts: {all: differs} -- id: a step names a different tool - why: *differ - left: {steps: [{id: a__step__1__mk, run: a__step__1__mk/mk.cwl, out: [file]}]} - right: {steps: [{id: a__step__1__xf, run: a__step__1__xf/xf.cwl, out: [file]}]} - verdicts: {all: differs} -- id: an edge points somewhere else - why: *differ - left: {steps: [{id: a__step__1__mk, in: {f: a__step__1__mk/file}}]} - right: {steps: [{id: a__step__1__mk, in: {f: a__step__2__xf/file}}]} - verdicts: {all: differs} -- id: an output disappeared - why: *differ - left: {steps: [], outputs: {x: {type: File}}} - right: {steps: [], outputs: {}} - verdicts: {all: differs} -- id: a requirement disappeared - why: *differ - left: {steps: [], requirements: {ScatterFeatureRequirement: {}}} - right: {steps: [], requirements: {}} - verdicts: {all: differs} -- id: an output changed format - why: "`format` is the only thing separating `mk_file` from `mk_text` in the synthetic registry, so a relation - comparing `type` alone cannot tell a workflow ending in one from a workflow ending in the other. Drop `format` - from `_SHAPE_KEYS` and this case fails." - left: {steps: [], outputs: {x: {type: File, format: "edam:format_2330"}}} - right: {steps: [], outputs: {x: {type: File, format: "edam:format_3752"}}} - verdicts: {all: differs} -- id: two workflow outputs swapped producers - why: "The case whose absence let `outputSource` stay dropped after the same argument had already been accepted for - `in[].source`. Nothing else can see it: `_port_shapes` reduces the outputs to a *sorted* multiset, which no - permutation of the pairing changes, and workflow outputs were not nodes, so the DAG check never saw them either." - left: {steps: [{id: a__step__1__mk_file, out: [file]}, {id: a__step__2__count, out: [n]}], - outputs: {p: {type: File, outputSource: a__step__1__mk_file/file}, - q: {type: int, outputSource: a__step__2__count/n}}} - right: {steps: [{id: a__step__1__mk_file, out: [file]}, {id: a__step__2__count, out: [n]}], - outputs: {p: {type: File, outputSource: a__step__2__count/n}, - q: {type: int, outputSource: a__step__1__mk_file/file}}} - verdicts: {all: differs} -- id: the relation is reflexive - why: "Necessary, and nowhere near sufficient — the `all: differs` cases are what make this meaningful rather than a - property of the constant function None." - left: {steps: [{id: a__step__1__mk, in: {f: x}, out: [file]}], requirements: {ScatterFeatureRequirement: {}}} - verdicts: {all: null} -- id: a divergence names where it found the difference - why: "A pipeline migration runs this over thousands of inputs. A report that says only \"not equivalent\" moves the - work to a human with two long documents." - left: {steps: [{id: a__step__1__mk, in: {f: left}}]} - right: {steps: [{id: a__step__1__mk, in: {f: right}}]} - verdicts: {IDENTICAL: {path: ".steps[0].in.f", left: left, right: right}} -- id: a divergence names a missing key - why: &paths "The two paths the case 'a divergence names where it found the difference' does not reach. A walk that - reported `` for these would still pass that case while being useless on the two shapes a real compiler diff - most often has: a key one side stopped emitting, and a step that vanished." - left: {steps: [], outputs: {x: {type: File}}} - right: {steps: [], outputs: {}} - verdicts: {IDENTICAL: {path: ".outputs.x", left: {type: File}, right: null}} -- id: a divergence names a shorter list - why: *paths - left: {steps: [{id: a__step__1__mk}]} - right: {steps: []} - verdicts: {IDENTICAL: {path: ".steps[]", left: 1, right: 0}} -- id: the DAG check sees a moved edge - why: "The companion for `_same_dag`'s derived graph. The `all: differs` case \"an edge points somewhere else\" is the - one that forced it to exist, so this asserts the mechanism directly rather than only through that verdict: two - documents with identical step ids and identical tool labels, differing only in where one `in:` source points, must - diverge at UP_TO_RENAMING with the DAG named as the place it happened." - left: {steps: [{id: a__step__1__mk, out: [file]}, {id: a__step__2__xform, in: {file: {source: a__step__1__mk/file}}}]} - right: {steps: [{id: a__step__1__mk, out: [file]}, {id: a__step__2__xform, - in: {file: {source: a__step__9__mk/file}}}]} - verdicts: {UP_TO_RENAMING: {path: ""}} -- id: the DAG check sees the same tools wired up differently - why: "The companion for `_dataflow`'s node labels. Both documents hold the same three tools, so the process multiset - agrees, and both graphs are three nodes with one edge and one isolate, so a bare `DiGraphMatcher` maps them onto - each other. Only matching nodes by the process each runs sees that the edge runs `mk_file -> xform` on one side - and `join -> xform` on the other. Written as its own case because mutating `node_match` to `True` left every other - case here green." - left: {steps: [{id: a__step__1__mk_file, run: mk_file.cwl, out: [file]}, - {id: a__step__2__join, run: join.cwl, out: [file]}, {id: a__step__3__xform, run: xform.cwl, - in: {file: {source: a__step__1__mk_file/file}}}]} - right: {steps: [{id: a__step__1__join, run: join.cwl, out: [file]}, - {id: a__step__2__mk_file, run: mk_file.cwl, out: [file]}, - {id: a__step__3__xform, run: xform.cwl, in: {file: {source: a__step__1__join/file}}}]} - verdicts: {UP_TO_RENAMING: {path: ""}} -- id: the DAG check sees one of two edges replaced by an outside source - why: "`join` binds `left` and `right` in both documents, so its two nodes have identical labels; on the right - `join.right` comes from outside the workflow, a node of its own, so the graphs differ in shape. It once isolated - `edge_match`; it stopped when a workflow-level source became a node, and mutating `edge_match` to `True` now fails - only 'a port rewired onto a differently typed workflow input'." - left: {steps: [{id: a__step__1__mk_file, out: [file]}, {id: a__step__2__join, - in: {left: {source: a__step__1__mk_file/file}, right: {source: a__step__1__mk_file/file}}}]} - right: {steps: [{id: a__step__1__mk_file, out: [file]}, {id: a__step__2__join, - in: {left: {source: a__step__1__mk_file/file}, right: {source: outside___right}}}]} - verdicts: {UP_TO_RENAMING: {path: ""}} -- id: an output port vanished from out - why: &meaning "Differences inside a step that carry meaning and that no renaming can produce: `UP_TO_RENAMING` - forgives a step's `id`, the directory of its `run` and the `source` inside each binding, and nothing else. Each - returned None once, when the relation looked only at `id` and `in[].source`." - left: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, out: [file, text]}]} - right: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, out: [file]}]} - verdicts: {UP_TO_RENAMING: differs} -- id: a step became scattered - why: *meaning - left: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, scatter: [name]}]} - right: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl}]} - verdicts: {UP_TO_RENAMING: differs} -- id: the scatter method changed - why: *meaning - left: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, scatter: [a, b], scatterMethod: dotproduct}]} - right: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, scatter: [a, b], scatterMethod: flat_crossproduct}]} - verdicts: {UP_TO_RENAMING: differs} -- id: a conditional flipped - why: *meaning - left: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, when: "$(true)"}]} - right: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, when: "$(false)"}]} - verdicts: {UP_TO_RENAMING: differs} -- id: an input default changed - why: *meaning - left: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, in: {name: {source: wf___name, default: 1}}}]} - right: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, in: {name: {source: wf___name, default: 999}}}]} - verdicts: {UP_TO_RENAMING: differs} -- id: a binding moved to another input - why: *meaning - left: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, in: {name: {source: wf___name}}}]} - right: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, in: {other: {source: wf___name}}}]} - verdicts: {UP_TO_RENAMING: differs} -- id: a valueFrom appeared - why: *meaning - left: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, in: {name: {source: wf___name}}}]} - right: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, - in: {name: {source: wf___name, valueFrom: "$(self + 1)"}}}]} - verdicts: {UP_TO_RENAMING: differs} -- id: embedding may move a child's ontology into its parent - why: "An embedded tool's `$schemas` can only be declared by the document holding it, so embedding moves it up, as it - moves `$namespaces`." - left: {class: Workflow, steps: [{id: echo, run: greeting~echo.cwl, out: []}]} - right: {class: Workflow, "$schemas": ["https://example.org/EDAM.owl"], - "$namespaces": {edam: "https://edamontology.org/"}, steps: [{id: echo, run: {class: CommandLineTool}, out: []}]} - verdicts: {UP_TO_EMBEDDING: null, UP_TO_ORDER: differs} -- id: only IDENTICAL compares key order at the root - why: &order "IDENTICAL is a claim about bytes; the weaker strengths are claims about a workflow, and a YAML mapping is - unordered by its own specification. Emitted key order is the subject here — `requirements` built from a set, eight - hash seeds giving eight orders — so a relation that normalised order away at every strength would make the - regression that predicate exists to catch invisible to it." - left: {class: Workflow, steps: []} - right: {steps: [], class: Workflow} - verdicts: {IDENTICAL: {path: " (key order)", left: [class, steps], right: [steps, class]}, UP_TO_ORDER: null, - UP_TO_EMBEDDING: null, UP_TO_RENAMING: null} -- id: only IDENTICAL compares key order in a step - why: *order - left: {steps: [{id: a__step__1__mk, out: [f], run: r}]} - right: {steps: [{id: a__step__1__mk, run: r, out: [f]}]} - verdicts: {IDENTICAL: {path: ".steps[0] (key order)"}, UP_TO_ORDER: null, UP_TO_EMBEDDING: null} -- id: the DAG check sees two edges dangling at different places - why: "The companion for `_dataflow` keeping absent producers as nodes. A reference to a step the document does not - contain is what a renaming that missed one site leaves behind, and it is the shape an IR migration fails at. - Discard those references and the two documents below are both \"one step, no edges\" and the relation calls them - equivalent; keep them and the tool at the far end of each edge is visibly different." - left: {steps: [{id: a__step__1__xform, in: {file: {source: a__step__7__mk_file/file}}}]} - right: {steps: [{id: a__step__1__xform, in: {file: {source: a__step__7__join/file}}}]} - verdicts: {UP_TO_RENAMING: {path: ""}} -- id: a declared step is not the same as one only referenced - why: "The companion for `_dataflow`'s `('external', ...)` node marker. Left declares `mk_file` and consumes its - output. Right consumes the same output from a step it never declares — a dangling reference, which is what a - migration that dropped a step from `steps:` while leaving its consumers intact produces. Both graphs are two nodes - and one edge, and neither document has ports or requirements to compare, so nothing but the marker separates them. - Relabelling absent producers as if they were declared steps left every other case here green." - left: {steps: [{id: a__step__1__mk_file}, {id: a__step__2__xform, in: {file: {source: a__step__1__mk_file/file}}}]} - right: {steps: [{id: a__step__2__xform, in: {file: {source: a__step__1__mk_file/file}}}]} - verdicts: {UP_TO_RENAMING: {path: ""}} -- id: the array forms of ports and requirements are read - why: &arrays "CWL admits `requirements` as a list of `{class: ...}` and ports as an array of records; the Sophios - compiler emits neither today, so without this those branches would be code no test reaches — and a migrated - pipeline that started emitting them would silently compare `repr` of a whole list against `repr` of another, i.e. - would still be \"working\"." - left: {steps: [], requirements: [{class: ScatterFeatureRequirement}], outputs: [{id: x, type: File}]} - right: {steps: [], requirements: {ScatterFeatureRequirement: {}}, outputs: {y: {type: File}}} - verdicts: {UP_TO_RENAMING: null} -- id: the array forms of ports and requirements are compared - why: *arrays - left: {steps: [], requirements: [{class: ScatterFeatureRequirement}], outputs: [{id: x, type: File}]} - right: {steps: [], requirements: [], outputs: []} - verdicts: {UP_TO_RENAMING: differs} -- id: isomorphism alone would not be enough - why: "Why the matcher is labelled rather than bare. The retired source-inlining regression compared two compilations - with a bare `DiGraphMatcher` and nothing else. These two documents have the same shape — two nodes, one edge — and - a different tool at every node, so a bare matcher calls them equivalent. That is precisely the kind of thing an IR - migration could get wrong, which is why the relation a migration imports must not be the one already in the tree. - Asserts the *verdict*, not the path string. Asserting `'tool multiset' in found.path` would be this project's - recurring failure written into the artifact everything imports: a separate tool-multiset check had by then been - subsumed by the labelled isomorphism, so the name of the test claimed a discrimination the code no longer - performed and only the string kept it green. The check was deleted; this is what remains, and it fails if - `node_match` stops looking at the label." - left: {steps: [{id: a__step__1__mk_file, run: mk_file.cwl, out: [file]}, - {id: a__step__2__xform, run: xform.cwl, in: {file: {source: a__step__1__mk_file/file}}}]} - right: {steps: [{id: a__step__1__mk_text, run: mk_text.cwl, out: [file]}, - {id: a__step__2__join, run: join.cwl, in: {file: {source: a__step__1__mk_text/file}}}]} - verdicts: {UP_TO_RENAMING: {path: ""}} -- id: a port rewired onto a differently typed workflow input - why: &inputs "The companion for `_dataflow`'s workflow-level input nodes. Every argument a step does not receive from - another step is emitted as `in: {arg: {source: {step_id}___{arg}}}` against a declared workflow-level input -- the - majority of the bindings in any compiled document. Those sources name no producer, and skipping them on that - ground makes the two documents below UP_TO_RENAMING-equal: both declare a `File` input and a `string` input, both - have one step and no edges, and which port reads which is nowhere in the comparison. Both directions, because the - fix must not overshoot. Feeding `left` from the `string` input instead of the `File` one is a divergence; feeding - it from the *other* `File` input is not, because relabelling two ports of the same shape is precisely what - re-rooting a namespace does." - left: {steps: [{id: a__step__1__join, in: {left: {source: a___p}, right: {source: a___q}}}], - inputs: {a___p: {type: File}, a___q: {type: string}}, outputs: {}} - right: {steps: [{id: a__step__1__join, in: {left: {source: a___q}, right: {source: a___p}}}], - inputs: {a___p: {type: File}, a___q: {type: string}}, outputs: {}} - verdicts: {UP_TO_RENAMING: {path: ""}} -- id: two ports swapped between workflow inputs of one type - why: *inputs - left: {steps: [{id: a__step__1__join, in: {left: {source: a___p}, right: {source: a___q}}}], - inputs: {a___p: {type: File}, a___q: {type: File}}, outputs: {}} - right: {steps: [{id: a__step__1__join, in: {left: {source: a___q}, right: {source: a___p}}}], - inputs: {a___p: {type: File}, a___q: {type: File}}, outputs: {}} - verdicts: {UP_TO_RENAMING: null} -- id: a workflow output rewired onto a differently typed producer - why: &outputs "The companion for `_dataflow`'s workflow-level output nodes. The mirror of the input-side cases, and - written the same way because the fix must not overshoot in the same direction: rewiring an output onto a - differently-shaped producer is a divergence, and permuting two outputs of the *same* shape is not, that - permutation being what a renaming is. The `all: differs` case 'two workflow outputs swapped producers' carries the - swap as well. This exists beside it to assert the mechanism — that the pairing lives in the graph — rather than - only the verdict, and to pin the second direction, which no `all: differs` case can express." - left: {steps: [{id: a__step__1__mk_file, out: [file]}, {id: a__step__2__count, out: [n]}], - outputs: {p: {type: File, outputSource: a__step__1__mk_file/file}, - q: {type: int, outputSource: a__step__2__count/n}}} - right: {steps: [{id: a__step__1__mk_file, out: [file]}, {id: a__step__2__count, out: [n]}], - outputs: {p: {type: File, outputSource: a__step__2__count/n}, - q: {type: int, outputSource: a__step__1__mk_file/file}}} - verdicts: {UP_TO_RENAMING: {path: ""}} -- id: two workflow outputs of one type swapped producers - why: *outputs - left: {steps: [{id: a__step__1__mk_file, out: [file]}, {id: a__step__2__count, out: [n]}], - outputs: {p: {type: File, outputSource: a__step__1__mk_file/file}, - q: {type: File, outputSource: a__step__2__count/n}}} - right: {steps: [{id: a__step__1__mk_file, out: [file]}, {id: a__step__2__count, out: [n]}], - outputs: {p: {type: File, outputSource: a__step__2__count/n}, - q: {type: File, outputSource: a__step__1__mk_file/file}}} - verdicts: {UP_TO_RENAMING: null} -- id: an output that lost its producer is not the same document - why: "The companion for `_dataflow` giving an output no node without a source. An output whose `outputSource` vanished - — the shape of a lowering that stopped wiring one up — keeps its declared shape, so `_port_shapes` cannot see it - go. The graph can: the node and its edge are simply absent." - left: {steps: [{id: a__step__1__mk_file, out: [file]}], outputs: {p: {type: File, - outputSource: a__step__1__mk_file/file}}} - right: {steps: [{id: a__step__1__mk_file, out: [file]}], outputs: {p: {type: File}}} - verdicts: {UP_TO_RENAMING: {path: ""}} -- id: mapping-form steps cannot be read - why: &loud "The module's WILL NOT READ contract, asserted rather than described. Each of these was previously read - as \"nothing here\" — a non-list `steps:` coerced to `[]`, a step without `id` filtered out, an array-form `in:` - forgiven by `_FORGIVEN_STEP_KEYS` and restored by neither reader — and so each made a pair of *different* - documents compare equal. Compared against an empty document, which is the pair that was equal, so a coercion - coming back returns this test to red rather than merely to a different exception." - left: {steps: {s: {run: r}}} - right: {steps: []} - verdicts: {UP_TO_RENAMING: TypeError} -- id: a step with no id cannot be read - why: *loud - left: {steps: [{out: [file]}]} - right: {steps: []} - verdicts: {UP_TO_RENAMING: TypeError} -- id: array-form in cannot be read - why: *loud - left: {steps: [{id: a__step__1__join, in: [{id: left, source: x}]}]} - right: {steps: []} - verdicts: {UP_TO_RENAMING: TypeError} -- id: an unparsable producer keeps its whole name - why: "The companion for `_dataflow`'s `('external', name)` label. A producer the document does not declare has no - `run:` to read, so it is labelled by the whole name it is referenced by. That is the *stricter* choice — two - different absent producers have to be equal rather than being lumped together as one anonymous \"external\". - Nothing else pins it: a constant label leaves these two documents equivalent." - left: {steps: [{id: a__step__1__xform, in: {file: {source: handwritten_a/file}}}]} - right: {steps: [{id: a__step__1__xform, in: {file: {source: handwritten_b/file}}}]} - verdicts: {UP_TO_RENAMING: {path: ""}} -- id: UP_TO_EMBEDDING forgives run - why: &run "`run` is the whole of what this strength ignores. `_rewrite_run_paths` shows the forgiveness happens; this - shows it stops there. A normalisation widened by one key — deleting `label` alongside `run`, say — is invisible to - every other case here, and that is the shape of change an IR migration makes when a key starts moving around." - left: {steps: [{id: a__step__1__mk_file, run: a__step__1__mk_file/mk_file.cwl, label: x}]} - right: {steps: [{id: a__step__1__mk_file, run: flat/mk_file.cwl, label: x}]} - verdicts: {UP_TO_EMBEDDING: null} -- id: UP_TO_EMBEDDING forgives nothing else - why: *run - left: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, label: x}]} - right: {steps: [{id: a__step__1__mk_file, run: a/mk_file.cwl, label: y}]} - verdicts: {UP_TO_EMBEDDING: {path: ".steps[0].label"}} diff --git a/tests/core/data/nextflow/runs/commands/cat_file.cwl b/tests/core/data/examples/commands/cat_file.cwl similarity index 100% rename from tests/core/data/nextflow/runs/commands/cat_file.cwl rename to tests/core/data/examples/commands/cat_file.cwl diff --git a/tests/core/data/nextflow/runs/commands/copy_file.cwl b/tests/core/data/examples/commands/copy_file.cwl similarity index 100% rename from tests/core/data/nextflow/runs/commands/copy_file.cwl rename to tests/core/data/examples/commands/copy_file.cwl diff --git a/tests/core/data/nextflow/runs/commands/count_bytes.cwl b/tests/core/data/examples/commands/count_bytes.cwl similarity index 100% rename from tests/core/data/nextflow/runs/commands/count_bytes.cwl rename to tests/core/data/examples/commands/count_bytes.cwl diff --git a/tests/core/data/nextflow/runs/commands/expected.yaml b/tests/core/data/examples/commands/expected.yaml similarity index 68% rename from tests/core/data/nextflow/runs/commands/expected.yaml rename to tests/core/data/examples/commands/expected.yaml index a6a25a7db..7a1a7147f 100644 --- a/tests/core/data/nextflow/runs/commands/expected.yaml +++ b/tests/core/data/examples/commands/expected.yaml @@ -18,3 +18,23 @@ outputs: produce~result: {class: File, basename: data.txt, contents: fanout} read_once~result: {class: File, basename: read.txt, contents: fanout} read_again~result: {class: File, basename: read.txt, contents: fanout} +# The CWL workflow.wic compiles to: its requirements, and of each step, in order, what it reads from another +# step or from a workflow input, and its scatter and when; a literal an input is given is left out. +compiled: + requirements: {exact: {}} + steps: + touch_file: {} + copy_file: {in: {source: touch_file/result}} + emit: {} + copy_emitted: {in: {source: {source: emit/stdout}}} + count_bytes: {in: {source: {source: emit/stdout}}} + three_words: {} + a_dollar: {} + an_ampersand: {} + append: {} + shell_redirect: {} + three_commands: {} + print_bindings: {} + produce: {} + read_once: {in: {source: {source: produce/result}}} + read_again: {in: {source: {source: produce/result}}} diff --git a/tests/core/data/nextflow/runs/commands/greeting.txt b/tests/core/data/examples/commands/greeting.txt similarity index 100% rename from tests/core/data/nextflow/runs/commands/greeting.txt rename to tests/core/data/examples/commands/greeting.txt diff --git a/tests/core/data/nextflow/runs/commands/print_bindings.cwl b/tests/core/data/examples/commands/print_bindings.cwl similarity index 100% rename from tests/core/data/nextflow/runs/commands/print_bindings.cwl rename to tests/core/data/examples/commands/print_bindings.cwl diff --git a/tests/core/data/nextflow/runs/commands/produce.cwl b/tests/core/data/examples/commands/produce.cwl similarity index 100% rename from tests/core/data/nextflow/runs/commands/produce.cwl rename to tests/core/data/examples/commands/produce.cwl diff --git a/tests/core/data/nextflow/runs/commands/shell_redirect.cwl b/tests/core/data/examples/commands/shell_redirect.cwl similarity index 100% rename from tests/core/data/nextflow/runs/commands/shell_redirect.cwl rename to tests/core/data/examples/commands/shell_redirect.cwl diff --git a/tests/core/data/nextflow/runs/commands/three_commands.cwl b/tests/core/data/examples/commands/three_commands.cwl similarity index 100% rename from tests/core/data/nextflow/runs/commands/three_commands.cwl rename to tests/core/data/examples/commands/three_commands.cwl diff --git a/tests/core/data/nextflow/runs/commands/touch_file.cwl b/tests/core/data/examples/commands/touch_file.cwl similarity index 100% rename from tests/core/data/nextflow/runs/commands/touch_file.cwl rename to tests/core/data/examples/commands/touch_file.cwl diff --git a/tests/core/data/nextflow/runs/commands/workflow.wic b/tests/core/data/examples/commands/workflow.wic similarity index 100% rename from tests/core/data/nextflow/runs/commands/workflow.wic rename to tests/core/data/examples/commands/workflow.wic diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/cat_pair.cwl b/tests/core/data/examples/conditions_and_scatter/cat_pair.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/cat_pair.cwl rename to tests/core/data/examples/conditions_and_scatter/cat_pair.cwl diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/copy_note.cwl b/tests/core/data/examples/conditions_and_scatter/copy_note.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/copy_note.cwl rename to tests/core/data/examples/conditions_and_scatter/copy_note.cwl diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/echo_item.cwl b/tests/core/data/examples/conditions_and_scatter/echo_item.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/echo_item.cwl rename to tests/core/data/examples/conditions_and_scatter/echo_item.cwl diff --git a/tests/core/data/examples/conditions_and_scatter/expected.yaml b/tests/core/data/examples/conditions_and_scatter/expected.yaml new file mode 100644 index 000000000..1d6ac584a --- /dev/null +++ b/tests/core/data/examples/conditions_and_scatter/expected.yaml @@ -0,0 +1,72 @@ +# Every output of workflow.wic, by step and port, in the order of its steps. +outputs: + up~result: "ok\n" + up_skipped~result: null + counted~result: "ok\n" + uncounted~result: null + carried~result: "ok\n" + gated~result: "1 2 3\n" + gated_prev_last~result: "1 2 3\n" + gated_after_skip~result: null + gated_flag_false~result: null + after_skip~done: {class: File, basename: done.txt, contents: ""} + write_note~note: {class: File, basename: note.txt, contents: "shared\n"} + copy_note~copy: + - {class: File, basename: a.txt, contents: "shared\n"} + - {class: File, basename: b.txt, contents: "shared\n"} + - {class: File, basename: c.txt, contents: "shared\n"} + echo_item~out: + - {class: File, basename: a.txt, contents: "1\n"} + - {class: File, basename: a.txt, contents: "2\n"} + - {class: File, basename: a.txt, contents: "3\n"} + cat_pair~out: + - {class: File, basename: b.txt, contents: "1\nREF\n"} + - {class: File, basename: b.txt, contents: "2\nREF\n"} + - {class: File, basename: b.txt, contents: "3\nREF\n"} + cat_pair_flat~out: + - {class: File, basename: b.txt, contents: "1\nREF\n"} + - {class: File, basename: b.txt, contents: "2\nREF\n"} + - {class: File, basename: b.txt, contents: "3\nREF\n"} + cat_pair_nested~out: + - {class: File, basename: b.txt, contents: "1\nREF\n"} + - {class: File, basename: b.txt, contents: "2\nREF\n"} + - {class: File, basename: b.txt, contents: "3\nREF\n"} + pair_nested~line: + - - {class: File, basename: out.txt, contents: a-x} + - {class: File, basename: out.txt, contents: a-y} + - - {class: File, basename: out.txt, contents: b-x} + - {class: File, basename: out.txt, contents: b-y} + pair_unless_b~line: + - {class: File, basename: out.txt, contents: "a-x"} + - null + - {class: File, basename: out.txt, contents: "c-z"} + pair_unless_skipped~line: + - {class: File, basename: out.txt, contents: "a-0.2"} + - null + - {class: File, basename: out.txt, contents: "c-0"} +# The CWL workflow.wic compiles to: its requirements, and of each step, in order, what it reads from another +# step or from a workflow input, and its scatter and when; a literal an input is given is left out. +compiled: + requirements: {InlineJavascriptRequirement: {}, ScatterFeatureRequirement: {}} + steps: + up: {in: {go: go}, when: $(inputs.go)} + up_skipped: {in: {go: no_go}, when: $(inputs.go)} + counted: {in: {go: go}, when: $(inputs.n > 0)} + uncounted: {in: {go: go}, when: $(inputs.n > 0)} + carried: {in: {go: no_go, enabled: {source: go}}, when: $(inputs.enabled)} + gated: {in: {flag: go, maybe: maybe, xs: xs, prev: {source: up/result}}, + when: &gate $(inputs.prev !== null && inputs.flag && inputs.maybe === null)} + gated_prev_last: {in: {flag: go, maybe: maybe, xs: xs, prev: {source: up/result}}, when: *gate} + gated_after_skip: {in: {flag: go, maybe: maybe, xs: xs, prev: {source: up_skipped/result}}, when: *gate} + gated_flag_false: {in: {flag: no_go, maybe: maybe, xs: xs, prev: {source: up/result}}, when: *gate} + after_skip: {in: {maybe: {source: uncounted/result}}} + write_note: {in: {after: {source: counted/result}}} + copy_note: {in: {note: {source: write_note/note}}, scatter: [name], scatterMethod: dotproduct} + echo_item: {scatter: [item], scatterMethod: dotproduct} + cat_pair: {in: {f: {source: echo_item/out}}, scatter: [f], scatterMethod: dotproduct} + cat_pair_flat: {in: {f: {source: echo_item/out}}, scatter: [f], scatterMethod: flat_crossproduct} + cat_pair_nested: {in: {f: {source: echo_item/out}}, scatter: [f], scatterMethod: nested_crossproduct} + pair_nested: {scatter: [first, second], scatterMethod: nested_crossproduct} + pair_unless_b: {scatter: [first, second], scatterMethod: dotproduct, when: $(inputs.first !== 'b')} + pair_unless_skipped: {scatter: [first, seconds], scatterMethod: dotproduct, + when: $(inputs.seconds !== inputs.skipped)} diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/job.yml b/tests/core/data/examples/conditions_and_scatter/job.yml similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/job.yml rename to tests/core/data/examples/conditions_and_scatter/job.yml diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/never_runs.cwl b/tests/core/data/examples/conditions_and_scatter/never_runs.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/never_runs.cwl rename to tests/core/data/examples/conditions_and_scatter/never_runs.cwl diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if.cwl b/tests/core/data/examples/conditions_and_scatter/numbers_if.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if.cwl rename to tests/core/data/examples/conditions_and_scatter/numbers_if.cwl diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if_prev_last.cwl b/tests/core/data/examples/conditions_and_scatter/numbers_if_prev_last.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/numbers_if_prev_last.cwl rename to tests/core/data/examples/conditions_and_scatter/numbers_if_prev_last.cwl diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/pair.cwl b/tests/core/data/examples/conditions_and_scatter/pair.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/pair.cwl rename to tests/core/data/examples/conditions_and_scatter/pair.cwl diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/pair_after_sleeping.cwl b/tests/core/data/examples/conditions_and_scatter/pair_after_sleeping.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/pair_after_sleeping.cwl rename to tests/core/data/examples/conditions_and_scatter/pair_after_sleeping.cwl diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/ref.txt b/tests/core/data/examples/conditions_and_scatter/ref.txt similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/ref.txt rename to tests/core/data/examples/conditions_and_scatter/ref.txt diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/say_ok.cwl b/tests/core/data/examples/conditions_and_scatter/say_ok.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/say_ok.cwl rename to tests/core/data/examples/conditions_and_scatter/say_ok.cwl diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/touch_done.cwl b/tests/core/data/examples/conditions_and_scatter/touch_done.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/touch_done.cwl rename to tests/core/data/examples/conditions_and_scatter/touch_done.cwl diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/workflow.wic b/tests/core/data/examples/conditions_and_scatter/workflow.wic similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/workflow.wic rename to tests/core/data/examples/conditions_and_scatter/workflow.wic diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/write_note.cwl b/tests/core/data/examples/conditions_and_scatter/write_note.cwl similarity index 100% rename from tests/core/data/nextflow/runs/conditions_and_scatter/write_note.cwl rename to tests/core/data/examples/conditions_and_scatter/write_note.cwl diff --git a/tests/core/data/nextflow/runs/nested/child.wic b/tests/core/data/examples/nested/child.wic similarity index 100% rename from tests/core/data/nextflow/runs/nested/child.wic rename to tests/core/data/examples/nested/child.wic diff --git a/tests/core/data/nextflow/runs/nested/copy_file.cwl b/tests/core/data/examples/nested/copy_file.cwl similarity index 100% rename from tests/core/data/nextflow/runs/nested/copy_file.cwl rename to tests/core/data/examples/nested/copy_file.cwl diff --git a/tests/core/data/nextflow/runs/nested/count_lines.cwl b/tests/core/data/examples/nested/count_lines.cwl similarity index 100% rename from tests/core/data/nextflow/runs/nested/count_lines.cwl rename to tests/core/data/examples/nested/count_lines.cwl diff --git a/tests/core/data/nextflow/runs/nested/echo_each.cwl b/tests/core/data/examples/nested/echo_each.cwl similarity index 100% rename from tests/core/data/nextflow/runs/nested/echo_each.cwl rename to tests/core/data/examples/nested/echo_each.cwl diff --git a/tests/core/data/nextflow/runs/nested/expected.yaml b/tests/core/data/examples/nested/expected.yaml similarity index 63% rename from tests/core/data/nextflow/runs/nested/expected.yaml rename to tests/core/data/examples/nested/expected.yaml index c1e0dce0e..1c555de4a 100644 --- a/tests/core/data/nextflow/runs/nested/expected.yaml +++ b/tests/core/data/examples/nested/expected.yaml @@ -11,3 +11,13 @@ outputs: count_lines~count: {class: File, basename: count.txt, contents: "1\n"} sibling~copy_file~result: {class: File, basename: copy.txt, contents: "nested composition\n"} touch_n~out: {class: File, basename: n.txt, contents: ""} +# The CWL workflow.wic compiles to: its requirements, and of each step, in order, what it reads from another +# step or from a workflow input, and its scatter and when; a literal an input is given is left out. +compiled: + requirements: {SubworkflowFeatureRequirement: {}} + steps: + write_source: {} + child: {in: {source: {source: write_source/result}}} + count_lines: {in: {source: {source: child/copy}}} + sibling: {in: {source: {source: write_source/result}}} + touch_n: {} diff --git a/tests/core/data/nextflow/runs/nested/grandchild.wic b/tests/core/data/examples/nested/grandchild.wic similarity index 100% rename from tests/core/data/nextflow/runs/nested/grandchild.wic rename to tests/core/data/examples/nested/grandchild.wic diff --git a/tests/core/data/nextflow/runs/nested/sibling.wic b/tests/core/data/examples/nested/sibling.wic similarity index 100% rename from tests/core/data/nextflow/runs/nested/sibling.wic rename to tests/core/data/examples/nested/sibling.wic diff --git a/tests/core/data/nextflow/runs/nested/touch_n.cwl b/tests/core/data/examples/nested/touch_n.cwl similarity index 100% rename from tests/core/data/nextflow/runs/nested/touch_n.cwl rename to tests/core/data/examples/nested/touch_n.cwl diff --git a/tests/core/data/nextflow/runs/nested/workflow.wic b/tests/core/data/examples/nested/workflow.wic similarity index 100% rename from tests/core/data/nextflow/runs/nested/workflow.wic rename to tests/core/data/examples/nested/workflow.wic diff --git a/tests/core/data/nextflow/runs/nested/write_source.cwl b/tests/core/data/examples/nested/write_source.cwl similarity index 100% rename from tests/core/data/nextflow/runs/nested/write_source.cwl rename to tests/core/data/examples/nested/write_source.cwl diff --git a/tests/core/data/nextflow/runs/outputs/backtick_named.cwl b/tests/core/data/examples/outputs/backtick_named.cwl similarity index 100% rename from tests/core/data/nextflow/runs/outputs/backtick_named.cwl rename to tests/core/data/examples/outputs/backtick_named.cwl diff --git a/tests/core/data/nextflow/runs/outputs/brace_named.cwl b/tests/core/data/examples/outputs/brace_named.cwl similarity index 100% rename from tests/core/data/nextflow/runs/outputs/brace_named.cwl rename to tests/core/data/examples/outputs/brace_named.cwl diff --git a/tests/core/data/nextflow/runs/outputs/dollar_named.cwl b/tests/core/data/examples/outputs/dollar_named.cwl similarity index 100% rename from tests/core/data/nextflow/runs/outputs/dollar_named.cwl rename to tests/core/data/examples/outputs/dollar_named.cwl diff --git a/tests/core/data/nextflow/runs/outputs/expected.yaml b/tests/core/data/examples/outputs/expected.yaml similarity index 59% rename from tests/core/data/nextflow/runs/outputs/expected.yaml rename to tests/core/data/examples/outputs/expected.yaml index da7619c12..88a213307 100644 --- a/tests/core/data/nextflow/runs/outputs/expected.yaml +++ b/tests/core/data/examples/outputs/expected.yaml @@ -9,3 +9,17 @@ outputs: pattern_none~o: null pattern_one~o: {class: File, basename: a.log, contents: ""} touch_names~result: {class: File, basename: a.txt, contents: ""} +# The CWL workflow.wic compiles to: its requirements, and of each step, in order, what it reads from another +# step or from a workflow input, and its scatter and when; a literal an input is given is left out. +compiled: + requirements: {exact: {}} + steps: + brace_named: {} + dollar_named: {} + backtick_named: {} + first_of_braces: {} + named_absent: {} + named_present: {} + pattern_none: {} + pattern_one: {} + touch_names: {} diff --git a/tests/core/data/nextflow/runs/outputs/first_of_braces.cwl b/tests/core/data/examples/outputs/first_of_braces.cwl similarity index 100% rename from tests/core/data/nextflow/runs/outputs/first_of_braces.cwl rename to tests/core/data/examples/outputs/first_of_braces.cwl diff --git a/tests/core/data/nextflow/runs/outputs/maybe_log.cwl b/tests/core/data/examples/outputs/maybe_log.cwl similarity index 100% rename from tests/core/data/nextflow/runs/outputs/maybe_log.cwl rename to tests/core/data/examples/outputs/maybe_log.cwl diff --git a/tests/core/data/nextflow/runs/outputs/maybe_named.cwl b/tests/core/data/examples/outputs/maybe_named.cwl similarity index 100% rename from tests/core/data/nextflow/runs/outputs/maybe_named.cwl rename to tests/core/data/examples/outputs/maybe_named.cwl diff --git a/tests/core/data/nextflow/runs/outputs/touch_names.cwl b/tests/core/data/examples/outputs/touch_names.cwl similarity index 100% rename from tests/core/data/nextflow/runs/outputs/touch_names.cwl rename to tests/core/data/examples/outputs/touch_names.cwl diff --git a/tests/core/data/nextflow/runs/outputs/workflow.wic b/tests/core/data/examples/outputs/workflow.wic similarity index 100% rename from tests/core/data/nextflow/runs/outputs/workflow.wic rename to tests/core/data/examples/outputs/workflow.wic diff --git a/tests/core/data/nextflow/runs/resources/expected.yaml b/tests/core/data/examples/resources/expected.yaml similarity index 52% rename from tests/core/data/nextflow/runs/resources/expected.yaml rename to tests/core/data/examples/resources/expected.yaml index e22cf4318..5b96ad73c 100644 --- a/tests/core/data/nextflow/runs/resources/expected.yaml +++ b/tests/core/data/examples/resources/expected.yaml @@ -3,3 +3,9 @@ why: cwltool runs the tool only on a machine with the two devices, so there is n reference: none outputs: make_dir~result: {class: Directory, basename: made, contents: {}} +# The CWL workflow.wic compiles to: its requirements, and of each step, in order, what it reads from another +# step or from a workflow input, and its scatter and when; a literal an input is given is left out. +compiled: + requirements: {exact: {}} + steps: + make_dir: {} diff --git a/tests/core/data/nextflow/runs/resources/make_dir.cwl b/tests/core/data/examples/resources/make_dir.cwl similarity index 100% rename from tests/core/data/nextflow/runs/resources/make_dir.cwl rename to tests/core/data/examples/resources/make_dir.cwl diff --git a/tests/core/data/nextflow/runs/resources/nextflow.config b/tests/core/data/examples/resources/nextflow.config similarity index 100% rename from tests/core/data/nextflow/runs/resources/nextflow.config rename to tests/core/data/examples/resources/nextflow.config diff --git a/tests/core/data/nextflow/runs/resources/workflow.nf b/tests/core/data/examples/resources/workflow.nf similarity index 100% rename from tests/core/data/nextflow/runs/resources/workflow.nf rename to tests/core/data/examples/resources/workflow.nf diff --git a/tests/core/data/nextflow/runs/resources/workflow.wic b/tests/core/data/examples/resources/workflow.wic similarity index 100% rename from tests/core/data/nextflow/runs/resources/workflow.wic rename to tests/core/data/examples/resources/workflow.wic diff --git a/tests/core/data/nextflow/runs/staging/capture_own_entry.cwl b/tests/core/data/examples/staging/capture_own_entry.cwl similarity index 100% rename from tests/core/data/nextflow/runs/staging/capture_own_entry.cwl rename to tests/core/data/examples/staging/capture_own_entry.cwl diff --git a/tests/core/data/nextflow/runs/staging/capture_renamed_entry.cwl b/tests/core/data/examples/staging/capture_renamed_entry.cwl similarity index 100% rename from tests/core/data/nextflow/runs/staging/capture_renamed_entry.cwl rename to tests/core/data/examples/staging/capture_renamed_entry.cwl diff --git a/tests/core/data/nextflow/runs/staging/copy_named_after_source.cwl b/tests/core/data/examples/staging/copy_named_after_source.cwl similarity index 100% rename from tests/core/data/nextflow/runs/staging/copy_named_after_source.cwl rename to tests/core/data/examples/staging/copy_named_after_source.cwl diff --git a/tests/core/data/nextflow/runs/staging/expected.yaml b/tests/core/data/examples/staging/expected.yaml similarity index 56% rename from tests/core/data/nextflow/runs/staging/expected.yaml rename to tests/core/data/examples/staging/expected.yaml index b4ecf5cd2..cfd78fd2d 100644 --- a/tests/core/data/nextflow/runs/staging/expected.yaml +++ b/tests/core/data/examples/staging/expected.yaml @@ -9,3 +9,16 @@ outputs: copy_captured~result: {class: File, basename: lines.txt.copy, contents: "staged content\n"} capture_renamed_entry~wild: {class: File, basename: renamed.txt, contents: "staged content\n"} plugin~outDir: {class: Directory, basename: plugin_out, contents: {result.txt: written}} +# The CWL workflow.wic compiles to: its requirements, and of each step, in order, what it reads from another +# step or from a workflow input, and its scatter and when; a literal an input is given is left out. +compiled: + requirements: {exact: {}} + steps: + write_source: {} + copy_named_after_source: {in: {source: {source: write_source/result}}} + stage_own_basename: {in: {source: {source: write_source/result}}} + stage_and_read: {in: {source: {source: write_source/result}}} + capture_own_entry: {in: {source: {source: write_source/result}}} + copy_captured: {in: {source: {source: capture_own_entry/same}}} + capture_renamed_entry: {in: {source: {source: write_source/result}}} + plugin: {} diff --git a/tests/core/data/nextflow/runs/staging/plugin.cwl b/tests/core/data/examples/staging/plugin.cwl similarity index 100% rename from tests/core/data/nextflow/runs/staging/plugin.cwl rename to tests/core/data/examples/staging/plugin.cwl diff --git a/tests/core/data/nextflow/runs/staging/stage_and_read.cwl b/tests/core/data/examples/staging/stage_and_read.cwl similarity index 100% rename from tests/core/data/nextflow/runs/staging/stage_and_read.cwl rename to tests/core/data/examples/staging/stage_and_read.cwl diff --git a/tests/core/data/nextflow/runs/staging/stage_own_basename.cwl b/tests/core/data/examples/staging/stage_own_basename.cwl similarity index 100% rename from tests/core/data/nextflow/runs/staging/stage_own_basename.cwl rename to tests/core/data/examples/staging/stage_own_basename.cwl diff --git a/tests/core/data/nextflow/runs/staging/workflow.wic b/tests/core/data/examples/staging/workflow.wic similarity index 100% rename from tests/core/data/nextflow/runs/staging/workflow.wic rename to tests/core/data/examples/staging/workflow.wic diff --git a/tests/core/data/nextflow/runs/staging/write_source.cwl b/tests/core/data/examples/staging/write_source.cwl similarity index 100% rename from tests/core/data/nextflow/runs/staging/write_source.cwl rename to tests/core/data/examples/staging/write_source.cwl diff --git a/tests/core/data/nextflow/runs/step_inputs/cat_files.cwl b/tests/core/data/examples/step_inputs/cat_files.cwl similarity index 100% rename from tests/core/data/nextflow/runs/step_inputs/cat_files.cwl rename to tests/core/data/examples/step_inputs/cat_files.cwl diff --git a/tests/core/data/examples/step_inputs/expected.yaml b/tests/core/data/examples/step_inputs/expected.yaml new file mode 100644 index 000000000..7b840f021 --- /dev/null +++ b/tests/core/data/examples/step_inputs/expected.yaml @@ -0,0 +1,43 @@ +# Every output of workflow.wic, by step and port, in the order of its steps. +outputs: + write_each~file: + - {class: File, basename: out.txt, contents: "a\n"} + - {class: File, basename: out.txt, contents: "b\n"} + write_one~file: {class: File, basename: out.txt, contents: "c\n"} + write_two~file: {class: File, basename: out.txt, contents: "d\n"} + skipped~said: null + ran~said: only + cat_flat~line: {class: File, basename: all.txt, contents: "a\nb\nc\n"} + cat_nested~line: {class: File, basename: all.txt, contents: "d\nc\n"} + cat_single~line: {class: File, basename: all.txt, contents: "c\n"} + say_nested~line: {class: File, basename: out.txt, contents: "x y z\n"} + say_single~line: {class: File, basename: out.txt, contents: "x\n"} + default_unsourced~line: {class: File, basename: out.txt, contents: "d1\n"} + default_for_absent~line: {class: File, basename: out.txt, contents: "d2\n"} + default_not_taken~line: {class: File, basename: out.txt, contents: "g\n"} + default_after_skip~line: {class: File, basename: out.txt, contents: "d4\n"} + pick_first~line: {class: File, basename: out.txt, contents: "g\n"} + pick_only~line: {class: File, basename: out.txt, contents: "only\n"} + pick_all~line: {class: File, basename: out.txt, contents: "g only\n"} +# The CWL workflow.wic compiles to: its requirements, and of each step, in order, what it reads from another +# step or from a workflow input, and its scatter and when; a literal an input is given is left out. +compiled: + requirements: {InlineJavascriptRequirement: {}, MultipleInputFeatureRequirement: {}, ScatterFeatureRequirement: {}} + steps: + write_each: {scatter: [name], scatterMethod: dotproduct} + write_one: {} + write_two: {} + skipped: {when: $(inputs.go)} + ran: {when: $(inputs.go)} + cat_flat: {in: {files: {source: [write_each/file, write_one/file], linkMerge: merge_flattened}}} + cat_nested: {in: {files: {source: [write_two/file, write_one/file]}}} + cat_single: {in: {files: {source: [write_one/file], linkMerge: merge_nested}}} + say_nested: {in: {words: {source: [x, y]}}} + say_single: {in: {words: {source: [x], linkMerge: merge_nested}}} + default_unsourced: {in: {words: {default: d1}}} + default_for_absent: {in: {words: {source: unset, default: d2}}} + default_not_taken: {in: {words: {source: given, default: d3}}} + default_after_skip: {in: {words: {source: skipped/said, default: d4}}} + pick_first: {in: {words: {source: [unset, skipped/said, given, x], pickValue: first_non_null}}} + pick_only: {in: {words: {source: [skipped/said, ran/said], pickValue: the_only_non_null}}} + pick_all: {in: {words: {source: [given, skipped/said, ran/said, unset], pickValue: all_non_null}}} diff --git a/tests/core/data/nextflow/runs/step_inputs/job.yml b/tests/core/data/examples/step_inputs/job.yml similarity index 100% rename from tests/core/data/nextflow/runs/step_inputs/job.yml rename to tests/core/data/examples/step_inputs/job.yml diff --git a/tests/core/data/nextflow/runs/step_inputs/say_if.cwl b/tests/core/data/examples/step_inputs/say_if.cwl similarity index 100% rename from tests/core/data/nextflow/runs/step_inputs/say_if.cwl rename to tests/core/data/examples/step_inputs/say_if.cwl diff --git a/tests/core/data/nextflow/runs/step_inputs/say_word.cwl b/tests/core/data/examples/step_inputs/say_word.cwl similarity index 100% rename from tests/core/data/nextflow/runs/step_inputs/say_word.cwl rename to tests/core/data/examples/step_inputs/say_word.cwl diff --git a/tests/core/data/nextflow/runs/step_inputs/say_words.cwl b/tests/core/data/examples/step_inputs/say_words.cwl similarity index 100% rename from tests/core/data/nextflow/runs/step_inputs/say_words.cwl rename to tests/core/data/examples/step_inputs/say_words.cwl diff --git a/tests/core/data/nextflow/runs/step_inputs/workflow.wic b/tests/core/data/examples/step_inputs/workflow.wic similarity index 100% rename from tests/core/data/nextflow/runs/step_inputs/workflow.wic rename to tests/core/data/examples/step_inputs/workflow.wic diff --git a/tests/core/data/nextflow/runs/step_inputs/write_name.cwl b/tests/core/data/examples/step_inputs/write_name.cwl similarity index 100% rename from tests/core/data/nextflow/runs/step_inputs/write_name.cwl rename to tests/core/data/examples/step_inputs/write_name.cwl diff --git a/tests/core/data/infer/calls/a_call_output_is_a_candidate/sub.wic b/tests/core/data/infer/calls/a_call_output_is_a_candidate/sub.wic new file mode 100644 index 000000000..a1d6d2ec4 --- /dev/null +++ b/tests/core/data/infer/calls/a_call_output_is_a_candidate/sub.wic @@ -0,0 +1,3 @@ +steps: +- id: mk_file + in: {name: !ii child.txt} diff --git a/tests/core/data/infer/calls/a_call_output_is_a_candidate/workflow.wic b/tests/core/data/infer/calls/a_call_output_is_a_candidate/workflow.wic new file mode 100644 index 000000000..f40162114 --- /dev/null +++ b/tests/core/data/infer/calls/a_call_output_is_a_candidate/workflow.wic @@ -0,0 +1,4 @@ +# A child output stays visible to a later tool in its parent. +steps: +- id: sub.wic +- id: count diff --git a/tests/core/data/infer/calls/a_file_fanned_out_to_two_inner_steps/fan.wic b/tests/core/data/infer/calls/a_file_fanned_out_to_two_inner_steps/fan.wic new file mode 100644 index 000000000..db9e1283f --- /dev/null +++ b/tests/core/data/infer/calls/a_file_fanned_out_to_two_inner_steps/fan.wic @@ -0,0 +1,3 @@ +steps: +- id: count +- id: count diff --git a/tests/core/data/infer/calls/a_file_fanned_out_to_two_inner_steps/workflow.wic b/tests/core/data/infer/calls/a_file_fanned_out_to_two_inner_steps/workflow.wic new file mode 100644 index 000000000..af9474bf1 --- /dev/null +++ b/tests/core/data/infer/calls/a_file_fanned_out_to_two_inner_steps/workflow.wic @@ -0,0 +1,6 @@ +# Each inner `count` is a tool step of its own, so each reads the file once. +steps: +- id: mk_file + in: + name: !ii a.txt +- id: fan.wic diff --git a/tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/fan.wic b/tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/fan.wic new file mode 100644 index 000000000..71e76883b --- /dev/null +++ b/tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/fan.wic @@ -0,0 +1,12 @@ +steps: +- id: count + in: + file: a +- id: xform + in: + file: b +inputs: + a: + type: File + b: + type: File diff --git a/tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/mid.wic b/tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/mid.wic new file mode 100644 index 000000000..ec6700fd5 --- /dev/null +++ b/tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/mid.wic @@ -0,0 +1,10 @@ +steps: +- id: fan.wic + in: + a: x + b: y +inputs: + x: + type: File + y: + type: File diff --git a/tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/workflow.wic b/tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/workflow.wic new file mode 100644 index 000000000..4a00cfcc0 --- /dev/null +++ b/tests/core/data/infer/calls/a_file_fanned_out_two_calls_down/workflow.wic @@ -0,0 +1,6 @@ +# `x` and `y` reach `count` and `xform` two calls down: two tool steps, each reading the file once. +steps: +- id: mk_file + in: + name: !ii a.txt +- id: mid.wic diff --git a/tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/make.wic b/tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/make.wic new file mode 100644 index 000000000..0e11fc51c --- /dev/null +++ b/tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/make.wic @@ -0,0 +1,2 @@ +steps: +- id: multi_file diff --git a/tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/use.wic b/tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/use.wic new file mode 100644 index 000000000..5d325c8eb --- /dev/null +++ b/tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/use.wic @@ -0,0 +1,2 @@ +steps: +- id: count diff --git a/tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/workflow.wic b/tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/workflow.wic new file mode 100644 index 000000000..73e81b4d0 --- /dev/null +++ b/tests/core/data/infer/calls/a_note_names_the_call_and_the_steps_down/workflow.wic @@ -0,0 +1,4 @@ +# The input is named at the call the author wrote, and the output by the steps down to the one that makes it. +steps: +- id: make.wic +- id: use.wic diff --git a/tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/pair.cwl b/tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/pair.cwl new file mode 100644 index 000000000..5872c51bb --- /dev/null +++ b/tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/pair.cwl @@ -0,0 +1,11 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + left: + type: File + inputBinding: {position: 1} + right: + type: File + inputBinding: {position: 1} +outputs: {} diff --git a/tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/src.wic b/tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/src.wic new file mode 100644 index 000000000..6ef5f5812 --- /dev/null +++ b/tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/src.wic @@ -0,0 +1,6 @@ +steps: +- id: mk_file + in: + name: !ii a.txt + out: + - file: !& f diff --git a/tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/workflow.wic b/tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/workflow.wic new file mode 100644 index 000000000..629196bbf --- /dev/null +++ b/tests/core/data/infer/calls/a_written_edge_to_an_anchor_in_a_call/workflow.wic @@ -0,0 +1,7 @@ +# `left` is written to the anchor `f` inside the call; `right` is inferred from the call's exposed port. Compiled +# whole, so the written edge reaches the deep output the way a document's does. +steps: +- id: src.wic +- id: pair + in: + left: !* f diff --git a/tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/make.wic b/tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/make.wic new file mode 100644 index 000000000..c69de9c15 --- /dev/null +++ b/tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/make.wic @@ -0,0 +1,4 @@ +steps: +- id: multi_file + out: + - first: !& f diff --git a/tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/use.wic b/tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/use.wic new file mode 100644 index 000000000..d09687f9c --- /dev/null +++ b/tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/use.wic @@ -0,0 +1,4 @@ +steps: +- id: count + in: + file: !* f diff --git a/tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/workflow.wic b/tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/workflow.wic new file mode 100644 index 000000000..12993a8e5 --- /dev/null +++ b/tests/core/data/infer/calls/an_edge_written_between_inner_steps_says_nothing/workflow.wic @@ -0,0 +1,4 @@ +# An edge written between the inner steps is not a choice, so nothing is said. +steps: +- id: make.wic +- id: use.wic diff --git a/tests/core/data/infer/calls/an_output_read_through_its_inner_port/src.wic b/tests/core/data/infer/calls/an_output_read_through_its_inner_port/src.wic new file mode 100644 index 000000000..6ef5f5812 --- /dev/null +++ b/tests/core/data/infer/calls/an_output_read_through_its_inner_port/src.wic @@ -0,0 +1,6 @@ +steps: +- id: mk_file + in: + name: !ii a.txt + out: + - file: !& f diff --git a/tests/core/data/infer/calls/an_output_read_through_its_inner_port/workflow.wic b/tests/core/data/infer/calls/an_output_read_through_its_inner_port/workflow.wic new file mode 100644 index 000000000..948fad676 --- /dev/null +++ b/tests/core/data/infer/calls/an_output_read_through_its_inner_port/workflow.wic @@ -0,0 +1,8 @@ +# `f` is anchored inside the subworkflow; `left` is written to it and `right` is inferred from the call's exposed +# twin of the same file. +steps: +- id: src.wic +- id: join + in: + name: !ii o.txt + left: !* f diff --git a/tests/core/data/infer/calls/expected.yaml b/tests/core/data/infer/calls/expected.yaml new file mode 100644 index 000000000..97238c85e --- /dev/null +++ b/tests/core/data/infer/calls/expected.yaml @@ -0,0 +1,28 @@ +a_note_names_the_call_and_the_steps_down: + compiled: true + diagnostics: + - {code: INFERENCE_GUESS, step: use.wic, index: 2, port: file, severity: note, message: {contains: [use.wic.file <- + make.wic/multi_file.first]}} +an_edge_written_between_inner_steps_says_nothing: + compiled: true +one_guess_read_by_two_inner_steps_is_one_note: + compiled: true + diagnostics: + - {code: INFERENCE_GUESS, step: use.wic, index: 2, port: file, severity: note, message: {contains: [use.wic.file <- + make.wic/multi_file.first]}} +a_file_fanned_out_to_two_inner_steps: {} +an_output_read_through_its_inner_port: + refused: true + diagnostics: + - {code: INFERENCE_DUPLICATE, severity: error, step: join, index: 2, port: right, message: {contains: [join.left and + join.right would both read src.wic/mk_file.file]}} +two_inputs_of_a_call_reading_one_file: {} +a_written_edge_to_an_anchor_in_a_call: + compiled: true + refused: true + diagnostics: + - {code: INFERENCE_DUPLICATE, severity: error, step: pair, index: 2, port: right, message: {contains: [pair.left and + pair.right would both read src.wic/mk_file.file]}} +a_file_fanned_out_two_calls_down: {} +a_call_output_is_a_candidate: + edges: {exact: {count@2.file: sub.wic@1.mk_file~file}} diff --git a/tests/core/data/infer/calls/multi_file.cwl b/tests/core/data/infer/calls/multi_file.cwl new file mode 100644 index 000000000..8a858b925 --- /dev/null +++ b/tests/core/data/infer/calls/multi_file.cwl @@ -0,0 +1,11 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + first: + type: File + outputBinding: {glob: first} + last: + type: File + outputBinding: {glob: last} diff --git a/tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/make.wic b/tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/make.wic new file mode 100644 index 000000000..0e11fc51c --- /dev/null +++ b/tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/make.wic @@ -0,0 +1,2 @@ +steps: +- id: multi_file diff --git a/tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/use.wic b/tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/use.wic new file mode 100644 index 000000000..db9e1283f --- /dev/null +++ b/tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/use.wic @@ -0,0 +1,3 @@ +steps: +- id: count +- id: count diff --git a/tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/workflow.wic b/tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/workflow.wic new file mode 100644 index 000000000..02a2f8f6e --- /dev/null +++ b/tests/core/data/infer/calls/one_guess_read_by_two_inner_steps_is_one_note/workflow.wic @@ -0,0 +1,4 @@ +# Two inner steps read the guessed output through the one call the author wrote, so one note says it. +steps: +- id: make.wic +- id: use.wic diff --git a/tests/core/data/infer/calls/two_inputs_of_a_call_reading_one_file/fan.wic b/tests/core/data/infer/calls/two_inputs_of_a_call_reading_one_file/fan.wic new file mode 100644 index 000000000..71e76883b --- /dev/null +++ b/tests/core/data/infer/calls/two_inputs_of_a_call_reading_one_file/fan.wic @@ -0,0 +1,12 @@ +steps: +- id: count + in: + file: a +- id: xform + in: + file: b +inputs: + a: + type: File + b: + type: File diff --git a/tests/core/data/infer/calls/two_inputs_of_a_call_reading_one_file/workflow.wic b/tests/core/data/infer/calls/two_inputs_of_a_call_reading_one_file/workflow.wic new file mode 100644 index 000000000..ef1917288 --- /dev/null +++ b/tests/core/data/infer/calls/two_inputs_of_a_call_reading_one_file/workflow.wic @@ -0,0 +1,6 @@ +# `a` goes to `count` and `b` to `xform`: two tool steps, each reading the one file once. +steps: +- id: mk_file + in: + name: !ii a.txt +- id: fan.wic diff --git a/tests/core/data/infer/cases.yaml b/tests/core/data/infer/cases.yaml deleted file mode 100644 index c085d2e61..000000000 --- a/tests/core/data/infer/cases.yaml +++ /dev/null @@ -1,288 +0,0 @@ -- id: the most recent step and the first declared output win - tools: - multi_file: - outputs: - first: &first {type: File, outputBinding: {glob: first}} - last: &last {type: File, outputBinding: {glob: last}} - steps: [{id: mk_file, in: {name: {wic_inline_input: x}}}, {id: multi_file}, {id: count}] - edges: {count@3.file: multi_file@2.first} - diagnostics: - - {code: INFERENCE_GUESS, message: "count.file <- multi_file.first (2 others fit)", step: count, index: 3, port: file} - why: "Candidate order is semantic, including ambiguity within one producer." -- id: a tie within one producer is noted with the alternatives - tools: {multi_file: {outputs: {first: *first, last: *last}}} - steps: [{id: multi_file}, {id: count}] - diagnostics: - - {code: INFERENCE_GUESS, message: "count.file <- multi_file.first (1 other fits)", step: count, index: 2, port: file} - why: "One line names the input, the output it reads and the output that also fit." -- id: recency between producers is noted - steps: &two_producers - - {id: mk_file, in: {name: {wic_inline_input: a}}} - - {id: mk_file, in: {name: {wic_inline_input: b}}} - - {id: count} - edges: {count@3.file: mk_file@2.file} - diagnostics: - - {code: INFERENCE_GUESS, message: "count.file <- mk_file@2.file (1 other fits)", step: count, index: 3, port: file} - why: "An earlier producer that also matched is named; a repeated name carries its position and the choice is - unchanged." -- id: a note across subworkflow calls names the call and the inner output - tools: &multi {multi_file: {outputs: {first: *first, last: *last}}} - compiled: true - steps: [{id: make.wic, subtree: {steps: [{id: multi_file}]}}, {id: use.wic, subtree: {steps: [{id: count}]}}] - diagnostics: - - {code: INFERENCE_GUESS, message: "use.wic.file <- make.wic/multi_file.first (1 other fits)", step: use.wic, - index: 2, port: file} - why: "The input is named at the call the author wrote, and the output by the steps down to the one that makes it." -- id: writing the edge between the inner steps of two calls compiles without a note - tools: *multi - compiled: true - steps: - - {id: make.wic, subtree: {steps: [{id: multi_file, out: [{first: {wic_anchor: f}}]}]}} - - {id: use.wic, subtree: {steps: [{id: count, in: {file: {wic_alias: f}}}]}} - why: "An edge written between the inner steps is not a choice, so nothing is said." -- id: strict mode turns notes into errors - steps: *two_producers - policy: {strict: true} - refused: true - diagnostics: - - {code: INFERENCE_GUESS, severity: error, message: "count.file <- mk_file@2.file was guessed, 1 other fits; write - the edge it should read", step: count, index: 3, port: file} - why: "`InferencePolicy.strict` refuses a choice between equals." -- id: one guess fanned out inside a call is one note - tools: *multi - compiled: true - steps: - - {id: make.wic, subtree: {steps: [{id: multi_file}]}} - - {id: use.wic, subtree: {steps: [{id: count}, {id: count}]}} - diagnostics: - - {code: INFERENCE_GUESS, message: "use.wic.file <- make.wic/multi_file.first (1 other fits)", step: use.wic, - index: 2, port: file} - why: "Two inner steps read the guessed output through the one call the author wrote, so one note says it." -- id: a pinned edge is not noted - steps: - - {id: mk_file, in: {name: {wic_inline_input: a}}} - - {id: mk_file, in: {name: {wic_inline_input: b}}, out: [{file: {wic_anchor: f}}]} - - {id: count, in: {file: {wic_alias: f}}} - why: "An explicit `!&`/`!*` edge is not a choice, so nothing is said." -- id: a tie settled by naming conventions is not noted - tools: - named: - outputs: - output_file: {type: File, outputBinding: {glob: a}} - output_other: {type: File, outputBinding: {glob: b}} - steps: [{id: named}, {id: count}] - policy: {use_naming_conventions: true} - why: "When the naming conventions single out one output, order did not decide." -- id: an output named log feeds an input named log - tools: - logger: {outputs: {output_log_path: {type: File, outputBinding: {glob: a}}}} - reader: {inputs: {input_log_path: {type: File}}} - steps: [{id: logger}, {id: reader}] - policy: {use_naming_conventions: true} - edges: {reader@2.input_log_path: logger@1.output_log_path} - why: "Names decide nothing against an output that fits: `output_log_path` feeds `input_log_path`, the sander_mdrun - to process_mdout pattern." -- id: a step that makes only a log is not skipped for its name - tools: - make: {outputs: {output_crd_path: {type: File, outputBinding: {glob: a}}}} - logger: {outputs: {output_log_path: {type: File, outputBinding: {glob: a}}}} - reader: {inputs: {input_crd_path: {type: File}}} - steps: [{id: make}, {id: logger}, {id: reader}] - policy: {use_naming_conventions: true} - edges: {reader@3.input_crd_path: logger@2.output_log_path} - diagnostics: - - {code: INFERENCE_GUESS, message: "reader.input_crd_path <- logger.output_log_path (1 other fits)", step: reader, - index: 3, port: input_crd_path} - why: "A log is a File like any other: the nearest step with a fitting output wins, and the guess is noted." -- id: an input pairs by its own name before its renamed name - tools: - maker: - outputs: - output_structure_file: {type: File, outputBinding: {glob: s}} - output_tpr_file: {type: File, outputBinding: {glob: t}} - output_report_file: {type: File, outputBinding: {glob: r}} - reader: &structure_reader {inputs: {input_structure_file: {type: File}}} - steps: &make_read [{id: maker}, {id: reader}] - policy: &tpr {use_naming_conventions: true, renaming_conventions: [[structure_, tpr_]]} - edges: {reader@2.input_structure_file: maker@1.output_structure_file} - why: "`input_structure_file` takes `output_structure_file` over `output_tpr_file`, the name its renaming gives, - and over `output_report_file`." -- id: a renamed name pairs when the input's own name pairs with nothing - tools: - maker: - outputs: - output_tpr_file: {type: File, outputBinding: {glob: t}} - output_report_file: {type: File, outputBinding: {glob: r}} - reader: *structure_reader - steps: *make_read - policy: *tpr - edges: {reader@2.input_structure_file: maker@1.output_tpr_file} - why: "No `output_structure_file`, so the renamed name of `input_structure_file` pairs: `output_tpr_file`." -- id: a scalar literal under scatter is wic020 - compiled: true - steps: [{id: mk_file, in: {name: {wic_inline_input: a}}, scatter: [name]}] - refused: true - diagnostics: - - {code: LITERAL_TYPE_MISMATCH, message: {contains: [scattered]}, step: mk_file, index: 1, port: name} - why: "A scatter splits its value; a scalar is not wrapped into a one-element list." -- id: a list literal under scatter is scattered over - compiled: true - steps: [{id: mk_file, in: {name: {wic_inline_input: [a, b]}}, scatter: [name]}] - job_inputs: {exact: {mk_file~name: [a, b]}} - why: "The list form is unchanged: each element is one scattered value." -- id: a lenient compile carries the note - compiled: true - steps: *two_producers - diagnostics: - - {code: INFERENCE_GUESS, message: "count.file <- mk_file@2.file (1 other fits)", step: count, index: 3, port: file} - why: "The compiler returns the notes with its result." -- id: a strict compile refuses - compiled: true - steps: *two_producers - policy: {strict: true} - refused: true - diagnostics: - - {code: INFERENCE_GUESS, severity: error, message: "count.file <- mk_file@2.file was guessed, 1 other fits; write - the edge it should read", step: count, index: 3, port: file} - why: "The compiler forwards the strict flag." -- id: naming conventions pick the name-matched output over the first declared - tools: &structure - producer: - canonical: true - outputs: - output_other: {type: File, outputBinding: {glob: o}} - output_structure: {type: File, outputBinding: {glob: s}} - consumer: {canonical: true, inputs: {input_structure: {type: File, inputBinding: {position: 1}}}} - steps: &produce_consume [{id: producer}, {id: consumer}] - edges: {consumer@2.input_structure: producer@1.output_structure} - why: "With no setting, `input_structure` takes `output_structure` although `output_other` is declared first." -- id: naming conventions off take the first declared output - tools: *structure - steps: *produce_consume - policy: {use_naming_conventions: false} - edges: {consumer@2.input_structure: producer@1.output_other} - diagnostics: - - {code: INFERENCE_GUESS, message: "consumer.input_structure <- producer.output_other (1 other fits)", - step: consumer, index: 2, port: input_structure} - why: "With conventions off the first declared output is taken." -- id: two inferred bare file inputs reading one output are refused - steps: &join_after_make - - {id: mk_file, in: {name: {wic_inline_input: a.txt}}} - - {id: join, in: {name: {wic_inline_input: o.txt}}} - refused: true - diagnostics: - - {code: INFERENCE_DUPLICATE, severity: error, message: "join.left and join.right would both read mk_file.file; - write the edge each should read", step: join, index: 2, port: left} - why: "`join` would take the one file as `left` and as `right`, and nothing says that is meant." -- id: a written edge and an inferred one reading one output are refused - steps: &make_then_join_left - - &make {id: mk_file, in: {name: {wic_inline_input: a.txt}}, out: [{file: {wic_anchor: f}}]} - - {id: join, in: {name: {wic_inline_input: o.txt}, left: {wic_alias: f}}} - refused: true - diagnostics: - - {code: INFERENCE_DUPLICATE, severity: error, message: "join.left and join.right would both read mk_file.file; - write the edge each should read", step: join, index: 2, port: right} - why: "The written `left` does not vouch for the inferred `right`, so the refusal points at `right`, the first - inferred input." -- id: two written edges reading one output are never refused - steps: - - *make - - {id: join, in: {name: {wic_inline_input: o.txt}, left: {wic_alias: f}, right: {wic_alias: f}}} - why: "An author who wrote both edges meant both." -- id: inputs that declare the format the output carries may read it twice - tools: &pair_text - pair: - canonical: true - inputs: - left: &text {type: File, inputBinding: {position: 1}, format: 'edam:format_2330'} - right: *text - steps: [*make, {id: pair}] - why: "`mk_file` makes text; both inputs of `pair` declare text, which counts as saying so." -- id: one input without the evidence refuses the group - tools: {pair: {canonical: true, inputs: {left: *text, right: {type: File, inputBinding: {position: 1}}}}} - steps: [*make, {id: pair}] - refused: true - diagnostics: - - {code: INFERENCE_DUPLICATE, severity: error, message: "pair.left and pair.right would both read mk_file.file; - write the edge each should read", step: pair, index: 2, port: left} - why: "Every input has to declare a format the output carries: a bare `right` does not." -- id: a file fanned out to two inner steps of a subworkflow is not a duplicate - steps: - - {id: mk_file, in: {name: {wic_inline_input: a.txt}}} - - {id: fan.wic, subtree: {steps: [{id: count}, {id: count}]}} - why: "Each inner `count` is a tool step of its own, so each reads the file once." -- id: an output read through its inner port and the calls twin is one output - steps: - - {id: src.wic, subtree: {steps: [*make]}} - - {id: join, in: {name: {wic_inline_input: o.txt}, left: {wic_alias: f}}} - refused: true - diagnostics: - - {code: INFERENCE_DUPLICATE, severity: error, message: "join.left and join.right would both read - src.wic/mk_file.file; write the edge each should read", step: join, index: 2, port: right} - why: "`f` is anchored inside the subworkflow; `left` is written to it and `right` is inferred from the call's - exposed twin of the same file." -- id: two plain inputs of a subworkflow for different inner steps are not a duplicate - steps: - - {id: mk_file, in: {name: {wic_inline_input: a.txt}}} - - id: fan.wic - subtree: - inputs: {a: {type: File}, b: {type: File}} - steps: [{id: count, in: {file: a}}, {id: xform, in: {file: b}}] - why: "`a` goes to `count` and `b` to `xform`: two tool steps, each reading the one file once." -- id: a written edge to an anchor in a call and the calls exposed port are one output - tools: - pair: - canonical: true - inputs: - left: &bare {type: File, inputBinding: {position: 1}} - right: *bare - compiled: true - steps: [{id: src.wic, subtree: {steps: [*make]}}, {id: pair, in: {left: {wic_alias: f}}}] - refused: true - diagnostics: - - {code: INFERENCE_DUPLICATE, severity: error, message: "pair.left and pair.right would both read - src.wic/mk_file.file; write the edge each should read", step: pair, index: 2, port: right} - why: "`left` is written to the anchor `f` inside the call; `right` is inferred from the call's exposed port. - Compiled whole, so the written edge reaches the deep output the way a document's does." -- id: a file fanned out through nested subworkflows to different leaves is not a duplicate - steps: - - {id: mk_file, in: {name: {wic_inline_input: a.txt}}} - - id: mid.wic - subtree: - inputs: {x: {type: File}, y: {type: File}} - steps: - - id: fan.wic - parentargs: {in: {a: x, b: y}} - subtree: - inputs: {a: {type: File}, b: {type: File}} - steps: [{id: count, in: {file: a}}, {id: xform, in: {file: b}}] - why: "`x` and `y` reach `count` and `xform` two calls down: two tool steps, each reading the file once." -- id: a format name that is merely a substring is not a candidate - tools: - producer: {canonical: true, outputs: {file: {type: File, format: 'edam:format_123'}}} - consumer: {canonical: true, inputs: {file: {type: File, format: 'edam:format_1234'}}} - steps: &produce_consume_formats [{id: producer}, {id: consumer}] - edges: {exact: {}} - why: "A format name that is merely a substring is not a candidate." -- id: a non-File output without a format can satisfy a formatted input - tools: - producer: {canonical: true, outputs: {value: {type: string}}} - consumer: {canonical: true, inputs: {value: {type: string, format: someformat}}} - steps: *produce_consume_formats - edges: {exact: {consumer@2.value: producer@1.value}} - why: "A non-File cannot declare a format, so omission is unconstrained." -- id: an unknown file format does not outrank an exact match - tools: - producer: - canonical: true - outputs: {matching: {type: File, format: 'edam:format_3816'}, unknown: {type: File}} - consumer: {canonical: true, inputs: {file: {type: File, format: ['edam:format_3816']}}} - steps: *produce_consume_formats - edges: {consumer@2.file: producer@1.matching} - why: "A formatless File is unknown, not a wildcard over exact formats." -- id: iteration exhaustion is exactly wic022 - steps: [{id: mk_file}] - policy: {iteration_limit: 0} - refused: true - diagnostics: [{code: FIXED_POINT_NOT_REACHED}] - why: "The limit cannot be removed or exhausted silently." diff --git a/tests/core/data/infer/converters/a_break_stops_the_search/workflow.wic b/tests/core/data/infer/converters/a_break_stops_the_search/workflow.wic new file mode 100644 index 000000000..f47698f7e --- /dev/null +++ b/tests/core/data/infer/converters/a_break_stops_the_search/workflow.wic @@ -0,0 +1,10 @@ +# Insertion cannot reuse formats hidden behind a local break rule: use_1 takes its file from the workflow. +wic: + steps: + (2, mk_2): + wic: + inference: {file: break} +steps: +- id: mk_1 +- id: mk_2 +- id: use_1 diff --git a/tests/core/data/infer/converters/a_call_output_feeds_a_converter/sub.wic b/tests/core/data/infer/converters/a_call_output_feeds_a_converter/sub.wic new file mode 100644 index 000000000..74cc5a03a --- /dev/null +++ b/tests/core/data/infer/converters/a_call_output_feeds_a_converter/sub.wic @@ -0,0 +1,2 @@ +steps: +- id: mk_2 diff --git a/tests/core/data/infer/converters/a_call_output_feeds_a_converter/workflow.wic b/tests/core/data/infer/converters/a_call_output_feeds_a_converter/workflow.wic new file mode 100644 index 000000000..1c2fc2f22 --- /dev/null +++ b/tests/core/data/infer/converters/a_call_output_feeds_a_converter/workflow.wic @@ -0,0 +1,4 @@ +# Converter search sees the formats a workflow call exports. +steps: +- id: sub.wic +- id: use_2 diff --git a/tests/core/data/infer/converters/expected.yaml b/tests/core/data/infer/converters/expected.yaml new file mode 100644 index 000000000..631fed98e --- /dev/null +++ b/tests/core/data/infer/converters/expected.yaml @@ -0,0 +1,11 @@ +two_insertions_reach_one_fixed_point: + policy: {insert_steps_automatically: true} + inserted: 2 + iterations: 3 +a_call_output_feeds_a_converter: + policy: {insert_steps_automatically: true} + inserted: 1 +a_break_stops_the_search: + policy: {insert_steps_automatically: true} + inserted: 0 + inputs: [use_1~file] diff --git a/tests/core/data/infer/converters/insert_steps_automatically_conv_1.cwl b/tests/core/data/infer/converters/insert_steps_automatically_conv_1.cwl new file mode 100644 index 000000000..13f47ab5f --- /dev/null +++ b/tests/core/data/infer/converters/insert_steps_automatically_conv_1.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {edam: 'https://edamontology.org/'} +inputs: {file: {type: File, format: 'edam:format_src1'}} +outputs: {file: {type: File, format: 'edam:format_dst1'}} diff --git a/tests/core/data/infer/converters/insert_steps_automatically_conv_2.cwl b/tests/core/data/infer/converters/insert_steps_automatically_conv_2.cwl new file mode 100644 index 000000000..944e1634a --- /dev/null +++ b/tests/core/data/infer/converters/insert_steps_automatically_conv_2.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {edam: 'https://edamontology.org/'} +inputs: {file: {type: File, format: 'edam:format_src2'}} +outputs: {file: {type: File, format: 'edam:format_dst2'}} diff --git a/tests/core/data/infer/converters/mk_1.cwl b/tests/core/data/infer/converters/mk_1.cwl new file mode 100644 index 000000000..1c03d6f8e --- /dev/null +++ b/tests/core/data/infer/converters/mk_1.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {edam: 'https://edamontology.org/'} +inputs: {} +outputs: {file: {type: File, format: 'edam:format_src1'}} diff --git a/tests/core/data/infer/converters/mk_2.cwl b/tests/core/data/infer/converters/mk_2.cwl new file mode 100644 index 000000000..2096630a8 --- /dev/null +++ b/tests/core/data/infer/converters/mk_2.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {edam: 'https://edamontology.org/'} +inputs: {} +outputs: {file: {type: File, format: 'edam:format_src2'}} diff --git a/tests/core/data/infer/converters/two_insertions_reach_one_fixed_point/workflow.wic b/tests/core/data/infer/converters/two_insertions_reach_one_fixed_point/workflow.wic new file mode 100644 index 000000000..53c1ebc93 --- /dev/null +++ b/tests/core/data/infer/converters/two_insertions_reach_one_fixed_point/workflow.wic @@ -0,0 +1,7 @@ +# Two branches, each needing exactly one whitelisted converter between its maker and its user: speculative +# insertion reaches its fixed point in three iterations. +steps: +- id: mk_1 +- id: use_1 +- id: mk_2 +- id: use_2 diff --git a/tests/core/data/infer/converters/use_1.cwl b/tests/core/data/infer/converters/use_1.cwl new file mode 100644 index 000000000..c03f87495 --- /dev/null +++ b/tests/core/data/infer/converters/use_1.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {edam: 'https://edamontology.org/'} +inputs: {file: {type: File, format: 'edam:format_dst1'}} +outputs: {} diff --git a/tests/core/data/infer/converters/use_2.cwl b/tests/core/data/infer/converters/use_2.cwl new file mode 100644 index 000000000..0d178a5ff --- /dev/null +++ b/tests/core/data/infer/converters/use_2.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +$namespaces: {edam: 'https://edamontology.org/'} +inputs: {file: {type: File, format: 'edam:format_dst2'}} +outputs: {} diff --git a/tests/core/data/infer/duplicates/a_written_edge_and_an_inferred_one/workflow.wic b/tests/core/data/infer/duplicates/a_written_edge_and_an_inferred_one/workflow.wic new file mode 100644 index 000000000..bbf6d46cd --- /dev/null +++ b/tests/core/data/infer/duplicates/a_written_edge_and_an_inferred_one/workflow.wic @@ -0,0 +1,12 @@ +# The written `left` does not vouch for the inferred `right`, so the refusal points at `right`, the first inferred +# input. +steps: +- id: mk_file + in: + name: !ii a.txt + out: + - file: !& f +- id: join + in: + name: !ii o.txt + left: !* f diff --git a/tests/core/data/infer/duplicates/expected.yaml b/tests/core/data/infer/duplicates/expected.yaml new file mode 100644 index 000000000..14f9a28e6 --- /dev/null +++ b/tests/core/data/infer/duplicates/expected.yaml @@ -0,0 +1,17 @@ +two_bare_inputs_reading_one_output_refuse: + refused: true + diagnostics: + - {code: INFERENCE_DUPLICATE, severity: error, step: join, index: 2, port: left, message: {contains: [join.left and + join.right would both read mk_file.file]}} +a_written_edge_and_an_inferred_one: + refused: true + diagnostics: + - {code: INFERENCE_DUPLICATE, severity: error, step: join, index: 2, port: right, message: {contains: [join.left and + join.right would both read mk_file.file]}} +two_written_edges_reading_one_output_are_meant: {} +inputs_that_declare_the_format_may_share_an_output: {} +one_input_without_the_evidence_refuses: + refused: true + diagnostics: + - {code: INFERENCE_DUPLICATE, severity: error, step: pair, index: 2, port: left, message: {contains: [pair.left and + pair.right would both read mk_file.file]}} diff --git a/tests/core/data/infer/duplicates/inputs_that_declare_the_format_may_share_an_output/pair.cwl b/tests/core/data/infer/duplicates/inputs_that_declare_the_format_may_share_an_output/pair.cwl new file mode 100644 index 000000000..f8440efb0 --- /dev/null +++ b/tests/core/data/infer/duplicates/inputs_that_declare_the_format_may_share_an_output/pair.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + left: + type: File + inputBinding: {position: 1} + format: edam:format_2330 + right: + type: File + inputBinding: {position: 1} + format: edam:format_2330 +outputs: {} +$namespaces: {edam: 'https://edamontology.org/'} diff --git a/tests/core/data/infer/duplicates/inputs_that_declare_the_format_may_share_an_output/workflow.wic b/tests/core/data/infer/duplicates/inputs_that_declare_the_format_may_share_an_output/workflow.wic new file mode 100644 index 000000000..cafe9f329 --- /dev/null +++ b/tests/core/data/infer/duplicates/inputs_that_declare_the_format_may_share_an_output/workflow.wic @@ -0,0 +1,8 @@ +# `mk_file` makes text; both inputs of `pair` declare text, which counts as saying so. +steps: +- id: mk_file + in: + name: !ii a.txt + out: + - file: !& f +- id: pair diff --git a/tests/core/data/infer/duplicates/one_input_without_the_evidence_refuses/pair.cwl b/tests/core/data/infer/duplicates/one_input_without_the_evidence_refuses/pair.cwl new file mode 100644 index 000000000..fae59962e --- /dev/null +++ b/tests/core/data/infer/duplicates/one_input_without_the_evidence_refuses/pair.cwl @@ -0,0 +1,13 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + left: + type: File + inputBinding: {position: 1} + format: edam:format_2330 + right: + type: File + inputBinding: {position: 1} +outputs: {} +$namespaces: {edam: 'https://edamontology.org/'} diff --git a/tests/core/data/infer/duplicates/one_input_without_the_evidence_refuses/workflow.wic b/tests/core/data/infer/duplicates/one_input_without_the_evidence_refuses/workflow.wic new file mode 100644 index 000000000..94a5591ac --- /dev/null +++ b/tests/core/data/infer/duplicates/one_input_without_the_evidence_refuses/workflow.wic @@ -0,0 +1,8 @@ +# Every input has to declare a format the output carries: a bare `right` does not. +steps: +- id: mk_file + in: + name: !ii a.txt + out: + - file: !& f +- id: pair diff --git a/tests/core/data/infer/duplicates/two_bare_inputs_reading_one_output_refuse/workflow.wic b/tests/core/data/infer/duplicates/two_bare_inputs_reading_one_output_refuse/workflow.wic new file mode 100644 index 000000000..cf315eaa2 --- /dev/null +++ b/tests/core/data/infer/duplicates/two_bare_inputs_reading_one_output_refuse/workflow.wic @@ -0,0 +1,8 @@ +# `join` would take the one file as `left` and as `right`, and nothing says that is meant. +steps: +- id: mk_file + in: + name: !ii a.txt +- id: join + in: + name: !ii o.txt diff --git a/tests/core/data/infer/duplicates/two_written_edges_reading_one_output_are_meant/workflow.wic b/tests/core/data/infer/duplicates/two_written_edges_reading_one_output_are_meant/workflow.wic new file mode 100644 index 000000000..c9dce2900 --- /dev/null +++ b/tests/core/data/infer/duplicates/two_written_edges_reading_one_output_are_meant/workflow.wic @@ -0,0 +1,12 @@ +# An author who wrote both edges meant both. +steps: +- id: mk_file + in: + name: !ii a.txt + out: + - file: !& f +- id: join + in: + name: !ii o.txt + left: !* f + right: !* f diff --git a/tests/core/data/infer/formats/a_format_substring_is_no_candidate/consumer.cwl b/tests/core/data/infer/formats/a_format_substring_is_no_candidate/consumer.cwl new file mode 100644 index 000000000..5d7557294 --- /dev/null +++ b/tests/core/data/infer/formats/a_format_substring_is_no_candidate/consumer.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + file: {type: File, format: 'edam:format_1234'} +outputs: {} +$namespaces: {edam: 'https://edamontology.org/'} diff --git a/tests/core/data/infer/formats/a_format_substring_is_no_candidate/producer.cwl b/tests/core/data/infer/formats/a_format_substring_is_no_candidate/producer.cwl new file mode 100644 index 000000000..ba39a2c9d --- /dev/null +++ b/tests/core/data/infer/formats/a_format_substring_is_no_candidate/producer.cwl @@ -0,0 +1,7 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + file: {type: File, format: 'edam:format_123'} +$namespaces: {edam: 'https://edamontology.org/'} diff --git a/tests/core/data/infer/formats/a_format_substring_is_no_candidate/workflow.wic b/tests/core/data/infer/formats/a_format_substring_is_no_candidate/workflow.wic new file mode 100644 index 000000000..b1c504d3c --- /dev/null +++ b/tests/core/data/infer/formats/a_format_substring_is_no_candidate/workflow.wic @@ -0,0 +1,4 @@ +# A format name that is merely a substring is not a candidate. +steps: +- id: producer +- id: consumer diff --git a/tests/core/data/infer/formats/a_non_file_output_needs_no_format/consumer.cwl b/tests/core/data/infer/formats/a_non_file_output_needs_no_format/consumer.cwl new file mode 100644 index 000000000..8c938e43d --- /dev/null +++ b/tests/core/data/infer/formats/a_non_file_output_needs_no_format/consumer.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + value: {type: string, format: someformat} +outputs: {} diff --git a/tests/core/data/infer/formats/a_non_file_output_needs_no_format/producer.cwl b/tests/core/data/infer/formats/a_non_file_output_needs_no_format/producer.cwl new file mode 100644 index 000000000..1f090cc2a --- /dev/null +++ b/tests/core/data/infer/formats/a_non_file_output_needs_no_format/producer.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + value: {type: string} diff --git a/tests/core/data/infer/formats/a_non_file_output_needs_no_format/workflow.wic b/tests/core/data/infer/formats/a_non_file_output_needs_no_format/workflow.wic new file mode 100644 index 000000000..af097d480 --- /dev/null +++ b/tests/core/data/infer/formats/a_non_file_output_needs_no_format/workflow.wic @@ -0,0 +1,4 @@ +# A non-File cannot declare a format, so omission is unconstrained. +steps: +- id: producer +- id: consumer diff --git a/tests/core/data/infer/formats/a_scatter_lifts_both_sides/file_array_sink.cwl b/tests/core/data/infer/formats/a_scatter_lifts_both_sides/file_array_sink.cwl new file mode 100644 index 000000000..50ec8c0bd --- /dev/null +++ b/tests/core/data/infer/formats/a_scatter_lifts_both_sides/file_array_sink.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {files: 'File[]'} +outputs: {} diff --git a/tests/core/data/infer/formats/a_scatter_lifts_both_sides/workflow.wic b/tests/core/data/infer/formats/a_scatter_lifts_both_sides/workflow.wic new file mode 100644 index 000000000..b59cace52 --- /dev/null +++ b/tests/core/data/infer/formats/a_scatter_lifts_both_sides/workflow.wic @@ -0,0 +1,7 @@ +# A producing scatter matches an array sink, and a scalar sink it does not. +steps: +- id: mk_file + in: {name: !ii [a, b]} + scatter: name +- id: file_array_sink +- id: count diff --git a/tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/consumer.cwl b/tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/consumer.cwl new file mode 100644 index 000000000..de3839582 --- /dev/null +++ b/tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/consumer.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + file: + type: File + format: ['edam:format_3816'] +outputs: {} +$namespaces: {edam: 'https://edamontology.org/'} diff --git a/tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/producer.cwl b/tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/producer.cwl new file mode 100644 index 000000000..987512466 --- /dev/null +++ b/tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/producer.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + matching: {type: File, format: 'edam:format_3816'} + unknown: {type: File} +$namespaces: {edam: 'https://edamontology.org/'} diff --git a/tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/workflow.wic b/tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/workflow.wic new file mode 100644 index 000000000..474bcbb3b --- /dev/null +++ b/tests/core/data/infer/formats/an_unknown_format_does_not_outrank_an_exact_one/workflow.wic @@ -0,0 +1,4 @@ +# A formatless File is unknown, not a wildcard over exact formats. +steps: +- id: producer +- id: consumer diff --git a/tests/core/data/infer/formats/expected.yaml b/tests/core/data/infer/formats/expected.yaml new file mode 100644 index 000000000..e43aba431 --- /dev/null +++ b/tests/core/data/infer/formats/expected.yaml @@ -0,0 +1,9 @@ +a_format_substring_is_no_candidate: + edges: {exact: {}} +a_non_file_output_needs_no_format: + edges: {exact: {consumer@2.value: producer@1.value}} +an_unknown_format_does_not_outrank_an_exact_one: + edges: {consumer@2.file: producer@1.matching} +a_scatter_lifts_both_sides: + edges: {exact: {file_array_sink@2.files: mk_file@1.file}} + inputs: [count~file] diff --git a/tests/core/data/infer/names/a_log_is_a_file_like_any_other/make.cwl b/tests/core/data/infer/names/a_log_is_a_file_like_any_other/make.cwl new file mode 100644 index 000000000..653eefc4c --- /dev/null +++ b/tests/core/data/infer/names/a_log_is_a_file_like_any_other/make.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + output_crd_path: + type: File + outputBinding: {glob: a} diff --git a/tests/core/data/infer/names/a_log_is_a_file_like_any_other/reader.cwl b/tests/core/data/infer/names/a_log_is_a_file_like_any_other/reader.cwl new file mode 100644 index 000000000..fee00bc27 --- /dev/null +++ b/tests/core/data/infer/names/a_log_is_a_file_like_any_other/reader.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + input_crd_path: {type: File} +outputs: {} diff --git a/tests/core/data/infer/names/a_log_is_a_file_like_any_other/workflow.wic b/tests/core/data/infer/names/a_log_is_a_file_like_any_other/workflow.wic new file mode 100644 index 000000000..3a8db1eae --- /dev/null +++ b/tests/core/data/infer/names/a_log_is_a_file_like_any_other/workflow.wic @@ -0,0 +1,5 @@ +# A log is a File like any other: the nearest step with a fitting output wins, and the guess is noted. +steps: +- id: make +- id: logger +- id: reader diff --git a/tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/maker.cwl b/tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/maker.cwl new file mode 100644 index 000000000..31f1064d1 --- /dev/null +++ b/tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/maker.cwl @@ -0,0 +1,11 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + output_tpr_file: + type: File + outputBinding: {glob: t} + output_report_file: + type: File + outputBinding: {glob: r} diff --git a/tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/reader.cwl b/tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/reader.cwl new file mode 100644 index 000000000..786cda7e9 --- /dev/null +++ b/tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/reader.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + input_structure_file: {type: File} +outputs: {} diff --git a/tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/workflow.wic b/tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/workflow.wic new file mode 100644 index 000000000..b3b6575a1 --- /dev/null +++ b/tests/core/data/infer/names/a_renamed_name_pairs_when_its_own_is_missing/workflow.wic @@ -0,0 +1,4 @@ +# No `output_structure_file`, so the renamed name of `input_structure_file` pairs: `output_tpr_file`. +steps: +- id: maker +- id: reader diff --git a/tests/core/data/infer/names/a_tie_settled_by_names_is_not_noted/named.cwl b/tests/core/data/infer/names/a_tie_settled_by_names_is_not_noted/named.cwl new file mode 100644 index 000000000..dc585b2c0 --- /dev/null +++ b/tests/core/data/infer/names/a_tie_settled_by_names_is_not_noted/named.cwl @@ -0,0 +1,11 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + output_file: + type: File + outputBinding: {glob: a} + output_other: + type: File + outputBinding: {glob: b} diff --git a/tests/core/data/infer/names/a_tie_settled_by_names_is_not_noted/workflow.wic b/tests/core/data/infer/names/a_tie_settled_by_names_is_not_noted/workflow.wic new file mode 100644 index 000000000..ce474aba2 --- /dev/null +++ b/tests/core/data/infer/names/a_tie_settled_by_names_is_not_noted/workflow.wic @@ -0,0 +1,4 @@ +# When the naming conventions single out one output, order did not decide. +steps: +- id: named +- id: count diff --git a/tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/maker.cwl b/tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/maker.cwl new file mode 100644 index 000000000..8d4658d69 --- /dev/null +++ b/tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/maker.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + output_structure_file: + type: File + outputBinding: {glob: s} + output_tpr_file: + type: File + outputBinding: {glob: t} + output_report_file: + type: File + outputBinding: {glob: r} diff --git a/tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/reader.cwl b/tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/reader.cwl new file mode 100644 index 000000000..786cda7e9 --- /dev/null +++ b/tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/reader.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + input_structure_file: {type: File} +outputs: {} diff --git a/tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/workflow.wic b/tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/workflow.wic new file mode 100644 index 000000000..6b02fdb10 --- /dev/null +++ b/tests/core/data/infer/names/an_input_pairs_by_its_own_name_first/workflow.wic @@ -0,0 +1,5 @@ +# `input_structure_file` takes `output_structure_file` over `output_tpr_file`, the name its renaming gives, and over +# `output_report_file`. +steps: +- id: maker +- id: reader diff --git a/tests/core/data/infer/names/an_output_log_feeds_an_input_log/reader.cwl b/tests/core/data/infer/names/an_output_log_feeds_an_input_log/reader.cwl new file mode 100644 index 000000000..407d454e6 --- /dev/null +++ b/tests/core/data/infer/names/an_output_log_feeds_an_input_log/reader.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + input_log_path: {type: File} +outputs: {} diff --git a/tests/core/data/infer/names/an_output_log_feeds_an_input_log/workflow.wic b/tests/core/data/infer/names/an_output_log_feeds_an_input_log/workflow.wic new file mode 100644 index 000000000..e48a42a03 --- /dev/null +++ b/tests/core/data/infer/names/an_output_log_feeds_an_input_log/workflow.wic @@ -0,0 +1,5 @@ +# Names decide nothing against an output that fits: `output_log_path` feeds `input_log_path`, the sander_mdrun to +# process_mdout pattern. +steps: +- id: logger +- id: reader diff --git a/tests/core/data/infer/names/consumer.cwl b/tests/core/data/infer/names/consumer.cwl new file mode 100644 index 000000000..4e9358e24 --- /dev/null +++ b/tests/core/data/infer/names/consumer.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + input_structure: + type: File + inputBinding: {position: 1} +outputs: {} diff --git a/tests/core/data/infer/names/expected.yaml b/tests/core/data/infer/names/expected.yaml new file mode 100644 index 000000000..c867d0bf2 --- /dev/null +++ b/tests/core/data/infer/names/expected.yaml @@ -0,0 +1,25 @@ +a_tie_settled_by_names_is_not_noted: + policy: {use_naming_conventions: true} +an_output_log_feeds_an_input_log: + policy: {use_naming_conventions: true} + edges: {reader@2.input_log_path: logger@1.output_log_path} +a_log_is_a_file_like_any_other: + policy: {use_naming_conventions: true} + edges: {reader@3.input_crd_path: logger@2.output_log_path} + diagnostics: + - {code: INFERENCE_GUESS, step: reader, index: 3, port: input_crd_path, severity: note, message: {contains: [reader.input_crd_path + <- logger.output_log_path]}} +an_input_pairs_by_its_own_name_first: + policy: {use_naming_conventions: true, renaming_conventions: [[structure_, tpr_]]} + edges: {reader@2.input_structure_file: maker@1.output_structure_file} +a_renamed_name_pairs_when_its_own_is_missing: + policy: {use_naming_conventions: true, renaming_conventions: [[structure_, tpr_]]} + edges: {reader@2.input_structure_file: maker@1.output_tpr_file} +naming_conventions_pick_the_matching_name: + edges: {consumer@2.input_structure: producer@1.output_structure} +naming_conventions_off_take_the_first_output: + policy: {use_naming_conventions: false} + edges: {consumer@2.input_structure: producer@1.output_other} + diagnostics: + - {code: INFERENCE_GUESS, step: consumer, index: 2, port: input_structure, severity: note, message: {contains: [consumer.input_structure + <- producer.output_other]}} diff --git a/tests/core/data/infer/names/logger.cwl b/tests/core/data/infer/names/logger.cwl new file mode 100644 index 000000000..1b71d61f0 --- /dev/null +++ b/tests/core/data/infer/names/logger.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + output_log_path: + type: File + outputBinding: {glob: a} diff --git a/tests/core/data/infer/names/naming_conventions_off_take_the_first_output/workflow.wic b/tests/core/data/infer/names/naming_conventions_off_take_the_first_output/workflow.wic new file mode 100644 index 000000000..f63ffba55 --- /dev/null +++ b/tests/core/data/infer/names/naming_conventions_off_take_the_first_output/workflow.wic @@ -0,0 +1,4 @@ +# With conventions off the first declared output is taken. +steps: +- id: producer +- id: consumer diff --git a/tests/core/data/infer/names/naming_conventions_pick_the_matching_name/workflow.wic b/tests/core/data/infer/names/naming_conventions_pick_the_matching_name/workflow.wic new file mode 100644 index 000000000..aa2eb9d66 --- /dev/null +++ b/tests/core/data/infer/names/naming_conventions_pick_the_matching_name/workflow.wic @@ -0,0 +1,4 @@ +# With no setting, `input_structure` takes `output_structure` although `output_other` is declared first. +steps: +- id: producer +- id: consumer diff --git a/tests/core/data/infer/names/producer.cwl b/tests/core/data/infer/names/producer.cwl new file mode 100644 index 000000000..e231e0ccf --- /dev/null +++ b/tests/core/data/infer/names/producer.cwl @@ -0,0 +1,11 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + output_other: + type: File + outputBinding: {glob: o} + output_structure: + type: File + outputBinding: {glob: s} diff --git a/tests/core/data/infer/recency/a_lenient_compile_carries_the_note/workflow.wic b/tests/core/data/infer/recency/a_lenient_compile_carries_the_note/workflow.wic new file mode 100644 index 000000000..df9b99034 --- /dev/null +++ b/tests/core/data/infer/recency/a_lenient_compile_carries_the_note/workflow.wic @@ -0,0 +1,9 @@ +# The compiler returns the notes with its result. +steps: +- id: mk_file + in: + name: !ii a +- id: mk_file + in: + name: !ii b +- id: count diff --git a/tests/core/data/infer/recency/a_pinned_edge_is_not_noted/workflow.wic b/tests/core/data/infer/recency/a_pinned_edge_is_not_noted/workflow.wic new file mode 100644 index 000000000..dc88b9294 --- /dev/null +++ b/tests/core/data/infer/recency/a_pinned_edge_is_not_noted/workflow.wic @@ -0,0 +1,13 @@ +# An explicit `!&`/`!*` edge is not a choice, so nothing is said. +steps: +- id: mk_file + in: + name: !ii a +- id: mk_file + in: + name: !ii b + out: + - file: !& f +- id: count + in: + file: !* f diff --git a/tests/core/data/infer/recency/a_strict_compile_refuses/workflow.wic b/tests/core/data/infer/recency/a_strict_compile_refuses/workflow.wic new file mode 100644 index 000000000..afc3ed2e6 --- /dev/null +++ b/tests/core/data/infer/recency/a_strict_compile_refuses/workflow.wic @@ -0,0 +1,9 @@ +# The compiler forwards the strict flag. +steps: +- id: mk_file + in: + name: !ii a +- id: mk_file + in: + name: !ii b +- id: count diff --git a/tests/core/data/infer/recency/a_tie_within_one_producer_names_every_fit/workflow.wic b/tests/core/data/infer/recency/a_tie_within_one_producer_names_every_fit/workflow.wic new file mode 100644 index 000000000..93a37c07d --- /dev/null +++ b/tests/core/data/infer/recency/a_tie_within_one_producer_names_every_fit/workflow.wic @@ -0,0 +1,4 @@ +# One line names the input, the output it reads and the output that also fit. +steps: +- id: multi_file +- id: count diff --git a/tests/core/data/infer/recency/expected.yaml b/tests/core/data/infer/recency/expected.yaml new file mode 100644 index 000000000..0a4bfa868 --- /dev/null +++ b/tests/core/data/infer/recency/expected.yaml @@ -0,0 +1,27 @@ +the_most_recent_step_and_its_first_output_win: + edges: {count@3.file: multi_file@2.first} + diagnostics: + - {code: INFERENCE_GUESS, step: count, index: 3, port: file, severity: note, message: {contains: [count.file <- multi_file.first]}} +a_tie_within_one_producer_names_every_fit: + diagnostics: + - {code: INFERENCE_GUESS, step: count, index: 2, port: file, severity: note, message: {contains: [count.file <- multi_file.first]}} +recency_between_producers_is_noted: + edges: {count@3.file: mk_file@2.file} + diagnostics: + - {code: INFERENCE_GUESS, step: count, index: 3, port: file, severity: note, message: {contains: [count.file <- mk_file@2.file]}} +strict_mode_turns_notes_into_errors: + policy: {strict: true} + refused: true + diagnostics: + - {code: INFERENCE_GUESS, severity: error, step: count, index: 3, port: file, message: {contains: [count.file <- mk_file@2.file]}} +a_pinned_edge_is_not_noted: {} +a_lenient_compile_carries_the_note: + compiled: true + diagnostics: + - {code: INFERENCE_GUESS, step: count, index: 3, port: file, severity: note, message: {contains: [count.file <- mk_file@2.file]}} +a_strict_compile_refuses: + policy: {strict: true} + compiled: true + refused: true + diagnostics: + - {code: INFERENCE_GUESS, severity: error, step: count, index: 3, port: file, message: {contains: [count.file <- mk_file@2.file]}} diff --git a/tests/core/data/infer/recency/multi_file.cwl b/tests/core/data/infer/recency/multi_file.cwl new file mode 100644 index 000000000..8a858b925 --- /dev/null +++ b/tests/core/data/infer/recency/multi_file.cwl @@ -0,0 +1,11 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: + first: + type: File + outputBinding: {glob: first} + last: + type: File + outputBinding: {glob: last} diff --git a/tests/core/data/infer/recency/recency_between_producers_is_noted/workflow.wic b/tests/core/data/infer/recency/recency_between_producers_is_noted/workflow.wic new file mode 100644 index 000000000..7d104dcc9 --- /dev/null +++ b/tests/core/data/infer/recency/recency_between_producers_is_noted/workflow.wic @@ -0,0 +1,9 @@ +# An earlier producer that also matched is named; a repeated name carries its position and the choice is unchanged. +steps: +- id: mk_file + in: + name: !ii a +- id: mk_file + in: + name: !ii b +- id: count diff --git a/tests/core/data/infer/recency/strict_mode_turns_notes_into_errors/workflow.wic b/tests/core/data/infer/recency/strict_mode_turns_notes_into_errors/workflow.wic new file mode 100644 index 000000000..61878ddf3 --- /dev/null +++ b/tests/core/data/infer/recency/strict_mode_turns_notes_into_errors/workflow.wic @@ -0,0 +1,9 @@ +# `InferencePolicy.strict` refuses a choice between equals. +steps: +- id: mk_file + in: + name: !ii a +- id: mk_file + in: + name: !ii b +- id: count diff --git a/tests/core/data/infer/recency/the_most_recent_step_and_its_first_output_win/workflow.wic b/tests/core/data/infer/recency/the_most_recent_step_and_its_first_output_win/workflow.wic new file mode 100644 index 000000000..b22db713f --- /dev/null +++ b/tests/core/data/infer/recency/the_most_recent_step_and_its_first_output_win/workflow.wic @@ -0,0 +1,7 @@ +# Candidate order is semantic, including ambiguity within one producer. +steps: +- id: mk_file + in: + name: !ii x +- id: multi_file +- id: count diff --git a/tests/core/data/infer/values/a_list_literal_under_scatter_is_unchanged/workflow.wic b/tests/core/data/infer/values/a_list_literal_under_scatter_is_unchanged/workflow.wic new file mode 100644 index 000000000..e8e8abaae --- /dev/null +++ b/tests/core/data/infer/values/a_list_literal_under_scatter_is_unchanged/workflow.wic @@ -0,0 +1,9 @@ +# The list form is unchanged: each element is one scattered value. +steps: +- id: mk_file + in: + name: !ii + - a + - b + scatter: + - name diff --git a/tests/core/data/infer/values/a_scalar_literal_under_scatter_is_refused/workflow.wic b/tests/core/data/infer/values/a_scalar_literal_under_scatter_is_refused/workflow.wic new file mode 100644 index 000000000..71ce715a7 --- /dev/null +++ b/tests/core/data/infer/values/a_scalar_literal_under_scatter_is_refused/workflow.wic @@ -0,0 +1,7 @@ +# A scatter splits its value; a scalar is not wrapped into a one-element list. +steps: +- id: mk_file + in: + name: !ii a + scatter: + - name diff --git a/tests/core/data/infer/values/expected.yaml b/tests/core/data/infer/values/expected.yaml new file mode 100644 index 000000000..abec90458 --- /dev/null +++ b/tests/core/data/infer/values/expected.yaml @@ -0,0 +1,16 @@ +a_scalar_literal_under_scatter_is_refused: + compiled: true + refused: true + diagnostics: + - {code: LITERAL_TYPE_MISMATCH, step: mk_file, index: 1, port: name, severity: error, message: {contains: [scattered]}} +a_list_literal_under_scatter_is_unchanged: + compiled: true + job_inputs: {exact: {mk_file~name: [a, b]}} +iteration_exhaustion_is_exactly_wic022: + policy: {iteration_limit: 0} + refused: true + diagnostics: + - {code: FIXED_POINT_NOT_REACHED, severity: error} +falsy_defaults_satisfy_inputs: + edges: {exact: {}} + inputs: [] diff --git a/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/defaulted.cwl b/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/defaulted.cwl new file mode 100644 index 000000000..bfe3941c8 --- /dev/null +++ b/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/defaulted.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + number: {type: int, default: 0} + flag: {type: boolean, default: false} + text: {type: string, default: ''} + items: {type: 'string[]', default: []} +outputs: {} diff --git a/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/workflow.wic b/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/workflow.wic new file mode 100644 index 000000000..13c80ca0d --- /dev/null +++ b/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/workflow.wic @@ -0,0 +1,3 @@ +# Presence, not truthiness, suppresses inference for a defaulted port: none is inferred or lifted. +steps: +- id: defaulted diff --git a/tests/core/data/infer/values/iteration_exhaustion_is_exactly_wic022/workflow.wic b/tests/core/data/infer/values/iteration_exhaustion_is_exactly_wic022/workflow.wic new file mode 100644 index 000000000..e6f5fd55f --- /dev/null +++ b/tests/core/data/infer/values/iteration_exhaustion_is_exactly_wic022/workflow.wic @@ -0,0 +1,3 @@ +# The limit cannot be removed or exhausted silently. +steps: +- id: mk_file diff --git a/tests/core/data/inline/defaulted.wic b/tests/core/data/inline/defaulted.wic new file mode 100644 index 000000000..3d353535c --- /dev/null +++ b/tests/core/data/inline/defaulted.wic @@ -0,0 +1,5 @@ +inputs: + name: {type: string, default: x} +steps: +- id: xform + in: {name: name} diff --git a/tests/core/data/inline/embedded/cwltool_names.cwl b/tests/core/data/inline/embedded/cwltool_names.cwl new file mode 100644 index 000000000..abb0e8af0 --- /dev/null +++ b/tests/core/data/inline/embedded/cwltool_names.cwl @@ -0,0 +1,9 @@ +# cwltool renames its namespaced classes, by prefix or by URI; embedded, nothing does. +cwlVersion: v1.0 +class: CommandLineTool +baseCommand: 'true' +hints: + cwltool:LoadListingRequirement: {loadListing: shallow_listing} + http://commonwl.org/cwltool#NetworkAccess: {networkAccess: false} +inputs: {} +outputs: {} diff --git a/tests/core/data/inline/embedded/cwltool_names_listed.cwl b/tests/core/data/inline/embedded/cwltool_names_listed.cwl new file mode 100644 index 000000000..a5b75a263 --- /dev/null +++ b/tests/core/data/inline/embedded/cwltool_names_listed.cwl @@ -0,0 +1,8 @@ +# Renamed in the list form too. +cwlVersion: v1.0 +class: CommandLineTool +baseCommand: 'true' +hints: [{class: 'cwltool:LoadListingRequirement', loadListing: no_listing}] +requirements: [{class: 'http://commonwl.org/cwltool#NetworkAccess', networkAccess: true}] +inputs: {} +outputs: {} diff --git a/tests/core/data/inline/embedded/declared.cwl b/tests/core/data/inline/embedded/declared.cwl new file mode 100644 index 000000000..afe520c34 --- /dev/null +++ b/tests/core/data/inline/embedded/declared.cwl @@ -0,0 +1,8 @@ +# What the tool wrote wins: a hint it declares, and a requirement, so nothing of that class is added. +cwlVersion: v1.0 +class: CommandLineTool +baseCommand: 'true' +hints: {NetworkAccess: {networkAccess: false}} +requirements: {LoadListingRequirement: {loadListing: no_listing}} +inputs: {} +outputs: {} diff --git a/tests/core/data/inline/embedded/expected.yaml b/tests/core/data/inline/embedded/expected.yaml new file mode 100644 index 000000000..4f62ca3a9 --- /dev/null +++ b/tests/core/data/inline/embedded/expected.yaml @@ -0,0 +1,22 @@ +# Expected by hand from CWL v1.0 -> v1.1 as cwltool's updater (cwltool/update.py, v1_0to1_1) applies it to a file it +# loads: the keys of the embedded `run:`, which has no cwlVersion, or the refusal. +v1_0.cwl: + hints: {exact: {LoadListingRequirement: {loadListing: deep_listing}, NetworkAccess: {networkAccess: true}}} + inputs: {name: {secondaryFiles: [{pattern: .fai}]}, other: {secondaryFiles: [.crai, .csi]}, plain: string} + outputs: {file: {secondaryFiles: [.bai]}} +v1_0_without_hints.cwl: + hints: {exact: {LoadListingRequirement: {loadListing: deep_listing}, NetworkAccess: {networkAccess: true}}} + inputs: [{id: name, secondaryFiles: [.fai]}] + outputs: [{id: file, secondaryFiles: [.bai]}] +v1_1.cwl: {hints: {exact: {ResourceRequirement: {ramMin: 8}}}} +declared.cwl: {hints: {exact: {NetworkAccess: {networkAccess: false}}}} +listed.cwl: + hints: [{class: LoadListingRequirement, loadListing: deep_listing}, {class: ResourceRequirement, ramMin: 8}] +cwltool_names.cwl: + hints: {exact: {LoadListingRequirement: {loadListing: shallow_listing}, NetworkAccess: {networkAccess: false}}} +cwltool_names_listed.cwl: + hints: [{class: LoadListingRequirement, loadListing: no_listing}] + requirements: [{class: NetworkAccess, networkAccess: true}] +no_ports.cwl: {exact: {class: CommandLineTool, baseCommand: 'true'}} +v1_3_dev.cwl: {refused: "declares cwlVersion 'v1.3.0-dev1'"} +no_version.cwl: {refused: declares no cwlVersion} diff --git a/tests/core/data/inline/embedded/listed.cwl b/tests/core/data/inline/embedded/listed.cwl new file mode 100644 index 000000000..f72a4da74 --- /dev/null +++ b/tests/core/data/inline/embedded/listed.cwl @@ -0,0 +1,8 @@ +# A packed tool writes its hints as a list of {class} entries; a requirement it lists wins too. +cwlVersion: v1.0 +class: CommandLineTool +baseCommand: 'true' +hints: [{class: ResourceRequirement, ramMin: 8}] +requirements: [{class: NetworkAccess, networkAccess: false}] +inputs: {} +outputs: {} diff --git a/tests/core/data/inline/embedded/no_ports.cwl b/tests/core/data/inline/embedded/no_ports.cwl new file mode 100644 index 000000000..ad2e87cb5 --- /dev/null +++ b/tests/core/data/inline/embedded/no_ports.cwl @@ -0,0 +1,4 @@ +# No inputs and no outputs, which cwltool refuses when it loads the document: embedding leaves the refusal to it. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' diff --git a/tests/core/data/inline/embedded/no_version.cwl b/tests/core/data/inline/embedded/no_version.cwl new file mode 100644 index 000000000..1e0ed0b00 --- /dev/null +++ b/tests/core/data/inline/embedded/no_version.cwl @@ -0,0 +1,5 @@ +# The message does not claim it declared one. +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/inline/embedded/v1_0.cwl b/tests/core/data/inline/embedded/v1_0.cwl new file mode 100644 index 000000000..ccfcad698 --- /dev/null +++ b/tests/core/data/inline/embedded/v1_0.cwl @@ -0,0 +1,12 @@ +# cwltool gives a v1.0 file network access and a deep listing (cwltool/update.py, v1_0to1_1); embedded, nothing +# updates it, so they are written out. Its updater lists a single secondaryFiles pattern, which its checker indexes. +cwlVersion: v1.0 +class: CommandLineTool +baseCommand: 'true' +hints: {} +inputs: + name: {type: File, secondaryFiles: {pattern: .fai}} + other: {type: File, secondaryFiles: [.crai, .csi]} + plain: string +outputs: + file: {type: File, secondaryFiles: .bai, outputBinding: {glob: f}} diff --git a/tests/core/data/inline/embedded/v1_0_without_hints.cwl b/tests/core/data/inline/embedded/v1_0_without_hints.cwl new file mode 100644 index 000000000..ea993d8f3 --- /dev/null +++ b/tests/core/data/inline/embedded/v1_0_without_hints.cwl @@ -0,0 +1,8 @@ +# No hints key is the usual case, not an exception; ports written as lists are listed alike. +cwlVersion: v1.0 +class: CommandLineTool +baseCommand: 'true' +inputs: +- {id: name, type: File, secondaryFiles: .fai} +outputs: +- {id: file, type: File, secondaryFiles: .bai, outputBinding: {glob: f}} diff --git a/tests/core/data/inline/embedded/v1_1.cwl b/tests/core/data/inline/embedded/v1_1.cwl new file mode 100644 index 000000000..f17056b6f --- /dev/null +++ b/tests/core/data/inline/embedded/v1_1.cwl @@ -0,0 +1,7 @@ +# Only v1.0 implied anything. +cwlVersion: v1.1 +class: CommandLineTool +baseCommand: 'true' +hints: {ResourceRequirement: {ramMin: 8}} +inputs: {} +outputs: {} diff --git a/tests/core/data/inline/embedded/v1_3_dev.cwl b/tests/core/data/inline/embedded/v1_3_dev.cwl new file mode 100644 index 000000000..2df114f48 --- /dev/null +++ b/tests/core/data/inline/embedded/v1_3_dev.cwl @@ -0,0 +1,6 @@ +# Embedding would otherwise guess what a version Sophios has never seen implied. +cwlVersion: v1.3.0-dev1 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/inline/expected.yaml b/tests/core/data/inline/expected.yaml new file mode 100644 index 000000000..fa80d0c18 --- /dev/null +++ b/tests/core/data/inline/expected.yaml @@ -0,0 +1,42 @@ +# Each kept call, and why, said once; the flat root, its steps named for the calls they came from; and what each +# step of each form runs. +said: +- {contains: ["step 'gated.wic'", carries `when`]} +- {contains: ["step 'required.wic'", carries `requirements`]} +- {contains: ["step 'labelled.wic'", carries `label`]} +- {contains: ["step 'opted_out.wic'", 'wic: inlineable: false']} +- {contains: ["step 'javascript.wic'", different InlineJavascriptRequirement]} +- {contains: ["step 'scattered.wic'", carries `scatter`]} +- {contains: ["step 'valued.wic'", "input 'name' is bound to", not to a single source]} +- {contains: ["step 'defaulted.wic'", "input 'name' has a default"]} +- {contains: [sealing.wic, "step 'sealed.wic'", 'wic: inlineable: false']} +flat: + requirements: {exact: {InlineJavascriptRequirement: {expressionLib: [var a = 1;]}, MultipleInputFeatureRequirement: {}, + ScatterFeatureRequirement: {}, StepInputExpressionRequirement: {}, + SubworkflowFeatureRequirement: {}}} + steps: + - {id: mk_file, run: workflow~mk_file.cwl} + - {id: plain~xform, run: workflow~plain~xform.cwl, in: {file: mk_file/file}} + - {id: opted_in~xform, in: {file: plain~xform/file}} + - {id: gated, run: workflow~gated.cwl, when: $(true)} + - {id: required, requirements: {exact: {ResourceRequirement: {ramMin: 1}}}} + - {id: labelled, label: a call} + - {id: opted_out} + - {id: javascript} + - {id: scattered, scatter: [name]} + - {id: valued, in: {name: {exact: {source: w, valueFrom: $(self)}}}} + - {id: defaulted} + - {id: listed~xform, requirements: {exact: {EnvVarRequirement: {envDef: {A: b}}}}} + - {id: moved~xform, when: $(inputs.name != null), + requirements: {exact: {EnvVarRequirement: {envDef: {FOO: bar}}, ResourceRequirement: {ramMin: 5}}}} + - {id: middle~inner~xform, run: workflow~middle~inner~xform.cwl} + - {id: sealing~sealed, run: workflow~sealing~sealed.cwl} + - {id: unbound~xform, in: {name: {exact: {valueFrom: fallback}}}} + - {id: sink, in: {file: {source: plain~xform/file}, + extras: {source: [plain~xform/file, plain~xform/file], linkMerge: merge_flattened}}} +# What each step runs: T a CommandLineTool, W a Workflow, under each flag and both. +runs: + nested: [T, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, T] + --cwl_inline_subworkflows: [T, T, T, W, W, W, W, W, W, W, W, T, T, T, W, T, T] + --cwl_inline_runtag: [T, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, T] + both: [T, T, T, W, W, W, W, W, W, W, W, T, T, T, W, T, T] diff --git a/tests/core/data/inline/gated.wic b/tests/core/data/inline/gated.wic new file mode 100644 index 000000000..b4651a6f7 --- /dev/null +++ b/tests/core/data/inline/gated.wic @@ -0,0 +1,3 @@ +steps: +- id: xform + in: {name: !ii b} diff --git a/tests/core/data/inline/inner.wic b/tests/core/data/inline/inner.wic new file mode 100644 index 000000000..b4651a6f7 --- /dev/null +++ b/tests/core/data/inline/inner.wic @@ -0,0 +1,3 @@ +steps: +- id: xform + in: {name: !ii b} diff --git a/tests/core/data/inline/javascript.wic b/tests/core/data/inline/javascript.wic new file mode 100644 index 000000000..db6895f00 --- /dev/null +++ b/tests/core/data/inline/javascript.wic @@ -0,0 +1,5 @@ +requirements: + InlineJavascriptRequirement: {expressionLib: ['var a = 2;']} +steps: +- id: xform + in: {name: !ii b} diff --git a/tests/core/data/inline/labelled.wic b/tests/core/data/inline/labelled.wic new file mode 100644 index 000000000..b4651a6f7 --- /dev/null +++ b/tests/core/data/inline/labelled.wic @@ -0,0 +1,3 @@ +steps: +- id: xform + in: {name: !ii b} diff --git a/tests/core/data/inline/listed.wic b/tests/core/data/inline/listed.wic new file mode 100644 index 000000000..02de56f33 --- /dev/null +++ b/tests/core/data/inline/listed.wic @@ -0,0 +1,5 @@ +requirements: +- {class: EnvVarRequirement, envDef: {A: b}} +steps: +- id: xform + in: {name: !ii b} diff --git a/tests/core/data/inline/middle.wic b/tests/core/data/inline/middle.wic new file mode 100644 index 000000000..9c105775f --- /dev/null +++ b/tests/core/data/inline/middle.wic @@ -0,0 +1,2 @@ +steps: +- id: inner.wic diff --git a/tests/core/data/inline/moved.wic b/tests/core/data/inline/moved.wic new file mode 100644 index 000000000..146787296 --- /dev/null +++ b/tests/core/data/inline/moved.wic @@ -0,0 +1,9 @@ +requirements: + InlineJavascriptRequirement: {expressionLib: ['var a = 1;']} # the caller's, so no reason to stay + EnvVarRequirement: {envDef: {FOO: bar}} + ResourceRequirement: {ramMin: 100} +steps: +- id: xform + in: {name: !ii b} + requirements: {ResourceRequirement: {ramMin: 5}} # the step's own entry wins, as in CWL + when: $(inputs.name != null) # the engine reads `when` against the root diff --git a/tests/core/data/inline/opted_in.wic b/tests/core/data/inline/opted_in.wic new file mode 100644 index 000000000..0377d29d0 --- /dev/null +++ b/tests/core/data/inline/opted_in.wic @@ -0,0 +1,4 @@ +wic: {inlineable: true} +steps: +- id: xform + in: {name: !ii b} diff --git a/tests/core/data/inline/opted_out.wic b/tests/core/data/inline/opted_out.wic new file mode 100644 index 000000000..d32acbbb0 --- /dev/null +++ b/tests/core/data/inline/opted_out.wic @@ -0,0 +1,4 @@ +wic: {inlineable: false} +steps: +- id: xform + in: {name: !ii b} diff --git a/tests/core/data/inline/plain.wic b/tests/core/data/inline/plain.wic new file mode 100644 index 000000000..214c91bae --- /dev/null +++ b/tests/core/data/inline/plain.wic @@ -0,0 +1,5 @@ +steps: +- id: xform + in: {name: !ii b} +outputs: + file: {type: File, outputSource: xform/file} diff --git a/tests/core/data/inline/required.wic b/tests/core/data/inline/required.wic new file mode 100644 index 000000000..b4651a6f7 --- /dev/null +++ b/tests/core/data/inline/required.wic @@ -0,0 +1,3 @@ +steps: +- id: xform + in: {name: !ii b} diff --git a/tests/core/data/inline/scattered.wic b/tests/core/data/inline/scattered.wic new file mode 100644 index 000000000..52b2e4c96 --- /dev/null +++ b/tests/core/data/inline/scattered.wic @@ -0,0 +1,5 @@ +inputs: + name: string +steps: +- id: xform + in: {name: name} diff --git a/tests/core/data/inline/sealed.wic b/tests/core/data/inline/sealed.wic new file mode 100644 index 000000000..d32acbbb0 --- /dev/null +++ b/tests/core/data/inline/sealed.wic @@ -0,0 +1,4 @@ +wic: {inlineable: false} +steps: +- id: xform + in: {name: !ii b} diff --git a/tests/core/data/inline/sealing.wic b/tests/core/data/inline/sealing.wic new file mode 100644 index 000000000..d3f1fdb7a --- /dev/null +++ b/tests/core/data/inline/sealing.wic @@ -0,0 +1,2 @@ +steps: +- id: sealed.wic diff --git a/tests/core/data/inline/unbound.wic b/tests/core/data/inline/unbound.wic new file mode 100644 index 000000000..66fab105b --- /dev/null +++ b/tests/core/data/inline/unbound.wic @@ -0,0 +1,5 @@ +inputs: + name: string? +steps: +- id: xform + in: {name: !cwl {source: name, valueFrom: fallback}} diff --git a/tests/core/data/inline/valued.wic b/tests/core/data/inline/valued.wic new file mode 100644 index 000000000..52b2e4c96 --- /dev/null +++ b/tests/core/data/inline/valued.wic @@ -0,0 +1,5 @@ +inputs: + name: string +steps: +- id: xform + in: {name: name} diff --git a/tests/core/data/inline/workflow.wic b/tests/core/data/inline/workflow.wic new file mode 100644 index 000000000..d328178f1 --- /dev/null +++ b/tests/core/data/inline/workflow.wic @@ -0,0 +1,38 @@ +# --cwl_inline_subworkflows dissolves each call of only `in` and `out` into the steps of its workflow, named for +# where they came from; a call that carries more, or whose workflow opts out or would have to be guessed at, keeps its +# place as a Workflow, and one line says why. Calls are judged one at a time. mk_file and xform are the suite's +# synthetic tools (tests/core/synthetic_tools.py). +inputs: + w: string +requirements: + InlineJavascriptRequirement: {expressionLib: ['var a = 1;']} +steps: +- id: mk_file + in: {name: !ii a} +- id: plain.wic # dissolves + out: [file: !& made] +- id: opted_in.wic # dissolves: its workflow opts in +- id: gated.wic # kept: the call carries `when` + when: $(true) +- id: required.wic # kept: the call carries `requirements` + requirements: {ResourceRequirement: {ramMin: 1}} +- id: labelled.wic # kept: the call carries `label` + label: a call +- id: opted_out.wic # kept: its workflow says `wic: inlineable: false` +- id: javascript.wic # kept: two InlineJavascriptRequirement bodies cannot both be the root's +- id: scattered.wic # kept: the call carries `scatter` + in: {name: !ii [b, c]} + scatter: [name] +- id: valued.wic # kept: dissolving would drop the valueFrom its input is bound with + in: {name: !cwl {source: w, valueFrom: $(self)}} +- id: defaulted.wic # kept: its input has a default +- id: listed.wic # dissolves: its requirements, a list, are read as the mapping and move with its step +- id: moved.wic # dissolves: its requirements move onto the step that ran under them +- id: middle.wic # dissolves at every level: middle~inner~xform +- id: sealing.wic # dissolves, but the call it holds is sealed, so the root still runs a Workflow +- id: unbound.wic # dissolves: its input, left unbound, is null, and the valueFrom it is bound with applies +- id: sink # reads a dissolved call's output among its sources: the flat step is named instead + in: + file: !* made + n: !ii 1 + extras: !cwl {source: [!* made, !* made], linkMerge: merge_flattened} diff --git a/tests/core/data/kept_calls/cases.yaml b/tests/core/data/kept_calls/cases.yaml deleted file mode 100644 index b3d4cb8f4..000000000 --- a/tests/core/data/kept_calls/cases.yaml +++ /dev/null @@ -1,14 +0,0 @@ -# `mk_file` and a call of `child.wic` (one `xform`) with what the root, the call and the child carry, and the reason -# the call stays nested (null: it dissolves). Expected by hand from the rule: only a call of `in` and `out` dissolves. -- {id: when, call: {when: '$(inputs.file != null)'}, kept: it carries `when`, - why: the call carries more than in and out} -- {id: requirements, call: {requirements: {ResourceRequirement: {ramMin: 1}}}, kept: it carries `requirements`, - why: the call carries more than in and out} -- {id: label, call: {label: a call}, kept: it carries `label`, why: the call carries more than in and out} -- {id: opted-out, child: {wic: {inlineable: false}}, kept: 'it is marked `wic: inlineable: false`', - why: "the child's own file opts out"} -- {id: opted-in, child: {wic: {inlineable: true}}, kept: null, why: a child that opts in dissolves like any other} -- {id: different-javascript, root: {requirements: {InlineJavascriptRequirement: {expressionLib: ['var a = 1;']}}}, - child: {requirements: {InlineJavascriptRequirement: {expressionLib: ['var a = 2;']}}}, - kept: it declares a different InlineJavascriptRequirement from its caller, - why: "two bodies cannot both be the root's"} diff --git a/tests/core/data/lower/cases.yaml b/tests/core/data/lower/cases.yaml deleted file mode 100644 index 442450842..000000000 --- a/tests/core/data/lower/cases.yaml +++ /dev/null @@ -1,64 +0,0 @@ -- {id: an empty input name, source: "steps:\n- id: s\n in:\n \"\": !* e\n", graph: false, - diagnostics: [code: EMPTY_NAME], - why: &empty "`parse` accepts these; the types refuse them. Lowering has to bridge that. Refusing an unnamed port is - right, but the refusal is a `ValueError`, and every one of these is a document the parser hands back. Reported - here, the caller gets a diagnostic rather than a traceback -- the same treatment an unnamed step already had. Out - of reach of `documents()`, which draws names from the synthetic registry and so never draws an empty one."} -- {id: an empty out entry name, source: "steps:\n- id: s\n out:\n - \"\": f\n", graph: false, - diagnostics: [code: EMPTY_NAME], why: *empty} -- {id: an empty edge definition, source: "steps:\n- id: s\n out:\n - f: !& \"\"\n", graph: false, - diagnostics: [code: EMPTY_NAME], - why: &agree "`!& \"\"` and `!* \"\"` agree. They did not: the reference raised while the definition was accepted and - put `''` into the edge table as a live producer name, where it would match any later `!* \"\"` that managed not - to raise first."} -- {id: an empty edge reference, source: "steps:\n- id: s\n in:\n f: !* \"\"\n", graph: false, - diagnostics: [code: EMPTY_NAME], why: *agree} -- {id: a reference before its definition, source: "steps:\n- id: use\n in:\n f: !* e\n- id: mk\n out:\n - file: !& - e\n", diagnostics: [code: UNDEFINED_EDGE], - why: "`!* e` above its `!& e` is `wic025`, as the .wic reference and compiler say. Resolving it by pre-scanning every - definition would make Lower accept a document the compiler refuses, and silently change an ordering rule."} -- {id: a name defined twice, source: "steps:\n- id: a\n out:\n - f: !& e\n- id: b\n out:\n - f: !& e\n", - diagnostics: [code: DUPLICATE_EDGE_DEF], - why: "Keeping the first definition and dropping the second leaves nothing to report it with, here or in any later - phase."} -- {id: a sidecar out mentioning the name does not mask a real duplicate, diagnostics: [code: DUPLICATE_EDGE_DEF], - source: "wic:\n steps:\n (1, a):\n out:\n - f: {wic_anchor: e}\nsteps:\n- id: a\n out:\n - f: !& e\n- - id: b\n out:\n - f: !& e\n", - why: "A `wic:` sidecar `out:` entry (.wic reference §3.6) is inert passthrough, never itself a second definition -- - `basic.wic` relies on exactly this to place `min.tpr`'s one definition at a distance. A real duplicate among the - document's own steps must still be reported once, whether or not a sidecar block happens to mention the same - name."} -- {id: a step with no id, source: "steps:\n- id: \"\"\n in: {}\n", graph: false, diagnostics: [code: EMPTY_STEP_ID], - why: "The parser recovers such a document, which is exactly when a caller is least able to handle an exception. - `wic007` rather than `wic006`, matching what the parser already reports for the same document: the id is present - and empty, not missing."} -- {id: "scatter: [1]", source: "steps:\n- id: mk_file\n in: {name: !ii [a, b]}\n scatter: [1]\n", - diagnostics: {contains: [code: UNKNOWN_SCATTER_PORT]}, - why: &scatter "`scatter:` names inputs. An entry that is no name at all, or a `scatter:` that is neither a name nor a - list, names none of them: it is reported rather than dropped or emitted verbatim."} -- {id: "scatter: [null]", source: "steps:\n- id: mk_file\n in: {name: !ii [a, b]}\n scatter: [null]\n", - diagnostics: {contains: [code: UNKNOWN_SCATTER_PORT]}, why: *scatter} -- {id: "scatter: 5", source: "steps:\n- id: mk_file\n in: {name: !ii [a, b]}\n scatter: 5\n", - diagnostics: {contains: [code: UNKNOWN_SCATTER_PORT]}, why: *scatter} -- {id: "scatter: {a: 1}", source: "steps:\n- id: mk_file\n in: {name: !ii [a, b]}\n scatter: {a: 1}\n", - diagnostics: {contains: [code: UNKNOWN_SCATTER_PORT]}, why: *scatter} -- {id: "scatter: [name, 1]", source: "steps:\n- id: mk_file\n in: {name: !ii [a, b]}\n scatter: [name, 1]\n", - diagnostics: {contains: [code: UNKNOWN_SCATTER_PORT]}, why: *scatter} -- {id: a positional output source naming the wrong step, diagnostics: [code: POSITIONAL_OUTPUT_SOURCE], - source: "steps:\n- id: s\n out: [f]\n- id: s\n out: [f]\noutputs:\n o:\n type: File\n outputSource: (2, - t)/f\n", - why: &positional "A wrong name or an index past the last step is refused as wic039."} -- {id: a positional output source past the last step, diagnostics: [code: POSITIONAL_OUTPUT_SOURCE], why: *positional, - source: "steps:\n- id: s\n out: [f]\n- id: s\n out: [f]\noutputs:\n o:\n type: File\n outputSource: (3, - s)/f\n"} -- {id: a positional output source naming a port the step lacks, - diagnostics: [{code: UNDECLARED_PORT, message: {contains: ["'nope'", "its outputs are: f"]}}], - source: "steps:\n- id: s\n out: [f]\n- id: s\n out: [f]\noutputs:\n o:\n type: File\n outputSource: (2, - s)/nope\n", - why: "The step is known, so the missing port is reported with the step's outputs."} -- {id: a record source before its definition, diagnostics: [code: UNDEFINED_EDGE], - source: "steps:\n- id: use\n in:\n f: !cwl {source: !* e}\n- id: mk\n out:\n - file: !& e\n", - why: "A record's `!*` source resolves as a bare `!*` does: above its `!& e` it is `wic025`."} -- {id: a record with several sources takes none from outside its document, diagnostics: [code: UNDEFINED_EDGE], - source: "inputs:\n w: string\nsteps:\n- id: use\n in:\n f: !cwl {source: [!* e, w]}\n", - why: "One input crosses a workflow boundary through one relay, so it cannot carry several outside sources."} diff --git a/tests/core/data/lower/edges.wic b/tests/core/data/lower/edges.wic new file mode 100644 index 000000000..03194920e --- /dev/null +++ b/tests/core/data/lower/edges.wic @@ -0,0 +1,24 @@ +# `!* e` above its `!& e` is wic025: resolving it by pre-scanning every definition would make Lower accept a document +# the compiler refuses. A name defined twice is reported, and a `wic:` sidecar `out:` entry, inert passthrough as +# basic.wic relies on, neither defines it a second time nor masks the real duplicate. +wic: + steps: + (2, a): + out: + - f: {wic_anchor: e} +steps: +- id: use + in: + f: !* e +- id: a + out: + - f: !& e +- id: b + out: + - f: !& e +- id: record_use # a record's `!*` source resolves as a bare one does + in: + f: !cwl {source: !* later} +- id: mk + out: + - file: !& later diff --git a/tests/core/data/lower/empty_step_id.wic b/tests/core/data/lower/empty_step_id.wic new file mode 100644 index 000000000..97c3ef974 --- /dev/null +++ b/tests/core/data/lower/empty_step_id.wic @@ -0,0 +1,4 @@ +# The parser recovers a step with an empty id; lowering reports it as the parser does, wic007, not wic006. +steps: +- id: "" + in: {} diff --git a/tests/core/data/lower/expected.yaml b/tests/core/data/lower/expected.yaml new file mode 100644 index 000000000..2083d7e90 --- /dev/null +++ b/tests/core/data/lower/expected.yaml @@ -0,0 +1,30 @@ +# Every diagnostic lowering gives each document, in order, by code, severity, line, step and port. +names.wic: +- {code: EMPTY_NAME, severity: error, line: 4, step: s} +- {code: EMPTY_NAME, severity: error, line: 9, step: t} +- {code: EMPTY_NAME, severity: error, line: 12, step: u, port: f} +- {code: EMPTY_NAME, severity: error, line: 15, step: v, port: f} +empty_step_id.wic: +- {code: EMPTY_STEP_ID, severity: error, line: 3} +edges.wic: +- {code: DUPLICATE_EDGE_DEF, severity: error, line: 18, step: b, port: f} +- {code: UNDEFINED_EDGE, severity: error, line: 12, step: use, port: f} +- {code: UNDEFINED_EDGE, severity: error, line: 21, step: record_use, port: f} +record_sources.wic: +- {code: UNDEFINED_EDGE, severity: error, line: 8, step: use, port: f, message: {contains: [several sources]}} +scatter.wic: +- {code: UNKNOWN_SCATTER_PORT, severity: error, line: 4, step: mk_file} +- {code: UNKNOWN_SCATTER_PORT, severity: error, line: 7, step: mk_file} +- {code: UNKNOWN_SCATTER_PORT, severity: error, line: 10, step: mk_file} +- {code: UNKNOWN_SCATTER_PORT, severity: error, line: 13, step: mk_file} +- {code: UNKNOWN_SCATTER_PORT, severity: error, line: 16, step: mk_file} +outputs.wic: +- {code: POSITIONAL_OUTPUT_SOURCE, severity: error, step: t, port: f, message: {contains: ["'wrong_step'"]}} +- {code: POSITIONAL_OUTPUT_SOURCE, severity: error, step: s, port: f, message: {contains: ["'past_the_last'"]}} +- {code: UNDECLARED_PORT, severity: error, step: s, port: nope, message: {contains: ["'nope'", 'its outputs are: f']}} +merged_outputs.wic: +- {code: STEP_INPUT_RECORD, severity: error, message: {contains: ["'merged'", linkMerge]}} +- {code: STEP_INPUT_RECORD, severity: error, message: {contains: ["'picked'", pickValue]}} +- {code: STEP_INPUT_RECORD, severity: error, message: {contains: ["'two_sources'", a list outputSource]}} +- {code: STEP_INPUT_RECORD, severity: error, message: {contains: ["'one_listed'", a list outputSource]}} +- {code: STEP_INPUT_RECORD, severity: error, message: {contains: ["'none_listed'", a list outputSource]}} diff --git a/tests/core/data/lower/merged_outputs.wic b/tests/core/data/lower/merged_outputs.wic new file mode 100644 index 000000000..53eaa5057 --- /dev/null +++ b/tests/core/data/lower/merged_outputs.wic @@ -0,0 +1,11 @@ +# CWL's merge fields on a workflow output, and a list `outputSource:`, are wic038: they were copied out unread, and a +# list named steps by their authored ids, which cwltool cannot resolve. +steps: +- id: s + out: [f] +outputs: + merged: {type: File, outputSource: s/f, linkMerge: merge_flattened} + picked: {type: File, outputSource: s/f, pickValue: first_non_null} + two_sources: {type: File, outputSource: [a/f, b/f]} + one_listed: {type: File, outputSource: [s/f]} + none_listed: {type: File, outputSource: []} diff --git a/tests/core/data/lower/names.wic b/tests/core/data/lower/names.wic new file mode 100644 index 000000000..a574fa355 --- /dev/null +++ b/tests/core/data/lower/names.wic @@ -0,0 +1,15 @@ +# `parse` accepts empty names; the types refuse them, and lowering bridges that with a diagnostic, not a ValueError. +# `!& ""` and `!* ""` agree: neither puts '' into the edge table as a live producer name. +steps: +- id: s + in: + "": !* e +- id: t + out: + - "": f +- id: u + out: + - f: !& "" +- id: v + in: + f: !* "" diff --git a/tests/core/data/lower/outputs.wic b/tests/core/data/lower/outputs.wic new file mode 100644 index 000000000..8229b96c8 --- /dev/null +++ b/tests/core/data/lower/outputs.wic @@ -0,0 +1,17 @@ +# A positional `outputSource:` names a step by its place: a wrong name or a place past the last step is wic039, and a +# port the step lacks is reported with the step's outputs. +steps: +- id: s + out: [f] +- id: s + out: [f] +outputs: + wrong_step: + type: File + outputSource: (2, t)/f + past_the_last: + type: File + outputSource: (3, s)/f + no_such_port: + type: File + outputSource: (2, s)/nope diff --git a/tests/core/data/lower/record_sources.wic b/tests/core/data/lower/record_sources.wic new file mode 100644 index 000000000..08bb55e13 --- /dev/null +++ b/tests/core/data/lower/record_sources.wic @@ -0,0 +1,8 @@ +# One input crosses a workflow boundary through one relay, so a record with several sources takes none from outside +# its document. +inputs: + w: string +steps: +- id: use + in: + f: !cwl {source: [!* e, w]} diff --git a/tests/core/data/lower/scatter.wic b/tests/core/data/lower/scatter.wic new file mode 100644 index 000000000..4807b32c3 --- /dev/null +++ b/tests/core/data/lower/scatter.wic @@ -0,0 +1,18 @@ +# `scatter:` names inputs. An entry that is no name, or a `scatter:` that is neither a name nor a list, names none of +# them: reported, not dropped or emitted as written. +steps: +- id: mk_file + in: {name: !ii [a, b]} + scatter: [1] +- id: mk_file + in: {name: !ii [a, b]} + scatter: [null] +- id: mk_file + in: {name: !ii [a, b]} + scatter: 5 +- id: mk_file + in: {name: !ii [a, b]} + scatter: {a: 1} +- id: mk_file + in: {name: !ii [a, b]} + scatter: [name, 1] diff --git a/tests/core/data/nextflow/runs/conditions_and_scatter/expected.yaml b/tests/core/data/nextflow/runs/conditions_and_scatter/expected.yaml deleted file mode 100644 index 315ae2169..000000000 --- a/tests/core/data/nextflow/runs/conditions_and_scatter/expected.yaml +++ /dev/null @@ -1,46 +0,0 @@ -# Every output of workflow.wic, by step and port, in the order of its steps. -outputs: - up~result: "ok\n" - up_skipped~result: null - counted~result: "ok\n" - uncounted~result: null - carried~result: "ok\n" - gated~result: "1 2 3\n" - gated_prev_last~result: "1 2 3\n" - gated_after_skip~result: null - gated_flag_false~result: null - after_skip~done: {class: File, basename: done.txt, contents: ""} - write_note~note: {class: File, basename: note.txt, contents: "shared\n"} - copy_note~copy: - - {class: File, basename: a.txt, contents: "shared\n"} - - {class: File, basename: b.txt, contents: "shared\n"} - - {class: File, basename: c.txt, contents: "shared\n"} - echo_item~out: - - {class: File, basename: a.txt, contents: "1\n"} - - {class: File, basename: a.txt, contents: "2\n"} - - {class: File, basename: a.txt, contents: "3\n"} - cat_pair~out: - - {class: File, basename: b.txt, contents: "1\nREF\n"} - - {class: File, basename: b.txt, contents: "2\nREF\n"} - - {class: File, basename: b.txt, contents: "3\nREF\n"} - cat_pair_flat~out: - - {class: File, basename: b.txt, contents: "1\nREF\n"} - - {class: File, basename: b.txt, contents: "2\nREF\n"} - - {class: File, basename: b.txt, contents: "3\nREF\n"} - cat_pair_nested~out: - - {class: File, basename: b.txt, contents: "1\nREF\n"} - - {class: File, basename: b.txt, contents: "2\nREF\n"} - - {class: File, basename: b.txt, contents: "3\nREF\n"} - pair_nested~line: - - - {class: File, basename: out.txt, contents: a-x} - - {class: File, basename: out.txt, contents: a-y} - - - {class: File, basename: out.txt, contents: b-x} - - {class: File, basename: out.txt, contents: b-y} - pair_unless_b~line: - - {class: File, basename: out.txt, contents: "a-x"} - - null - - {class: File, basename: out.txt, contents: "c-z"} - pair_unless_skipped~line: - - {class: File, basename: out.txt, contents: "a-0.2"} - - null - - {class: File, basename: out.txt, contents: "c-0"} diff --git a/tests/core/data/nextflow/runs/step_inputs/expected.yaml b/tests/core/data/nextflow/runs/step_inputs/expected.yaml deleted file mode 100644 index e74820ae7..000000000 --- a/tests/core/data/nextflow/runs/step_inputs/expected.yaml +++ /dev/null @@ -1,21 +0,0 @@ -# Every output of workflow.wic, by step and port, in the order of its steps. -outputs: - write_each~file: - - {class: File, basename: out.txt, contents: "a\n"} - - {class: File, basename: out.txt, contents: "b\n"} - write_one~file: {class: File, basename: out.txt, contents: "c\n"} - write_two~file: {class: File, basename: out.txt, contents: "d\n"} - skipped~said: null - ran~said: only - cat_flat~line: {class: File, basename: all.txt, contents: "a\nb\nc\n"} - cat_nested~line: {class: File, basename: all.txt, contents: "d\nc\n"} - cat_single~line: {class: File, basename: all.txt, contents: "c\n"} - say_nested~line: {class: File, basename: out.txt, contents: "x y z\n"} - say_single~line: {class: File, basename: out.txt, contents: "x\n"} - default_unsourced~line: {class: File, basename: out.txt, contents: "d1\n"} - default_for_absent~line: {class: File, basename: out.txt, contents: "d2\n"} - default_not_taken~line: {class: File, basename: out.txt, contents: "g\n"} - default_after_skip~line: {class: File, basename: out.txt, contents: "d4\n"} - pick_first~line: {class: File, basename: out.txt, contents: "g\n"} - pick_only~line: {class: File, basename: out.txt, contents: "only\n"} - pick_all~line: {class: File, basename: out.txt, contents: "g only\n"} diff --git a/tests/core/data/when_boolean.yaml b/tests/core/data/when_boolean.yaml deleted file mode 100644 index 4b41c22a0..000000000 --- a/tests/core/data/when_boolean.yaml +++ /dev/null @@ -1,92 +0,0 @@ -# The one check of a `when` both targets share: it must give `true` or `false` (CWL v1.2's WorkflowStep `when`, in -# Workflow.yml), and cwltool stops the run at one that gives anything else (`WorkflowJob.try_make_job`, in -# cwltool/workflow_job.py). `notes` is what the CWL target notes of a case, `refused` what the Nextflow target refuses, -# [] where it lowers; each as it prints, less its span. Expected by hand from design_docs/resolved-view-design.md §10. -- id: a-number - why: cwltool fails a when that gives 2; the Nextflow target refused it already, and now reads the same check - workflow: {inputs: {n: int}, steps: [{id: gated, in: {n: n}, when: $(inputs.n + 1)}]} - tools: [&gated {id: gated, inputs: {n: {type: int}}, baseCommand: 'true'}] - job: &one {n: 1} - notes: ["note [wic056] when '$(inputs.n + 1)' must compute a boolean, not a number: cwltool stops the run when it - gives anything but true or false (step 'gated')"] - refused: ["step 'gated': when: '$(inputs.n + 1)' must compute a boolean, not a number"] -- id: a-string-the-tool-does-not-take - why: a when is typed by what each step input delivers, a step-only input among them - workflow: {inputs: {n: int, s: string}, steps: [{id: gated, in: {n: n, s: {wic_raw_cwl: {source: s}}}, - when: $(inputs.s)}]} - tools: [*gated] - job: {n: 1, s: a} - notes: ["note [wic056] when '$(inputs.s)' must compute a boolean, not a string: cwltool stops the run when it gives - anything but true or false (step 'gated')"] - refused: ["step 'gated': when: '$(inputs.s)' must compute a boolean, not a string"] -- id: a-null - why: null is neither true nor false - workflow: {inputs: {n: int}, steps: [{id: gated, in: {n: n}, when: $(null)}]} - tools: [*gated] - job: *one - notes: ["note [wic056] when '$(null)' must compute a boolean, not a null: cwltool stops the run when it gives - anything but true or false (step 'gated')"] - refused: ["step 'gated': when: '$(null)' must compute a boolean, not a null"] -- id: an-element-of-a-scatter - why: a when is evaluated in each job of a scatter, over one element of a scattered input - workflow: {inputs: {n: {type: {type: array, items: int}}}, steps: [{id: gated, in: {n: n}, scatter: [n], - when: $(inputs.n)}]} - tools: [*gated] - job: {n: [1]} - notes: ["note [wic056] when '$(inputs.n)' must compute a boolean, not a number: cwltool stops the run when it gives - anything but true or false (step 'gated')"] - refused: ["step 'gated': when: '$(inputs.n)' must compute a boolean, not a number"] -- id: text - why: a string with no expression in it is no CWL Expression, which cwltool's validation refuses - workflow: {inputs: {n: int}, steps: [{id: gated, in: {n: n}, when: 'true'}]} - tools: [*gated] - job: *one - notes: ["note [wic056] when 'true' is not one $(...) or ${...} expression: cwltool stops the run when it gives - anything but true or false (step 'gated')"] - refused: ["step 'gated': when: 'true' is not one $(...) or ${...} expression"] -- id: a-template - why: text around an expression is interpolated, so it gives a string however its expression types - workflow: {inputs: {n: int}, steps: [{id: gated, in: {n: n}, when: $(inputs.n > 0) or not}]} - tools: [*gated] - job: *one - notes: ["note [wic056] when '$(inputs.n > 0) or not' is not one $(...) or ${...} expression: cwltool stops the run - when it gives anything but true or false (step 'gated')"] - refused: ["step 'gated': when: '$(inputs.n > 0) or not' is not one $(...) or ${...} expression"] -- id: on-a-call - why: a call's when is a CWL when like any other; the Nextflow target refuses a when on a call before it reads one - workflow: {inputs: {n: int}, steps: [{id: child.wic, subtree: {inputs: {n: int}, steps: [{id: gated, in: {n: n}}]}, - parentargs: {in: {n: n}, when: $(inputs.n)}}]} - tools: [*gated] - job: *one - notes: ["note [wic056] when '$(inputs.n)' must compute a boolean, not a number: cwltool stops the run when it gives - anything but true or false (step 'child')"] - refused: ["step 'child': when: a when on a nested-workflow step is not supported; put it on a tool step"] -- id: a-boolean - why: a comparison gives true or false - workflow: {inputs: {n: int}, steps: [{id: gated, in: {n: n}, when: ' $(inputs.n > 0) '}]} - tools: [*gated] - job: *one - notes: [] - refused: [] -- id: outside-the-subset - why: a when the subset cannot read says nothing of what it gives, so the check says nothing of it - workflow: {inputs: {n: int}, steps: [{id: gated, in: {n: n}, when: $(inputs.n ** 2)}]} - tools: [*gated] - job: *one - notes: [] - refused: ["step 'gated': when: '$(inputs.n ** 2)' is outside the safe JavaScript subset: unsupported construct - '**'"] -- id: a-body - why: a ${...} body is one expression, which the subset does not read - workflow: {inputs: {n: int}, steps: [{id: gated, in: {n: n}, when: '${ return inputs.n; }'}]} - tools: [*gated] - job: *one - notes: [] - refused: ["step 'gated': when: '${ return inputs.n; }' must be a safe JavaScript subset $( … ) expression"] -- id: not-a-string - why: a when that is not a string is cwltool's schema validation's to refuse - workflow: {inputs: {n: int}, steps: [{id: gated, in: {n: n}, when: true}]} - tools: [*gated] - job: *one - notes: [] - refused: ["step 'gated': when: True must be a safe JavaScript subset $( … ) expression"] diff --git a/tests/core/helpers.py b/tests/core/helpers.py index c20d07445..9a146950e 100644 --- a/tests/core/helpers.py +++ b/tests/core/helpers.py @@ -1,15 +1,21 @@ """Setup many tests repeat: files written under a directory, the command line run in-process, the shipped tools -as Python API steps, a real-time analysis declared, a run kept off the container engine, and a test run under -each CWL runner.""" +as Python API steps, a real-time analysis declared, a run kept off the container engine, a test run under +each CWL runner, and the example workflows of tests/core/data/examples read and run.""" +from collections.abc import Callable import functools +import hashlib +import io import json import os +import shutil import subprocess import sys from pathlib import Path from typing import Any, Final, Iterable, Mapping +from urllib.parse import unquote, urlsplit import pytest +import yaml import sophios import sophios.plugins @@ -22,6 +28,7 @@ ADAPTERS: Final = REPO_ROOT / 'cwl_adapters' HELLOWORLD: Final = REPO_ROOT / 'docs' / 'tutorials' / 'helloworld.wic' EACH_RUNNER: Final = pytest.mark.parametrize('runner', ['cwltool', 'toil-cwl-runner']) +EXAMPLES: Final = Path(__file__).resolve().parent / 'data' / 'examples' def write_tree(root: Path, files: Mapping[str, str]) -> Path: @@ -102,3 +109,78 @@ def run_local_process(workflow: Path, *flags: str, **options: Any) -> subprocess logging state that one process running both leaves broken.""" return python_process('-m', 'sophios.main', '--yaml', workflow, '--run_local', '--ignore_docker_install', '--ignore_docker_processes', *flags, **options) + + +def examples() -> list[Any]: + """Each example directory of tests/core/data/examples, by its name.""" + return [pytest.param(path, id=path.name) for path in sorted(EXAMPLES.iterdir()) if path.is_dir()] + + +def stated(folder: Path) -> Any: + """What the example `folder`'s expected.yaml states.""" + return yaml.safe_load((folder / 'expected.yaml').read_text(encoding='utf-8')) + + +def example_workflow(folder: Path, directory: Path) -> Workflow: + """A copy of the example `folder` at `directory`, and the workflow its `workflow.wic` is: read with the tools and + child workflows beside it and the tools Sophios ships, its inputs given the values of `job.yml`. A relative path in + it is read against the working directory, which the caller makes `directory`.""" + shutil.copytree(folder, directory) + tools = sophios.plugins.get_tools_cwl({'search_paths_cwl': {'global': [str(directory), str(ADAPTERS)]}}) + children = {'global': {path.stem: path for path in directory.glob('*.wic') if path.name != 'workflow.wic'}} + workflow = Workflow.from_wic(directory / 'workflow.wic', tool_registry=tools, workflow_paths=children) + job = directory / 'job.yml' + for name, value in (yaml.safe_load(job.read_text(encoding='utf-8')) if job.exists() else {}).items(): + setattr(workflow.inputs, name, value) + return workflow + + +def tree(path: Path) -> Any: + """What a runner-independent observer sees at `path`: a file's text, or a directory's files and texts.""" + if path.is_dir(): + return {str(item.relative_to(path)): tree(item) for item in sorted(path.rglob('*')) if item.is_file()} + data = path.read_bytes() + try: + return data.decode('utf-8') + except UnicodeDecodeError: + return hashlib.sha256(data).hexdigest() + + +def observed(value: Any) -> Any: + """An output as a runner-independent observer sees it: a File's or Directory's class, basename and contents, + never its path; null and a string, number or boolean as they are.""" + if isinstance(value, list): + return [observed(item) for item in value] + if not isinstance(value, dict): + return value + # cwltool gives a Directory it left where its step made it a location and no path, and an entry it captured the + # path of the file the entry links to: the name is the object's. + path = Path(value['path'] if 'path' in value else unquote(urlsplit(value['location']).path)) + return {'class': value['class'], 'basename': value.get('basename', path.name), 'contents': tree(path)} + + +def files_beside(directory: Path) -> dict[str, Any]: + """What `directory` holds, each file as its text.""" + return {path.name: tree(path) for path in directory.iterdir()} + + +def cwltool_run(cwltool_main: Callable[..., int], workflow: Workflow, directory: Path) -> tuple[int, str, str]: + """cwltool's exit code, output object and messages for the CWL `workflow` compiles to, written in `directory`. + Each output stays where its step left it: moved into one directory, two steps' out.txt could not both keep + the name.""" + compiled = workflow.compile() + document, job = compiled.write_cwl(directory), compiled.write_job_inputs(directory) + stdout, stderr = io.StringIO(), io.StringIO() + code = cwltool_main( + ['--quiet', '--leave-outputs', '--leave-tmpdir', '--tmpdir-prefix', f'{directory}/tmp/', + '--tmp-outdir-prefix', f'{directory}/tmp_out/', str(document), str(job)], + stdout=stdout, stderr=stderr, + ) + return code, stdout.getvalue(), stderr.getvalue() + + +def cwltool_outputs(cwltool_main: Callable[..., int], workflow: Workflow, directory: Path) -> dict[str, Any]: + """The output object of a successful `cwltool_run`.""" + code, outputs, messages = cwltool_run(cwltool_main, workflow, directory) + assert code == 0, messages + return dict(json.loads(outputs)) diff --git a/tests/core/nextflow/test_import.py b/tests/core/nextflow/test_import.py index 805430b0b..18a9e5a6f 100644 --- a/tests/core/nextflow/test_import.py +++ b/tests/core/nextflow/test_import.py @@ -38,13 +38,13 @@ from ..budgets import budget from ..cases import DATA +from ..helpers import EXAMPLES, example_workflow, examples from ..hermetic import network_refused from ..provocations import IMPORT_EDITS, import_edited from .test_phase3_cells import calculator_workflow, predicates_workflow -from .testkit import example_workflow, examples -#: The example workflows of tests/core/data/nextflow/runs, by name. -RUNS = [param.values[0].name for param in examples("runs")] +#: The example workflows of tests/core/data/examples, by name. +RUNS = [param.values[0].name for param in examples()] _FILES = (NEXTFLOW_SCRIPT, NEXTFLOW_PARAMS, NEXTFLOW_CONFIG) @@ -56,7 +56,7 @@ def _model(name: str) -> ExecutableNextflowWorkflow: return calculator_workflow().compile(target="nextflow").nextflow_workflow with tempfile.TemporaryDirectory() as scratch: directory = Path(scratch) / name - workflow = example_workflow(DATA / "nextflow" / "runs" / name, directory) + workflow = example_workflow(EXAMPLES / name, directory) with contextlib.chdir(directory): return workflow.compile(target="nextflow").nextflow_workflow @@ -85,7 +85,7 @@ def _echo(name: str, **inputs: Input) -> CommandLineTool: @pytest.mark.parametrize("name", RUNS) def test_the_pipeline_of_an_example_imports_to_its_model( name: str, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """The three files written for each example of tests/core/data/nextflow/runs, alone in a directory and read with + """The three files written for each example of tests/core/data/examples, alone in a directory and read with the network refused, import to a workflow that compiles to the model they were written from; no path a parameter names is looked at: not `nextflow_workflow.json`, no tool registry, no input file.""" model = _model(name) diff --git a/tests/core/nextflow/test_phase3_cells.py b/tests/core/nextflow/test_phase3_cells.py index 8af3221c0..44a156741 100644 --- a/tests/core/nextflow/test_phase3_cells.py +++ b/tests/core/nextflow/test_phase3_cells.py @@ -1,6 +1,6 @@ """The Phase 3 acceptance cells (design §6) as builders. A1-A9, W1-W7 are decided in test_subset_differential.py, S1-S14 in test_runtime.py's scatter property, W8-W11 and A11 in the example workflows of -tests/core/data/nextflow/runs and stops; A10 has no runtime test (rejected).""" +tests/core/data/examples and nextflow/stops; A10 has no runtime test (rejected).""" # pylint: disable=missing-function-docstring diff --git a/tests/core/nextflow/test_reference_differential.py b/tests/core/nextflow/test_reference_differential.py index 3f91bb978..10ac75f11 100644 --- a/tests/core/nextflow/test_reference_differential.py +++ b/tests/core/nextflow/test_reference_differential.py @@ -5,12 +5,8 @@ from collections.abc import Callable from functools import partial -import hashlib -import io -import json from pathlib import Path -from typing import Any, cast -from urllib.parse import unquote, urlsplit +from typing import Any import pytest @@ -19,6 +15,7 @@ from sophios.api.python.workflow import Step, Workflow from sophios.backends import recorded_outputs +from ..helpers import cwltool_outputs, cwltool_run, observed, tree from .testkit import assert_succeeded, execute_nextflow #: One script for every cell. $1, $2, $3 are `$(inputs.x)`, `$(inputs.x.path)`, `$(inputs.x.basename)` as @@ -120,33 +117,9 @@ def _workflow(values: dict[str, Any]) -> Workflow: return workflow -def _tree(path: Path) -> Any: - """What a runner-independent observer sees at ``path``: a file's text, or a directory's files and texts.""" - if path.is_dir(): - return {str(item.relative_to(path)): _tree(item) for item in sorted(path.rglob("*")) if item.is_file()} - data = path.read_bytes() - try: - return data.decode("utf-8") - except UnicodeDecodeError: - return hashlib.sha256(data).hexdigest() - - -def _observed(value: Any) -> Any: - """An output as a runner-independent observer sees it: a File's or Directory's class, basename and contents, - never its path; null and a string, number or boolean as they are.""" - if isinstance(value, list): - return [_observed(item) for item in value] - if not isinstance(value, dict): - return value - # cwltool gives a Directory it left where its step made it a location and no path, and an entry it captured the - # path of the file the entry links to: the name is the object's. - path = Path(value["path"] if "path" in value else unquote(urlsplit(value["location"]).path)) - return {"class": value["class"], "basename": value.get("basename", path.name), "contents": _tree(path)} - - def _snapshot(values: dict[str, Any]) -> dict[str, Any]: flat = [item for value in values.values() for item in (value if isinstance(value, list) else [value])] - return {path.name: _tree(path) for path in flat} + return {path.name: tree(path) for path in flat} def _run_nextflow(workflow: Workflow, directory: Path) -> dict[str, Any]: @@ -155,27 +128,6 @@ def _run_nextflow(workflow: Workflow, directory: Path) -> dict[str, Any]: return dict(recorded_outputs(result.stdout)) -def _cwltool(main: Callable[..., int], workflow: Workflow, directory: Path) -> tuple[int, str, str]: - """cwltool's exit code, output object and messages for the CWL `workflow` compiles to, written in `directory`. - Each output stays where its step left it: moved into one directory, two steps' out.txt could not both keep - the name.""" - compiled = workflow.compile() - document, job = compiled.write_cwl(directory), compiled.write_job_inputs(directory) - stdout, stderr = io.StringIO(), io.StringIO() - code = main( - ["--quiet", "--leave-outputs", "--leave-tmpdir", "--tmpdir-prefix", f"{directory}/tmp/", - "--tmp-outdir-prefix", f"{directory}/tmp_out/", str(document), str(job)], - stdout=stdout, stderr=stderr, - ) - return code, stdout.getvalue(), stderr.getvalue() - - -def _run_cwltool(main: Callable[..., int], workflow: Workflow, directory: Path) -> dict[str, Any]: - code, outputs, messages = _cwltool(main, workflow, directory) - assert code == 0, messages - return cast(dict[str, Any], json.loads(outputs)) - - @pytest.mark.nextflow @pytest.mark.serial @pytest.mark.needs_cwltool @@ -187,16 +139,16 @@ def test_a_path_inputs_references_mean_under_nextflow_what_they_mean_under_cwlto target refuses it when compiling instead of running what CWL does not (design §6).""" import cwltool.main # pylint: disable=import-outside-toplevel - observed, problems = {}, [] - for runner, run in (("nextflow", _run_nextflow), ("cwltool", partial(_run_cwltool, cwltool.main.main))): + seen, problems = {}, [] + for runner, run in (("nextflow", _run_nextflow), ("cwltool", partial(cwltool_outputs, cwltool.main.main))): values = _inputs(tmp_path / runner / "inputs") before = _snapshot(values) outputs = run(_workflow(values), tmp_path / runner / "run") - observed[runner] = {name: _observed(value) for name, value in sorted(outputs.items())} + seen[runner] = {name: observed(value) for name, value in sorted(outputs.items())} after = _snapshot(values) problems += [f"{runner} changed its input {name}: {after[name]}" for name in before if after[name] != before[name]] - nf, cw = observed["nextflow"], observed["cwltool"] + nf, cw = seen["nextflow"], seen["cwltool"] problems += [ f"output {name}:\n nextflow: {nf.get(name)}\n cwltool: {cw.get(name)}" for name in sorted(nf.keys() | cw.keys()) if nf.get(name) != cw.get(name) @@ -219,5 +171,5 @@ def _neither_globs_an_entrys_object(main: Callable[..., int], directory: Path) - workflow.compile(target="nextflow") assert [(refusal.code.value, refusal.subject) for refusal in refused.value.refusals] == [ ("nf-s046", "fill.cwl: outputs.o.outputBinding.glob")] - code, _, messages = _cwltool(main, workflow, directory) + code, _, messages = cwltool_run(main, workflow, directory) assert code != 0 and "Resolved glob patterns must be strings" in messages, messages diff --git a/tests/core/nextflow/test_runtime.py b/tests/core/nextflow/test_runtime.py index 47ac89458..9df783897 100644 --- a/tests/core/nextflow/test_runtime.py +++ b/tests/core/nextflow/test_runtime.py @@ -16,7 +16,6 @@ from hypothesis import example, given, strategies as st import pytest -import yaml from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl from sophios.api.python.workflow import Step, StepInput, Workflow @@ -26,11 +25,12 @@ from ..budgets import budget from ..cases import DATA, case_dirs -from ..helpers import python_process, search_config +from ..helpers import (cwltool_outputs, cwltool_run, example_workflow, examples, files_beside, observed, python_process, + search_config, stated) from .test_executable_ir import NAMES from .test_public_api import supported_workflow -from .test_reference_differential import _cwltool, _observed, _run_cwltool, _run_nextflow, _tree -from .testkit import assert_succeeded, example_workflow, examples, execute_nextflow +from .test_reference_differential import _run_nextflow +from .testkit import assert_succeeded, execute_nextflow @pytest.mark.nextflow @@ -168,45 +168,28 @@ def _example(folder: Path, directory: Path, monkeypatch: pytest.MonkeyPatch) -> return workflow -def _files(directory: Path) -> dict[str, Any]: - """What `directory` holds, each file as its text.""" - return {path.name: _tree(path) for path in directory.iterdir()} - - def _kept(directory: Path, before: dict[str, Any]) -> bool: """Whether a run left every file `directory` held `before` it as it was.""" - return {name: found for name, found in _files(directory).items() if name in before} == before + return {name: found for name, found in files_beside(directory).items() if name in before} == before @pytest.mark.nextflow @pytest.mark.serial -@pytest.mark.needs_cwltool -@pytest.mark.parametrize("folder", examples("runs")) -def test_an_example_workflow_runs_under_nextflow_as_under_cwltool( +@pytest.mark.parametrize("folder", examples()) +def test_an_example_workflow_runs_under_nextflow_as_stated( folder: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """Each directory of tests/core/data/nextflow/runs is a workflow to read and to run: `workflow.wic`, the tools - and child workflows it names, `job.yml` for its inputs, and `expected.yaml` stating every output by class, - basename and contents. Run as Nextflow it gives exactly those outputs, and so does cwltool, the reference runner, - for the CWL the same workflow compiles to: the statement is CWL's answer, not Sophios's. The two runners agreeing - is not enough, since a compiler that reversed a list of sources would reverse it for both. Both leave the files - beside the workflow as they were. An example with no `reference` run here is run as Nextflow only. A - `workflow.nf` and `nextflow.config` are the pipeline written, for what no run shows.""" - import cwltool.main # pylint: disable=import-outside-toplevel - - stated = yaml.safe_load((folder / "expected.yaml").read_text(encoding="utf-8")) - for runner in ("nextflow", "cwltool")[:1 if stated.get("reference") == "none" else 2]: - directory = tmp_path / runner - workflow = _example(folder, directory, monkeypatch) - before = _files(directory) - if runner == "nextflow": - ran = workflow.run(target="nextflow", basepath=str(directory / "out")) - assert ran is not None and isinstance(ran.outputs, dict) - outputs = ran.outputs - else: - outputs = _run_cwltool(cwltool.main.main, workflow, directory) - assert {name: _observed(value) for name, value in outputs.items()} == stated["outputs"], runner - assert _kept(directory, before), f"{runner} changed a file beside the workflow" - pipeline = tmp_path / "nextflow" / "out" / "nextflow_workflow" + """Each directory of tests/core/data/examples, run as Nextflow, gives exactly the outputs its `expected.yaml` + states by class, basename and contents, the outputs cwltool gives too (test_compiler.py's cwltool leg), and + leaves the files beside the workflow as they were. A `workflow.nf` and `nextflow.config` beside it are the + pipeline written, for what no run shows.""" + directory = tmp_path / "example" + workflow = _example(folder, directory, monkeypatch) + before = files_beside(directory) + ran = workflow.run(target="nextflow", basepath=str(directory / "out")) + assert ran is not None and isinstance(ran.outputs, dict) + assert {name: observed(value) for name, value in ran.outputs.items()} == stated(folder)["outputs"] + assert _kept(directory, before), "Nextflow changed a file beside the workflow" + pipeline = directory / "out" / "nextflow_workflow" for written in ("workflow.nf", "nextflow.config"): if (folder / written).exists(): assert (pipeline / written).read_text(encoding="utf-8") == (folder / written).read_text(encoding="utf-8") @@ -222,7 +205,7 @@ def _stopped(folder: Path, expected: dict[str, Any], tmp_path: Path, directory = tmp_path / "nextflow" workflow = _example(folder, directory, monkeypatch) - before = _files(directory) + before = files_beside(directory) handle = workflow.start(target="nextflow", basepath=str(directory / "out")) status = handle.wait() assert status.state is RunState.FAILED, handle.logs() @@ -232,7 +215,7 @@ def _stopped(folder: Path, expected: dict[str, Any], tmp_path: Path, assert expected["says"] in logs + (pipeline / ".nextflow.log").read_text(encoding="utf-8"), logs assert _kept(directory, before) reference = _example(folder, tmp_path / "cwltool", monkeypatch) - code, _, messages = _cwltool(cwltool.main.main, reference, tmp_path / "cwltool") + code, _, messages = cwltool_run(cwltool.main.main, reference, tmp_path / "cwltool") assert ("fails" if code else "runs") == expected["cwltool"], messages return status, pipeline / "work" @@ -374,8 +357,9 @@ def test_a_command_receives_the_arguments_cwltool_gives_it( import cwltool.main # pylint: disable=import-outside-toplevel root = tmp_path_factory.mktemp("argv") + runners = (("nextflow", _run_nextflow), ("cwltool", partial(cwltool_outputs, cwltool.main.main))) printed = {runner: Path(run(_argv_workflow(spec), root / runner)["out"]["path"]).read_bytes() - for runner, run in (("nextflow", _run_nextflow), ("cwltool", partial(_run_cwltool, cwltool.main.main)))} + for runner, run in runners} assert printed["nextflow"] == printed["cwltool"] assert not list(root.rglob("SHOULD_NOT_EXIST")) diff --git a/tests/core/nextflow/testkit.py b/tests/core/nextflow/testkit.py index c42197a66..16ba8843a 100644 --- a/tests/core/nextflow/testkit.py +++ b/tests/core/nextflow/testkit.py @@ -3,16 +3,12 @@ from collections.abc import Sequence import copy import os -import shutil import subprocess from pathlib import Path from typing import Any -import pytest import yaml -from sophios.api.python.workflow import Workflow - from sophios.cli import default_compilation_settings from sophios.compiler import compile_source, resolved_view from sophios.input_output_nf import write_nextflow_artifacts @@ -37,8 +33,6 @@ from sophios.utils_nf import NEXTFLOW from sophios.wic_types import StepId, Tool, Yaml -from ..cases import DATA -from ..helpers import ADAPTERS from ..hermetic import bundle from ..synthetic_tools import SYNTHETIC_NS @@ -169,14 +163,6 @@ def refusal_of(root: Path) -> NotLowered: raise AssertionError(f"{root} is lowered: the Nextflow target refuses nothing of it") -def refusal_lines(refused: NotLowered) -> list[str]: - """Each refusal's owner and message: `step '': `, or `workflow '': `. Its span, - which the line the document is written at decides, and its code, which a case names as its `codes`, are left - out.""" - return [f"{f'step {refusal.step!r}' if refusal.step is not None else f'workflow {refusal.workflow!r}'}: " - f"{refusal.message}" for refusal in refused.refusals] - - def runtime_workflow() -> ExecutableNextflowWorkflow: """A two-process produce/copy pipeline used across render and runtime tests.""" produce = NfProcess( @@ -244,22 +230,3 @@ def run_observed( emit: (directory / f"{emit}.sink").read_text(encoding="utf-8").split("\x01") for emit in names if (directory / f"{emit}.sink").exists() } - - -def examples(group: str) -> list[Any]: - """Each example directory of tests/core/data/nextflow/, by its name.""" - return [pytest.param(path, id=path.name) for path in sorted((DATA / "nextflow" / group).iterdir()) if path.is_dir()] - - -def example_workflow(folder: Path, directory: Path) -> Workflow: - """A copy of the example `folder` at `directory`, and the workflow its `workflow.wic` is: read with the tools and - child workflows beside it and the tools Sophios ships, its inputs given the values of `job.yml`. A relative path in - it is read against the working directory, which the caller makes `directory`.""" - shutil.copytree(folder, directory) - tools = get_tools_cwl({"search_paths_cwl": {"global": [str(directory), str(ADAPTERS)]}}) - children = {"global": {path.stem: path for path in directory.glob("*.wic") if path.name != "workflow.wic"}} - workflow = Workflow.from_wic(directory / "workflow.wic", tool_registry=tools, workflow_paths=children) - job = directory / "job.yml" - for name, value in (yaml.safe_load(job.read_text(encoding="utf-8")) if job.exists() else {}).items(): - setattr(workflow.inputs, name, value) - return workflow diff --git a/tests/core/reference_model.py b/tests/core/reference_model.py index 5150880fd..ae62d9b95 100644 --- a/tests/core/reference_model.py +++ b/tests/core/reference_model.py @@ -1,9 +1,13 @@ -"""Independent test model for reference-type judgments: it lowers declarations to a small set of structural variants and -compares the Cartesian product, so generated inputs never ask the system under test which cases it should generate.""" +"""Independent test models: reference-type judgments, lowering declarations to a small set of structural variants and +comparing the Cartesian product, so generated inputs never ask the system under test which cases it should generate; +and inference's default choice of source for an unbound input.""" from enum import Enum from typing import Any, Final +from sophios.ir.declarations import input_rank, layered, output_rank +from sophios.ir.types import DerivedName, Port, PortDeclaration, PortId, PortName, StepNode + class ReferenceExpectation(Enum): """Expected relation between two generated endpoint declarations.""" @@ -75,3 +79,65 @@ def reference_expectation(source: Any, sink: Any) -> ReferenceExpectation: def may_reference(source: Any, sink: Any) -> bool: """Whether a generator may safely put this reference in a compilable document.""" return reference_expectation(source, sink) is not ReferenceExpectation.DISJOINT + + +def inference_choice(steps: tuple[StepNode, ...], position: int, sink: Port) -> PortId | None: + """Independent, deliberately small model of default candidate selection: the most recent earlier step with an + output whose type and format fit, the first such output declared, among those exposed through the same steps.""" + sink_type = layered(sink.type, input_rank(steps[position], sink.id.port)).canonical + sink_formats = _formats(sink.declaration) + for producer in reversed(steps[:position]): + matches = [output for output in producer.outputs + if _types_match(sink_type, _source_type(producer, output)) + and _formats_match(sink_formats, _formats(output.declaration), _source_type(producer, output))] + if matches: + through = _exposed_through(matches[-1].id.port) + return next(output.id for output in matches if _exposed_through(output.id.port) == through) + return None + + +def _exposed_through(name: PortName) -> list[object]: + """The steps a port name was exposed through, outermost first.""" + steps: list[object] = [] + while isinstance(name, DerivedName): + steps.append(name.step) + name = name.port + return steps + + +def _types_match(sink: Any, source: Any) -> bool: + if sink == source: + return True + sink_members = sink if isinstance(sink, list) else [sink] + source_members = source if isinstance(source, list) else [source] + return any(member in sink_members for member in source_members) + + +def _formats(declaration: PortDeclaration | None) -> tuple[Any, ...]: + if declaration is None or not declaration.has_format: + return () + return tuple(declaration.format) if isinstance(declaration.format, list) else (declaration.format,) + + +def _formats_match(sink: tuple[Any, ...], source: tuple[Any, ...], source_type: Any) -> bool: + if not sink: + return True + if source: + return any(item in sink for item in source) + return not _permits_format(source_type) + + +def _permits_format(value: Any) -> bool: + if value == 'File': + return True + if isinstance(value, list): + return any(_permits_format(item) for item in value) + if isinstance(value, dict) and value.get('type') == 'array': + return _permits_format(value.get('items')) + return False + + +def _source_type(step: StepNode, port: Port) -> Any: + """CWL v1.2: `nested_crossproduct` nests one array per scattered input; every other method yields one flat array. + Rank is `output_rank`.""" + return layered(port.type, output_rank(step)).canonical diff --git a/tests/core/test_canonical_path.py b/tests/core/test_canonical_path.py index 47cc77473..604a5cdc9 100644 --- a/tests/core/test_canonical_path.py +++ b/tests/core/test_canonical_path.py @@ -1,6 +1,5 @@ -"""Two front ends, one payload: the Python API and `write_wic`'s file compile to one result, every compiled workflow -makes a request the compute schema takes, and passthrough survives beside a scatter.""" -import json +"""Two front ends, one payload: the Python API and the file `write_wic` writes compile to one result, whatever the file +is called and whatever the steps were renamed to after binding.""" import tempfile from dataclasses import dataclass from pathlib import Path @@ -14,17 +13,13 @@ import sophios.compiler from sophios.api.python.workflow import Step, Workflow from sophios.cli import default_compilation_settings -from sophios import compute from sophios.ir.artifacts import CompilationResult from sophios.ir.frontdoor import bundle_from_disk from sophios.wic_types import StepId, Yaml -from . import ast_strategies as strat -from .ast_strategies import passthrough_keys, passthrough_values from .equivalence import Strength, equivalent -from .hermetic import ORACLE, PARTITION, compile_hermetic, compile_hermetic_cwl +from .hermetic import PARTITION from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS -from .wic_reading import read_wic def _tool_document(stem: str) -> Yaml: @@ -33,17 +28,20 @@ def _tool_document(stem: str) -> Yaml: @dataclass(frozen=True, slots=True) -class _BundleSpec: +class _BundleSpec: # pylint: disable=too-many-instance-attributes # one field per varied fact """A small workflow the Python API can build twice: two File sources feeding a `join` step; `rename`, `nest` and - `bound` vary its name, a nested call and a bound name. Narrower than ast_strategies.documents(): the API refuses - duplicate names and links to later siblings.""" + `bound` vary its name, a nested call and a bound name, `renamed` renames `join` after its output is bound, and + `stem` names the file written. Narrower than ast_strategies.documents(): the API refuses duplicate names and links + to later siblings.""" file_name: str text_name: str join_name: str rename: bool nest: bool - bound: bool = False + bound: bool + renamed: bool + stem: str def _build_workflow(spec: _BundleSpec) -> Workflow: @@ -74,6 +72,8 @@ def _build_workflow(spec: _BundleSpec) -> Workflow: if spec.bound: join.inputs.name = workflow.inputs.name workflow.inputs.name = spec.join_name + if spec.renamed: + join.process_name = 'after' return workflow @@ -86,33 +86,6 @@ def _compile_bundle(root: Path) -> CompilationResult: quiet=False) -@pytest.mark.fast -def test_the_written_wic_file_is_a_real_independent_document() -> None: - """Tautology guard for path agreement. - - "A test whose assertion is guaranteed true by something other than the - thing it names is not a test": without this, the path-agreement property - could hold for free — if `write_wic` did not really produce an - independent, reloadable document, comparing "compiled directly" against - "compiled from the file" would just be comparing a workflow with itself - under a different name. Proves the file exists, is text, and loads into - the document of the workflow that wrote it. - """ - workflow = _build_workflow(_BundleSpec('a', 'b', 'c', rename=True, nest=False)) - with tempfile.TemporaryDirectory() as workdir: - path = workflow.write_wic(Path(workdir) / 'oracle.wic') - assert path.exists(), 'write_wic did not write a file' - text = path.read_text(encoding='utf-8') - - assert isinstance(text, str) and 'steps:' in text, 'the written file is not .wic text' - loaded = read_wic(text) - assert [step['id'] for step in loaded['steps']] == ['mk_file', 'mk_text', 'joined'], ( - 'the file on disk does not even reflect the workflow that wrote it, so any ' - 'agreement downstream would prove nothing about the file-based path') - assert loaded['steps'][2]['run'] == 'join.cwl' - assert loaded['outputs']['result']['outputSource'] == 'joined/file' - - #: The three string-typed literals `_BundleSpec` carries, restricted to keep #: this property about path agreement rather than YAML's exotic corners. _safe_text: Final = st.text('abcxyz_', max_size=8) @@ -120,8 +93,8 @@ def test_the_written_wic_file_is_a_real_independent_document() -> None: @st.composite def _bundle_specs(draw: st.DrawFn) -> _BundleSpec: - return _BundleSpec(draw(_safe_text), draw(_safe_text), draw(_safe_text), draw(st.booleans()), - draw(st.booleans()), draw(st.booleans())) + return _BundleSpec(draw(_safe_text), draw(_safe_text), draw(_safe_text), draw(st.booleans()), draw(st.booleans()), + draw(st.booleans()), draw(st.booleans()), draw(st.sampled_from(['oracle', 'pipeline']))) @pytest.mark.slow @@ -140,6 +113,9 @@ def test_the_two_front_ends_compile_to_the_same_cwl(spec: _BundleSpec) -> None: Built twice from one drawn `spec` (see `_build_workflow`'s own docstring for why sharing one object would weaken the claim). + The output is bound to `join` and named by its step's name at compile time, a rename after binding included: + binding once captured the name, so a rename raised a bare `KeyError` from inside serialization. + BLIND SPOTS: one fixed topology (two File sources into one `join`, one workflow output) rather than the full grammar `ast_strategies.documents()` covers — see `_BundleSpec`'s docstring for why. No `scatter`/`when`, a @@ -150,11 +126,13 @@ def test_the_two_front_ends_compile_to_the_same_cwl(spec: _BundleSpec) -> None: via_file_workflow = _build_workflow(spec) with tempfile.TemporaryDirectory() as workdir: - root = via_file_workflow.write_wic(workdir) + root = via_file_workflow.write_wic(Path(workdir) / f'{spec.stem}.wic') written_text = root.read_text(encoding='utf-8') info = _compile_bundle(root) via_file = _workflow_runtime.compiled_workflow_from_result(via_file_workflow, info) + step = 'after' if spec.renamed else 'joined' if spec.rename else 'join' + assert direct.cwl_workflow['outputs']['result']['outputSource'] == f'{step}/file', 'the output lost its step' found = equivalent(direct.cwl_workflow, via_file.cwl_workflow, Strength.IDENTICAL) assert found is None, ( 'the Python API and the bundle it writes disagree about what this workflow compiles to.\n' @@ -168,105 +146,3 @@ def test_the_two_front_ends_compile_to_the_same_cwl(spec: _BundleSpec) -> None: assert inputs_found is None, ( f'the two front ends disagree about the generated job inputs.\n{inputs_found}\n\n' f'--- written .wic ---\n{written_text}') - - -@pytest.mark.fast -@given(strat.workflows()) -@ORACLE -def test_every_compiled_workflow_makes_a_request_the_compute_service_schema_takes(yml: Yaml) -> None: - """`request_for` builds and checks the request for everything this oracle compiles, against Sophios's copy of - the service's `run-request.schema.json`; it raises `RequestRefused` on a mismatch. Nothing is sent. - - BLIND SPOTS: no `workflowOutDir`, `leader`, `steps` or `logLevel`; whether the copy is the service's - own is `test_compute_service.py`'s. - """ - info = compile_hermetic(yml, 'oracle') - request = compute.request_for('oracle', info.artifact.cwl, info.artifact.job_inputs) - assert (request['workflow'], request['inputs']) == (info.artifact.cwl, info.artifact.job_inputs) - assert json.loads(json.dumps(request)) == request - - -@pytest.mark.slow -@given(st.data()) -@ORACLE -def test_passthrough_survives_a_scatter_in_a_multi_step_workflow(data: st.DataObject) -> None: - """Passthrough fidelity, re-quantified over the workflows - `test_leak_boundary.py`'s single-step generator cannot reach. - - `test_step_passthrough_is_byte_identical` and its siblings quantify over - `_touch_workflow`'s one, always-non-scattering step, so the requirement - merge in `ir/complete.py` never fires there and a step that scatters - *beside* its own passthrough freight is unreachable by that generator. - `ast_strategies.freighted_documents` forces exactly that shape; the - passthrough alphabets are imported from `test_leak_boundary` rather than - restated, so the next widening of either (`$`, uppercase, a real CWL key) - reaches this property too, instead of a second copy silently missing it. - - Includes its own tautology guard: `ScatterFeatureRequirement` must appear - in the compiled `requirements`, proving the requirement merge really - fired for this example rather than this property silently degrading into - `test_leak_boundary`'s already-covered case. - - BLIND SPOTS: `freighted_documents`'s own (no mapping-form `steps:`, no - subworkflow, no sidecar). Only one step is ever forced to scatter, and - only via `scatter` — `when` and a `.wic` subworkflow step are the - merge's other two triggers, neither exercised here. - """ - document, index = data.draw(strat.freighted_documents()) - freight = data.draw(st.dictionaries(passthrough_keys, passthrough_values, min_size=1, max_size=4)) - yml = strat.to_yml_with_freight(document, index, freight) - - compiled = compile_hermetic_cwl(yml, 'oracle') - - requirements = compiled.get('requirements') or {} - assert 'ScatterFeatureRequirement' in requirements, ( - 'the designated step did not actually scatter; this example is vacuous for the claim') - - step = compiled['steps'][index] - for key, value in freight.items(): - assert step[key] == value, f'{key} was altered by compilation' - - -def _written_output_source(workflow: Workflow, directory: Path) -> str: - """The `outputSource` of `result` in the document `write_wic` writes for `workflow`.""" - document = read_wic(workflow.write_wic(directory).read_text(encoding='utf-8')) - return str(document['outputs']['result']['outputSource']) - - -@pytest.mark.fast -def test_a_renamed_step_still_resolves_the_workflow_output_bound_to_it(tmp_path: Path) -> None: - """`process_name` is a mutable public attribute, so a bound output may not - cache it. - - Binding captured the source step's name at bind time and serialization - indexed the concrete-step mapping with that snapshot, so renaming a step - after binding raised a bare `KeyError` from inside serialization — on an - object graph that is still perfectly valid, since the output is bound to - the same child object it always was. Resolution goes through the source - parameter's live owner now. - """ - workflow = _build_workflow(_BundleSpec('a', 'b', 'c', rename=False, nest=False)) - before = _written_output_source(workflow, tmp_path / 'before') - - renamed = next(step for step in workflow.steps if step.process_name == 'join') - renamed.process_name = 'after' - after = _written_output_source(workflow, tmp_path / 'after') - - assert before == 'join/file' - assert after == 'after/file', 'the output did not follow the step it is bound to' - - -@pytest.mark.fast -@pytest.mark.parametrize('stem', ['oracle', 'pipeline']) -def test_a_written_document_compiles_under_any_file_name(stem: str) -> None: - """`write_wic` accepts any `*.wic` name, and nothing in the document depends - on it: outputs name their authored step, and the bundle compiles from disk - under the name it was saved as.""" - workflow = _build_workflow(_BundleSpec('a', 'b', 'c', rename=True, nest=False)) - with tempfile.TemporaryDirectory() as workdir: - root = workflow.write_wic(Path(workdir) / f'{stem}.wic') - document = read_wic(root.read_text(encoding='utf-8')) - compiled = _compile_bundle(root).artifact.cwl - - assert document['outputs']['result']['outputSource'] == 'joined/file' - assert compiled['outputs']['result']['outputSource'] == 'joined/file' diff --git a/tests/core/test_ci_coverage.py b/tests/core/test_ci_coverage.py index 02720f78f..ef77a6555 100644 --- a/tests/core/test_ci_coverage.py +++ b/tests/core/test_ci_coverage.py @@ -338,18 +338,10 @@ def _tests_importing(module: str, path: Path) -> set[str]: # runner (preflight.PLATFORM_LACKS_RUNNERS), so it never uses the command line built for them. 'tests/core/test_backends.py::test_each_cwl_runner_reads_its_command_line_as_the_request_says', 'tests/core/test_emit.py::test_emit_validates_as_cwl_v1_2', - 'tests/core/test_emit.py::test_validator_rejects_the_independent_invalid_control', - # A strict xfail on one cwltool validation of a `schemed` workflow, under a - # second. It states the SchemaDefRequirement gap the generators exclude, - # which only cwltool's validator can show, so it runs where the pair does. - 'tests/core/test_emit.py::test_a_schema_def_typed_input_validates', 'tests/core/test_leak_boundary.py::test_residue_validates_as_cwl_v1_2', - # One compile and one `--validate` of a four-line workflow, under a second. - # It buys the authored `outputSource` path, which the residue property - # above cannot reach: the workflow strategy never writes one, so only the - # synthesized path was ever validated, and the authored one emitted a - # reference to a step the document does not contain. - 'tests/core/test_leak_boundary.py::test_an_authored_output_source_validates', + # Six example workflows run by cwltool, in about three seconds together. What each compiles to is stated and + # checked on every leg by the compile leg beside it; only a runner shows the outputs. + 'tests/core/test_compiler.py::test_an_example_runs_under_cwltool_as_stated', # One `cwltool --validate` of a one-step workflow whose tool was unpacked from # a `$graph`, under a second. The ports and the file written are checked on # every leg by the test before it. @@ -387,7 +379,7 @@ def _tests_importing(module: str, path: Path) -> set[str]: 'tests/core/test_python_api_workflow.py::test_a_real_failed_step_is_named_with_its_status', # Two roots of a few echo steps, nested two deep, each run through the command line by cwltool # and by Toil with provenance, in about twenty seconds. Which files are written is checked on - # every leg by `test_names_emitted.py`; only a runner shows what its snapshot holds. + # every leg by tests/core/data/compiler/names; only a runner shows what its snapshot holds. 'tests/core/test_provenance.py::test_every_step_file_is_in_the_provenance_snapshot', # One echo step run through the command line by cwltool and by Toil with provenance, its # `.wic` or its tool declaring EDAM from another URL, in about five seconds each. That no @@ -414,10 +406,8 @@ def _tests_importing(module: str, path: Path) -> set[str]: # references the target refuses is checked on every leg by the staging family of test_capabilities.py. 'tests/core/nextflow/test_reference_differential.py::' 'test_a_path_inputs_references_mean_under_nextflow_what_they_mean_under_cwltool', - # Seven example workflows run under Nextflow, six of them under cwltool too, and nine that stop, in about - # forty-five seconds together. Lint And Test's Linux Nextflow step collects them, so the Windows leg gives up - # nothing it ran. - 'tests/core/nextflow/test_runtime.py::test_an_example_workflow_runs_under_nextflow_as_under_cwltool', + # Nine examples that stop, each run under Nextflow and under cwltool, in about twenty seconds together. Lint And + # Test's Linux Nextflow step collects them, so the Windows leg gives up nothing it ran. 'tests/core/nextflow/test_runtime.py::test_a_run_stops_before_a_step_whose_inputs_it_cannot_decide', 'tests/core/nextflow/test_runtime.py::test_a_run_stops_at_a_task_that_leaves_no_one_answer', # Four batches of up to twelve small workflows, each run under Nextflow and under cwltool, in about ten diff --git a/tests/core/test_compiler.py b/tests/core/test_compiler.py index 180a04a86..bf7a01756 100644 --- a/tests/core/test_compiler.py +++ b/tests/core/test_compiler.py @@ -1,19 +1,135 @@ -"""Regression coverage for `sophios.compiler` bugs that have no home elsewhere.""" +"""The compiler, judged on example workflows in files: each example of tests/core/data/examples compiles to the CWL its +expected.yaml states (every platform) and runs under cwltool to the outputs it states (POSIX); each example of +tests/core/data/compiler compiles, or is refused, as its expected.yaml states.""" +import contextlib import copy -from dataclasses import replace +import io +from pathlib import Path +from typing import Any, cast import pytest +import yaml -from sophios.compiler import cwl_notes, resolved_view +from sophios.cli import default_compilation_settings +from sophios.compiler import compile_source, cwl_notes, resolved_view +from sophios.input_output import write_artifacts_to_disk +from sophios.ir.frontdoor import bundle_from_disk from sophios.ir.resolved import NotLowered -from sophios.wic_types import StepId, Yaml - -from .cases import cases -from .hermetic import compile_hermetic_cwl, compile_production, subworkflow_step -from .nextflow.testkit import compiled_case, lowered_case, refusal_lines +from sophios.lang.diagnostics import SophiosError +from sophios.utils_cwl import desugar_into_canonical_normal_form +from sophios.utils_nf import NEXTFLOW +from sophios.wic_types import CompilerOptions, StepId, Tool, Tools, Yaml + +from .cases import DATA, diagnostic, match +from .helpers import cwltool_outputs, example_workflow, examples, files_beside, observed, stated +from .hermetic import compile_hermetic_cwl from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS -pytestmark = pytest.mark.package + +@pytest.mark.fast +@pytest.mark.parametrize('folder', examples()) +def test_an_example_compiles_to_the_cwl_it_states(folder: Path, tmp_path: Path, + monkeypatch: pytest.MonkeyPatch) -> None: + """Each example's `compiled` states its CWL's requirements and, step by step in order, what each step reads from + another step or a workflow input, how it scatters and when it runs: a compiler that reversed a list of sources + would reverse it for every runner, so only a stated document catches it.""" + workflow = example_workflow(folder, tmp_path / 'example') + monkeypatch.chdir(tmp_path / 'example') + with contextlib.redirect_stdout(io.StringIO()): + cwl = workflow.compile().cwl_workflow + expected = stated(folder)['compiled'] + steps = {step['id']: step for step in cwl['steps']} + assert list(steps) == list(expected['steps']) + assert match(expected, {**cwl, 'steps': steps, 'requirements': cwl.get('requirements', {})}) + + +@pytest.mark.needs_cwltool +@pytest.mark.serial +@pytest.mark.parametrize('folder', [example for example in examples() + if stated(example.values[0]).get('reference') != 'none']) +def test_an_example_runs_under_cwltool_as_stated(folder: Path, tmp_path: Path, + monkeypatch: pytest.MonkeyPatch) -> None: + """cwltool, the reference runner, gives each example exactly the outputs its expected.yaml states by class, + basename and contents, for the CWL the workflow compiles to, and leaves the files beside the workflow as they + were: the statement is CWL's answer, which the Nextflow leg (test_runtime.py) is held to as well.""" + import cwltool.main # pylint: disable=import-outside-toplevel + + directory = tmp_path / 'example' + workflow = example_workflow(folder, directory) + monkeypatch.chdir(directory) + before = files_beside(directory) + outputs = cwltool_outputs(cwltool.main.main, workflow, directory) + assert {name: observed(value) for name, value in outputs.items()} == stated(folder)['outputs'] + assert {name: found for name, found in files_beside(directory).items() if name in before} == before + + +def _tools(directory: Path) -> Tools: + """The synthetic tools, each tool beside the example under its stem, and each in a folder beside it under that + folder's name as its namespace, desugared as discovery desugars them.""" + return {**SYNTHETIC_TOOLS, **{ + StepId(path.stem, SYNTHETIC_NS if path.parent == directory else path.parent.name): Tool( + str(path), desugar_into_canonical_normal_form(yaml.safe_load(path.read_text(encoding='utf-8')))) + for path in [*directory.glob('*.cwl'), *directory.glob('*/*.cwl')]}} + + +def _written(directory: Path) -> dict[str, Any]: + """Every file written in `directory`, read as YAML.""" + return {path.name: yaml.safe_load(path.read_text(encoding='utf-8')) + for path in sorted(directory.iterdir(), key=lambda path: path.name)} + + +def _compiled_as_stated(folder: Path, root: str, expected: Yaml, out: Path, + capsys: pytest.CaptureFixture[str]) -> None: + """The root `.wic` of the example `folder`, compiled as the command line reads it, checked against `expected`; + what it writes goes into `out`.""" + others = {'global': {path.stem: path for path in folder.glob('*.wic') if path.name != root}} + bundled = bundle_from_disk(folder / root, others, _tools(folder)) + options = cast(CompilerOptions, {**default_compilation_settings(), **expected.get('options', {})}) + if 'refused' in expected: + with pytest.raises(SophiosError) as caught: + compile_source(bundled, options, quiet=True) + assert match(expected['refused'], [diagnostic(found) for found in caught.value.diagnostics]), root + return + result = compile_source(bundled, options, quiet=False) + notes = [*result.diagnostics, *cwl_notes(resolved_view(result))] + assert match(expected.get('notes', []), [diagnostic(found) for found in notes]), root + assert match(expected.get('said', []), capsys.readouterr().err.splitlines()), root + write_artifacts_to_disk(result.artifact, out) + if 'nextflow' in expected: + job = folder / 'job.yml' + values = yaml.safe_load(job.read_text(encoding='utf-8')) if job.exists() else {} + try: + NEXTFLOW.lower(resolved_view(result, values={name: value for name, value in values.items() + if name in result.artifact.cwl['inputs']})) + refusals = [] + except NotLowered as refused: + refusals = [{'step': found.step, 'says': found.message} for found in refused.refusals] + assert match(expected['nextflow'], refusals), root + + +@pytest.mark.fast +@pytest.mark.parametrize('folder', [pytest.param(path, id=path.name) + for path in sorted((DATA / 'compiler').iterdir()) if path.is_dir()]) +def test_a_compiler_example_compiles_as_it_states(folder: Path, tmp_path: Path, + capsys: pytest.CaptureFixture[str]) -> None: + """Each root `.wic` of a directory of tests/core/data/compiler, compiled as the command line reads it (the tools + and workflows beside it, and the synthetic tools) under the compile `options` it states, is `refused` with the + diagnostics stated, by code, severity, step and port; or compiles with exactly the `notes` stated and the lines + `said` on stderr, writes the files `written` states into one directory shared by every root, so a root that + overwrote another's file fails it, as the `files` named for the root and no others; and, where `nextflow` is + stated, is refused by the Nextflow target, given the values the directory's `job.yml` holds for its inputs, as it + states, by step and subject.""" + out = tmp_path / 'out' + out.mkdir() + roots: dict[str, Yaml] = stated(folder) + for root, expected in roots.items(): + _compiled_as_stated(folder, root, expected, out, capsys) + written = _written(out) + for root, expected in roots.items(): + stem = Path(root).stem + mine = [name for name in written if name.split('~')[0] in (f'{stem}.cwl', stem, f'{stem}_inputs.yml')] + assert 'files' not in expected or mine == expected['files'], root + assert match(expected.get('written', {}), written), root @pytest.mark.fast @@ -49,98 +165,3 @@ def test_a_referenced_input_merges_the_documentation_of_the_argument_it_binds( } compiled = compile_hermetic_cwl(document, 'docs', tools=tools) assert compiled['inputs']['wf_name'] == {'type': 'string', **expected}, claim - - -def _mk_file(name: str = 'x') -> Yaml: - """A step of the synthetic registry that binds its one input.""" - return {'id': 'mk_file', 'in': {'name': {'wic_inline_input': name}}} - - -@pytest.mark.fast -@pytest.mark.parametrize('steps', [[_mk_file()], [_mk_file('x'), _mk_file('y')]], ids=['one-step', 'repeated-id']) -def test_a_generated_step_name_in_output_source_is_an_unknown_step(steps: list[Yaml]) -> None: - """`__step____` is not a spelling the compiler emits: it names no step, so it is - written through as it is and the step's own output is lifted as if nothing had asked for it.""" - compiled = compile_hermetic_cwl({ - 'outputs': {'o': {'type': 'File', 'outputSource': 'oracle__step__1__mk_file/file'}}, - 'steps': steps}) - assert compiled['outputs']['o']['outputSource'] == 'oracle__step__1__mk_file/file' - assert {step['id'] for step in compiled['steps']} == { - name.removesuffix('~file') for name in compiled['outputs'] if name != 'o'} - - -@pytest.mark.fast -@pytest.mark.parametrize(('source', 'names', 'resolved', 'said'), [ - ('mk_file/file', 'xy', 'mk_file@1/file', - ["Warning! oracle.wic: output 'o' has outputSource 'mk_file/file', but 2 steps have the id 'mk_file' and it " - "means the first. Write '(1, mk_file)/file' to say so."]), - ('mk_file/file', 'x', 'mk_file/file', []), - ('(2, mk_file)/file', 'xy', 'mk_file@2/file', []), - ('(1, mk_file)/file', 'x', 'mk_file/file', [])], - ids=['shared-bare-id', 'authored', 'positional', 'positional-unique']) -def test_an_output_source_names_the_spelling_the_compiler_generated_and_only_that( - capsys: pytest.CaptureFixture[str], source: str, names: str, resolved: str, said: list[str]) -> None: - """A bare id shared by two steps still means the first, and the line gives `(index, id)`; it is for the generated - spelling only, so an authored one prints nothing; and the `(index, name)/port` spelling is what the line - recommends, so it is never reported; a position naming a step whose id is unique resolves to that plain id. - A quiet compile prints no line at all.""" - document: Yaml = {'outputs': {'o': {'type': 'File', 'outputSource': source}}, - 'steps': [_mk_file(name) for name in names]} - compiled = compile_production(document, 'oracle').artifact.cwl - assert compiled['outputs']['o']['outputSource'] == resolved - assert capsys.readouterr().err.splitlines() == said - compile_hermetic_cwl(document) - assert tuple(capsys.readouterr()) == ('', '') - - -@pytest.mark.fast -@pytest.mark.parametrize('expression, prints', [ - ('$(inputs.nope != null)', True), ('$(inputs["nope"] != null)', True), ('$(inputs.name != null)', False), - ('$(inputs.name-1 > 0)', False)], - ids=['dot', 'bracket', 'declared', 'minus']) -def test_a_when_that_reads_an_input_the_step_lacks_is_named_and_still_compiles( - expression: str, prints: bool) -> None: - """`inputs.nope` has no value in a `when`, so the run stopped there or the step never ran, and nothing said - so: the compile's diagnostics do, as a `wic056` note.""" - result = compile_production({'steps': [{**_mk_file(), 'when': expression}]}, 'oracle') - assert result.artifact.cwl['steps'][0]['when'] == expression - assert any('which its process does not declare' in note.message and str(note.code) == 'wic056' - for note in result.diagnostics) is prints - - -def _call_when(expression: str) -> Yaml: - """A call to `child.wic`, whose `mk_file` leaves `name` for the caller, made conditional on `expression`.""" - return {'steps': [{**subworkflow_step('child.wic', {'steps': [{'id': 'mk_file'}]}), - 'parentargs': {'when': expression}}]} - - -@pytest.mark.fast -@pytest.mark.parametrize(('expression', 'said'), [ - ('$(inputs["mk_file~name"] != null)', []), - ('$(inputs.mk_file~name != null)', - ["when reads inputs.mk_file, which its process does not declare; it has no value there, and cwltool stops " - "the run when it gives anything but true or false. Write inputs['mk_file~name'] to read one it declares."])], - ids=['bracket', 'dotted']) -def test_a_when_on_a_call_that_reads_a_made_name_dotted_is_told_the_bracket_form( - expression: str, said: list[str]) -> None: - """A call declares the names its child exposes, `mk_file~name` among them, and the bracket form reads it, so it - draws no note. `inputs.mk_file~name` is `inputs.mk_file`, then `~name`: the note names the input and how to - read it.""" - result = compile_production(_call_when(expression), 'oracle') - assert 'mk_file~name' in result.artifact.cwl['steps'][0]['in'] - assert [note.message for note in result.diagnostics] == said - - -@pytest.mark.fast -@pytest.mark.parametrize('case', cases('when_boolean.yaml', 'workflow', 'tools', 'job', 'notes', 'refused')) -def test_a_when_that_cannot_give_a_boolean_is_a_note_on_cwl_and_refused_on_nextflow(case: Yaml) -> None: - """Each case of data/when_boolean.yaml, compiled once: the CWL target notes what the shared check finds, at the - step, and refuses nothing; the Nextflow target refuses it.""" - result = compiled_case(case) - assert [str(replace(note, span=None)) for note in cwl_notes(resolved_view(result))] == case['notes'] - try: - lowered_case(case) - refused = [] - except NotLowered as error: - refused = refusal_lines(error) - assert refused == case['refused'] diff --git a/tests/core/test_diagnostics.py b/tests/core/test_diagnostics.py index 1f6cd3707..be2655cdd 100644 --- a/tests/core/test_diagnostics.py +++ b/tests/core/test_diagnostics.py @@ -1,5 +1,5 @@ """The library reports failures; only the CLI adapter exits: compilation never terminates the process, every failure -yields a diagnostic, exit codes are unchanged. The no-exit claim's dynamic half is test_pipeline.py's.""" +yields a diagnostic, exit codes are unchanged. The no-exit claim's dynamic half is test_emit.py's laws.""" import datetime import json import math diff --git a/tests/core/test_emit.py b/tests/core/test_emit.py index 824d6d747..ef3cc5c59 100644 --- a/tests/core/test_emit.py +++ b/tests/core/test_emit.py @@ -1,16 +1,21 @@ -"""Canonical CWL emission from the workflow graph: byte-sensitive determinism, narrower than the compiler's contract -(UP_TO_EMBEDDING). Generated workflows inherit ast_strategies.workflows's exclusions; validation runs no CWL.""" +"""Canonical CWL emission, judged on drawn workflows by the laws every compile keeps and on documents stated by hand. +Generated workflows inherit ast_strategies.workflows's exclusions; the hand-stated anchors are what a law cannot see: +the order of a record's sources, the fields it carries, a graph built without the compiler.""" +import builtins import copy +import json +import re from pathlib import Path import tempfile from typing import Any, Final +from unittest.mock import patch import pytest from cwl_utils.parser import cwl_v1_2 from hypothesis import assume, example, given, strategies as st from schema_salad.utils import yaml_no_ts # pylint: disable=no-name-in-module -import sophios.post_compile +from sophios import compute, post_compile from sophios.input_output import dump_wic_yaml from sophios.ir import ( BoundaryDeclaration, @@ -23,6 +28,7 @@ PortType, ProcessRun, RegistryKey, + RegistrySnapshot, StepId, StepNode, WorkflowGraph, @@ -31,39 +37,142 @@ emit_job_inputs, surface, ) +from sophios.ir.artifacts import CompilationArtifact +from sophios.ir.complete import coerce_job_value, complete +from sophios.ir.declarations import port_declaration +from sophios.ir.infer import infer +from sophios.ir.link import link from sophios.ir.names import Names -from sophios.ir.types import AuthoredName, StepOutputRef +from sophios.ir.pipeline import front_end +from sophios.ir.resolve import resolve +from sophios.ir.types import AuthoredName, EdgeOrigin, StepOutputRef from sophios.lang.cwl import CWL_VERSION from sophios.lang.diagnostics import SophiosError -from sophios.lang.error_codes import SophiosErrorCode -from sophios.wic_types import StepId as LegacyStepId, Tools, Yaml +from sophios.wic_types import StepId as LegacyStepId, Yaml from . import ast_strategies as strat -from .cases import match from .cwl_validation import validate_cwl -from .equivalence import Strength, equivalent -from .hermetic import ORACLE, compile_hermetic, compile_hermetic_cwl, network_refused, subworkflow_step -from .strategies import pinned -from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS, clt, registered +from .equivalence import Strength, equivalent, flatten_model +from .hermetic import (COVERAGE, ORACLE, bundle, compile_hermetic, compile_hermetic_cwl, network_refused, + subworkflow_step) +from .reference_model import inference_choice +from .strategies import cwl_types, pinned +from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS, clt, inputs_of, outputs_of, registered + + +def _render(graph: WorkflowGraph) -> Any: + """`graph` emitted as the compiler emits its root document.""" + names = Names.of(graph) + return emit(surface(graph, names), names) + + +def _graphs(graph: WorkflowGraph) -> tuple[WorkflowGraph, ...]: + return (graph,) + tuple(item for child in graph.children for item in _graphs(child)) + + +def _resolves_from_the_registry_alone(document: Any) -> None: + """Every non-generated process is the tool the registry holds under the name its step authored, run path and both + interfaces, recursively through child workflows: not the key the resolver returned, which a resolver answering + every lookup with one tool would report too.""" + for step in document.steps: + process = step.process + if process.child is not None: + _resolves_from_the_registry_alone(process.child) + elif not process.generated: + stem = step.source.id + assert process.key.name == stem + assert process.run_path == SYNTHETIC_TOOLS[LegacyStepId(stem, SYNTHETIC_NS)].run_path + assert tuple(port.name for port in process.inputs) == tuple(inputs_of(stem)) + assert tuple(port.name for port in process.outputs) == tuple(outputs_of(stem)) + + +def _documents(node: CompilationArtifact) -> list[Any]: + return [node.cwl, node.job_inputs, *(document for child in node.children for document in _documents(child))] + + +def _addresses(node: CompilationArtifact) -> list[str]: + """Each step that runs a tool, beneath `node` at any depth, by its address: the calls above it and its name.""" + calls = {child.namespace[-1]: child for child in node.children if child.graph is not None} + return [address for step in node.cwl['steps'] for name in [step['id']] + for address in ([f'{name}~{inner}' for inner in _addresses(calls[name])] if name in calls else [name])] + + +#: `child.wic` (mk_file, then xform twice) called from a root that counts its file. +_NESTED: Final[Yaml] = {'steps': [subworkflow_step('child.wic', {'steps': [{'id': 'mk_file'}, {'id': 'xform'}, + {'id': 'xform'}]}), {'id': 'count'}]} @pytest.mark.skip_pypi_ci -@given(strat.workflows()) +@given(strat.workflows().filter(lambda workflow: '___' not in json.dumps(workflow))) +@example({'steps': [{'id': 'join'}]}) # a resolver returning empty interfaces cannot satisfy this by accident +@example(_NESTED) @ORACLE -def test_one_graph_emits_identically(workflow: Yaml) -> None: - """A graph, not its mutable source dictionaries, determines every byte. - - Emit needs nothing beyond it: the source is emptied between the two - projections and neither byte moves. +def test_a_drawn_workflow_compiles_by_every_law(workflow: Yaml) -> None: # pylint: disable=too-many-locals + """The laws one compile keeps, each over the same drawn workflow: + + - resolution reads the registry and nothing else, the filesystem refused, and its order changes nothing; + - `complete` is idempotent: `_compile_front` calls it three times on that promise, and an arm reading its own + previous output, as the `run:` target once did, compounds silently; + - every edge inference adds is the independent model's choice (reference_model.inference_choice); + - the phases composed directly emit what the live compiler does, up to embedding; + - a graph, not its mutable source, determines every byte: the source is emptied between two emissions; + - every compiled workflow makes a request the compute service's schema takes (nothing is sent); + - no form of the compiled CWL, nested, embedded, flat or both, spells a name of its own: no `__step__`, `.wic`, + `___`, hash or `sophios` key; flattened, a step of a call is named by its address from the root; + - flattening dissolves every call to the DAG the independent model (equivalence.flatten_model) does, and keeps + the root's interface and job. """ + model = bundle(copy.deepcopy(workflow), 'oracle', SYNTHETIC_TOOLS) + assert model.parsed.document is not None + + def forbidden(*_args: Any, **_kwargs: Any) -> Any: + raise AssertionError('resolution attempted filesystem access') + with patch.object(builtins, 'open', forbidden), patch.object(Path, 'read_text', forbidden): + resolved = resolve(model.parsed.document, model.registry, name='oracle') + assert resolved.document is not None, list(resolved.diagnostics) + _resolves_from_the_registry_alone(resolved.document) + backwards = RegistrySnapshot(tuple(reversed(model.registry.tools)), tuple(reversed(model.registry.workflows))) + assert resolve(model.parsed.document, backwards, name='oracle').document == resolved.document + + front = front_end(model.parsed, model.registry, name='oracle') + assert front.graph is not None, list(front.diagnostics) + once = complete(front.graph) + assert _render(complete(once)) == _render(once) + linked = link(once) + assert linked.graph is not None, list(linked.diagnostics) + inferred = infer(complete(linked.graph)) + assert inferred.graph is not None, list(inferred.diagnostics) + for graph in _graphs(inferred.graph): + original = next(item for item in _graphs(linked.graph) if item.namespace == graph.namespace) + for edge in (edge for edge in graph.linked_edges if edge.origin is EdgeOrigin.INFERRED): + position = next(index for index, step in enumerate(original.steps) if step.id == edge.sink.step) + sink = next(port for port in original.steps[position].inputs if port.id.port == edge.sink.port) + assert inference_choice(original.steps, position, sink) == edge.source + source = copy.deepcopy(workflow) - graph = compile_hermetic(source).graph - names = Names.of(graph) - document = surface(graph, names) + compiled = compile_hermetic(source) + nested = compiled.artifact + assert equivalent(_render(complete(inferred.graph)), nested.cwl, Strength.UP_TO_EMBEDDING) is None + names = Names.of(compiled.graph) + document = surface(compiled.graph, names) first = emit(document, names) source.clear() - second = emit(document, names) - assert equivalent(first, second, Strength.IDENTICAL) is None + assert equivalent(first, emit(document, names), Strength.IDENTICAL) is None + + request = compute.request_for('oracle', nested.cwl, nested.job_inputs) + assert (request['workflow'], request['inputs']) == (nested.cwl, nested.job_inputs) + assert json.loads(json.dumps(request)) == request + + flat = post_compile.flatten_subworkflows(nested) + for form in (nested, flat, post_compile.inline_artifact_runs(nested), post_compile.inline_artifact_runs(flat)): + found = [hit for each in _documents(form) + for hit in re.findall(r'__step__|\.wic|___|_[0-9a-f]{8}\b|"sophios[^"]*":', json.dumps(each))] + assert not found, found + assert [step['id'] for step in flat.cwl['steps']] == _addresses(nested) + assert equivalent(flatten_model(nested), flatten_model(flat), Strength.UP_TO_RENAMING) is None + assert all(child.cwl['class'] != 'Workflow' for child in flat.children) + assert (list(flat.cwl['inputs']), list(flat.cwl['outputs']), flat.job_inputs) == \ + (list(nested.cwl['inputs']), list(nested.cwl['outputs']), nested.job_inputs) @pytest.mark.fast @@ -143,8 +252,7 @@ def _job_files(declared: Yaml, job: Yaml) -> list[str]: #: Stems whose emitted workflow cwltool rejects today, each with the reason, #: and kept out of the validation property below. Every other property still -#: draws them. `test_a_schema_def_typed_input_validates` is a strict xfail, so -#: the exclusion cannot outlive the gap. +#: draws them. Each is an xfail example of it, so the exclusion cannot outlive the gap. NOT_YET_VALID: Final[dict[str, str]] = { 'schemed': ('its input names a SchemaDefRequirement type, and two references to it break: the promoted ' 'workflow input carries the bare name without the requirement that defines it, and the ' @@ -157,7 +265,7 @@ def _cwltool_validates(workflow: Yaml) -> bool: `secondaryFiles` are created empty, a required unset input is made optional, and `$schemas` is dropped (cwltool would fetch it; test_leak_boundary pins that it survives).""" info = compile_hermetic(workflow) - inlined = sophios.post_compile.inline_artifact_runs(info.artifact).cwl + inlined = post_compile.inline_artifact_runs(info.artifact).cwl job = info.artifact.job_inputs for name, declared in inlined['inputs'].items(): if name not in job and 'default' not in declared: @@ -186,6 +294,8 @@ def _cwltool_validates(workflow: Yaml) -> bool: @example({'steps': [{'id': 'mk_file', 'in': {'name': {'wic_inline_input': '1E3'}}}]}) @example({'steps': [{'id': 'mk_file', 'in': {'name': {'wic_inline_input': '0o17'}}}]}) @example({'steps': [{'id': 'mk_file', 'in': {'name': {'wic_inline_input': '0o7'}}}]}) +@example({'steps': [{'id': 'schemed', 'in': {'coords': {'wic_inline_input': {'x': 1.0, 'y': 2.0}}}}]}).xfail( + raises=AssertionError, reason=NOT_YET_VALID['schemed']) @ORACLE def test_emit_validates_as_cwl_v1_2(workflow: Yaml) -> None: """CWL's external validator accepts each emitted workflow and its job inputs.""" @@ -210,107 +320,30 @@ def test_a_string_job_value_is_a_string_to_cwltool(texts: list[str]) -> None: assert yaml_no_ts().load(dump_wic_yaml(document)) == document, document -@pytest.mark.needs_cwltool -@pytest.mark.fast -@pytest.mark.xfail(strict=True, reason=NOT_YET_VALID['schemed']) -def test_a_schema_def_typed_input_validates() -> None: - """A workflow whose step input is typed by a SchemaDefRequirement name is valid CWL.""" - assert _cwltool_validates({'steps': [ - {'id': 'schemed', 'in': {'coords': {'wic_inline_input': {'x': 1.0, 'y': 2.0}}}}]}) - - -@pytest.mark.needs_cwltool -@pytest.mark.fast -def test_validator_rejects_the_independent_invalid_control(tmp_path: Path) -> None: - """A validator unable to reject would make the validity claim vacuous.""" - import cwltool.main # pylint: disable=import-outside-toplevel - - target = tmp_path / 'invalid.cwl' - target.write_text('class: Workflow\nsteps: []\n', encoding='utf-8') - with network_refused() as attempts: - assert cwltool.main.main(['--validate', '--quiet', '--skip-schemas', str(target)]) == 1 - assert not attempts - - -@pytest.mark.fast -@pytest.mark.parametrize('scatter, expected', [ - ({}, 'File'), - ({'in': {'name': {'wic_inline_input': ['a', 'b']}}, 'scatter': ['name']}, {'type': 'array', 'items': 'File'}), -], ids=['plain', 'scattered']) -def test_an_untyped_authored_output_takes_its_producers_type(scatter: Yaml, expected: object) -> None: - """An output with an `outputSource:` and no `type:` was emitted as `type: None`; under scatter it takes the - array type the scattered step's output has. A called workflow's output the author left untyped takes its - producer's type too, and so does the caller's output that names it, whether the call or the caller wrote it.""" - compiled = compile_hermetic({'outputs': {'o': {'outputSource': 'mk_file/file'}}, - 'steps': [{'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a'}}, **scatter}]}) - assert compiled.artifact.cwl['outputs']['o']['type'] == expected - kid = {'inputs': {'name': {'type': 'string'}}, - 'outputs': {'res': {'outputSource': 'mk_file/file'}}, - 'steps': [{'id': 'mk_file', 'in': {'name': 'name'}}]} - called = compile_hermetic({ - 'outputs': {'o': {'outputSource': 'kid.wic/res'}}, - 'steps': [{**subworkflow_step('kid.wic', kid), - 'parentargs': {'in': {'name': {'wic_inline_input': 'a'}}, **scatter}}], - }, 'out_f') - outputs = called.artifact.cwl['outputs'] - lifted = [declaration['type'] for name, declaration in outputs.items() if name.endswith('~res')] - assert [outputs['o']['type']] + lifted == [expected, expected] - - -@pytest.mark.fast -@pytest.mark.parametrize('output, said', [ - ({'label': 'no type here'}, ('has no `outputSource:` to take one from',)), - ({'outputSource': 'mk_file/fiel'}, - ('`outputSource: mk_file/fiel` names no output of a step', # codespell:ignore fiel - "Did you mean 'mk_file/file'?")), - ({'outputSource': 'kid/res'}, - ('`outputSource: kid/res` names no output of a step', "Did you mean 'kid.wic/res'?")), - ({'outputSource': 'nothing/at_all'}, - ('names no output of a step', 'Check the step and output names.')), - ({'outputSource': 'kid.wic/mk_file~file'}, - ('names no output of a step', "Did you mean 'mk_file/file'?")), - ({'outputSource': 'oracle__step__1__mk_file/file'}, - ('`outputSource: oracle__step__1__mk_file/file` names no output of a step',)), -], ids=['no-source', 'misspelled-output', 'workflow-without-its-extension', 'nothing-close', - 'name-the-compiler-derives', 'old-generated-spelling-names-nothing']) -def test_an_untyped_output_with_nothing_to_take_a_type_from_is_wic036( - output: Yaml, said: tuple[str, ...]) -> None: - """The message says which half of the author's `outputSource:` to fix, not only to add a `type:`.""" - kid = {'outputs': {'res': {'type': 'File', 'outputSource': 'mk_file/file'}}, - 'steps': [{'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'x'}}}]} - with pytest.raises(SophiosError) as caught: - compile_hermetic({'outputs': {'o': output}, - 'steps': [{'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a'}}}, - subworkflow_step('kid.wic', kid)]}) - (diagnostic,) = caught.value.diagnostics - assert diagnostic.code is SophiosErrorCode.UNTYPED_OUTPUT - assert all(part in diagnostic.message for part in ("'o'", *said)), diagnostic.message +_TYPES = cwl_types('null', 'string', 'int', 'float', 'boolean', 'File', 'Directory') +_OBJECTS = st.fixed_dictionaries( + {'class': st.sampled_from(['File', 'Directory']), 'location': st.text(max_size=2)}, + optional={'format': st.just('edam:format_2')}) +_VALUES = st.recursive( + # NaN is excluded: `nan != nan`, so no value holding it equals itself. + st.one_of(st.text(max_size=2), st.integers(), st.booleans(), st.floats(allow_nan=False), + st.sampled_from([float('inf'), float('-inf')]), _OBJECTS), + lambda inner: st.lists(inner, max_size=2), max_leaves=4) -@pytest.mark.fast -def test_list_form_outputs_and_requirements_compile_as_their_mapping_form() -> None: - """A scattered step beside list-form `outputs:` and `requirements:` emits what the mapping spelling does.""" - def compiled(requirements: Any, outputs: Any) -> Yaml: - return compile_hermetic_cwl({ - 'requirements': requirements, 'outputs': outputs, - 'steps': [{'id': 'mk_file', 'in': {'name': {'wic_inline_input': ['a', 'b']}}, 'scatter': ['name']}]}) - - listed = compiled([{'class': 'InlineJavascriptRequirement'}], - [{'id': 'o', 'type': 'File', 'outputSource': 'mk_file/file'}]) - mapped = compiled({'InlineJavascriptRequirement': {}}, - {'o': {'type': 'File', 'outputSource': 'mk_file/file'}}) - assert listed == mapped - assert listed['outputs']['o']['outputSource'] == 'mk_file/file' - assert set(listed['requirements']) == {'InlineJavascriptRequirement', 'ScatterFeatureRequirement'} - - -def _tools_with_probe(inputs: Yaml, outputs: Yaml, namespaces: Yaml | None = None, *, - tools: Tools | None = None, stem: str = 'probe') -> Tools: - """`tools` (the synthetic registry by default) plus a tool called `stem` declaring these ports and prefixes.""" - probe = clt(inputs, outputs) - if namespaces: - probe['$namespaces'] = namespaces - return registered({stem: probe}, SYNTHETIC_TOOLS if tools is None else tools) +@pytest.mark.skip_pypi_ci +@given(_TYPES, st.sampled_from([{}, {'format': 'edam:format_1'}]), _VALUES) +@COVERAGE +def test_a_job_value_is_its_own_normal_form(raw: Any, fmt: Yaml, value: Any) -> None: + """Coercing a coerced job value changes nothing, which is what lets a + child's job value be lifted a level and coerced against the outer port.""" + declaration = port_declaration({'type': raw, **fmt}) + name = AuthoredName('x') + try: + once = coerce_job_value(name, declaration, value) + except SophiosError: + return + assert coerce_job_value(name, declaration, once) == once #: How a tool may declare `secondaryFiles`: each entry static or an expression, in its pattern or its `required`, and @@ -348,42 +381,39 @@ def _promoted(port: Yaml, schema: Any) -> Yaml: def _boundary(inputs: Yaml, outputs: Yaml) -> Yaml: """The workflow `probe`, a tool with these ports and `plain`, compiles to; the tool's `InlineJavascriptRequirement`, which an expression needs, is not the workflow's.""" - compiled = compile_hermetic_cwl({'steps': [{'id': 'probe'}]}, tools=_tools_with_probe( + compiled = compile_hermetic_cwl({'steps': [{'id': 'probe'}]}, tools=registered({'probe': clt( {**inputs, 'plain': {**_PLAIN, 'inputBinding': {'position': 2}}}, - {**outputs, 'plain': {**_PLAIN, 'outputBinding': {'glob': 'p'}}})) + {**outputs, 'plain': {**_PLAIN, 'outputBinding': {'glob': 'p'}}})})) assert 'InlineJavascriptRequirement' not in (compiled.get('requirements') or {}) return compiled -@pytest.mark.fast -@given(st.fixed_dictionaries({'type': st.just('File'), 'inputBinding': st.just({'position': 1})}, optional={ +_INPUTS: Final = st.fixed_dictionaries({'type': st.just('File'), 'inputBinding': st.just({'position': 1})}, optional={ **_PORT_FIELDS, 'loadContents': st.booleans(), - 'loadListing': st.sampled_from(['no_listing', 'shallow_listing', 'deep_listing'])})) -@pinned({'type': 'File', 'secondaryFiles': ['.idx'], 'streamable': True, 'loadContents': True, - 'loadListing': 'shallow_listing', 'inputBinding': {'position': 1}}, - *({'type': 'File', 'secondaryFiles': declared, 'inputBinding': {'position': 1}} - for declared in _SECONDARY_CASES)) -@ORACLE -def test_a_promoted_input_keeps_the_fields_a_workflow_input_may_state(port: Yaml) -> None: - """A tool input promoted to the boundary keeps what `WorkflowInputParameter` allows, not its `inputBinding`, and - of its `secondaryFiles` the static entries, as a list.""" - promoted = _boundary({'f': port}, {})['inputs'] - assert promoted == {'probe~f': _promoted(port, cwl_v1_2.WorkflowInputParameter), 'probe~plain': _PLAIN} + 'loadListing': st.sampled_from(['no_listing', 'shallow_listing', 'deep_listing'])}) +_OUTPUTS: Final = st.fixed_dictionaries({'type': st.just('File'), 'outputBinding': st.just({'glob': 'o.bam'})}, + optional=_PORT_FIELDS) @pytest.mark.fast -@given(st.fixed_dictionaries({'type': st.just('File'), 'outputBinding': st.just({'glob': 'o.bam'})}, - optional=_PORT_FIELDS)) -@pinned({'type': 'File', 'secondaryFiles': ['.bai'], 'streamable': True, 'outputBinding': {'glob': 'o.bam'}}, - *({'type': 'File', 'secondaryFiles': declared, 'outputBinding': {'glob': 'o'}} +@given(st.tuples(_INPUTS, _OUTPUTS)) +@pinned(({'type': 'File', 'secondaryFiles': ['.idx'], 'streamable': True, 'loadContents': True, + 'loadListing': 'shallow_listing', 'inputBinding': {'position': 1}}, + {'type': 'File', 'secondaryFiles': ['.bai'], 'streamable': True, 'outputBinding': {'glob': 'o.bam'}}), + *(({'type': 'File', 'secondaryFiles': declared, 'inputBinding': {'position': 1}}, + {'type': 'File', 'secondaryFiles': declared, 'outputBinding': {'glob': 'o'}}) for declared in _SECONDARY_CASES)) @ORACLE -def test_a_promoted_output_keeps_the_fields_a_workflow_output_may_state(port: Yaml) -> None: - """A tool output promoted to the boundary keeps what `WorkflowOutputParameter` allows, not its `outputBinding`, and - of its `secondaryFiles` the static entries, as a list.""" - promoted = _boundary({}, {'o': port})['outputs'] - assert promoted == {'probe~o': {**_promoted(port, cwl_v1_2.WorkflowOutputParameter), 'outputSource': 'probe/o'}, - 'probe~plain': {**_PLAIN, 'outputSource': 'probe/plain'}} +def test_a_promoted_port_keeps_the_fields_a_workflow_port_may_state(ports: tuple[Yaml, Yaml]) -> None: + """A tool port promoted to the boundary keeps what `WorkflowInputParameter` or `WorkflowOutputParameter` allows, + not its binding, and of its `secondaryFiles` the static entries, as a list.""" + port_in, port_out = ports + compiled = _boundary({'f': port_in}, {'o': port_out}) + assert compiled['inputs'] == {'probe~f': _promoted(port_in, cwl_v1_2.WorkflowInputParameter), + 'probe~plain': _PLAIN} + assert compiled['outputs'] == { + 'probe~o': {**_promoted(port_out, cwl_v1_2.WorkflowOutputParameter), 'outputSource': 'probe/o'}, + 'probe~plain': {**_PLAIN, 'outputSource': 'probe/plain'}} _REQUIREMENTS = st.sampled_from(['ResourceRequirement', 'InlineJavascriptRequirement', 'ScatterFeatureRequirement', @@ -431,172 +461,6 @@ class the workflow needs, `ScatterFeatureRequirement` for a scatter and `InlineJ assert not hints or cwl['hints'] == cwl['steps'][0]['hints'] == hints -@pytest.mark.fast -@pytest.mark.xfail(strict=True, raises=AssertionError, reason='a class with no body the workflow does not need ' - 'stays null, which cwltool refuses') -def test_a_requirement_written_with_no_body_is_an_empty_one() -> None: - """The case `assume` rules out of the property above: nothing needs the class, so its null body is kept.""" - step = {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a'}}} - cwl = compile_hermetic({'requirements': {'ResourceRequirement': None}, 'steps': [step]}).artifact.cwl - assert cwl['requirements'] == {'ResourceRequirement': {}} - - -_MYNS: Final = 'http://tool.example/' - - -def _tools_binding_myns(**uris: str) -> Tools: - """One tool per stem, each taking a `File` whose `format:` is a `myns:` CURIE the tool binds to its URI.""" - tools = SYNTHETIC_TOOLS - for stem, uri in uris.items(): - tools = _tools_with_probe({'f': {'type': 'File', 'format': 'myns:format_1'}}, {}, {'myns': uri}, - tools=tools, stem=stem) - return tools - - -def _tools_prefix_alike() -> Tools: - """Two tools agreeing on `myns`, and disagreeing on `edam`, which Emit binds itself.""" - tools = _tools_binding_myns(probe=_MYNS, other=_MYNS) - for stem, uri in (('probe', 'http://edamontology.org/'), ('other', 'https://edamontology.org/')): - tools[LegacyStepId(stem, SYNTHETIC_NS)].cwl['$namespaces']['edam'] = uri - return tools - - -_OTHER_URI: Final = 'http://other.example/' -_MYNS_FORMAT: Final = {'format': 'myns:format_1'} - - -@pytest.mark.fast -@pytest.mark.parametrize('workflow, tools, expected', [ - ({'steps': [{'id': 'probe'}]}, _tools_binding_myns(probe=_MYNS), - {'inputs': {'probe~f': _MYNS_FORMAT}, '$namespaces': {'myns': _MYNS}}), - ({'steps': [{'id': 'probe'}, {'id': 'other'}, {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'x'}}}]}, - _tools_prefix_alike(), - {'outputs': {'mk_file~file': {'format': 'edam:format_2330'}}, - '$namespaces': {'myns': _MYNS, 'edam': 'https://edamontology.org/'}}), - ({'steps': [{'id': 'probe'}]}, - _tools_with_probe({}, {'o': {'type': 'File', **_MYNS_FORMAT, 'outputBinding': {'glob': 'o'}}}, {'myns': _MYNS}), - {'outputs': {'probe~o': _MYNS_FORMAT}, '$namespaces': {'myns': _MYNS}}), - ({'$namespaces': {'myns': _OTHER_URI}, 'inputs': {'x': {'type': 'File', **_MYNS_FORMAT}}, - 'steps': [{'id': 'probe', 'in': {'f': 'x'}}]}, - _tools_binding_myns(probe=_MYNS), {'inputs': {'x': _MYNS_FORMAT}, '$namespaces': {'myns': _OTHER_URI}}), -], ids=['input', 'prefix-alike-and-edam', 'output', 'authored']) -def test_a_tools_namespace_prefix_is_declared_by_the_document_that_promotes_its_port( - workflow: Yaml, tools: Tools, expected: Yaml) -> None: - """A promoted port keeps its `myns:` CURIE, so the document that promotes it declares `myns` (the author's own - binding wins over any tool's); tools agreeing on a prefix are no conflict, and `edam` is bound by Emit alone.""" - assert match(expected, compile_hermetic_cwl(workflow, tools=tools)) - - -@pytest.mark.fast -def test_a_prefix_declared_beneath_a_subworkflow_is_declared_by_the_root_that_promotes_it() -> None: - """A port promoted through a subworkflow reaches the root with its CURIE, so the root declares the prefix.""" - compiled = compile_hermetic_cwl({'steps': [subworkflow_step('child.wic', {'steps': [{'id': 'probe'}]})]}, - tools=_tools_binding_myns(probe=_MYNS)) - [promoted] = compiled['inputs'].values() - assert promoted['format'] == 'myns:format_1' - assert compiled['$namespaces'].get('myns') == _MYNS - - -@pytest.mark.fast -def test_a_workflow_an_explicit_edge_crosses_declares_the_prefix_of_the_step_beneath_its_subworkflow() -> None: - """An edge from the root into a grandchild promotes its port through the child, which keeps the CURIE. - - The step the port derives from sits two workflows down, so the child owns - the port by the call that reaches it, and declares the prefix that call's - workflow declares. - """ - grandchild = {'steps': [{'id': 'probe', 'in': {'f': {'wic_alias': 'shared'}}}]} - info = compile_hermetic({'steps': [ - {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a'}}, 'out': [{'file': {'wic_anchor': 'shared'}}]}, - subworkflow_step('child.wic', {'steps': [subworkflow_step('grand.wic', grandchild)]})]}, - tools=_tools_binding_myns(probe=_MYNS)) - child = next(artifact for artifact in info.artifact.children if artifact.namespace == ('child',)) - assert child.cwl['inputs']['probe~f']['format'] == 'myns:format_1' - assert child.cwl['$namespaces']['myns'] == _MYNS - - -@pytest.mark.fast -@pytest.mark.parametrize('workflow, tools, first, second', [ - ({'$namespaces': {'myns': _OTHER_URI}, 'steps': [{'id': 'probe'}]}, - _tools_binding_myns(probe=_MYNS), (_OTHER_URI, 'this document'), (_MYNS, "step 'probe'")), - ({'steps': [{'id': 'probe'}, {'id': 'other'}]}, - _tools_binding_myns(probe=_MYNS, other=_OTHER_URI), (_MYNS, "step 'probe'"), (_OTHER_URI, "step 'other'")), - ({'steps': [subworkflow_step('child.wic', {'steps': [{'id': 'probe'}]}), {'id': 'other'}]}, - _tools_binding_myns(probe=_MYNS, other=_OTHER_URI), (_MYNS, "step 'child.wic'"), (_OTHER_URI, "step 'other'")), - ({'steps': [subworkflow_step('child.wic', {'steps': [{'id': 'probe'}, {'id': 'other'}]})]}, - _tools_binding_myns(probe=_MYNS, other=_OTHER_URI), (_MYNS, "step 'probe'"), (_OTHER_URI, "step 'other'")), -], ids=['document-and-tool', 'tool-and-tool', 'subworkflow-and-tool', 'two-tools-in-a-subworkflow']) -def test_a_prefix_two_promoting_sources_bind_differently_is_reported( - workflow: Yaml, tools: Tools, first: tuple[str, str], second: tuple[str, str]) -> None: - """The promoted CURIE would resolve to whichever binding the document kept, so neither is kept. - - The sources are the document and the steps owning a promoted port that says - `myns:`. The one diagnostic is `wic031`, and names the prefix and what each - source binds it to. - """ - with pytest.raises(SophiosError) as caught: - compile_hermetic_cwl(workflow, tools=tools) - [diagnostic] = caught.value.diagnostics - assert diagnostic.code is SophiosErrorCode.DUPLICATE_DOCUMENT_NAME - assert "'myns'" in diagnostic.message - for uri, source in (first, second): - assert repr(uri) in diagnostic.message and source in diagnostic.message - - -def _tools_clashing_on_schema_org(*, probe_port: Yaml, namespaces: Yaml) -> Tools: - """`probe` takes `probe_port` and binds `namespaces`; `other` also binds `s` to a different URI.""" - tools = _tools_with_probe({'f': probe_port}, {}, namespaces) - return _tools_with_probe({'g': {'type': 'File'}}, {}, {'s': 'https://schema.org/'}, tools=tools, stem='other') - - -@pytest.mark.fast -@pytest.mark.parametrize('probe_port, namespaces, declared', [ - ({'type': 'File'}, {'s': 'http://schema.org/'}, {}), - ({'type': 'File', 'format': 'myns:format_1'}, {'s': 'http://schema.org/', 'myns': _MYNS}, {'myns': _MYNS}), -], ids=['no-prefix-used', 'another-prefix-used']) -def test_a_clash_on_a_prefix_no_promoted_format_uses_is_no_error( - probe_port: Yaml, namespaces: Yaml, declared: Yaml, capsys: pytest.CaptureFixture[str]) -> None: - """Two tools binding `s` differently conflict with nothing when no promoted port says `s:`. - - The document is the one its tools' agreement would give, and it declares - only what a promoted format needs. Nothing is printed. - """ - workflow = {'steps': [{'id': 'probe'}, {'id': 'other'}]} - compiled = compile_hermetic_cwl(workflow, tools=_tools_clashing_on_schema_org( - probe_port=probe_port, namespaces=namespaces)) - control = compile_hermetic_cwl(workflow, tools=_tools_with_probe( - {'f': probe_port}, {}, {'myns': _MYNS}, tools=_tools_with_probe({'g': {'type': 'File'}}, {}, stem='other'))) - assert compiled == control - assert compiled.get('$namespaces', {}) == declared - assert capsys.readouterr() == ('', '') - - -_ELSE_URI: Final = 'http://else.example/' - - -@pytest.mark.fast -@pytest.mark.parametrize('other_port, declared', [ - ({'type': 'File'}, {}), - ({'type': 'File', 'format': 'elsens:format_2'}, {'elsens': _ELSE_URI}), -], ids=['no-format', 'a-format-with-another-prefix']) -def test_a_step_promoting_no_format_with_a_prefix_is_no_source_for_it_wherever_it_sits( - other_port: Yaml, declared: Yaml) -> None: - """Only the document and the steps owning a promoted `myns:` port are sources for `myns`. - - `other` binds `myns` elsewhere, but no CURIE it promotes says `myns:`, so - its binding conflicts with nothing: beside `probe` or beneath a - subworkflow, the root declares the same prefixes. - """ - tools = _tools_with_probe({'g': other_port}, {}, {'myns': _OTHER_URI, 'elsens': _ELSE_URI}, - tools=_tools_binding_myns(probe=_MYNS), stem='other') - beside = compile_hermetic_cwl({'steps': [{'id': 'probe'}, {'id': 'other'}]}, tools=tools) - beneath = compile_hermetic_cwl( - {'steps': [{'id': 'probe'}, subworkflow_step('c.wic', {'steps': [{'id': 'other'}]})]}, tools=tools) - expected = {'myns': _MYNS, **declared} - assert beside['$namespaces'] == expected - assert beneath['$namespaces'] == expected - - @pytest.mark.fast def test_a_cwl_record_emits_the_fields_it_carries() -> None: """Two sources merged into `sink.extras` (File[]), a default on `n`, and the @@ -618,89 +482,3 @@ def test_a_cwl_record_emits_the_fields_it_carries() -> None: assert sink['in']['n'] == {'default': 3, 'valueFrom': '$(self + 1)'} assert {'MultipleInputFeatureRequirement', 'StepInputExpressionRequirement', 'InlineJavascriptRequirement'} <= set(compiled['requirements']) - - -@pytest.mark.fast -def test_a_record_with_one_source_and_link_merge_keeps_its_source_a_list() -> None: - """CWL merges a list beside `linkMerge`; flattening `[x]` to `x` would change the value.""" - compiled = compile_hermetic_cwl({'inputs': {'f': 'File'}, 'steps': [ - {'id': 'sink', 'in': {'file': 'f', 'n': {'wic_inline_input': 1}, - 'extras': {'wic_raw_cwl': {'source': ['f'], 'linkMerge': 'merge_nested'}}}}]}) - assert compiled['steps'][0]['in']['extras'] == {'source': ['f'], 'linkMerge': 'merge_nested'} - assert 'MultipleInputFeatureRequirement' in compiled['requirements'] - assert 'StepInputExpressionRequirement' not in compiled['requirements'] - - -@pytest.mark.fast -def test_a_record_may_bind_an_input_the_process_does_not_declare_for_when( - capsys: pytest.CaptureFixture[str]) -> None: - """`go` is bound only so `when:` can read it; the step declares it, so no stderr line names it. Bound plainly, - the same undeclared input is wic028.""" - workflow: Yaml = {'inputs': {'go': 'boolean'}, 'steps': [ - {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a'}, 'go': {'wic_raw_cwl': {'source': 'go'}}}, - 'when': '$(inputs.go)'}]} - compiled = compile_hermetic_cwl(workflow) - assert compiled['steps'][0]['in']['go'] == {'source': 'go'} - assert compiled['steps'][0]['when'] == '$(inputs.go)' - assert 'Warning!' not in capsys.readouterr().err - workflow['steps'][0]['in']['go'] = 'go' - with pytest.raises(SophiosError) as caught: - compile_hermetic(workflow) - assert SophiosErrorCode.UNDECLARED_PORT in {d.code for d in caught.value.diagnostics} - - -@pytest.mark.fast -def test_a_record_source_from_an_includer_is_discharged_like_a_bare_reference() -> None: - """The child's record names the boundary input Link relays the parent's edge through.""" - child = {'steps': [{'id': 'sink', 'in': {'file': {'wic_raw_cwl': {'source': {'wic_alias': 'f'}}}, - 'n': {'wic_inline_input': 1}}}]} - compiled = compile_hermetic({'steps': [ - {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a'}}, 'out': [{'file': {'wic_anchor': 'f'}}]}, - subworkflow_step('child.wic', child)]}) - (edge,) = compiled.graph.linked_edges - assert edge.sink.step.name == 'sink' - workflow = next(child.cwl for child in compiled.artifact.children if child.cwl['class'] == 'Workflow') - (inner,) = workflow['steps'] - assert inner['in']['file'] == {'source': 'sink~file'} - - -@pytest.mark.fast -@pytest.mark.parametrize('body', [{'source': 'w', 'nope': 1}, {'source': {'wic_inline_input': 3}}, {'source': 3}]) -def test_a_desugared_record_under_wic_steps_is_checked_like_the_tagged_one(body: dict[str, Any]) -> None: - """`{wic_raw_cwl: {...}}` contributed through `wic: steps:` is the record - `!cwl {...}` spells, so a field it may not carry is refused, not dropped.""" - with pytest.raises(SophiosError) as caught: - compile_hermetic({'inputs': {'w': 'File'}, 'steps': [{'id': 'count'}], - 'wic': {'steps': {'(1, count)': {'in': {'file': {'wic_raw_cwl': body}}}}}}) - assert [d.code for d in caught.value.diagnostics] == [SophiosErrorCode.STEP_INPUT_RECORD] - - -@pytest.mark.fast -def test_a_desugared_record_under_wic_steps_binds_like_the_tagged_one() -> None: - """The same record under `wic: steps:` reaches the emitted step as it is written.""" - record = {'source': 'w', 'loadContents': True} - compiled = compile_hermetic_cwl({'inputs': {'w': 'File'}, 'steps': [{'id': 'count'}], - 'wic': {'steps': {'(1, count)': {'in': {'file': {'wic_raw_cwl': record}}}}}}) - assert compiled['steps'][0]['in']['file'] == record - - -@pytest.mark.fast -def test_emitted_inputs_list_authored_names_first_then_derived_in_step_order() -> None: - """Authored inputs keep the order written and come before the inputs - exposing a step's port, which follow the steps. `mk_file.name` is lifted by - inference, after `mk_text`'s literal already exposed its own input.""" - compiled = compile_hermetic_cwl({ - 'inputs': {'zeta': 'string', 'alpha': 'string'}, - 'steps': [{'id': 'mk_file'}, - {'id': 'mk_text', 'in': {'name': {'wic_inline_input': 'a'}}}]}) - assert list(compiled['inputs']) == ['zeta', 'alpha', - 'mk_file~name', 'mk_text~name'] - - -@pytest.mark.fast -def test_a_workflows_schemas_are_what_its_author_wrote() -> None: - """A document depends on the ontologies its author named, and on none of Sophios's choosing.""" - mine = 'https://example.org/ontologies/mine.owl' - authored = compile_hermetic({'$schemas': [mine], 'steps': [{'id': 'mk_file'}]}).artifact.cwl - assert authored['$schemas'] == [mine] - assert '$schemas' not in compile_hermetic({'steps': [{'id': 'mk_file'}]}).artifact.cwl diff --git a/tests/core/test_equivalence.py b/tests/core/test_equivalence.py deleted file mode 100644 index 9423feba3..000000000 --- a/tests/core/test_equivalence.py +++ /dev/null @@ -1,174 +0,0 @@ -"""The equivalence relation, and proof it tells things apart: a relation returning None always passes every agreement -law, so cases built to catch a too-permissive relation come first.""" -import copy -from typing import Any, Final, cast - -import pytest -from hypothesis import given -from hypothesis import strategies as st - -from sophios.wic_types import Yaml - -from .cases import cases -from .equivalence import Strength, equivalent -from .hermetic import ORACLE -from .synthetic_tools import STEMS, inputs_of, outputs_of - - -@pytest.mark.fast -@pytest.mark.parametrize('case', cases('equivalence', 'left', 'right', 'verdicts')) -def test_equivalence_case(case: dict[str, Any]) -> None: - """`equivalent(left, right, strength)` for each strength `verdicts` names (`all` names every one) is None for - null, a divergence for `differs`, a `TypeError` for `TypeError`, or a divergence at `path` that reports `left` - and `right`. A `right` left out is `left`; the case's `why` names the defect it was built to see. - """ - left, right = case['left'], case.get('right', case['left']) - for name, verdict in case['verdicts'].items(): - for strength in Strength if name == 'all' else [Strength[name]]: - if verdict == 'TypeError': - with pytest.raises(TypeError): - equivalent(left, right, strength) - continue - found = equivalent(left, right, strength) - assert (found is None) is (verdict is None), f'{strength.name}: {found}' - if isinstance(verdict, dict): - assert found is not None and found.path == verdict['path'], found - for side in set(verdict) & {'left', 'right'}: - assert getattr(found, side) == verdict[side] and repr(verdict[side]) in str(found), found - - -@st.composite -def compiled_documents(draw: st.DrawFn) -> Yaml: - """A document shaped like emitted CWL (namespaced ids, ports, requirements), built without the compiler so that a - relation bug and a compiler bug stay distinguishable; the shape is copied from a hermetic compilation.""" - prefix = draw(st.sampled_from(('oracle', 'wf', 'root'))) - tools = draw(st.lists(st.sampled_from(STEMS), min_size=1, max_size=4)) - steps: list[Yaml] = [] - inputs: Yaml = {} - outputs: Yaml = {} - produced: list[str] = [] - for index, tool in enumerate(tools, start=1): - step_id = f'{prefix}__step__{index}__{tool}' - bindings: Yaml = {} - for name in sorted(inputs_of(tool)): - # `bool(...)` around the left operand: mypy otherwise uses it as - # the expected-argument context for the generic `DrawFn.__call__` - # on the right. Same reason as `ast_strategies._step`. - if bool(produced) and draw(st.booleans()): - bindings[name] = {'source': draw(st.sampled_from(produced))} - else: - port = f'{step_id}___{name}' - inputs[port] = {'type': 'string'} - bindings[name] = {'source': port} - steps.append({'id': step_id, 'in': bindings, 'run': f'{step_id}/{tool}.cwl', - 'out': sorted(outputs_of(tool))}) - for out_name in sorted(outputs_of(tool)): - outputs[f'{step_id}___{out_name}'] = {'type': 'File', - 'outputSource': f'{step_id}/{out_name}'} - produced.append(f'{step_id}/{out_name}') - requirements: Yaml = {name: {} for name in draw(st.lists( - st.sampled_from(('ScatterFeatureRequirement', 'SubworkflowFeatureRequirement', - 'InlineJavascriptRequirement')), unique=True, max_size=3))} - return {'class': 'Workflow', 'steps': steps, 'inputs': inputs, - 'outputs': outputs, 'requirements': requirements} - - -def _rewrite_run_paths(document: Yaml) -> Yaml: - """The rewrite UP_TO_EMBEDDING forgives: move every document somewhere else; nothing but the `run:` path changes.""" - moved = copy.deepcopy(document) - for step in moved['steps']: - step['run'] = 'flat/' + str(step['run']).rsplit('/', maxsplit=1)[-1] - return moved - - -def _rewrite_namespace(document: Yaml, prefix: str = 'renamed') -> Yaml: - """The rewrite UP_TO_RENAMING forgives: re-root the namespace by string substitution over the whole document, so it - hits step ids, sources, port keys and outputSource alike and leaves no dangling reference.""" - old = str(document['steps'][0]['id']).split('__step__', maxsplit=1)[0] - return cast(Yaml, _substitute(document, f'{old}__step__', f'{prefix}__step__')) - - -def _substitute(node: Any, old: str, new: str) -> Any: - """Replace `old` with `new` in every string, in keys and in values.""" - if isinstance(node, dict): - return {_substitute(k, old, new): _substitute(v, old, new) for k, v in node.items()} - if isinstance(node, list): - return [_substitute(v, old, new) for v in node] - return node.replace(old, new) if isinstance(node, str) else node - - -def _rewrite_drop_a_step(document: Yaml) -> Yaml: - """Not a rewrite the relation forgives — the control for the three above.""" - dropped = copy.deepcopy(document) - dropped['steps'] = dropped['steps'][:-1] - return dropped - - -#: The rewrite at each lattice level, paired with the strongest strength that -#: must accept it. `None` is the control: a rewrite no strength may accept. -#: Keyed by level rather than written inline so `test_each_rewrite_lands_at_ -#: exactly_the_strength_it_claims` can check both directions at once — that the -#: named strength accepts, and that the next one up rejects. -REWRITES: Final[tuple[tuple[str, Any, Strength | None], ...]] = ( - ('identity', copy.deepcopy, Strength.IDENTICAL), - ('run paths moved', _rewrite_run_paths, Strength.UP_TO_EMBEDDING), - ('namespace re-rooted', _rewrite_namespace, Strength.UP_TO_RENAMING), - ('a step dropped', _rewrite_drop_a_step, None), -) - - -@st.composite -def document_rewrites(draw: st.DrawFn) -> tuple[str, Yaml, Yaml, Strength | None]: - """A compiled-shaped document and a rewrite of it, with the level it claims.""" - document = draw(compiled_documents()) - # Every rewrite applies to every document, the control included. Withholding - # the control from one-step documents looks right -- dropping their only step - # seems to degenerate into `[] vs []` -- and is not: the workflow-level - # `inputs` and `outputs` the step produced are retained, and the graph goes - # from one node to none, so the pair is rejected for real reasons at all - # three strengths. - name, rewrite, level = draw(st.sampled_from(REWRITES)) - return name, document, rewrite(document), level - - -@pytest.mark.fast -@given(document_rewrites()) -@ORACLE -def test_each_rewrite_lands_at_exactly_the_strength_it_claims( - case: tuple[str, Yaml, Yaml, Strength | None]) -> None: - """Each strength accepts its own rewrite and the one above it does not. - - It pins the exact set each strength accepts, so each strength is *strictly* - weaker than the one above it. Checked in both directions on purpose — - "accepts" alone is satisfied by a relation that accepts everything, and - "rejects" alone by one that rejects everything. - """ - name, left, right, level = case - for strength in Strength: - found = equivalent(left, right, strength) - if level is not None and strength <= level: - assert found is None, f'{strength.name} rejected "{name}", which it must accept:\n{found}' - else: - assert found is not None, f'{strength.name} accepted "{name}", which it must reject' - - -@pytest.mark.fast -def test_every_rewrite_is_actually_drawn() -> None: - """The companion for the property above. - - It quantifies over `document_rewrites()` and is *weaker* in - proportion to how many rewrites the strategy stops producing — a - `sampled_from` that only ever yielded `identity` would leave them asserting - reflexivity and nothing else, silently. Same argument as construct coverage for the - document generator, at the same bounded sample. - """ - seen: set[str] = set() - - @ORACLE - @given(document_rewrites()) - def _collect(case: tuple[str, Yaml, Yaml, Strength | None]) -> None: - seen.add(case[0]) - - _collect() # pylint: disable=no-value-for-parameter # @given supplies `case` - missing = {name for name, _, _ in REWRITES} - seen - assert not missing, f'rewrites never drawn, so nothing above tested them: {sorted(missing)}' diff --git a/tests/core/test_equivalences.py b/tests/core/test_equivalences.py deleted file mode 100644 index cac234567..000000000 --- a/tests/core/test_equivalences.py +++ /dev/null @@ -1,275 +0,0 @@ -"""Every rewrite `transformations` names preserves the meaning it claims: one property over `Transformation`, with -partition independence and its nested case as instances, not tests with their own idea of "the same workflow".""" -import copy -from collections import Counter -from typing import Final - -import pytest -import yaml -from hypothesis import given, reject -from hypothesis import strategies as st - -from sophios import post_compile -from sophios.ir.artifacts import CompilationArtifact -from sophios.wic_types import Yaml - -from . import ast_strategies as strat -from .equivalence import Strength, equivalent, flatten_model -from .hermetic import PARTITION, compile_hermetic, subworkflow_step -from .transformations import TRANSFORMATIONS, Transformation, split, split_transformations - -#: The name both sides compile under. Identical on purpose: `identity` and -#: `text_roundtrip` claim IDENTICAL, and `equivalent(..., Strength.IDENTICAL)` -#: compares `steps[].id` literally (see `equivalence.py`'s own docstring — -#: IDENTICAL forgives nothing) — so compiling "before" and "after" under -#: different names would make every namespaced id disagree regardless of the -#: rewrite, and IDENTICAL would never hold for anything. UP_TO_RENAMING -#: ignores names either way, so the same choice costs those rewrites nothing. -_COMPILE_NAME: Final = 'oracle' - - -def _compile_flat(yml: Yaml) -> Yaml: - """Compile hermetically under the shared name and flatten the result.""" - info = compile_hermetic(yml, _COMPILE_NAME) - return flatten_model(info.artifact) - - -@pytest.mark.slow -@pytest.mark.parametrize('constant', [*TRANSFORMATIONS, None], - ids=[rewrite.name for rewrite in TRANSFORMATIONS] + ['split']) -@given(st.data()) -@PARTITION -def test_a_meaning_preserving_rewrite_preserves_meaning(constant: Transformation | None, - data: st.DataObject) -> None: - """Partition independence, its nested case, and every equivalence law, as one statement. - - Parameterised by transformation, so a failure names which rewrite broke - rather than which file it was written in — and so adding a rewrite is one - entry in a table instead of a new test module with a new idea of equality. - - Parametrised, not drawn. Drawing the rewrite alongside the document made - the property's strength per rewrite a matter of Hypothesis's weighting: - `identity` took about half the fifty examples and the thinnest real rewrite - could reach zero (see `split_transformations`). Each kind now gets the - whole budget, and `split`'s partitioning is what is drawn inside it. - - CANNOT GENERATE (declared): rewrites that change step order, which this - language's inference is not invariant under (see `transformations.py`'s - module docstring); `!cwl` and `python_script` steps, which `workflows()` - itself cannot generate (`ast_strategies.py`); partitionings that are not - contiguous, which the language cannot express (`ast_strategies.partitionings`). - """ - yml = data.draw(strat.workflows().filter(lambda w: len(w['steps']) >= 2)) - rewrite = constant if constant is not None else data.draw(split_transformations()) - transformed = rewrite.apply(copy.deepcopy(yml)) - - before = _compile_flat(yml) - after = _compile_flat(transformed) - - found = equivalent(before, after, rewrite.preserves) - assert found is None, ( - f'{rewrite.name} changed the meaning of the workflow.\n' - f'It claims to preserve {rewrite.preserves.name} because: {rewrite.rationale}\n\n' - f'{found}\n\n' - f'--- before ---\n{yaml.safe_dump(yml, sort_keys=False)}\n' - f'--- after ---\n{yaml.safe_dump(transformed, sort_keys=False)}') - - -def _closed(artifact: CompilationArtifact) -> bool: - """Whether every source in every workflow of the tree is a declared input or a step's output: CWL rejects a nested - document reading an undeclared root name.""" - cwl = artifact.cwl - if cwl['class'] == 'Workflow': - known = set(cwl.get('inputs', {})) | {step['id'] for step in cwl['steps']} - for step in cwl['steps']: - for value in step.get('in', {}).values(): - source = value.get('source') if isinstance(value, dict) else value - if isinstance(source, str) and source.partition('/')[0] not in known: - return False - return all(_closed(child) for child in artifact.children) - - -@pytest.mark.slow -@given(st.data()) -@PARTITION -def test_flattening_agrees_with_the_independent_model(data: st.DataObject) -> None: - """`flatten_subworkflows` and `flatten_model` dissolve a partitioned workflow to the same DAG. - - The model is written separately, in this directory, and knows nothing of - step ids; those are pinned by `test_inline_flags.py`. What both must agree - on is the dataflow, and that the root's interface does not move. - - CANNOT GENERATE (declared): a call that carries `scatter` or `when`, which - `strat.workflows()` cannot draw, so no draw leaves a call nested. - """ - yml = data.draw(strat.workflows().filter(lambda w: len(w['steps']) >= 2)) - nested = compile_hermetic(data.draw(split_transformations()).apply(yml), _COMPILE_NAME).artifact - if not _closed(nested): - reject() - flat = post_compile.flatten_subworkflows(nested) - found = equivalent(flatten_model(nested), flatten_model(flat), Strength.UP_TO_RENAMING) - assert found is None, found - assert all(isinstance(step['run'], str) for step in flat.cwl['steps']) - assert all(child.cwl['class'] != 'Workflow' for child in flat.children) - assert list(flat.cwl['inputs']) == list(nested.cwl['inputs']) - assert list(flat.cwl['outputs']) == list(nested.cwl['outputs']) - assert flat.job_inputs == nested.job_inputs - - -def _nesting_depth(document: Yaml) -> int: - """How many subworkflow layers a document goes down: a step with a `subtree` is a subworkflow, so depth 2 is the - nested case.""" - return max((1 + _nesting_depth(step['subtree']) for step in document.get('steps', []) - if isinstance(step, dict) and isinstance(step.get('subtree'), dict)), - default=0) - - -@pytest.mark.fast -def test_split_reaches_a_document_that_is_already_nested() -> None: - """The nested half of the property above, which nothing checked. - - The nested case is `split` composed with itself, and nothing - composes anything: one rewrite is applied once. The nested case is reached - when `workflows()` happens to draw a document that already contains a - subworkflow step and `split` wraps it — true today, but a fact about - `ast_strategies.documents()` rather than about anything in this file. If - that generator's subworkflow branch narrowed, the nested case's coverage would go to - zero with every test here still green. - - Which rewrite gets drawn is no longer a question — the property parametrises - over all four — so this measures the one thing left to chance: how often the - document underneath is deep enough for `split` to nest. Drawn exactly as the - property draws, filter included. - """ - depths: Counter[int] = Counter() - - @PARTITION - @given(st.data()) - def _collect(data: st.DataObject) -> None: - yml = data.draw(strat.workflows().filter(lambda w: len(w['steps']) >= 2)) - rewrite = data.draw(split_transformations()) - depths[_nesting_depth(rewrite.apply(copy.deepcopy(yml)))] += 1 - - _collect() # pylint: disable=no-value-for-parameter # @given supplies `data` - - assert sum(count for depth, count in depths.items() if depth >= 2), ( - 'no drawn split reached a document that already contained a subworkflow, so ' - f'nesting, rather than partitioning alone, went untested. Depths drawn: {dict(depths)}') - - -#: A document every constant transformation but `identity` must genuinely -#: change: a plain step plus an existing subworkflow, so -#: `rename_workflow`/`split`-style wrapping has more than one step to gather. -_NOOP_GUARD_FIXTURE: Final[Yaml] = { - 'steps': [ - {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a.txt'}}}, - subworkflow_step('sub0.wic', {'steps': [ - {'id': 'xform', 'in': {'name': {'wic_inline_input': 'b.txt'}}}, - ]}), - ], -} - - -@pytest.mark.fast -@pytest.mark.parametrize('rewrite', TRANSFORMATIONS, ids=lambda t: t.name) -def test_every_transformation_actually_transforms(rewrite: Transformation) -> None: - """The tautology check, per rewrite. - - A transformation that returned its input unchanged would satisfy the - equivalence property for free, and the property would then be a statement - about `identity` wearing four other names. `identity` is exempt and says - so: it is the one rewrite whose whole point is changing nothing, and what - it tests is that *the compiler* does not. - - IDENTICAL-claiming rewrites need a different check than the rest, and that - is not a loophole: `text_roundtrip` is, by construction, value-preserving - (checked directly — `yaml.safe_dump` then `yaml.safe_load` round-trips this - fixture to something `==` its input), so `apply(yml) != yml` would fail - for a *correct* implementation just as loudly as for a broken one, and - could never tell them apart. What a no-op could fake there is skipping the - round trip entirely and handing back the very object it was given, so - that is what is checked: a fresh, value-equal object, not a different one. - - `apply` is handed `yml` itself and the comparison is against a pristine - `expected`, which is the whole of what makes that check real. An earlier - version passed `apply` a fresh `copy.deepcopy(yml)` and then asserted - `result is not yml` — true for *every* implementation, `lambda w: w` - included, because the identity being compared was the copy's and not the - one `apply` received. Replacing `_text_roundtrip`'s body with - `return document` left this test green. Comparing against `expected` - rather than `yml` matters for the same reason on the other branch: a - rewrite that mutated in place would otherwise be compared against itself. - """ - yml = copy.deepcopy(_NOOP_GUARD_FIXTURE) - if rewrite.name == 'identity': - pytest.skip('identity changes the input by definition; see the module docstring') - expected = copy.deepcopy(yml) - result = rewrite.apply(yml) - if rewrite.preserves is Strength.IDENTICAL: - assert result is not yml, f'{rewrite.name} returned its input unchanged, doing no work' - assert result == expected, f'{rewrite.name} claims IDENTICAL but changed the value' - else: - assert result != expected, f'{rewrite.name} is a no-op' - - -@pytest.mark.fast -def test_splitting_really_renames() -> None: - """`split` claims only UP_TO_RENAMING. If it renamed nothing, that claim - would be free and partition independence would assert nothing beyond IDENTICAL. - - Compiles both sides and checks both halves of the claim directly: IDENTICAL - must *not* hold (there is really something for a renaming to forgive) and - UP_TO_RENAMING must (the DAG that remains, once names are ignored, is the - same DAG). - """ - yml: Yaml = {'steps': [ - {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a.txt'}}}, - {'id': 'xform', 'in': {'name': {'wic_inline_input': 'b.txt'}}}, - ]} - rewrite = split(((0,), (1,))) - before = _compile_flat(yml) - after = _compile_flat(rewrite.apply(copy.deepcopy(yml))) - - assert equivalent(before, after, Strength.IDENTICAL) is not None, ( - 'split produced a byte-identical compilation; UP_TO_RENAMING would be a vacuous claim') - found = equivalent(before, after, Strength.UP_TO_RENAMING) - assert found is None, found - - -@pytest.mark.fast -def test_split_uses_distinct_formal_and_actual_input_names() -> None: - """The split/inline oracle must exercise parameter substitution. - - Identity bindings let an inliner delete the child interface without doing - any substitution and still pass every partition-independence property. - """ - yml: Yaml = { - 'inputs': {'actual': {'type': 'string'}}, - 'steps': [{'id': 'mk_file', 'in': {'name': 'actual'}}], - } - transformed = split(((0,),)).apply(copy.deepcopy(yml)) - wrapper = transformed['steps'][0] - formal_to_actual = wrapper['parentargs']['in'] - - assert formal_to_actual - assert all(formal != actual for formal, actual in formal_to_actual.items()) - formal = next(iter(formal_to_actual)) - assert wrapper['subtree']['steps'][0]['in']['name'] == formal - - -@pytest.mark.fast -def test_the_property_fails_for_a_rewrite_that_changes_meaning() -> None: - """A deliberately dishonest transformation — one that drops a step while - claiming to preserve UP_TO_RENAMING — must be caught. Without this, a - mis-wired property (comparing a document with itself, say) is green.""" - liar = Transformation( - name='drops_a_step', preserves=Strength.UP_TO_RENAMING, - apply=lambda w: {**w, 'steps': w['steps'][:-1]}, - rationale='none; this rewrite is wrong on purpose') - yml: Yaml = {'steps': [ - {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a.txt'}}}, - {'id': 'xform', 'in': {'name': {'wic_inline_input': 'b.txt'}}}, - ]} - before = _compile_flat(yml) - after = _compile_flat(liar.apply(copy.deepcopy(yml))) - assert equivalent(before, after, liar.preserves) is not None diff --git a/tests/core/test_examples.py b/tests/core/test_examples.py index 02a15b0b6..52a4d6a76 100644 --- a/tests/core/test_examples.py +++ b/tests/core/test_examples.py @@ -36,7 +36,6 @@ from .test_setup import CorpusRegistry, corpus_registry, workflow_paths from .cwl_validation import validate_cwl from .equivalence import Strength, equivalent, flatten_model -from .test_metadata_emitted import DECLARATIONS, declared_beneath yml_paths = workflow_paths() @@ -537,6 +536,22 @@ def test_a_corpus_declaration_compiles_its_analysis(stem: str, analysis: str, assert analyses[0].artifact.cwl['steps'] +#: The fields a CWL document declares its prefixes and ontologies in. +DECLARATIONS: Final = ('$namespaces', '$schemas') + + +def declared_beneath(artifact: CompilationArtifact) -> dict[str, Any]: + """The `$namespaces` and `$schemas` of `artifact` and of every process beneath it, merged as + embedding merges them: an embedded process may not declare its own, so they move up.""" + namespaces = dict(artifact.cwl.get('$namespaces', {})) + schemas = list(artifact.cwl.get('$schemas', [])) + for child in artifact.children: + below = declared_beneath(child) + namespaces |= below.get('$namespaces', {}) + schemas += [schema for schema in below.get('$schemas', []) if schema not in schemas] + return {field: value for field, value in zip(DECLARATIONS, (namespaces, schemas)) if value} + + def _check_embedding_keeps_meaning(yml_path_str: str, yml_path: Path, corpus_registry: CorpusRegistry) -> None: nested = _compile_corpus_workflow(yml_path_str, yml_path, corpus_registry) embedded = inline_artifact_runs(nested) diff --git a/tests/core/test_generators.py b/tests/core/test_generators.py deleted file mode 100644 index eed481f79..000000000 --- a/tests/core/test_generators.py +++ /dev/null @@ -1,178 +0,0 @@ -"""The generator is adequate and its failures are usable: a property is only as strong as its generator, and a dropped -construct silently disables every property needing it. Strategies draw from a named alphabet, as bare text almost -never forms a YAML alias.""" -import re -from collections import Counter -from typing import Any - -import pytest -from hypothesis import given -from hypothesis.strategies import SearchStrategy - -from sophios.lang import Document, Step, parse - -from . import ast_strategies as strat -from .hermetic import COVERAGE - - -@pytest.mark.fast -def test_every_construct_appears_within_a_bounded_sample() -> None: - """500 documents reach every construct kind in `CONSTRUCTS`. - - Stated over one drawn batch rather than as a per-example property, because - the claim is about the *sample*, not about any document: no single document - contains every construct, and a per-example property saying so would be - false by construction. - - Not `@given(st.data())` drawing 500 documents inside one execution, despite - that being the natural reading of "one drawn batch": Hypothesis's engine - always runs one deterministic "simplest choice" trial first — every - `sampled_from`/`lists`/`booleans` draw takes its minimum — and with - `st.data()` that trial draws the *same* trivial one-step document 500 times - over. A batch that uniform is missing thirteen-plus constructs by - construction, so a coverage assertion evaluated on it fails for every - generator regardless of quality (verified empirically before writing this - fix), and Hypothesis then spends minutes shrinking a interactively-drawn - 500-step failure that can never get smaller. Accumulating across 500 - independently-generated Hypothesis examples — only one of which is that - trivial trial — and asserting once after generation completes keeps the - claim about the sample, not any example, while never asking a single - execution to be internally diverse. - - CANNOT GENERATE (declared, per the negative-testing rules): - `python_script` steps, whose module definition belongs to the registry; - multi-document YAML streams; merge keys. - """ - seen: Counter[str] = Counter() - - @COVERAGE - @given(strat.documents()) - def _collect(document: Document) -> None: - seen.update(strat.constructs_in(document)) - - _collect() # pylint: disable=no-value-for-parameter # @given supplies `document` - - missing = [c for c in strat.CONSTRUCTS if not seen[c]] - assert not missing, ( - f'{missing} never appeared in 500 documents. Every property fed by this ' - f'generator is silent about them.\nSeen: {dict(seen)}' - ) - - -@pytest.mark.fast -def test_the_compilable_subset_still_reaches_every_construct_it_does_not_exclude() -> None: - """The companion `NOT_YET_COMPILABLE` claims, and did not have. - - `compilable_documents()` is what the compile-driving properties quantify - over, and its filter is the one place a construct can leave the oracle's - reach without anything going red — `documents()` keeps producing the whole - language, so coverage stays green no matter what the filter removes. An - exclusion predicate of `lambda d: True` empties the strategy entirely, and - without the check below every test in this file would still pass. - - So the filter is held to the same standard as the generator. An exclusion - that costs a construct has to be argued for by whoever adds it, here, in - this test — that is the decision `NOT_YET_COMPILABLE` exists to make - visible, and a test that pre-authorised it by subtracting the exclusions - from the expected set would authorise the silent narrowing too. - - `excluded_documents` is called for each entry as well: it is the only - caller that keeps `_EXCLUSION_PREDICATES` keyed identically to - `NOT_YET_COMPILABLE` at runtime rather than only at import. - """ - seen: Counter[str] = Counter() - - @COVERAGE - @given(strat.compilable_documents()) - def _collect(document: Document) -> None: - seen.update(strat.constructs_in(document)) - - _collect() # pylint: disable=no-value-for-parameter # @given supplies `document` - - for name in strat.NOT_YET_COMPILABLE: - assert strat.excluded_documents(name) is not None - - missing = [c for c in strat.CONSTRUCTS if not seen[c]] - assert not missing, ( - f'{missing} never appeared in 500 documents drawn from compilable_documents(), ' - f'so every compile-driving property is silent about them. Active exclusions: ' - f'{sorted(strat.NOT_YET_COMPILABLE)}.\nSeen: {dict(seen)}' - ) - - -@pytest.mark.fast -@given(strat.hostile_documents()) -@COVERAGE -def test_every_ill_formed_document_earns_its_own_diagnostic(case: tuple[str, object]) -> None: - """The hostile sibling's contract: rejected, with the right code, and never - silently normalised or repaired into something that compiles.""" - source, expected = case - result = parse(source, 'hostile.wic') - codes = [d.code for d in result.diagnostics] - assert expected in codes, f'expected {expected}, got {codes}\n{source}' - - -@pytest.mark.fast -def test_no_step_the_generator_draws_is_discarded(monkeypatch: pytest.MonkeyPatch) -> None: - """Every step drawn reaches the document. - - Mapping form cannot repeat a step name, so its stems are drawn unique up - front. A step drawn and then dropped on a collision would keep the edge - names it defined (a dangling `!*`, `wic025`) and shrink the sample, so a - document asking for four steps gets two. The dangling edge is rare (4 - documents in 2000); the discard is common and only the drawing site sees - it, so it is recorded there. - """ - drawn: list[str] = [] - real = strat._step # pylint: disable=protected-access # the drawing site is the subject - - def _recording(stem: str, defined_edges: list[tuple[str, Any]], - referenced_inputs: set[str]) -> SearchStrategy[Step]: - drawn.append(stem) - return real(stem, defined_edges, referenced_inputs) - - monkeypatch.setattr(strat, '_step', _recording) - - @COVERAGE - @given(strat.documents()) - def _check(document: Document) -> None: - # The *tail* of `drawn`, not all of it: Hypothesis abandons a partly - # drawn example whenever a draw comes back unusable — the unique list - # of stems is one such draw — and those abandoned steps are recorded - # too, with no document to compare them against. The steps of the - # example that survived are the last ones drawn, and under this - # generator they are exactly as many as the document keeps. - kept = [step.id for step in document.steps if not step.id.endswith('.wic')] - assert drawn[-len(kept):] == kept, ( - f'the generator drew {drawn[-len(kept) - 2:]} and the document kept {kept}. A ' - f'discarded step takes its !& names with it and shrinks the sample silently') - drawn.clear() - - _check() # pylint: disable=no-value-for-parameter # @given supplies `document` - - -@pytest.mark.fast -def test_the_construct_inventory_accounts_for_every_input_kind() -> None: - """Every member of the `InputValue` union is drawn, or declared undrawable. - - The coverage test above quantifies over `CONSTRUCTS`, so a kind missing from - that tuple is invisible to it -- the inventory would shrink and the sample - would still be "complete". Deriving the kinds from the union instead means - adding an AST node fails here until someone either generates it or writes - down why they cannot. - """ - import typing # pylint: disable=import-outside-toplevel - - from sophios.lang.nodes import InputValue # pylint: disable=import-outside-toplevel - - def snake(name: str) -> str: - return re.sub(r'(? None: #: Test files whose passing constitutes "the oracle suite ran with plugin #: discovery disabled". ORACLE_FILES: tuple[str, ...] = ( - 'tests/core/test_generators.py', - 'tests/core/test_equivalence.py', - 'tests/core/test_equivalences.py', 'tests/core/test_predicates.py', 'tests/core/test_reference_compatibility.py', 'tests/core/test_canonical_path.py', 'tests/core/test_emit.py', 'tests/core/test_resolve.py', - 'tests/core/test_link.py', 'tests/core/test_infer_phase.py', - 'tests/core/test_names_emitted.py', 'tests/core/test_edge_binding.py', ) diff --git a/tests/core/test_infer_phase.py b/tests/core/test_infer_phase.py index 8038cd275..9f2b65219 100644 --- a/tests/core/test_infer_phase.py +++ b/tests/core/test_infer_phase.py @@ -1,334 +1,73 @@ -"""Inference and speculative insertion against a local candidate model, judged at UP_TO_EMBEDDING. -Blind spot: generated workflows put no tool after a workflow call and no converters exist, so those are planted.""" -import copy +"""Inference, judged on cases in files: tests/core/data/infer// is a workflow.wic with the tools and child +workflows it names (beside it, or shared by the theme), and the theme's expected.yaml states what each case infers. +That every inferred edge is the independent model's choice is a law of test_emit.py's drawn workflows.""" +from pathlib import Path from typing import Any import pytest -from hypothesis import given +import yaml -from sophios.ir import ( - InferencePolicy, - InsertionCatalog, - front_end, - infer, - link, -) +from sophios.cli import default_compilation_settings +from sophios.compiler import compile_source +from sophios.ir import InferencePolicy, InsertionCatalog, front_end, infer, link +from sophios.ir.frontdoor import bundle_from_disk from sophios.ir.names import Names -from sophios.ir.declarations import input_rank, layered, output_rank -from sophios.ir.types import (DerivedName, EdgeOrigin, Port, PortDeclaration, PortId, PortName, - StepNode, WorkflowGraph) +from sophios.ir.types import EdgeOrigin, WorkflowGraph from sophios.lang.diagnostics import Diagnostics, SophiosError -from sophios.wic_types import StepId as LegacyStepId, Tool, Tools, Yaml - -from . import ast_strategies as strat -from .cases import cases, diagnostic, match -from .hermetic import ORACLE, bundle, compile_hermetic, subworkflow_step -from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS, clt, insertion_registry, registered - - -def _typed(workflow: Yaml, tools: Tools = SYNTHETIC_TOOLS): # type: ignore[no-untyped-def] - model = bundle(workflow, 'oracle', tools) - result = front_end(model.parsed, model.registry, name='oracle') - assert result.graph is not None and result.resolved is not None - linked = link(result.graph) +from sophios.utils_cwl import desugar_into_canonical_normal_form + +from .cases import DATA, diagnostic, match +from .helpers import stated +from .synthetic_tools import registered + + +def _tools(*directories: Path) -> Any: + """The synthetic tools, and each tool in `directories`, the later winning, desugared as discovery desugars them.""" + return registered({path.stem: desugar_into_canonical_normal_form(yaml.safe_load(path.read_text(encoding='utf-8'))) + for directory in directories for path in sorted(directory.glob('*.cwl'))}) + + +def _inferred(case: Path, expected: dict[str, Any]) -> tuple[WorkflowGraph | None, Diagnostics, int]: + """The graph inference gives the case, every diagnostic its door gives, and how many passes it took: the phases + run directly under `policy`, or the whole compile where `compiled` is set.""" + others = {'global': {path.stem: path for path in case.glob('*.wic') if path.name != 'workflow.wic'}} + bundled = bundle_from_disk(case / 'workflow.wic', others, _tools(case.parent, case)) + policy = expected.get('policy', {}) + if expected.get('compiled'): + options = default_compilation_settings() + options['inference_strict'] = policy.get('strict', False) + try: + compiled = compile_source(bundled, options, quiet=True) + except SophiosError as error: + return None, error.diagnostics, 0 + return compiled.graph, compiled.diagnostics, 0 + front = front_end(bundled.parsed, bundled.registry, name='workflow') + assert front.graph is not None, list(front.diagnostics) + linked = link(front.graph) assert linked.graph is not None, list(linked.diagnostics) - return result, linked.graph, model.registry - - -@pytest.mark.skip_pypi_ci -@given(strat.workflows()) -@ORACLE -def test_every_inferred_edge_is_the_independent_models_choice(workflow: Yaml) -> None: - """Removing candidate selection or changing its order breaks this predicate.""" - _, linked, _ = _typed(workflow) - inferred = infer(linked) - assert inferred.graph is not None, list(inferred.diagnostics) - for graph in _graphs(inferred.graph): - original = next(item for item in _graphs(linked) if item.namespace == graph.namespace) - for edge in graph.linked_edges: - if edge.origin is not EdgeOrigin.INFERRED: - continue - position = next(index for index, step in enumerate(original.steps) - if step.id == edge.sink.step) - sink = _port(original.steps[position].inputs, edge.sink.port) - assert _model_candidate(original.steps, position, sink) == edge.source - - -def _built(value: Any) -> Any: - """`value`, each step with a `subtree` built as subworkflow_step builds a call.""" - if isinstance(value, list): - return [_built(each) for each in value] - if isinstance(value, dict): - built = {key: _built(each) for key, each in value.items()} - return {**subworkflow_step(built['id'], built['subtree']), **built} if 'subtree' in built else built - return value - - -def _ran(case: dict[str, Any]) -> tuple[Any, Diagnostics]: - """What the case's door returns and every diagnostic it gives, the compile's error included.""" - for stem, tool in case.get('tools', {}).items(): - if unread := set(tool) - {'inputs', 'outputs', 'canonical'}: - raise ValueError(f"{case['id']}: tool {stem} has keys nothing reads: {sorted(unread)}") - if case.get('compiled') and (unread := set(case.get('policy', {})) - {'strict'}): - raise ValueError(f"{case['id']}: a compiled case reads only policy.strict, not {sorted(unread)}") - tools = registered({stem: clt(tool.get('inputs', {}), tool.get('outputs', {}), - canonical=tool.get('canonical', False)) - for stem, tool in case.get('tools', {}).items()}) - policy = case.get('policy', {}) - workflow = {'steps': _built(case['steps'])} - if not case.get('compiled'): - _, linked, _ = _typed(workflow, tools) - result = infer(linked, InferencePolicy(**policy)) - return result.graph, result.diagnostics - try: - compiled = compile_hermetic(workflow, tools=tools, inference_strict=policy.get('strict', False)) - except SophiosError as error: - return None, error.diagnostics - return compiled, compiled.diagnostics - - -@pytest.mark.fast -@pytest.mark.parametrize('case', cases('infer', 'tools', 'steps', 'policy', 'compiled', 'refused', 'diagnostics', - 'edges', 'job_inputs')) -def test_inference_case(case: dict[str, Any]) -> None: - """`steps` are inferred over the synthetic registry plus `tools` (stem: inputs, outputs, canonical), under - `policy`, or compiled whole where `compiled` is set (which reads only `policy.strict`); a call is a step with a - `subtree`. A tool key other than those three, or a compiled policy key other than `strict`, is an error, so a - misspelling cannot pass without being read. - - `diagnostics` is every diagnostic the door returns, in order; `refused` (default false) is no graph, or a compile - that raised; `edges` the inferred edges of the graph as sink: source, and `job_inputs` those of the compile. - """ - ran, diagnostics = _ran(case) - assert (ran is None) is case.get('refused', False), list(diagnostics) - assert match(case.get('diagnostics', []), [diagnostic(d) for d in diagnostics]), list(diagnostics) - if 'edges' in case: - assert match(case['edges'], { - f'{e.sink.step.name}@{e.sink.step.index}.{e.sink.port}': - f'{e.source.step.name}@{e.source.step.index}.{e.source.port}' - for e in ran.linked_edges if e.origin is EdgeOrigin.INFERRED}) - if 'job_inputs' in case: - assert match(case['job_inputs'], ran.artifact.job_inputs) - - -@pytest.mark.fast -@pytest.mark.parametrize('default', [0, False, '', []]) -def test_falsy_defaults_satisfy_inputs(default: object) -> None: - """Presence, not truthiness, suppresses inference for a defaulted port.""" - tool = clt({'value': {'type': 'string', 'default': default}}, {}) - tools = {LegacyStepId('defaulted', SYNTHETIC_NS): - Tool('/synthetic/defaulted.cwl', tool)} - _, linked, _ = _typed({'steps': [{'id': 'defaulted'}]}, tools) - result = infer(linked) - assert result.graph is not None - assert not any(edge.origin is EdgeOrigin.INFERRED for edge in result.graph.linked_edges) - assert result.graph.workflow_inputs == () - - -@pytest.mark.fast -@pytest.mark.parametrize('expression', [ - '$(inputs.source.format)', - '${ return inputs.source.format; }', -]) -def test_promoted_input_preserves_a_cwl_format_expression(expression: str) -> None: - """A lifted input carries the tool's `format` verbatim, in the graph and - in the emitted document -- the one test that a promoted boundary keeps - `format` at all. An expression is the spelling a rewrite would most - likely break. - """ - tool = clt({'file': {'type': 'File', 'format': expression}}, {}, canonical=True) - tools = {LegacyStepId('formatted_sink', SYNTHETIC_NS): - Tool('/synthetic/formatted_sink.cwl', tool)} - workflow = {'steps': [{'id': 'formatted_sink'}]} - _, linked, _ = _typed(workflow, tools) - result = infer(linked) - assert result.graph is not None, list(result.diagnostics) - assert result.graph.workflow_inputs[0].declaration.format == expression - compiled = compile_hermetic(copy.deepcopy(workflow), tools=copy.deepcopy(tools)) - boundary = next(iter(compiled.artifact.cwl['inputs'].values())) - assert boundary['format'] == expression - - -@pytest.mark.fast -def test_scatter_lifts_both_sides_of_candidate_selection() -> None: - """A producing scatter matches an array sink, while a scalar sink does not.""" - tools = copy.deepcopy(SYNTHETIC_TOOLS) - tools[LegacyStepId('file_array_sink', SYNTHETIC_NS)] = Tool( - '/synthetic/file_array_sink.cwl', clt({'files': {'type': 'File[]'}}, {}, canonical=True)) - workflow = {'steps': [ - {'id': 'mk_file', 'in': {'name': {'wic_inline_input': ['a', 'b']}}, - 'scatter': 'name'}, - {'id': 'file_array_sink'}, - {'id': 'count'}, - ]} - _, linked, _ = _typed(workflow, tools) - result = infer(linked) - assert result.graph is not None - sinks = {(edge.sink.step.name, edge.sink.port) for edge in result.graph.linked_edges - if edge.origin is EdgeOrigin.INFERRED} - assert ('file_array_sink', 'files') in sinks - assert ('count', 'file') not in sinks - - -@pytest.mark.fast -def test_converter_insertion_reaches_the_same_fixed_point() -> None: - """Two speculative insertions agree with the live typed compiler.""" - workflow, tools = insertion_registry() - _, linked, registry = _typed(workflow, tools) - result = infer(linked, InferencePolicy(insert_steps_automatically=True), - InsertionCatalog.from_registry(registry)) - assert result.graph is not None, list(result.diagnostics) - assert result.iterations == 3 - assert sum(step.synthesized for step in result.graph.steps) == 2 - live = compile_hermetic(copy.deepcopy(workflow), tools=copy.deepcopy(tools), - insert_steps_automatically=True).graph - assert sum(step.synthesized for step in live.steps) == 2 - - -@pytest.mark.fast -def test_workflow_call_outputs_are_inference_candidates() -> None: - """A child output remains visible to a later tool in its parent.""" - child = {'steps': [ - {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'child.txt'}}}, - ]} - workflow = {'steps': [subworkflow_step('sub.wic', child), {'id': 'count'}]} - _, linked, _ = _typed(workflow) - result = infer(linked) - assert result.graph is not None, list(result.diagnostics) - assert any(edge.sink.step.name == 'count' for edge in result.graph.linked_edges - if edge.origin is EdgeOrigin.INFERRED) - # The live compiler infers the same edge from the same document. - live = compile_hermetic(copy.deepcopy(workflow)).graph - assert any(edge.sink.step.name == 'count' for edge in live.linked_edges - if edge.origin is EdgeOrigin.INFERRED) - - -@pytest.mark.fast -def test_workflow_call_outputs_can_feed_inserted_converters() -> None: - """Converter search sees formats exported through a workflow call.""" - _, tools = insertion_registry() - child = {'steps': [{'id': 'mk_2'}]} - workflow = {'steps': [subworkflow_step('sub.wic', child), {'id': 'use_2'}]} - typed, linked, registry = _typed(workflow, tools) - result = infer(linked, InferencePolicy(insert_steps_automatically=True), - InsertionCatalog.from_registry(registry)) - assert result.graph is not None, list(result.diagnostics) - assert sum(step.synthesized for step in result.graph.steps) == 1 - # The live compiler reaches the same conclusion from the same document. - live = compile_hermetic(copy.deepcopy(workflow), tools=copy.deepcopy(tools), - insert_steps_automatically=True) - assert sum(step.synthesized for step in live.graph.steps) == 1 - - -@pytest.mark.fast -def test_converter_search_stops_at_the_candidate_break() -> None: - """Insertion cannot reuse formats hidden behind a local break rule.""" - _, tools = insertion_registry() - workflow = { - 'steps': [{'id': 'mk_1'}, {'id': 'mk_2'}, {'id': 'use_1'}], - 'wic': {'steps': { - '(2, mk_2)': {'wic': {'inference': {'file': 'break'}}}, - }}, - } - _, linked, registry = _typed(workflow, tools) - result = infer(linked, InferencePolicy(insert_steps_automatically=True), - InsertionCatalog.from_registry(registry)) - assert result.graph is not None, list(result.diagnostics) - assert not any(step.synthesized for step in result.graph.steps) - assert [Names.of(result.graph).port(port.name) for port in result.graph.workflow_inputs] == [ - 'use_1~file'] - live = compile_hermetic(copy.deepcopy(workflow), tools=copy.deepcopy(tools), - insert_steps_automatically=True) - assert not any('insert_steps_automatically_' in step['id'] - for step in live.artifact.cwl['steps']) - - -def _model_candidate(steps: tuple[StepNode, ...], position: int, - sink: Port) -> PortId | None: - """Independent, deliberately small model of default candidate selection.""" - sink_type = _model_sink_type(steps[position], sink) - sink_formats = _model_formats(sink.declaration) - for producer in reversed(steps[:position]): - matches = [output for output in producer.outputs - if _model_types_match(sink_type, _model_source_type(producer, output)) - and _model_formats_match(sink_formats, _model_formats(output.declaration), - _model_source_type(producer, output))] - if matches: - through = _model_exposed_through(matches[-1].id.port) - return next(output.id for output in matches - if _model_exposed_through(output.id.port) == through) - return None - - -def _model_exposed_through(name: PortName) -> list[object]: - """The steps a port name was exposed through, outermost first.""" - steps: list[object] = [] - while isinstance(name, DerivedName): - steps.append(name.step) - name = name.port - return steps - - -def _model_types_match(sink: Any, source: Any) -> bool: - if sink == source: - return True - sink_members = sink if isinstance(sink, list) else [sink] - source_members = source if isinstance(source, list) else [source] - return any(member in sink_members for member in source_members) - - -def _model_formats(declaration: PortDeclaration | None) -> tuple[Any, ...]: - if declaration is None or not declaration.has_format: - return () - return tuple(declaration.format) if isinstance(declaration.format, list) \ - else (declaration.format,) - - -def _model_formats_match(sink: tuple[Any, ...], source: tuple[Any, ...], - source_type: Any) -> bool: - if not sink: - return True - if source: - return any(item in sink for item in source) - return not _model_permits_format(source_type) - - -def _model_permits_format(value: Any) -> bool: - if value == 'File': - return True - if isinstance(value, list): - return any(_model_permits_format(item) for item in value) - if isinstance(value, dict) and value.get('type') == 'array': - return _model_permits_format(value.get('items')) - return False - - -def _model_source_type(step: StepNode, port: Port) -> Any: - """CWL v1.2: `nested_crossproduct` nests one array per scattered input; - every other method yields one flat array. Rank is `output_rank`.""" - return layered(port.type, output_rank(step)).canonical - - -def _model_sink_type(step: StepNode, port: Port) -> Any: - """One array per time `scatter:` names the input, which is `input_rank`.""" - return layered(port.type, input_rank(step, port.id.port)).canonical - - -def _port(ports: tuple[Port, ...], name: PortName) -> Port: - return next(port for port in ports if port.id.port == name) - - -def _graphs(graph: WorkflowGraph) -> tuple[WorkflowGraph, ...]: - return (graph,) + tuple(item for child in graph.children for item in _graphs(child)) + result = infer(linked.graph, InferencePolicy(**policy), InsertionCatalog.from_registry(bundled.registry)) + return result.graph, result.diagnostics, result.iterations @pytest.mark.fast -def test_a_positional_output_source_compiles_beside_an_inferred_edge() -> None: - """Inference moves no step, so `(4, count)` still names the fourth step.""" - mk = {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'x'}}} - compiled = compile_hermetic({'outputs': {'n': {'type': 'int', 'outputSource': '(4, count)/n'}}, - 'steps': [mk, {'id': 'count'}, mk, {'id': 'count'}]}) - cwl = compiled.artifact.cwl - assert cwl['outputs']['n']['outputSource'] == 'count@4/n' - fourth = next(step for step in cwl['steps'] if step['id'] == 'count@4') - assert fourth['in']['file'] == 'mk_file@3/file' +@pytest.mark.parametrize('theme', [pytest.param(path, id=path.name) + for path in sorted((DATA / 'infer').iterdir()) if path.is_dir()]) +def test_inference_decides_each_case_as_its_theme_states(theme: Path) -> None: + """For each case: `refused` (default false) is no graph; `diagnostics` is every diagnostic, in order, by code, + severity, step and port, and what a guess or refusal names; `edges` the inferred edges as sink: source; `inputs` + the workflow inputs left to the job; `inserted` how many converter steps were inserted, in `iterations` passes.""" + for name, expected in stated(theme).items(): + graph, diagnostics, iterations = _inferred(theme / name, expected) + assert (graph is None) is expected.get('refused', False), (name, list(diagnostics)) + assert match(expected.get('diagnostics', []), [diagnostic(d) for d in diagnostics]), (name, list(diagnostics)) + if graph is None: + continue + names = Names.of(graph) + edges = {f'{e.sink.step.name}@{e.sink.step.index}.{names.port(e.sink.port)}': + f'{e.source.step.name}@{e.source.step.index}.{names.port(e.source.port)}' + for e in graph.linked_edges if e.origin is EdgeOrigin.INFERRED} + assert match(expected.get('edges', edges), edges), name + assert match(expected.get('inputs', [names.port(port.name) for port in graph.workflow_inputs]), + [names.port(port.name) for port in graph.workflow_inputs]), name + assert expected.get('inserted', 0) == sum(step.synthesized for step in graph.steps), name + assert expected.get('iterations', iterations) == iterations, name diff --git a/tests/core/test_inline_flags.py b/tests/core/test_inline_flags.py index dde9eda10..1c884260a 100644 --- a/tests/core/test_inline_flags.py +++ b/tests/core/test_inline_flags.py @@ -1,5 +1,6 @@ -"""`--cwl_inline_runtag` packages a compiled workflow as one file with every step's `run:` carrying its process, without -changing meaning: a tool embedded in a newer document keeps the defaults its own version gave it.""" +"""`--cwl_inline_subworkflows` and `--cwl_inline_runtag`, judged on the inline tree of tests/core/data/inline: the flat +document it states, which calls dissolve and which stay and why, and what each step runs under each flag; a tool +embedded in a newer document keeps the defaults its own version gave it; and the flags on the command line.""" import sys from dataclasses import replace from pathlib import Path @@ -10,36 +11,88 @@ import sophios.main from sophios import post_compile +from sophios.cli import default_compilation_settings +from sophios.compiler import compile_source from sophios.ir.artifacts import CompilationArtifact +from sophios.ir.frontdoor import bundle_from_disk from sophios.lang.diagnostics import SophiosError from sophios.lang.error_codes import SophiosErrorCode from sophios.wic_types import Yaml -from .cases import cases -from .hermetic import compile_hermetic, subworkflow_step +from .cases import DATA, match +from .helpers import stated +from .test_compiler import _tools from .test_setup import workflow_paths pytestmark = pytest.mark.package -MK_FILE: Yaml = {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a'}}} +TREE = DATA / 'inline' + + +def _compiled(root: str) -> CompilationArtifact: + """`root` of the inline tree compiled, its children the other `.wic` files beside it.""" + others = {'global': {path.stem: path for path in TREE.glob('*.wic') if path.name != root}} + artifact = compile_source(bundle_from_disk(TREE / root, others, _tools(TREE)), default_compilation_settings(), + quiet=True).artifact + assert artifact is not None + return artifact + + +def _runs(form: CompilationArtifact) -> list[str]: + """What each step of `form` runs, `T` a CommandLineTool and `W` a Workflow: embedded in its `run:`, or the child + document its step names.""" + children = {child.namespace: child.cwl['class'] for child in form.children} + classes = [step['run']['class'] if isinstance(step['run'], dict) else children[(step['id'],)] + for step in form.cwl['steps']] + return ['T' if kind == 'CommandLineTool' else 'W' for kind in classes] + + +@pytest.mark.fast +def test_the_inline_tree_flattens_to_the_document_it_states(capsys: pytest.CaptureFixture[str]) -> None: + """Flattened, the tree is the document expected.yaml states, with the root's interface and job unchanged, and + each kept call said once, with its reason; the flags apply shape first and do not depend on each other.""" + nested = _compiled('workflow.wic') + expected = stated(TREE) + flat = post_compile.flatten_subworkflows(nested) + assert match(expected['said'], capsys.readouterr().err.splitlines()) + assert match(expected['flat'], flat.cwl) + assert (list(flat.cwl['inputs']), list(flat.cwl['outputs']), flat.job_inputs) == \ + (list(nested.cwl['inputs']), list(nested.cwl['outputs']), nested.job_inputs) + assert post_compile.apply_inline_options(nested, subworkflows=False, runtag=False) is nested + forms = {'nested': nested, '--cwl_inline_subworkflows': flat, + '--cwl_inline_runtag': post_compile.apply_inline_options(nested, subworkflows=False, runtag=True), + 'both': post_compile.apply_inline_options(nested, subworkflows=True, runtag=True)} + assert {name: _runs(form) for name, form in forms.items()} == expected['runs'] + assert [step['id'] for step in forms['both'].cwl['steps']] == [step['id'] for step in flat.cwl['steps']] + # A child whose requirements a script listed after the compile keeps its call: flattening reads the mapping only. + listed = replace(nested, children=tuple( + replace(child, cwl={**child.cwl, 'requirements': [{'class': 'EnvVarRequirement', 'envDef': {'A': 'b'}}]}) + if child.namespace == ('plain',) else child for child in nested.children)) + assert [step['id'] for step in post_compile.flatten_subworkflows(listed).cwl['steps']][1] == 'plain' + assert match({'contains': [{'contains': ["step 'plain.wic'", 'requirements are written as a list']}]}, + capsys.readouterr().err.splitlines()) @pytest.mark.fast -@pytest.mark.parametrize('case', cases('embedded_tools', 'tool', 'embedded', 'says')) -def test_an_embedded_tool_keeps_the_defaults_its_own_version_gave_it(case: Yaml) -> None: +def test_an_embedded_tool_keeps_the_defaults_its_own_version_gave_it() -> None: """Embedded, a tool loses its `cwlVersion`, and nothing updates it as cwltool updates a file it loads: what its - version implied is written out, what it declares itself is kept, or a version Sophios cannot read is refused.""" - artifact = compile_hermetic({'steps': [MK_FILE]}).artifact - artifact = replace(artifact, children=(replace(artifact.children[0], cwl=case['tool']),)) - if 'says' in case: - with pytest.raises(SophiosError) as caught: - post_compile.inline_artifact_runs(artifact) - (diagnostic,) = caught.value.diagnostics - assert diagnostic.code is SophiosErrorCode.UNSUPPORTED_CWL_VERSION and case['says'] in diagnostic.message - return - (step,) = post_compile.inline_artifact_runs(artifact).cwl['steps'] - assert 'cwlVersion' not in step['run'] - assert {key: step['run'][key] for key in case['embedded']} == case['embedded'] + version implied is written out, what it declares itself is kept, and a version Sophios cannot read is refused. + Each tool of tests/core/data/inline/embedded stands in for the one step of plain.wic.""" + artifact = _compiled('plain.wic') + tools = TREE / 'embedded' + for name, expected in stated(tools).items(): + tool = yaml.safe_load((tools / name).read_text(encoding='utf-8')) + swapped = replace(artifact, children=(replace(artifact.children[0], cwl=tool),)) + if 'refused' in expected: + with pytest.raises(SophiosError) as caught: + post_compile.inline_artifact_runs(swapped) + (diagnostic,) = caught.value.diagnostics + assert diagnostic.code is SophiosErrorCode.UNSUPPORTED_CWL_VERSION, name + assert expected['refused'] in diagnostic.message, name + continue + (step,) = post_compile.inline_artifact_runs(swapped).cwl['steps'] + assert 'cwlVersion' not in step['run'], name + assert match(expected, step['run']), (name, step['run']) def _cli(directory: Path, monkeypatch: pytest.MonkeyPatch, workflow: str, *flags: str) -> Path: @@ -53,248 +106,51 @@ def _cli(directory: Path, monkeypatch: pytest.MonkeyPatch, workflow: str, *flags return directory / 'autogenerated' -@pytest.mark.fast -def test_inline_runtag_embeds_a_tool_with_the_defaults_it_was_written_for( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """The flag, end to end: `echo.cwl` is v1.0 and the embedded copy still reaches the network.""" - written = _cli(tmp_path / 'embedded', monkeypatch, 'helloworld', '--cwl_inline_runtag') - loaded = yaml.safe_load((written / 'helloworld.cwl').read_text(encoding='utf-8')) - (step,) = loaded['steps'] - assert step['run']['hints']['NetworkAccess'] == {'networkAccess': True} - - def _document(written: Path, name: str) -> Yaml: """The root document the CLI wrote into `written`.""" return cast(Yaml, yaml.safe_load((written / f'{name}.cwl').read_text(encoding='utf-8'))) -NESTED_IDS = ['touch', 'append_twice', 'cat'] -FLAT_IDS = ['touch', 'append_twice~append@1', 'append_twice~append@2', 'cat'] - - @pytest.mark.fast -def test_inline_subworkflows_writes_one_flat_workflow(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str]) -> None: - """Shape: no step runs a Workflow, tools stay files, and the root interface is the nested one's.""" - nested = _cli(tmp_path / 'default', monkeypatch, 'multistep3') +def test_the_inline_flags_on_the_command_line( # pylint: disable=too-many-locals + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + """End to end on the tutorials. multistep3 (touch, append_twice.wic calling append twice, cat) flattened: tools + stay files, a dissolved call leaves no Workflow document, the root interface and job are the nested one's, and + nothing is said; with --cwl_inline_runtag too, one document carrying every process. helloworld's echo.cwl is + v1.0, and embedded it still reaches the network. test_rand_fail scatters over fail.wic, and the `when` + --partial_failure_enable gives a call gates its inputs: both calls keep their place, and one line names each.""" + nested = _cli(tmp_path / 'nested', monkeypatch, 'multistep3') flat = _cli(tmp_path / 'flat', monkeypatch, 'multistep3', '--cwl_inline_subworkflows') document, default = _document(flat, 'multistep3'), _document(nested, 'multistep3') - assert [step['id'] for step in default['steps']] == NESTED_IDS - assert [step['id'] for step in document['steps']] == FLAT_IDS - assert all(isinstance(step['run'], str) for step in document['steps']), 'tools stay separate files' - assert document['steps'][1]['run'] == 'multistep3~append_twice~append@1.cwl' - assert (flat / 'multistep3~append_twice~append@1.cwl').is_file() - assert not (flat / 'multistep3~append_twice.cwl').exists(), 'a dissolved call leaves no Workflow document' + flat_ids = ['touch', 'append_twice~append@1', 'append_twice~append@2', 'cat'] + assert [step['id'] for step in document['steps']] == flat_ids + assert [step['run'] for step in document['steps']] == [f'multistep3~{name}.cwl' for name in flat_ids] + assert all((flat / step['run']).is_file() for step in document['steps']) + assert not (flat / 'multistep3~append_twice.cwl').exists() assert 'SubworkflowFeatureRequirement' not in document.get('requirements', {}) - assert document['steps'][2]['in']['file'] == f'{FLAT_IDS[1]}/file' - assert document['steps'][3]['in']['file'] == f'{FLAT_IDS[2]}/file' - for key in ('inputs', 'outputs'): - assert list(document[key]) == list(default[key]), f'the flat form keeps the root {key}' - last = 'append_twice~append@2~file' - assert document['outputs'][last]['outputSource'] == f'{FLAT_IDS[2]}/file' + assert [document['steps'][2]['in']['file'], document['steps'][3]['in']['file']] == \ + [f'{flat_ids[1]}/file', f'{flat_ids[2]}/file'] + assert document['outputs']['append_twice~append@2~file']['outputSource'] == f'{flat_ids[2]}/file' + assert (list(document['inputs']), list(document['outputs'])) == (list(default['inputs']), list(default['outputs'])) assert (flat / 'multistep3_inputs.yml').read_text() == (nested / 'multistep3_inputs.yml').read_text() - assert 'Warning!' not in capsys.readouterr().err, 'nothing stayed nested, so nothing is said' - - -@pytest.mark.fast -@pytest.mark.parametrize('flags, ids, runs, requirements', [ - (['--cwl_inline_runtag'], NESTED_IDS, ['CommandLineTool', ['CommandLineTool'] * 2, 'CommandLineTool'], - {'SubworkflowFeatureRequirement': {}}), - (['--cwl_inline_subworkflows', '--cwl_inline_runtag'], FLAT_IDS, ['CommandLineTool'] * 4, None)]) -# pylint: disable-next=too-many-arguments,too-many-positional-arguments -def test_inline_runtag_writes_one_document_that_carries_every_process( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], - flags: list[str], ids: list[str], runs: list[Any], requirements: Yaml | None) -> None: - """The root and its job, nothing beside them; a subworkflow step embeds its Workflow, here the classes of its - steps. The flags are orthogonal: with `--cwl_inline_subworkflows`, the flat shape with every process embedded.""" - written = _cli(tmp_path / 'embedded', monkeypatch, 'multistep3', *flags) - assert sorted(path.name for path in written.iterdir()) == ['multistep3.cwl', 'multistep3_inputs.yml'] - document = _document(written, 'multistep3') - assert [step['id'] for step in document['steps']] == ids - assert [[inner['run']['class'] for inner in step['run']['steps']] if step['run']['class'] == 'Workflow' - else step['run']['class'] for step in document['steps']] == runs - assert document.get('requirements') == requirements assert 'Warning!' not in capsys.readouterr().err - -@pytest.mark.fast -def test_a_scattered_call_stays_nested_and_the_compile_says_so(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str]) -> None: - """`test_rand_fail` scatters over `fail.wic`: the call keeps its place, and one line names it.""" - written = _cli(tmp_path / 'kept', monkeypatch, 'test_rand_fail', '--cwl_inline_subworkflows') - document = _document(written, 'test_rand_fail') - kept = next(step for step in document['steps'] if step['id'] == 'fail') - assert kept['run'].endswith('fail.cwl') and 'scatter' in kept - assert (written / kept['run']).is_file(), 'the Workflow document it runs is still written' - assert document['requirements']['SubworkflowFeatureRequirement'] == {} - stderr = capsys.readouterr().err - assert "step 'fail.wic' stays a subworkflow under --cwl_inline_subworkflows: it carries `scatter`" in stderr - assert stderr.count('Warning!') == 1 - - -@pytest.mark.fast -def test_the_when_partial_failure_adds_keeps_a_call_nested(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str]) -> None: - """The `when` partial failure gives a call gates all its inputs, so dissolving the call would drop it.""" - written = _cli(tmp_path / 'both', monkeypatch, 'multistep3', '--cwl_inline_subworkflows', - '--partial_failure_enable') - document = _document(written, 'multistep3') - assert [step['id'] for step in document['steps']] == NESTED_IDS - assert document['requirements']['SubworkflowFeatureRequirement'] == {} - stderr = capsys.readouterr().err - assert "stays a subworkflow under --cwl_inline_subworkflows: it carries `when`" in stderr - - -XFORM: Yaml = {'id': 'xform', 'in': {'name': {'wic_inline_input': 'b'}}} - - -def _called(subtree: Yaml | None = None, **call: Any) -> Yaml: - """A step that runs `child.wic` (one `xform` unless `subtree`), with `call` keys of its own.""" - return {**subworkflow_step('child.wic', subtree or {'steps': [XFORM]}), 'parentargs': call} - - -def _nested(**call: Any) -> CompilationArtifact: - return compile_hermetic({'steps': [MK_FILE, _called(**call)]}, 'wf').artifact - - -def _stays(artifact: CompilationArtifact, capsys: pytest.CaptureFixture[str]) -> str: - """Flatten, assert the call kept its place as a Workflow, and return what was said on stderr.""" - flat = post_compile.flatten_subworkflows(artifact) - assert [step['id'] for step in flat.cwl['steps']] == [step['id'] for step in artifact.cwl['steps']] - assert flat.children[1].cwl['class'] == 'Workflow' - assert flat.cwl['requirements']['SubworkflowFeatureRequirement'] == {} - return capsys.readouterr().err - - -@pytest.mark.fast -@pytest.mark.parametrize('case', cases('kept_calls', 'root', 'child', 'call', 'kept')) -def test_a_call_dissolves_unless_it_or_its_child_says_otherwise(case: Yaml, capsys: pytest.CaptureFixture[str]) -> None: - """A kept call keeps its place as a Workflow and the root its requirements, and one line says why; a dissolved - call says nothing. `scatter` is pinned end to end by `test_a_scattered_call_stays_nested...`.""" - child = {**case.get('child', {}), 'steps': [XFORM]} - artifact = compile_hermetic({**case.get('root', {}), 'steps': [MK_FILE, _called(child, **case.get('call', {}))]}, - 'wf').artifact - if case['kept']: - assert f"step 'child.wic' stays a subworkflow under --cwl_inline_subworkflows: {case['kept']}" in _stays( - artifact, capsys) - assert post_compile.flatten_subworkflows(artifact).cwl['requirements'] == artifact.cwl['requirements'] - else: + both = _cli(tmp_path / 'both', monkeypatch, 'multistep3', '--cwl_inline_subworkflows', '--cwl_inline_runtag') + assert sorted(path.name for path in both.iterdir()) == ['multistep3.cwl', 'multistep3_inputs.yml'] + assert [(step['id'], step['run']['class']) for step in _document(both, 'multistep3')['steps']] == \ + [(name, 'CommandLineTool') for name in flat_ids] + (echo,) = _document(_cli(tmp_path / 'hello', monkeypatch, 'helloworld', '--cwl_inline_runtag'), + 'helloworld')['steps'] + assert echo['run']['hints']['NetworkAccess'] == {'networkAccess': True} + + kept: dict[str, Any] = {} + for name, workflow, step, flags in (('scattered', 'test_rand_fail', 'fail', ()), + ('gated', 'multistep3', 'append_twice', ('--partial_failure_enable',))): capsys.readouterr() - assert all(child.cwl['class'] != 'Workflow' for child in post_compile.flatten_subworkflows(artifact).children) - assert 'Warning!' not in capsys.readouterr().err - - -@pytest.mark.fast -def test_a_call_stays_nested_when_dissolving_it_would_have_to_guess(capsys: pytest.CaptureFixture[str]) -> None: - """Each boundary the flat form cannot remove without guessing keeps its call, with the reason.""" - merged = _nested() - name = next(iter(merged.cwl['steps'][1]['in'])) - merged.cwl['steps'][1]['in'][name] = {'source': 'a', 'valueFrom': '$(self)'} - assert f"input '{name}' is bound to" in _stays(merged, capsys) - - defaulted = _nested() - (child,) = (c for c in defaulted.children if c.cwl['class'] == 'Workflow') - next(iter(child.cwl['inputs'].values()))['default'] = 'x' - assert 'has a default' in _stays(defaulted, capsys) - - listed = _nested() - (child,) = (c for c in listed.children if c.cwl['class'] == 'Workflow') - child.cwl['requirements'] = [{'class': 'EnvVarRequirement', 'envDef': {'A': 'b'}}] - assert "its workflow's requirements are written as a list" in _stays(listed, capsys) - - -@pytest.mark.fast -def test_a_kept_call_does_not_stop_the_others_from_flattening(capsys: pytest.CaptureFixture[str]) -> None: - """Calls are judged one at a time; a reference to a dissolved call's output is rewired past a kept one.""" - two = {'steps': [MK_FILE, _called({'wic': {'inlineable': False}, 'steps': [XFORM]}), - subworkflow_step('other.wic', {'steps': [{**XFORM, 'id': 'xform'}]})]} - nested = compile_hermetic(two, 'wf').artifact - flat = post_compile.flatten_subworkflows(nested) - kinds = [(step['id'], child.cwl['class']) for step, child in zip(flat.cwl['steps'], flat.children)] - assert kinds == [('mk_file', 'CommandLineTool'), ('child', 'Workflow'), - ('other~xform', 'CommandLineTool')] - assert capsys.readouterr().err.count('Warning!') == 1 - - -@pytest.mark.fast -def test_flattening_moves_what_the_subworkflow_required_onto_the_steps_that_ran_under_it() -> None: - """Requirements move with the steps they applied to, and the step's own entry wins over the subworkflow's, as in - CWL; the engine's own features go to the root.""" - child = {'requirements': {'EnvVarRequirement': {'envDef': {'FOO': 'bar'}}, 'ResourceRequirement': {'ramMin': 100}}, - 'steps': [{**XFORM, 'when': '$(inputs.name != null)'}]} - nested = compile_hermetic({'steps': [MK_FILE, _called(child)]}).artifact - inner = next(c for c in nested.children if c.cwl['class'] == 'Workflow') - inner.cwl['steps'][0]['requirements'] = {'ResourceRequirement': {'ramMin': 5}} - flat = post_compile.flatten_subworkflows(nested).cwl - mk_file, xform = flat['steps'] - assert 'requirements' not in mk_file - assert xform['requirements'] == {'EnvVarRequirement': {'envDef': {'FOO': 'bar'}}, - 'ResourceRequirement': {'ramMin': 5}} - assert flat['requirements'] == {'InlineJavascriptRequirement': {}}, ( - 'the engine reads `when` against the root, so the feature goes there, and the call is gone') - - -@pytest.mark.fast -def test_an_input_the_call_leaves_unbound_keeps_what_else_the_inner_step_says_about_it() -> None: - """Unbound, a source yields null: the entry loses its source and keeps its `valueFrom`, or goes.""" - nested = _nested() - call = nested.cwl['steps'][1] - inner = next(c for c in nested.children if c.cwl['class'] == 'Workflow') - formal = next(iter(call['in'])) - del call['in'][formal] - (entry,) = (name for name, value in inner.cwl['steps'][0]['in'].items() if value == formal) - inner.cwl['steps'][0]['in'][entry] = {'source': formal, 'valueFrom': '$(self)'} - assert post_compile.flatten_subworkflows(nested).cwl['steps'][1]['in'][entry] == {'valueFrom': '$(self)'} - - -@pytest.mark.fast -def test_a_list_of_sources_that_names_a_dissolved_call_follows_its_steps() -> None: - """A merged input lists the call's output among its sources; the flat step is named instead.""" - nested = _nested() - call = nested.cwl['steps'][1] - produced = f"{call['id']}/{call['out'][0]}" - nested.cwl['steps'][0]['in']['merged'] = {'source': ['elsewhere', produced], 'linkMerge': 'merge_flattened'} - flat = post_compile.flatten_subworkflows(nested) - sources = flat.cwl['steps'][0]['in']['merged']['source'] - assert sources[0] == 'elsewhere' - assert sources[1] != produced - assert sources[1].split('/')[0] in {step['id'] for step in flat.cwl['steps']} - - -@pytest.mark.fast -def test_every_level_of_nesting_is_dissolved_and_named_for_where_the_step_came_from() -> None: - """A step in a subworkflow in a subworkflow carries both calls in its id.""" - middle = {'steps': [subworkflow_step('inner.wic', {'steps': [XFORM]})]} - nested = compile_hermetic({'steps': [MK_FILE, subworkflow_step('middle.wic', middle)]}, 'wf').artifact - flat = post_compile.flatten_subworkflows(nested) - assert [step['id'] for step in flat.cwl['steps']] == [ - 'mk_file', 'middle~inner~xform'] - assert [child.namespace for child in flat.children] == [(step['id'],) for step in flat.cwl['steps']] - assert all(child.cwl['class'] == 'CommandLineTool' for child in flat.children) - assert flat.job_inputs == nested.job_inputs - - -@pytest.mark.fast -def test_a_call_left_nested_inside_a_dissolved_workflow_keeps_the_subworkflow_requirement( - capsys: pytest.CaptureFixture[str]) -> None: - """The root still contains a Workflow step, so it still declares `SubworkflowFeatureRequirement`.""" - middle = {'steps': [subworkflow_step('inner.wic', {'wic': {'inlineable': False}, 'steps': [XFORM]})]} - nested = compile_hermetic({'steps': [MK_FILE, subworkflow_step('middle.wic', middle)]}, 'wf').artifact - flat = post_compile.flatten_subworkflows(nested) - assert [child.cwl['class'] for child in flat.children] == ['CommandLineTool', 'Workflow'] - assert flat.cwl['requirements']['SubworkflowFeatureRequirement'] == {} - assert 'it is marked `wic: inlineable: false`' in capsys.readouterr().err - - -@pytest.mark.fast -def test_the_flags_apply_shape_first_and_do_not_depend_on_each_other() -> None: - """Each flag alone, and both, from one nested workflow.""" - nested = _nested() - flat = post_compile.apply_inline_options(nested, subworkflows=True, runtag=False) - embedded = post_compile.apply_inline_options(nested, subworkflows=False, runtag=True) - both = post_compile.apply_inline_options(nested, subworkflows=True, runtag=True) - assert post_compile.apply_inline_options(nested, subworkflows=False, runtag=False) is nested - assert all(isinstance(step['run'], str) for step in flat.cwl['steps']) - assert embedded.cwl['steps'][1]['run']['class'] == 'Workflow' - assert [step['run']['class'] for step in both.cwl['steps']] == ['CommandLineTool'] * 2 - assert [step['id'] for step in both.cwl['steps']] == [step['id'] for step in flat.cwl['steps']] + written = _cli(tmp_path / name, monkeypatch, workflow, '--cwl_inline_subworkflows', *flags) + call = next(each for each in _document(written, workflow)['steps'] if each['id'] == step) + assert (written / call['run']).is_file() and _document(written, workflow)['requirements'][ + 'SubworkflowFeatureRequirement'] == {} + kept[name] = [line for line in capsys.readouterr().err.splitlines() if line.startswith('Warning!')] + assert match({'scattered': [{'contains': ["step 'fail.wic'", 'carries `scatter`']}], + 'gated': [{'contains': ["step 'append_twice.wic'", 'carries `when`']}]}, kept) diff --git a/tests/core/test_leak_boundary.py b/tests/core/test_leak_boundary.py index 56316b193..24db0cf9a 100644 --- a/tests/core/test_leak_boundary.py +++ b/tests/core/test_leak_boundary.py @@ -1,15 +1,13 @@ -"""The leak boundary against the real compiler: passthrough keys survive byte-identically, none is both interpreted -and passed through, the interpreted set is exhaustive and the residue validates; owned keys are pinned one by one.""" -import copy -import tempfile +"""The leak boundary against the real compiler: keys the language does not claim survive byte for byte and change +nothing else, and the residue validates as CWL. What the compiler does with the keys it owns is stated by +tests/core/data/compiler/boundary.""" from pathlib import Path -from typing import Any, cast - -from functools import partial +import tempfile +from typing import Any import pytest import yaml -from hypothesis import HealthCheck, given, settings +from hypothesis import HealthCheck, example, given, settings from hypothesis import strategies as st import sophios.post_compile @@ -17,309 +15,81 @@ from sophios.lang.cwl import CWL_VERSION from sophios.wic_types import Yaml +from . import ast_strategies as strat from .ast_strategies import hints_values, passthrough_keys, passthrough_values -from .compile_harness import COMPILED, FAST, compile_cwl, compile_info +from .compile_harness import COMPILED, compile_info from .cwl_validation import validate_cwl from .hermetic import compile_hermetic_cwl -#: Top-level keys the *compiler* owns, which is a larger set than the syntax -#: layer's. `_document` claims only `steps` and `wic`; `compile_workflow` also -#: writes `class` and `cwlVersion`, merges into `inputs`, `outputs` and -#: `requirements`, and reads `outputSource` out of the `outputs` you supply. -#: These properties drive the compiler, so they must exclude what the compiler -#: owns — the old filter named the parser's two and was saved from the rest -#: only by the improbability of `st.text` spelling `class`, which is safety by -#: luck rather than by statement. +#: Top-level keys the *compiler* owns, a larger set than the parser claims: it writes `class` and `cwlVersion`, +#: merges into `inputs`, `outputs` and `requirements`, and keeps `$namespaces` and `$schemas` by its own rules. COMPILER_OWNED_TOP_KEYS = frozenset({ - 'steps', 'wic', 'class', 'cwlVersion', 'inputs', 'outputs', 'requirements', - '$namespaces', '$schemas', + 'steps', 'wic', 'class', 'cwlVersion', 'inputs', 'outputs', 'requirements', '$namespaces', '$schemas', }) -#: `compile_cwl` under this file's name, so every call site reads the same. -_compile = partial(compile_cwl, name='leak') -_hermetic = partial(compile_hermetic_cwl, name='leak') - - -def _step(cwl: Yaml) -> Yaml: - """The single step of a compiled one-step workflow, as the live sub-dict (callers mutate it); `steps` is always a - list.""" - return cast(Yaml, cwl['steps'][0]) - - -def _touch_workflow(extra_step_keys: dict[str, Any], extra_top_keys: dict[str, Any]) -> Yaml: - """A minimal real workflow carrying the given passthrough freight.""" - return { - **extra_top_keys, - 'steps': [{'id': 'touch', - 'in': {'filename': {'wic_inline_input': 'empty.txt'}}, - **extra_step_keys}], - } - - -def _mk_file_workflow(extra_step_keys: dict[str, Any], extra_top_keys: dict[str, Any]) -> Yaml: - """The synthetic mk_file, for `_hermetic`; `_touch_workflow` is the real registry's tool, for `_compile`.""" - return {**extra_top_keys, 'steps': [{'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'empty.txt'}}, - **extra_step_keys}]} - - -@pytest.mark.slow -@given(st.dictionaries(passthrough_keys, passthrough_values, min_size=1, max_size=4)) -@COMPILED -def test_step_passthrough_is_byte_identical(freight: dict[str, Any]) -> None: - """A step key outside the claimed set survives compilation unchanged.""" - compiled = _hermetic(_mk_file_workflow(freight, {})) - step = _step(compiled) - for key, value in freight.items(): - assert step[key] == value, f'{key} was altered by compilation' - - -@pytest.mark.slow -@given(st.dictionaries(passthrough_keys.filter(lambda k: k not in COMPILER_OWNED_TOP_KEYS), - passthrough_values, min_size=1, max_size=3)) -@COMPILED -def test_top_level_passthrough_is_byte_identical(freight: dict[str, Any]) -> None: - """An uninterpreted top-level key survives compilation unchanged.""" - compiled = _hermetic(_mk_file_workflow({}, freight)) - for key, value in freight.items(): - assert compiled[key] == value, f'{key} was altered by compilation' - - -@pytest.mark.slow -@given(hints_values) -@COMPILED -def test_hints_survive_on_the_document_and_the_step_and_change_nothing_else(hints: dict[str, Any]) -> None: - """`hints:` is read by the parser, so it is generated as the mapping the parser keeps.""" - without = _hermetic(_mk_file_workflow({}, {})) - with_hints = _hermetic(_mk_file_workflow({'hints': hints}, {'hints': hints})) - assert _step(with_hints).pop('hints') == hints - assert with_hints.pop('hints') == hints - assert with_hints == without - - -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -@pytest.mark.parametrize('key', ['requirements', 'hints']) -def test_a_list_holding_an_import_is_emitted_as_authored_on_the_document_and_the_step(key: str) -> None: - """cwltool resolves an `$import` entry, so a list holding one reaches the emitted document untouched.""" - def entries() -> list[dict[str, Any]]: - return [{'$import': 'shared.yml'}, {'class': 'ResourceRequirement', 'coresMin': 1}] - - compiled = _compile(_touch_workflow({key: entries()}, {key: entries()})) - assert compiled[key] == entries() - assert _step(compiled)[key] == entries() - - -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -def test_a_requirements_list_holding_an_import_is_not_merged_into() -> None: - """The one `requirements:` that is not extended: a list holding an `$import` is emitted as written. - - The file it names is read only by cwltool, so the compiler adds nothing to - it, not the `ScatterFeatureRequirement` a scattering step needs. - """ - authored = [{'$import': 'shared.yml'}] - compiled = _compile({ - 'requirements': copy.deepcopy(authored), - 'steps': [{'id': 'touch', 'in': {'filename': {'wic_inline_input': ['a.txt', 'b.txt']}}, - 'scatter': ['filename']}], - }) - assert compiled['requirements'] == authored - - -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -@pytest.mark.parametrize('key', ['inputs', 'outputs']) -def test_a_root_inputs_or_outputs_list_holding_an_import_is_not_carried_into_the_output(key: str) -> None: - """The compiler models only the mapping form of `inputs:` and `outputs:`; the list is neither merged nor emitted.""" - compiled = _compile(_touch_workflow({}, {key: [{'$import': 'shared.yml'}]})) - assert '$import' not in yaml.safe_dump(compiled) - - -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -def test_user_namespaces_survive_and_edam_is_edams_where_a_format_says_it() -> None: - """`$namespaces` keeps every user binding. In a document whose formats say - `edam:`, the compiler reads those CURIEs as EDAM's and binds `edam` to the - canonical URL over the user's; in one whose formats do not, the user's - `edam` binding is theirs and survives too. - """ - bindings = {'$namespaces': {'mine': 'https://mine/', 'edam': 'https://not-edam/'}} - unused = _compile(_touch_workflow({}, bindings)) - assert unused['$namespaces'] == {'mine': 'https://mine/', 'edam': 'https://not-edam/'} - used = _compile(_touch_workflow({}, {**bindings, 'inputs': {'f': {'type': 'File', 'format': 'edam:format_2330'}}})) - assert used['$namespaces'] == {'mine': 'https://mine/', 'edam': 'https://edamontology.org/'} - - -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -def test_class_is_written_while_inputs_outputs_and_version_are_not() -> None: - """The other four compiler-owned keys, each behaving differently. - - These four had no test behind them, and the footnote claiming each was - pinned was wrong about three: `inputs`/`outputs` are merged, not written - (`{**yours, **generated}`, so your entry survives unless the compiler - generates the same name), and `cwlVersion` used to be *defaulted* — a - document declaring `v1.0` kept it and still received `when:`, emitting CWL - that cwltool rejects against the version it names. The compiler now writes - it. A row asserting facts about the compiler needs a test per fact, or it - is prose that drifts. - """ - # `outputs` entries are *read*, not merely kept: the compiler pulls - # `outputSource` out of each one, so a supplied entry needs a real one. - user_output = {'type': 'File', 'outputSource': 'touch/file'} - compiled = _compile({ - 'class': 'ExpressionTool', # a lie the compiler must overwrite - 'inputs': {'mine': {'type': 'string'}}, - 'outputs': {'mine': user_output}, - 'cwlVersion': 'v1.0', # older than the declared substrate - **_touch_workflow({}, {}), - }) - - assert compiled['class'] == 'Workflow', 'class is written, not merged' - assert compiled['inputs']['mine'] == {'type': 'string'}, 'user input lost' - assert len(compiled['inputs']) > 1, 'compiler inputs not merged alongside' - # Kept entry, rewritten reference: `outputSource` is the one field of a - # supplied output the compiler must not carry through, because emission - # renames the step it names. Asserting the authored spelling survived was - # asserting a document cwltool rejects. - assert compiled['outputs']['mine'] == { - **user_output, 'outputSource': 'touch/file', - }, 'user output lost, or its source not rewritten to the emitted step' - assert len(compiled['outputs']) > 1, 'compiler outputs not merged alongside' - - # The compiler wins. Sophios generates for one substrate version, so a - # document cannot claim another and still be valid: declaring v1.0 and - # receiving `when:` produced CWL that cwltool rejects. The tag is ignored - # with a warning rather than refused — a stale pin should not stop a - # workflow compiling. - assert compiled['cwlVersion'] == CWL_VERSION, 'a supplied cwlVersion must not win' - - -@pytest.mark.package -@pytest.mark.fast -@pytest.mark.parametrize('key', sorted(Grammar.INTERPRETED_STEP_KEYS)) -def test_every_declared_key_is_interpreted(key: str) -> None: - """Exhaustive half: each declared key routes to `interpreted`.""" - result = parse(f'steps:\n- id: s\n {key}: x\n', 'p11.wic') - assert result.document is not None - step = result.document.steps[0] - assert key in dict(step.interpreted) - assert key not in dict(step.passthrough) - - -@pytest.mark.fast -@given(passthrough_keys) -@FAST -def test_no_key_lands_on_both_sides(key: str) -> None: - """Generated half: any other key routes to passthrough, never both.""" - result = parse(f'steps:\n- id: s\n {key}: x\n', 'p11.wic') - assert result.document is not None - step = result.document.steps[0] - interpreted, passthrough = dict(step.interpreted), dict(step.passthrough) - assert key in passthrough - assert key not in interpreted - assert not set(interpreted) & set(passthrough) - - @pytest.mark.slow -@given(passthrough_keys, passthrough_values) +@given(st.data()) @COMPILED -def test_unknown_keys_change_nothing_else(key: str, value: Any) -> None: - """Adding an uninterpreted key changes exactly that key and nothing - else in the output — the observable meaning of "not interpreted". - """ - without = _hermetic(_mk_file_workflow({}, {})) - with_key = _hermetic(_mk_file_workflow({key: value}, {})) - - # The whole document, not just the step: the requirement merge reads - # step facts and writes a *top-level* key, so a step key reaching that path - # would change the document while leaving the step subtree identical — and - # comparing only the step would call that inert. `_step` returns a - # reference into `with_key`, so popping there removes the key from the - # document being compared. - assert _step(with_key).pop(key) == value - assert with_key == without, f'{key} altered more than itself' - - -#: Passthrough spelled in CWL vocabulary, because CWL v1.2 itself rejects -#: unknown step fields — arbitrary keys are covered by the fidelity properties -#: above, but a document carrying them is not *valid CWL*, and this last claim -#: is about validity. -cwl_passthrough = st.fixed_dictionaries( - {}, - optional={ - 'label': st.text('abc xyz', min_size=1, max_size=20), - 'doc': st.text('abc xyz.', min_size=1, max_size=40), - 'hints': st.just({'LoadListingRequirement': {'loadListing': 'shallow_listing'}}), - }, -) +def test_freight_survives_byte_for_byte_and_changes_nothing_else(data: st.DataObject) -> None: + """Step keys outside the claimed set, top-level keys outside the compiler's, and `hints:` on the document and the + step survive compilation unchanged, and compiled without them the document is the same: the observable meaning of + "not interpreted". The document has several steps and the freighted one scatters, so the requirement merge, which + reads step facts and writes a top-level key, fires beside the freight. The parser routes each freight key, and + no claimed one, to a step's passthrough, and each claimed key to what it interprets, never to both.""" + document, index = data.draw(strat.freighted_documents()) + step_freight = data.draw(st.dictionaries(passthrough_keys, passthrough_values, min_size=1, max_size=4)) + top_freight = data.draw(st.dictionaries(passthrough_keys.filter(lambda key: key not in COMPILER_OWNED_TOP_KEYS), + passthrough_values, max_size=3)) + hints = data.draw(hints_values) + hinted = {'hints': hints} if hints else {} + freighted = strat.to_yml_with_freight(document, index, {**step_freight, **hinted}) + freighted.update(top_freight, **hinted) + + compiled = compile_hermetic_cwl(freighted) + assert 'ScatterFeatureRequirement' in compiled['requirements'] + step = compiled['steps'][index] + for key, value in {**step_freight, **hinted}.items(): + assert step.pop(key) == value, f'{key} was altered by compilation' + for key, value in {**top_freight, **hinted}.items(): + assert compiled.pop(key) == value, f'{key} was altered by compilation' + assert compiled == compile_hermetic_cwl(strat.to_yml(document)) + + for key in [*step_freight, *Grammar.INTERPRETED_STEP_KEYS]: + parsed = parse(f'steps:\n- id: s\n {key}: x\n', 'freight.wic').document + assert parsed is not None + routed = (key in dict(parsed.steps[0].interpreted), key in dict(parsed.steps[0].passthrough)) + assert routed == ((True, False) if key in Grammar.INTERPRETED_STEP_KEYS else (False, True)), key + + +#: Passthrough spelled in CWL vocabulary: CWL v1.2 rejects unknown step fields, so arbitrary keys are the property +#: above's, and this one's claim is validity. +cwl_passthrough = st.fixed_dictionaries({}, optional={ + 'label': st.text('abc xyz', min_size=1, max_size=20), + 'doc': st.text('abc xyz.', min_size=1, max_size=40), + 'hints': st.just({'LoadListingRequirement': {'loadListing': 'shallow_listing'}}), +}) @pytest.mark.needs_cwltool @pytest.mark.skip_pypi_ci @pytest.mark.slow -# Ten examples, not the shared hundred: `cwl_passthrough` varies only in which -# of three optional keys are present — eight shapes — and the free text inside -# `label`/`doc` cannot change whether a document is valid CWL. Hypothesis keeps -# drawing new strings and so never detects the exhaustion, spending about a -# minute and a half of CI on a claim eight examples settle. -@given(cwl_passthrough) +# Ten examples, not the shared hundred: `cwl_passthrough` varies only in which of three optional keys are present, +# and the free text inside `label`/`doc` cannot change whether a document is valid CWL. +@given(cwl_passthrough, st.booleans()) +@example({}, True) @settings(max_examples=10, suppress_health_check=[HealthCheck.too_slow], deadline=None) -def test_residue_validates_as_cwl_v1_2(freight: dict[str, Any]) -> None: - """Strip the Sophios syntax, inline the tools, and cwltool agrees the - residue is CWL v1.2.""" - info = compile_info(_touch_workflow(freight, {}), 'leak') - inlined = sophios.post_compile.inline_artifact_runs(info.artifact).cwl - - # A throwaway file, not a repo artifact: it exists only to hand cwltool a - # path. `tmp_path` would be the obvious choice, but it is function-scoped - # and Hypothesis rightly refuses to reuse one fixture across examples. +def test_residue_validates_as_cwl_v1_2(freight: dict[str, Any], authored: bool) -> None: + """Strip the Sophios syntax, inline the tools, and cwltool agrees the residue is CWL v1.2. An `outputSource:` the + author wrote names a step cwltool finds: the workflow strategy never writes one, and the authored path once + carried the document's own spelling into a document whose steps are all renamed.""" + workflow: Yaml = {'steps': [{'id': 'touch', 'in': {'filename': {'wic_inline_input': 'empty.txt'}}, **freight}]} + if authored: + workflow['outputs'] = {'mine': {'type': 'File', 'outputSource': 'touch/file'}} + inlined = sophios.post_compile.inline_artifact_runs(compile_info(workflow, 'leak').artifact).cwl + assert not authored or inlined['outputs']['mine']['outputSource'] == 'touch/file' with tempfile.TemporaryDirectory() as workdir: target = Path(workdir) / 'residue.cwl' target.write_text(yaml.safe_dump(inlined, sort_keys=False), encoding='utf-8') assert validate_cwl(str(target)) == 0 assert inlined['cwlVersion'] == CWL_VERSION - - -@pytest.mark.needs_cwltool -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -def test_an_authored_output_source_validates() -> None: - """A supplied `outputSource` names a step cwltool can find. - - Planted rather than generated: the workflow strategy never writes an - authored `outputSource:`, so the property above reaches only the - synthesized path, which computes the emitted step name correctly. The - authored path carried the document's own spelling through to a document - whose steps are all renamed, and nothing looked until a runner did. - """ - info = compile_info({ - 'outputs': {'mine': {'type': 'File', 'outputSource': 'touch/file'}}, - **_touch_workflow({}, {}), - }, 'leak') - inlined = sophios.post_compile.inline_artifact_runs(info.artifact).cwl - assert inlined['outputs']['mine']['outputSource'] == 'touch/file' - with tempfile.TemporaryDirectory() as workdir: - target = Path(workdir) / 'authored_output_source.cwl' - target.write_text(yaml.safe_dump(inlined, sort_keys=False), encoding='utf-8') - assert validate_cwl(str(target)) == 0 - - -@pytest.mark.skip_pypi_ci -@pytest.mark.fast -def test_allow_raw_cwl_is_the_difference_between_report_and_compile() -> None: - """A bare unresolved name is reported without the flag and compiles - with it — the flag's one-line definition, observed at the boundary.""" - from sophios.lang.diagnostics import SophiosError - from sophios.lang.error_codes import SophiosErrorCode - - bare: Yaml = {'steps': [{'id': 'touch', 'in': {'filename': 'not_a_workflow_input'}}]} - - with pytest.raises(SophiosError) as caught: - _compile(bare) - assert caught.value.diagnostics[0].code is SophiosErrorCode.UNRESOLVED_INPUT - assert '!ii' in caught.value.diagnostics[0].message - - permitted = compile_cwl(bare, 'raw_cwl', allow_raw_cwl=True) - assert permitted['class'] == 'Workflow' diff --git a/tests/core/test_link.py b/tests/core/test_link.py deleted file mode 100644 index 9f373bedb..000000000 --- a/tests/core/test_link.py +++ /dev/null @@ -1,180 +0,0 @@ -"""Pure graph composition, reference linking and obligation discharge: lowest-common-ancestor ownership, wrapper output -redirection, omitted call arguments (cross-scope cases by code and edge source: data/edge-binding/cross_scope.yaml).""" -import pytest - -from sophios.ir import ( - Namespace, - RegistrySnapshot, - WorkflowGraph, - front_end, - link, -) -from sophios.ir.complete import complete -from sophios.ir.pipeline import FrontEndResult -from sophios.ir.types import AuthoredName -from sophios.lang import SophiosErrorCode, parse -from sophios.wic_types import StepId as LegacyStepId, Tool, Tools - -from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS, clt, registered - - -def _rooted(root: str, tools: Tools = SYNTHETIC_TOOLS, **children: str) -> FrontEndResult: - """`root` through the front end, against `tools` and the named child sources.""" - registry = RegistrySnapshot.from_tools(tools, workflows={ - (SYNTHETIC_NS, name): parse(text, f'{name}.wic') for name, text in children.items()}) - return front_end(parse(root, 'root.wic'), registry, name='root') - - -def _cross_scope(*, wrapped: bool = False) -> WorkflowGraph: - """`root` defines the edge `shared` with a string source and calls child.wic, whose mk_file consumes it; with - `wrapped`, root calls wrapper.wic, which calls child.wic, so the consumer sits two documents below.""" - tools = registered({'string_source': clt({}, {'value': {'type': 'string'}})}) - root = ('steps:\n- id: string_source\n out:\n - value: !& shared\n' - f'- id: {"wrapper" if wrapped else "child"}.wic\n') - result = _rooted(root, tools, child='steps:\n- id: mk_file\n in:\n name: !* shared\n', - **({'wrapper': 'steps:\n- id: child.wic\n'} if wrapped else {})) - assert result.graph is not None and result.resolved is not None - return result.graph - - -@pytest.mark.fast -@pytest.mark.parametrize(('source_type', 'codes'), [ - pytest.param('int', [SophiosErrorCode.INCOMPATIBLE_INPUT_REFERENCE], id='proven-disjoint'), - pytest.param('Any', [], id='opaque-any'), -]) -def test_only_proven_disjoint_cross_scope_types_are_rejected(source_type: str, codes: list[SophiosErrorCode]) -> None: - """Known incompatibility rejects; opaque Any remains delegated to final CWL validation.""" - tools = {**SYNTHETIC_TOOLS, LegacyStepId('typed_source', SYNTHETIC_NS): Tool( - '/synthetic/typed_source.cwl', clt({}, {'value': {'type': source_type}}))} - root = 'steps:\n- id: typed_source\n out:\n - value: !& shared\n- id: child.wic\n' - typed = _rooted(root, tools, child='steps:\n- id: mk_file\n in:\n name: !* shared\n') - assert typed.graph is not None - linked = link(typed.graph) - assert [diagnostic.code for diagnostic in linked.diagnostics] == codes - assert (linked.graph is None) is bool(codes) - - -@pytest.mark.fast -def test_cross_scope_obligation_discharged_two_levels_below_the_definition() -> None: - """A child two documents under the edge's definition still compiles. - - `prod.wic`, called from `basic.wic`, called from `stability.wic`, - consumes an edge only an ancestor's sibling defines. Building the - intermediate `wrapper.wic` graph while placing that discharge must not - raise, the obligation must end up fully discharged, and the boundary - name it is threaded through must resolve to the same sink at every - level on the way down -- never to a port that level's own steps do not - declare. - """ - typed = _cross_scope(wrapped=True) - linked = link(typed) - assert linked.graph is not None, list(linked.diagnostics) - assert linked.graph.obligations == () - assert len(linked.graph.linked_edges) == 1 - edge = linked.graph.linked_edges[0] - - wrapper = linked.graph.children[0] - child = wrapper.children[0] - assert not wrapper.linked_edges and not child.linked_edges - assert child.steps[0].inputs[0].id == edge.sink - - assert {port.name for port in wrapper.workflow_inputs} == \ - {name for name, _ in wrapper.input_mapping} - for _name, sinks in wrapper.input_mapping: - assert sinks == (edge.sink,) - for _name, sinks in child.input_mapping: - assert sinks == (edge.sink,) - - -@pytest.mark.fast -def test_wrapper_output_anchor_moves_to_the_concrete_producer() -> None: - """A call output is an interface; the child step is the value's producer.""" - child = ''' -steps: -- id: mk_file - in: {name: !ii child.txt} -outputs: - result: - type: File - outputSource: mk_file/file -''' - root = ''' -steps: -- id: child.wic - out: - - result: !& made -- id: count - in: {file: !* made} -''' - typed = _rooted(root, child=child) - assert typed.graph is not None - linked = link(typed.graph) - assert linked.graph is not None, list(linked.diagnostics) - edge = next(edge for edge in linked.graph.edges if edge.sink.step.name == 'count') - assert edge.source.step.name == 'mk_file' - assert edge.source.step.namespace.parts - - -@pytest.mark.fast -def test_omitted_nested_argument_remains_available_to_infer() -> None: - """Link does not synthesize a call binding for an omitted child input.""" - child = ''' -inputs: {name: {type: string}} -steps: -- id: mk_file - in: {name: name} -''' - typed = _rooted('steps:\n- id: child.wic\n', child=child) - assert typed.graph is not None - linked = link(typed.graph) - assert linked.graph is not None, list(linked.diagnostics) - wrapper = linked.graph.steps[0] - child_graph = linked.graph.children[0] - child_step = child_graph.steps[0] - assert wrapper.bindings == () - assert child_step.inputs and child_step.bindings - assert dict(child_graph.input_mapping)[AuthoredName('name')] == (child_step.inputs[0].id,) - - -@pytest.mark.fast -def test_graph_rejects_a_planted_namespace_collision() -> None: - """The injectivity assertion demonstrably detects a duplicate child graph.""" - typed = _cross_scope() - child = typed.children[0] - with pytest.raises(ValueError, match='injective'): - WorkflowGraph(Namespace(), children=(child, child)) - - -@pytest.mark.fast -def test_a_wrapper_scatters_a_declared_input_threaded_to_another_name() -> None: - """A callee may thread a declared input to an inner port of another name. - - `gen_topol_params.wic` declares `input_receptor_xyz_path` and scatters it; - the step that actually consumes it is `combine_structure.input_structure1`. - The wrapper's `scatter:` list can only name the boundary, so matching it - against the inner port's own name -- or against the mangled name an - inferred input would get -- finds neither, drops the layer, and reports a - producer's `File[]` as disjoint from a `File` it in fact feeds one element - of. The child's `input_mapping` already records which boundary reaches - which sink, and is what `complete._direct_sink` walks for the same edge. - """ - tools = dict(SYNTHETIC_TOOLS) - tools[LegacyStepId('make', SYNTHETIC_NS)] = Tool( - '/synthetic/make.cwl', clt({'seed': {'type': 'string'}}, {'value': {'type': 'File'}})) - tools[LegacyStepId('take', SYNTHETIC_NS)] = Tool( - '/synthetic/take.cwl', clt({'inner_name': {'type': 'File'}}, {})) - - producer = ('inputs:\n seed: {type: string}\n' - 'steps:\n- id: make\n in: {seed: seed}\n out:\n - value: !& shared\n') - # Declared as `outer_name`, consumed as `inner_name`: the two differ. - consumer = ('inputs:\n outer_name: {type: File}\n' - 'steps:\n- id: take\n in: {inner_name: outer_name}\n') - root = ('steps:\n' - '- id: producer.wic\n in: {seed: !ii [a, b]}\n scatter: [seed]\n' - '- id: consumer.wic\n in: {outer_name: !* shared}\n scatter: [outer_name]\n') - - typed = _rooted(root, tools, producer=producer, consumer=consumer) - assert typed.graph is not None, list(typed.diagnostics) - - linked = link(complete(typed.graph)) - assert linked.graph is not None, [str(item) for item in linked.diagnostics] diff --git a/tests/core/test_lower.py b/tests/core/test_lower.py index 6ee9bb037..487a91fe3 100644 --- a/tests/core/test_lower.py +++ b/tests/core/test_lower.py @@ -1,34 +1,24 @@ -"""Lowering a resolved document to a graph: total, every reference names an existing port, passthrough is never read, -iteration order is irrelevant. The test-side resolver needs no registry, filesystem or config.""" +"""Lowering a resolved document to a graph: total, every reference names an existing port, every authored binding +kept, deterministic; and each document of tests/core/data/lower lowers to the diagnostics its expected.yaml states. +The test-side resolver needs no registry, filesystem or config.""" import json -from typing import Any +from dataclasses import replace import pytest from hypothesis import example, given -from sophios.ir import ( - Direction, - Namespace, - PortId, - RegistryKey, - ResolvedDocument, - ResolvedPort, - ResolvedProcess, - ResolvedStep, - StepId, - WorkflowGraph, -) -from sophios.ir.lower import lower +from sophios.ir import (Direction, PortId, RegistryKey, ResolvedDocument, ResolvedPort, ResolvedProcess, + ResolvedStep, StepId, WorkflowGraph) from sophios.ir.declarations import port_declaration +from sophios.ir.lower import lower from sophios.ir.types import AuthoredName -from sophios.lang.diagnostics import SophiosError -from sophios.lang.error_codes import SophiosErrorCode from sophios.lang.nodes import Document, Step from sophios.lang.parser import parse from . import ast_strategies as strat -from .cases import cases, diagnostic, match -from .hermetic import COVERAGE, ORACLE, compile_hermetic, compile_hermetic_cwl, subworkflow_step +from .cases import DATA, diagnostic, match +from .hermetic import COVERAGE, ORACLE +from .helpers import stated from .strategies import shapes @@ -60,98 +50,51 @@ def _resolved(document: Document) -> ResolvedDocument: return ResolvedDocument('probe', document, steps, '0.0.1') -def _lower(source: str) -> Any: - """Parse and lower one document, for the example-based claims below.""" - document = parse(source, 'probe.wic').document - assert document is not None - return lower(_resolved(document)) - - @pytest.mark.fast -@pytest.mark.parametrize('case', cases('lower', 'source', 'graph', 'diagnostics')) -def test_lower_case(case: dict[str, Any]) -> None: - """`source` lowers to exactly `diagnostics`, and to no graph where `graph` is false, for the case's `why`.""" - result = _lower(case['source']) - assert match(case['diagnostics'], [diagnostic(d) for d in result.diagnostics]), list(result.diagnostics) - if 'graph' in case: - assert (result.graph is not None) is case['graph'] +def test_a_document_lowers_to_the_diagnostics_its_family_states() -> None: + """Each `.wic` of tests/core/data/lower, parsed and lowered, gives exactly the diagnostics expected.yaml lists for + it, by code, severity and line, and a graph exactly when none is an error.""" + expected = stated(DATA / 'lower') + assert sorted(expected) == sorted(path.name for path in (DATA / 'lower').glob('*.wic')) + for name, diagnostics in expected.items(): + document = parse((DATA / 'lower' / name).read_text(encoding='utf-8'), name).document + assert document is not None, name + result = lower(_resolved(document)) + found = [diagnostic(each) for each in result.diagnostics] + assert match(diagnostics, found), (name, found) + assert (result.graph is None) is result.diagnostics.has_errors, name @pytest.mark.fast @given(strat.documents()) @COVERAGE -def test_a_well_formed_document_actually_lowers(document: Document) -> None: - """`documents()` draws only well-formed documents, so every one of them - must produce a graph, never a diagnostic or an exception.""" - result = lower(_resolved(document)) +def test_a_well_formed_document_lowers_whole(document: Document) -> None: + """`documents()` draws only well-formed documents, so each lowers to a graph with a step for each of its steps, + never a diagnostic or an exception; the same graph twice, in full, mappings included, so none varies with set + iteration; with every binding written in `in:`, so Emit never reads the AST again; and with every reference its + edges, obligations and mappings hold naming a port that exists, which a dangling `source:` would not. A graph + refuses to be built holding a port no step declares, or one step twice.""" + resolved = _resolved(document) + result = lower(resolved) assert result.graph is not None, [d.code.value for d in result.diagnostics] assert len(result.graph.steps) == len(document.steps) - - -@pytest.mark.fast -@given(strat.documents()) -@COVERAGE -def test_every_reference_the_graph_holds_names_a_port_that_exists(document: Document) -> None: - """Edges, obligations and all four mappings, not the edges alone. - - An identity resolving to nothing is the same defect wherever it is stored, - and it reaches emission as a dangling `source:` -- which CWL accepts and a - runner then fails on. - """ - result = lower(_resolved(document)) - if result.graph is None: - return - known = {p.id for s in result.graph.steps for p in s.inputs + s.outputs} - for where, _name, port_id in result.graph._references(): # pylint: disable=protected-access + assert lower(resolved).graph == result.graph + assert [b.value for step in result.graph.steps for b in step.bindings] == \ + [value for step in document.steps for _, value in step.inputs] + graph = result.graph + known = {p.id for s in graph.steps for p in s.inputs + s.outputs} + for where, _name, port_id in graph._references(): # pylint: disable=protected-access assert port_id in known, f'{where} names {port_id}' - - -@pytest.mark.fast -@given(strat.documents()) -@ORACLE -def test_lowering_is_deterministic(document: Document) -> None: - """The same document lowers to the same graph, twice, in full. - - The whole graph, not a few fields: comparing only steps and edges leaves - the mappings free to vary with set iteration, which is the thing being - ruled out. - """ - resolved = _resolved(document) - first, second = lower(resolved), lower(resolved) - assert first.graph == second.graph - - -@pytest.mark.fast -@given(strat.documents()) -@COVERAGE -def test_lowering_keeps_every_authored_binding(document: Document) -> None: - """Nothing written in `in:` is dropped. - - Keeping only the edges makes two documents differing solely in a literal - lower to the same graph, so `Emit` would have to read the AST again. - """ - result = lower(_resolved(document)) - if result.graph is None: - return - authored = [v for step in document.steps for _, v in step.inputs] - carried = [b.value for step in result.graph.steps for b in step.bindings] - assert carried == authored - - -@pytest.mark.fast -def test_an_input_and_an_output_of_one_name_are_different_ports() -> None: - """CWL puts a step's inputs and outputs in separate namespaces. - - A tool declaring `file` on both is ordinary -- the synthetic registry has - them. Without direction in the identity the two compare equal, an edge - between them looks like a self-loop, and a set of port ids silently loses - one of every such pair. - """ - step = StepId(Namespace(), 1, 's') - file = AuthoredName('file') - assert PortId(step, Direction.INPUT, file) != PortId(step, Direction.OUTPUT, file) - assert len({PortId(step, Direction.INPUT, file), - PortId(step, Direction.OUTPUT, file)}) == 2 + assert {port for edge in graph.edges for port in (edge.source, edge.sink)} <= known + ghost = PortId(StepId(graph.namespace, len(graph.steps) + 1, 'ghost'), Direction.INPUT, AuthoredName('p')) + for held in ({'explicit_edge_defs': (('e', ghost),)}, {'explicit_edge_calls': (('e', ghost),)}, + {'output_mapping': ((AuthoredName('o'), ghost),)}, + {'input_mapping': ((AuthoredName('i'), (ghost,)),)}): + with pytest.raises(ValueError, match='names a port no step declares'): + replace(graph, **held) + if graph.steps: + with pytest.raises(ValueError, match='injective'): + WorkflowGraph(graph.namespace, children=(graph, graph)) @pytest.mark.fast @@ -170,95 +113,3 @@ def test_a_document_the_parser_recovered_never_raises(document: Document) -> Non """ result = lower(_resolved(document)) assert (result.graph is None) is result.diagnostics.has_errors, [str(d) for d in result.diagnostics] - - -@pytest.mark.fast -def test_a_union_member_written_either_way_parses_the_same() -> None: - """`?` on a union member makes the port optional in either spelling of that member. - - The shorthand expands; the same member written as a record does too, and a - `?` that sits on an array's items does not make the array itself optional. - """ - string = port_declaration(['File?', 'string']).type - record = port_declaration([{'type': 'array', 'items': 'string?'}, 'int']).type - assert string.optional - assert string.canonical == ['null', 'File', 'string'] - assert not record.optional - assert record.canonical == [ - {'type': 'array', 'items': ['null', 'string']}, 'int'] - - -@pytest.mark.fast -def test_a_reference_to_an_undefined_edge_becomes_an_obligation() -> None: - """What a subworkflow owes its includer has a name and a type, which is - what lets `Link` say whether every one was discharged.""" - graph = _lower('steps:\n- id: s\n in:\n f: !* from_parent\n').graph - assert graph is not None - assert [o.name for o in graph.obligations] == ['from_parent'] - assert graph.edges == () - - -@pytest.mark.fast -def test_a_reference_to_a_defined_edge_becomes_an_edge() -> None: - """The same reference, when this document produces what it names.""" - graph = _lower('steps:\n- id: mk\n out:\n - file: !& e\n- id: use\n in:\n f: !* e\n').graph - assert graph is not None - assert graph.obligations == () and len(graph.edges) == 1 - assert graph.edges[0].source.step.name == 'mk' and graph.edges[0].sink.step.name == 'use' - - -_GHOST = PortId(StepId(Namespace(), 1, 'ghost'), Direction.INPUT, AuthoredName('p')) - - -@pytest.mark.fast -@pytest.mark.parametrize(('build', 'where'), [ - (lambda: WorkflowGraph(Namespace(), explicit_edge_defs=(('e', _GHOST),)), "mapping 'e'"), - (lambda: WorkflowGraph(Namespace(), explicit_edge_calls=(('e', _GHOST),)), "mapping 'e'"), - (lambda: WorkflowGraph(Namespace(), output_mapping=((AuthoredName('o'), _GHOST),)), 'an output mapping'), - (lambda: WorkflowGraph(Namespace(), input_mapping=((AuthoredName('i'), (_GHOST,)),)), "input mapping 'i'"), -], ids=['edge defs', 'edge calls', 'output mapping', 'input mapping']) -def test_a_reference_to_a_port_no_step_declares_is_reported_where_it_is_held( - build: Any, where: str) -> None: - """The report says which mapping holds the reference and, for the ones keyed - by a name, under what name.""" - with pytest.raises(ValueError) as caught: - build() - assert str(caught.value) == f'{where} names a port no step declares: {_GHOST}' - - -@pytest.mark.fast -def test_an_anchor_on_an_undeclared_call_output_is_reported_not_raised() -> None: - """A call step anchoring a name its child never declares is wic028; the graph - is not built from a document the phase rejected, so no ValueError escapes.""" - child = {'steps': [{'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a'}}}]} - with pytest.raises(SophiosError) as caught: - compile_hermetic({'steps': [ - {**subworkflow_step('child.wic', child), - 'parentargs': {'out': [{'child__step__1__mk_file___file': {'wic_anchor': 'e'}}]}}, - {'id': 'sink', 'in': {'file': {'wic_alias': 'e'}, 'n': {'wic_inline_input': 1}}}]}) - assert {d.code for d in caught.value.diagnostics} == {SophiosErrorCode.UNDECLARED_PORT} - - -@pytest.mark.fast -@pytest.mark.parametrize('extra', [{'linkMerge': 'merge_flattened'}, {'pickValue': 'first_non_null'}, - {'outputSource': ['a/f', 'b/f']}, {'outputSource': ['s/f']}, - {'outputSource': []}]) -def test_link_merge_and_pick_value_on_an_output_are_wic038(extra: dict[str, Any]) -> None: - """CWL's merge fields on a workflow output were copied out unread, and a list - `outputSource` was emitted naming steps by their authored ids, which cwltool cannot resolve.""" - source = 'steps:\n- id: s\n out: [f]\noutputs:\n o:\n type: File\n' - for key, value in {'outputSource': 's/f', **extra}.items(): - source += f' {key}: {value}\n' - result = _lower(source) - assert SophiosErrorCode.STEP_INPUT_RECORD in {d.code for d in result.diagnostics} - - -@pytest.mark.fast -def test_scatter_ports_keep_the_authored_order() -> None: - """`scatter: [name, file]` on xform is emitted in that order: under - `nested_crossproduct` the order is the nesting of the output arrays.""" - compiled = compile_hermetic_cwl({'steps': [{'id': 'xform', 'scatter': ['name', 'file'], - 'scatterMethod': 'nested_crossproduct', - 'in': {'name': {'wic_inline_input': ['a']}, - 'file': {'wic_inline_input': ['x.txt']}}}]}) - assert compiled['steps'][0]['scatter'] == ['name', 'file'] diff --git a/tests/core/test_manufactured_documents.py b/tests/core/test_manufactured_documents.py deleted file mode 100644 index 62f234b50..000000000 --- a/tests/core/test_manufactured_documents.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Every document the compiler manufactures (the Python API's, a real-time analysis's one-step workflow) is one the -language accepts: built rather than parsed, the grammar has no say over them unless asked.""" -import importlib -from typing import Any, Final - -import pytest -import yaml - -from sophios import realtime -from sophios.cli import default_compilation_settings -from sophios.input_output import NoAliasDumper -from sophios.ir.realtime import Declaration -from sophios.lang import Document, parse, to_json -from sophios.api.python.workflow import Workflow -from sophios.wic_types import StepId, Tool - -from .helpers import ADAPTERS, HELLOWORLD, adapter_step - -#: What each site builds. Only `DOCUMENT` is a `.wic` document the language owns. -DOCUMENT: Final = 'DOCUMENT' -SCHEMA: Final = 'SCHEMA' # JSON Schema, a description of documents -RENDERER: Final = 'RENDERER' # sophios.lang's own writer, pinned separately -TOOL: Final = 'TOOL' # a CWL tool, which has `steps` only incidentally -CWL: Final = 'CWL' # compiled CWL workflow, not Sophios source -CONTRIB: Final = 'CONTRIB' # outside the core zone - -#: Every place in `src/sophios` that builds or rewrites a document-shaped object, -#: classified by hand. -MANUFACTURING_SITES: Final[dict[str, str]] = { - 'sophios/api/python/_workflow_runtime.py::workflow_document': DOCUMENT, - 'sophios/realtime.py::_wrapper': DOCUMENT, - # Not documents. - 'sophios/ir/emit.py::emit': CWL, - 'sophios/lang/render.py::_Writer.document': RENDERER, - 'sophios/lang/render.py::_Writer.sidecar': RENDERER, - 'sophios/lang/schema.py::_defs': SCHEMA, - 'sophios/utils_cwl.py::desugar_into_canonical_normal_form': TOOL, - 'sophios/contrib/converter.py::wfb_to_wic': CONTRIB, - 'sophios/contrib/rest/api.py::compile_wf': CONTRIB, -} - - -def _documents_in(value: Any, depth: int = 0) -> list[dict[str, Any]]: - """Every document-shaped mapping reachable from `value`, to a bounded depth: compiled trees are deep and self- - referential.""" - if depth > 6: - return [] - if isinstance(value, dict) and 'steps' in value: - return [value] - found: list[dict[str, Any]] = [] - if isinstance(value, dict): - for item in value.values(): - found += _documents_in(item, depth + 1) - elif isinstance(value, (list, tuple)): - for item in value: - found += _documents_in(item, depth + 1) - elif isinstance(value, Document): # the Python API builds the AST directly - found.append(to_json(value)) - return found - - -def _instrument(monkeypatch: pytest.MonkeyPatch, site: str, - seen: list[tuple[str, dict[str, Any]]]) -> None: - """Record every document-shaped object that passes through one site, arguments as well as returns: some sites - rewrite in place.""" - module_path, _, qualname = site.partition('::') - module = importlib.import_module(module_path[:-len('.py')].replace('/', '.')) - holder: Any = module - *outer, name = qualname.split('.') - for attribute in outer: - holder = getattr(holder, attribute) - original = getattr(holder, name) - - def recording(*args: Any, **kwargs: Any) -> Any: - result = original(*args, **kwargs) - for candidate in (result, *args, *kwargs.values()): - for document in _documents_in(candidate): - seen.append((site, document)) - return result - - monkeypatch.setattr(holder, name, recording) - - -def _parses(document: dict[str, Any]) -> tuple[bool, list[str]]: - """Whether `sophios.lang` accepts this document, and what it said if not, re-parsed in the desugared spelling (§2): - construct positions stay closed, a `wic_*` key elsewhere is open passthrough (§1).""" - text = yaml.dump(document, sort_keys=False, line_break='\n', indent=2, Dumper=NoAliasDumper) - result = parse(text, 'manufactured.wic') - return result.ok, [f'{d.code} at {d.span.start_line}:{d.span.start_column}' - for d in result.diagnostics if d.span] - - -@pytest.mark.fast -def test_every_manufactured_document_is_one_the_language_accepts() -> None: - """Whatever the compiler makes, `sophios.lang` parses. - - The documents are taken from the compiler while it runs rather than - rebuilt here, because a document reconstructed by the test proves something - about the test. Each is dumped and parsed in the desugared spelling the - compiler actually holds. - """ - monkeypatch = pytest.MonkeyPatch() - seen: list[tuple[str, dict[str, Any]]] = [] - instrumented = [site for site, kind in MANUFACTURING_SITES.items() if kind == DOCUMENT] - try: - for site in instrumented: - _instrument(monkeypatch, site, seen) - _drive_everything() - finally: - monkeypatch.undo() - - assert seen, 'no documents were captured at all, so this asserts nothing' - - rejected = [ - f'{site}: {codes}' for site, document in seen - for accepted, codes in [_parses(document)] if not accepted - ] - assert not rejected, ( - 'the compiler manufactured documents the language does not accept:\n ' - + '\n '.join(sorted(set(rejected)))) - - -def _drive_everything() -> None: - """Run every entry point these drivers reach, instrumentation in place: the Python API's `workflow_document` once - spelled step ids from the wrong stem.""" - touch = adapter_step('touch', filename='empty.txt') - append = adapter_step('append', file=touch.outputs.file, str='Hello') - # A declared workflow output, so the step's `out:` is built from a bound - # port rather than left empty: `Step._as_workflow_step` spells it as an edge, and - # an edge written there in the wrong spelling is the likeliest way this - # front end emits something the grammar refuses. - workflow = Workflow([touch, append], 'manufactured_py') - workflow.outputs.result = append.outputs.file - workflow.compile() - # A real-time analysis of each kind: a tool configured by its `in:`, and a - # `.wic` configured by its steps' sidecar, each with a file named by basename. - tools = {StepId(stem, 'global'): Tool(str(ADAPTERS / f'{stem}.cwl'), - yaml.safe_load((ADAPTERS / f'{stem}.cwl').read_text(encoding='utf-8'))) - for stem in ('append', 'echo')} - realtime.compile_analyses(( - Declaration('wf', 'append', '*.txt', 2, 60, {'in': {'file': 'empty.txt', 'str': 'Hello'}}), - Declaration('wf', 'helloworld.wic', '*.txt', 2, 60, {'(1, echo)': {'in': {'message': 'Hi'}}}), - ), {'global': {'helloworld': HELLOWORLD}}, - tools, default_compilation_settings()) diff --git a/tests/core/test_metadata_emitted.py b/tests/core/test_metadata_emitted.py deleted file mode 100644 index ceb6a8771..000000000 --- a/tests/core/test_metadata_emitted.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Compiled CWL is plain CWL: no `sophios` key or prefix, and EDAM only where a format says `edam:`.""" -from typing import Any - -import pytest - -from sophios.ir.artifacts import CompilationArtifact -from sophios.ir.emit import EDAM_NAMESPACE - -from .hermetic import compile_hermetic - -pytestmark = pytest.mark.package - - -#: The fields a CWL document declares its prefixes and ontologies in. -DECLARATIONS = ('$namespaces', '$schemas') - - -def declared_beneath(artifact: CompilationArtifact) -> dict[str, Any]: - """The `$namespaces` and `$schemas` of `artifact` and of every process beneath it, merged as - embedding merges them: an embedded process may not declare its own, so they move up.""" - namespaces = dict(artifact.cwl.get('$namespaces', {})) - schemas = list(artifact.cwl.get('$schemas', [])) - for child in artifact.children: - below = declared_beneath(child) - namespaces |= below.get('$namespaces', {}) - schemas += [schema for schema in below.get('$schemas', []) if schema not in schemas] - return {field: value for field, value in zip(DECLARATIONS, (namespaces, schemas)) if value} - - -@pytest.mark.fast -def test_a_workflow_no_format_of_says_edam_binds_no_prefix() -> None: - """`count` takes an unformatted File and makes an int: nothing in the document is an EDAM CURIE, so - there is no `$namespaces` or `$schemas` at all. (The corpus tests validate such documents with cwltool.)""" - artifact = compile_hermetic({'steps': [{'id': 'count'}]}, 'plain').artifact - assert '$namespaces' not in artifact.cwl and '$schemas' not in artifact.cwl - - -@pytest.mark.fast -@pytest.mark.parametrize('workflow', [ - {'inputs': {'f': {'type': 'File', 'format': 'edam:format_2330'}}, 'steps': [{'id': 'count', 'in': {'file': 'f'}}]}, - {'steps': [{'id': 'mk_file'}]}, - {'steps': [{'id': 'count', 'in': {'file': {'wic_inline_input': { - 'class': 'File', 'location': 'x.txt', 'format': 'edam:format_2330'}}}}]}, - {'inputs': {'f': {'type': 'File', 'default': {'class': 'File', 'location': 'x.txt', 'format': 'edam:format_2330'}}}, - 'steps': [{'id': 'count', 'in': {'file': 'f'}}]}, - {'steps': [{'id': 'count', 'in': {'file': {'wic_raw_cwl': { - 'default': {'class': 'File', 'location': 'x.txt', 'format': 'edam:format_2330'}}}}}]}, -], ids=['authored-input-format', 'promoted-output-format', 'job-file-format', 'input-default-format', - 'step-input-default-format']) -def test_a_workflow_a_format_of_says_edam_binds_the_prefix(workflow: dict[str, Any]) -> None: - """An authored format, a format promoted from a tool, and a File in the job file: a runner reads each - CURIE against the workflow's `$namespaces`, so each needs `edam` bound. No schema is added: an ontology - is a dependency only its author adds.""" - cwl = compile_hermetic(workflow).artifact.cwl - assert cwl['$namespaces'] == {EDAM_NAMESPACE[0]: EDAM_NAMESPACE[1]} and '$schemas' not in cwl diff --git a/tests/core/test_names_emitted.py b/tests/core/test_names_emitted.py deleted file mode 100644 index 7f4b150f4..000000000 --- a/tests/core/test_names_emitted.py +++ /dev/null @@ -1,259 +0,0 @@ -"""Compiled CWL calls each step what its author wrote, and spells nothing of its own.""" -import json -import re -from pathlib import Path -from typing import Any, Final, cast - -import pytest -import yaml -from hypothesis import example, given, strategies as st - -from sophios import post_compile -from sophios.cli import default_compilation_settings -from sophios.compiler import compile_source -from sophios.input_output import write_artifacts_to_disk -from sophios.ir.artifacts import CompilationArtifact -from sophios.ir.frontdoor import bundle_from_disk -from sophios.wic_types import Yaml - -from . import ast_strategies as strat -from .budgets import budget -from .hermetic import compile_hermetic, subworkflow_step -from .strategies import pinned -from .synthetic_tools import SYNTHETIC_TOOLS, clt, inputs_of, registered - - -def _steps(cwl: dict) -> list[str]: - return [step['id'] for step in cwl['steps']] - - -#: `child.wic` (mk_file, then xform twice) called from a root that counts its file. -_NESTED: Final[Yaml] = {'steps': [subworkflow_step('child.wic', {'steps': [{'id': 'mk_file'}, {'id': 'xform'}, - {'id': 'xform'}]}), {'id': 'count'}]} - - -def _nested() -> CompilationArtifact: - """`_NESTED`, compiled.""" - return compile_hermetic(_NESTED, 'root').artifact - - -@pytest.mark.fast -def test_a_step_is_called_by_its_id_and_a_call_without_its_wic() -> None: - """No workflow prefix, no position, no `.wic`: `child.wic` runs as `child`, from `root~child.cwl`. A lifted input - and a promoted output are `~`, nested once per call.""" - root = _nested() - child, = (artifact for artifact in root.children if artifact.graph is not None) - assert _steps(root.cwl) == ['child', 'count'] - assert root.cwl['steps'][0]['run'] == 'root~child.cwl' - assert (child.namespace, child.name) == (('child',), 'root~child') - assert 'child~mk_file~name' in root.cwl['inputs'] - assert root.cwl['outputs']['child~mk_file~file']['outputSource'] == 'child/mk_file~file' - - -@pytest.mark.fast -@given(st.tuples(st.lists(st.tuples(st.sampled_from(['mk_file', 'MK_File', 'xform', 'Xform', 'a', 'A']), - st.sampled_from(['mk_file', 'xform', 'count'])), min_size=1, max_size=4), - st.lists(st.sampled_from(['mk_file', 'Xform', 'a']), max_size=2, unique=True))) -@example(([('mk_file', 'mk_file'), ('xform', 'xform'), ('xform', 'xform')], [])) -@example(([('mk_file', 'mk_file')], ['mk_file'])) -@example(([('Fetch', 'mk_file'), ('fetch', 'mk_file')], [])) -@budget(100) -def test_a_step_is_numbered_exactly_when_another_id_has_its_name( - case: tuple[list[tuple[str, str]], list[str]]) -> None: - """docs/compiling-to-cwl.md: a step keeps its id, but every occurrence of a repeated id carries its position after - an `@`, the first too, so no name depends on what follows it; so does a step named like a workflow input, since - CWL keeps the three in one id space; and ids that differ only in case count as one id (`Fetch` and `fetch` would be - one step directory on macOS and Windows). An input keeps the name its author wrote, and a made one is - `~`.""" - steps, inputs = case - taken = [step_id.casefold() for step_id, _ in steps] - names = [f'{step_id}@{index}' if taken.count(step_id.casefold()) > 1 or step_id.casefold() in map( - str.casefold, inputs) else step_id for index, (step_id, _) in enumerate(steps, start=1)] - bound = {'in': {'name': inputs[0]}} if inputs else {} - cwl = compile_hermetic({'inputs': {name: {'type': 'string'} for name in inputs}, - 'steps': [{'id': step_id, 'run': run, **(bound if run == 'mk_file' else {})} - for step_id, run in steps]}).artifact.cwl - assert _steps(cwl) == names - assert list(cwl['inputs'])[:len(inputs)] == inputs - assert set(cwl['inputs']) - set(inputs) <= {f'{name}~{port}' for name, (_, run) in zip(names, steps) - for port in inputs_of(run)} - assert all(step['in'] == bound['in'] for step, (_, run) in zip(cwl['steps'], steps) if bound and run == 'mk_file') - - -def _clashes() -> CompilationArtifact: - """`greeting`, with every clash a document's names can have: repeated calls and steps, case, an authored input - spelled like a generated name, an `a~b` port, and an inner call that `flatten_subworkflows` dissolves.""" - tools = registered({'probe': clt({'a~b': {'type': 'string', 'inputBinding': {'position': 1}}}, {})}) - child = {'inputs': {'file': {'type': 'File'}}, 'outputs': {'file': {'outputSource': 'xform/file'}}, - 'steps': [subworkflow_step('inner.wic', {'steps': [{'id': 'mk_file'}]}), - {'id': 'xform', 'in': {'file': 'file'}}]} - root = {'inputs': {'echo': {'type': 'string'}, 'mk_file__name': {'type': 'string'}}, - 'steps': [subworkflow_step('child.wic', child), subworkflow_step('child.wic', child), - {'id': 'child', 'run': 'count'}, - {'id': 'echo', 'run': 'mk_file', 'in': {'name': 'echo'}}, {'id': 'mk_file'}, - {'id': 'Touch', 'run': 'mk_file'}, {'id': 'touch', 'run': 'mk_file'}, - {'id': 'xform'}, {'id': 'xform'}, {'id': 'probe'}]} - return compile_hermetic(root, 'greeting', tools=tools).artifact - - -def _documents(artifact: CompilationArtifact) -> list[CompilationArtifact]: - return [artifact, *(document for child in artifact.children if child.graph is not None - for document in _documents(child))] - - -@pytest.mark.fast -def test_no_two_identities_share_a_text() -> None: - """Steps are as written or `@`, a made name is `~` whatever else the document - holds, and in every document, nested or flattened, no step shares a text with another id.""" - nested = _clashes() - spelled = [(list(document.cwl['inputs']), list(document.cwl['outputs']), _steps(document.cwl)) - for document in _documents(nested)] - assert spelled[0] == ( - ['echo', 'mk_file__name', 'child@1~file', 'child@1~inner~mk_file~name', 'child@1~xform~name', - 'child@2~inner~mk_file~name', 'child@2~xform~name', 'mk_file~name', - 'Touch@6~name', 'touch@7~name', 'xform@8~name', 'xform@9~name', 'probe~a~b'], - ['child@1~file', 'child@1~inner~mk_file~file', 'child@1~xform~file', - 'child@2~file', 'child@2~inner~mk_file~file', 'child@2~xform~file', 'child@3~n', - 'echo@4~file', 'mk_file~file', 'Touch@6~file', 'touch@7~file', 'xform@8~file', 'xform@9~file'], - ['child@1', 'child@2', 'child@3', 'echo@4', 'mk_file', 'Touch@6', 'touch@7', 'xform@8', 'xform@9', - 'probe']) - assert spelled[1:] == 2 * [(['file', 'inner~mk_file~name', 'xform~name'], - ['file', 'inner~mk_file~file', 'xform~file'], ['inner', 'xform']), - (['mk_file~name'], ['mk_file~file'], ['mk_file'])] - flat = post_compile.flatten_subworkflows(nested) - assert _steps(flat.cwl) == ['child@1~inner~mk_file', 'child@1~xform', 'child@2~inner~mk_file', - 'child@2~xform', 'child@3', 'echo@4', 'mk_file', 'Touch@6', 'touch@7', - 'xform@8', 'xform@9', 'probe'] - for document in (*_documents(nested), flat): - ports = {name.casefold() for name in (*document.cwl['inputs'], *document.cwl['outputs'])} - steps = [step.casefold() for step in _steps(document.cwl)] - assert len(set(steps)) == len(steps) and not ports & set(steps) - for side in ('inputs', 'outputs'): - assert len({name.casefold() for name in document.cwl[side]}) == len(document.cwl[side]) - - -@pytest.mark.fast -def test_an_id_that_looks_generated_is_just_an_id() -> None: - """A step its author called `root__step__1__mk_file` is that step, by that name, and nothing more.""" - cwl = compile_hermetic({'steps': [{'id': 'root__step__1__mk_file', 'run': 'mk_file'}], - 'outputs': {'f': {'outputSource': 'root__step__1__mk_file/file'}}}, - 'root').artifact.cwl - assert _steps(cwl) == ['root__step__1__mk_file'] - assert cwl['outputs']['f']['outputSource'] == 'root__step__1__mk_file/file' - - -def _tool(path: Path, command: str) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(f'cwlVersion: v1.2\nclass: CommandLineTool\nbaseCommand: {command}\n' - 'inputs: {a: string}\noutputs: {}\n', encoding='utf-8') - - -def _compile_file(wic: Path) -> CompilationArtifact: - return compile_source(bundle_from_disk(wic, {}, SYNTHETIC_TOOLS), default_compilation_settings(), - quiet=True).artifact - - -def _runs(written: Path) -> list[str]: - return [step['run'] for step in yaml.safe_load(written.read_text(encoding='utf-8'))['steps']] - - -def _command(written: Path) -> str: - return cast(str, yaml.safe_load(written.read_text(encoding='utf-8'))['baseCommand']) - - -@pytest.mark.fast -def test_every_document_is_beside_the_root_named_by_its_address_from_the_root(tmp_path: Path) -> None: - """One directory and no folder: the root, its job, and `~
.cwl` for each step at every - depth; each `run:` names a file beside the document that holds it. A runner reads no other job.""" - inner = {'steps': [{'id': 'xform'}]} - child = {'steps': [{'id': 'mk_file'}, subworkflow_step('inner.wic', inner)]} - artifact = compile_hermetic({'steps': [subworkflow_step('child.wic', child), {'id': 'count'}]}, 'root').artifact - write_artifacts_to_disk(artifact, tmp_path) - assert sorted(path.name for path in tmp_path.iterdir()) == [ - 'root.cwl', 'root_inputs.yml', 'root~child.cwl', 'root~child~inner.cwl', 'root~child~inner~xform.cwl', - 'root~child~mk_file.cwl', 'root~count.cwl'] - assert _runs(tmp_path / 'root.cwl') == ['root~child.cwl', 'root~count.cwl'] - assert _runs(tmp_path / 'root~child.cwl') == ['root~child~mk_file.cwl', 'root~child~inner.cwl'] - assert _runs(tmp_path / 'root~child~inner.cwl') == ['root~child~inner~xform.cwl'] - - -@pytest.mark.fast -def test_a_tool_three_steps_run_is_written_three_times(tmp_path: Path) -> None: - """A file per step, not per tool: each step's file is its own, the same text three times.""" - artifact = compile_hermetic({'steps': [{'id': 'mk_file'}, {'id': 'xform'}, {'id': 'xform'}, {'id': 'xform'}]}, - 'root').artifact - write_artifacts_to_disk(artifact, tmp_path) - files = ['root~xform@2.cwl', 'root~xform@3.cwl', 'root~xform@4.cwl'] - assert _runs(tmp_path / 'root.cwl') == ['root~mk_file.cwl', *files] - assert len({(tmp_path / name).read_text(encoding='utf-8') for name in files}) == 1 - - -@pytest.mark.fast -def test_two_different_tools_with_one_file_name_are_two_files(tmp_path: Path) -> None: - """`run: a/echo.cwl` and `run: b/echo.cwl` are named by the steps that run them, never by the tools.""" - _tool(tmp_path / 'a' / 'echo.cwl', 'echo') - _tool(tmp_path / 'b' / 'echo.cwl', 'rm') - (tmp_path / 'greeting.wic').write_text('steps:\n - id: hello\n run: a/echo.cwl\n in: {a: !ii x}\n' - ' - id: shout\n run: b/echo.cwl\n in: {a: !ii y}\n', - encoding='utf-8') - out = tmp_path / 'out' - write_artifacts_to_disk(_compile_file(tmp_path / 'greeting.wic'), out) - assert _runs(out / 'greeting.cwl') == ['greeting~hello.cwl', 'greeting~shout.cwl'] - assert (_command(out / 'greeting~hello.cwl'), _command(out / 'greeting~shout.cwl')) == ('echo', 'rm') - - -@pytest.mark.fast -def test_two_roots_share_one_basepath_without_overwriting_each_other(tmp_path: Path) -> None: - """Every file starts with its root's name, so a second root written beside the first changes none of it.""" - _tool(tmp_path / 'a' / 'echo.cwl', 'echo') - _tool(tmp_path / 'b' / 'echo.cwl', 'rm') - for root, tool in (('greeting', 'a'), ('other', 'b')): - (tmp_path / f'{root}.wic').write_text(f'steps:\n - id: hello\n run: {tool}/echo.cwl\n' - ' in: {a: !ii x}\n', encoding='utf-8') - out = tmp_path / 'out' - write_artifacts_to_disk(_compile_file(tmp_path / 'greeting.wic'), out) - first = {path.name: path.read_text(encoding='utf-8') for path in out.iterdir()} - write_artifacts_to_disk(_compile_file(tmp_path / 'other.wic'), out) - assert {name: (out / name).read_text(encoding='utf-8') for name in first} == first - assert sorted(path.name for path in out.iterdir()) == [ - 'greeting.cwl', 'greeting_inputs.yml', 'greeting~hello.cwl', 'other.cwl', 'other_inputs.yml', 'other~hello.cwl'] - assert (_command(out / 'greeting~hello.cwl'), _command(out / 'other~hello.cwl')) == ('echo', 'rm') - - -@pytest.mark.fast -def test_a_step_named_con_writes_an_ordinary_file(tmp_path: Path) -> None: - """A step's name is a suffix of its file's, so `con`, `aux` and `nul` are no Windows device names there.""" - artifact = compile_hermetic({'steps': [{'id': name, 'run': 'mk_file'} for name in ('con', 'aux', 'nul')]}, - 'greeting').artifact - write_artifacts_to_disk(artifact, tmp_path) - assert _runs(tmp_path / 'greeting.cwl') == ['greeting~con.cwl', 'greeting~aux.cwl', 'greeting~nul.cwl'] - assert all((tmp_path / name).is_file() for name in _runs(tmp_path / 'greeting.cwl')) - - -def _addresses(node: CompilationArtifact) -> list[str]: - """Each step that runs a tool, beneath `node` at any depth, by its address: the calls above it and its name.""" - calls = {child.namespace[-1]: child for child in node.children if child.graph is not None} - return [address for name in _steps(node.cwl) - for address in ([f'{name}~{inner}' for inner in _addresses(calls[name])] if name in calls else [name])] - - -@pytest.mark.fast -@given(st.tuples(strat.workflows().filter(lambda workflow: '___' not in json.dumps(workflow)), - st.sampled_from(['nested', 'embedded', 'flat', 'flat_embedded']))) -@pinned(*((_NESTED, form) for form in ('nested', 'embedded', 'flat', 'flat_embedded'))) -@budget(50) -def test_no_form_of_the_compiled_cwl_spells_a_name_of_its_own(case: tuple[Yaml, str]) -> None: - """Whichever way the tree is written, no id carries `__step__`, `.wic`, `___` or a hash, and nothing in it is - Sophios's own: no `sophios` key, or prefix; a literal is the author's, and `___` the one a drawn literal can spell. - Flattened, a step of a call, one deep as drawn, is named by its address from the root.""" - workflow, form = case - nested = compile_hermetic(workflow, 'root').artifact - flat = post_compile.flatten_subworkflows(nested) if form.startswith('flat') else nested - artifact = post_compile.inline_artifact_runs(flat) if form.endswith('embedded') else flat - - def documents(node: CompilationArtifact) -> list[Any]: - return [node.cwl, node.job_inputs, *(document for child in node.children for document in documents(child))] - found = [hit for document in documents(artifact) - for hit in re.findall(r'__step__|\.wic|___|_[0-9a-f]{8}\b|"sophios[^"]*":', json.dumps(document))] - assert not found, found - assert not form.startswith('flat') or _steps(artifact.cwl) == _addresses(nested) diff --git a/tests/core/test_nesting_scaling.py b/tests/core/test_nesting_scaling.py index ba8377e4f..598aca1b5 100644 --- a/tests/core/test_nesting_scaling.py +++ b/tests/core/test_nesting_scaling.py @@ -65,13 +65,6 @@ def _step_nested_in(depth: int) -> StepId: return step -@pytest.mark.fast -def test_hashing_a_nested_step_does_not_double_per_level() -> None: - """A step id holds its namespace and the namespace holds every enclosing step - id, so a hash that walks them is called twice as often at each level down.""" - _assert_growth_is_bounded(lambda depth: hash(_step_nested_in(depth)), range(10, 21, 2)) - - class _CountedHashes(str): """A name that counts how often it is hashed.""" @@ -83,24 +76,18 @@ def __hash__(self) -> int: @pytest.mark.fast -def test_hashing_a_derived_name_does_not_hash_what_it_was_derived_from_again() -> None: - """A derived name is a key all through the compiler and holds the name it was - derived from, which may be derived in turn, so a hash that walks them costs - one step for every level the name was exposed through, on every lookup.""" +def test_the_cost_of_a_nested_step_does_not_double_per_nesting_level() -> None: + """Every phase names the steps of a nested workflow by identities that hold their enclosing steps, so anything that + writes them out, hashes them or reports on them eagerly pays twice as much at each level down: compiling a nested + workflow, and hashing a step id, whose namespace holds every enclosing step id, keep their growth per level + bounded; and a derived name, a key all through the compiler that holds the name it was derived from, hashes the + name it was derived from once, not once per level it was exposed through.""" + _assert_growth_is_bounded(lambda depth: compile_hermetic(nested_workflow(depth)), range(6, 13, 2)) + _assert_growth_is_bounded(lambda depth: hash(_step_nested_in(depth)), range(10, 21, 2)) port = _CountedHashes('port') name: PortName = AuthoredName(port) for level in range(1, 6): name = DerivedName(StepId(Namespace(), level, 'level'), name) - for _ in range(3): hash(name) - assert port.hashed <= 1 - - -@pytest.mark.fast -def test_compile_time_does_not_double_per_nesting_level() -> None: - """Every phase names the steps of a nested workflow by identities that hold - their enclosing steps, so anything that writes them out, hashes them or - reports on them eagerly pays twice as much at each level down.""" - _assert_growth_is_bounded(lambda depth: compile_hermetic(nested_workflow(depth)), range(6, 13, 2)) diff --git a/tests/core/test_pipeline.py b/tests/core/test_pipeline.py deleted file mode 100644 index 8a17d52d3..000000000 --- a/tests/core/test_pipeline.py +++ /dev/null @@ -1,97 +0,0 @@ -"""The completed typed pipeline, end to end: the independently tested phases composed over the full generator and -compared by ``UP_TO_EMBEDDING``. No test checks a retired name stays retired: such a scan only restates its deletion.""" -import copy -from typing import Any - -import pytest -from hypothesis import given, strategies as st - -from sophios.ir.complete import coerce_job_value, complete -from sophios.ir.declarations import port_declaration -from sophios.ir.emit import emit, surface -from sophios.ir.names import Names -from sophios.ir.types import AuthoredName, WorkflowGraph -from sophios.ir.infer import infer -from sophios.ir.link import link -from sophios.ir.pipeline import front_end -from sophios.lang.diagnostics import SophiosError -from sophios.wic_types import Yaml - -from . import ast_strategies as strat -from .equivalence import Strength, equivalent -from .hermetic import COVERAGE, ORACLE, bundle, compile_hermetic -from .strategies import cwl_types -from .synthetic_tools import SYNTHETIC_TOOLS - - -def _render(graph: WorkflowGraph) -> Any: - """`graph` emitted as the compiler emits its root document.""" - names = Names.of(graph) - return emit(surface(graph, names), names) - - -@pytest.mark.skip_pypi_ci -@given(strat.workflows()) -@ORACLE -def test_full_pipeline_agrees_at_up_to_embedding(workflow: Yaml) -> None: - """The live boundary agrees with direct typed phase composition.""" - model = bundle(copy.deepcopy(workflow), 'oracle', SYNTHETIC_TOOLS) - front = front_end(model.parsed, model.registry, name='oracle') - assert front.graph is not None, list(front.diagnostics) - - prepared = complete(front.graph) - linked = link(prepared) - assert linked.graph is not None, list(linked.diagnostics) - inferred = infer(complete(linked.graph)) - assert inferred.graph is not None, list(inferred.diagnostics) - direct = _render(complete(inferred.graph)) - - live = compile_hermetic(copy.deepcopy(workflow)).artifact.cwl - divergence = equivalent(direct, live, Strength.UP_TO_EMBEDDING) - assert divergence is None, divergence - - -@pytest.mark.skip_pypi_ci -@given(strat.workflows()) -@ORACLE -def test_completing_twice_is_completing_once_for_any_workflow(workflow: Yaml) -> None: - """`complete` is idempotent, over the generated space. - - It documents itself so and `_compile_front` calls it three times on that - promise, so any arm reading its own previous output compounds silently. - One such arm shipped, in the half that is now `surface`: the `run:` target - was recomputed from the last pass and grew a prefix each time. That half - runs once per document now and cannot compound; this covers what still - repeats. - """ - model = bundle(copy.deepcopy(workflow), 'oracle', SYNTHETIC_TOOLS) - front = front_end(model.parsed, model.registry, name='oracle') - assert front.graph is not None, list(front.diagnostics) - once = complete(front.graph) - assert _render(complete(once)) == _render(once) - - -_TYPES = cwl_types('null', 'string', 'int', 'float', 'boolean', 'File', 'Directory') -_OBJECTS = st.fixed_dictionaries( - {'class': st.sampled_from(['File', 'Directory']), 'location': st.text(max_size=2)}, - optional={'format': st.just('edam:format_2')}) -_VALUES = st.recursive( - # NaN is excluded: `nan != nan`, so no value holding it equals itself. - st.one_of(st.text(max_size=2), st.integers(), st.booleans(), st.floats(allow_nan=False), - st.sampled_from([float('inf'), float('-inf')]), _OBJECTS), - lambda inner: st.lists(inner, max_size=2), max_leaves=4) - - -@pytest.mark.skip_pypi_ci -@given(_TYPES, st.sampled_from([{}, {'format': 'edam:format_1'}]), _VALUES) -@COVERAGE -def test_a_job_value_is_its_own_normal_form(raw: Any, fmt: Yaml, value: Any) -> None: - """Coercing a coerced job value changes nothing, which is what lets a - child's job value be lifted a level and coerced against the outer port.""" - declaration = port_declaration({'type': raw, **fmt}) - name = AuthoredName('x') - try: - once = coerce_job_value(name, declaration, value) - except SophiosError: - return - assert coerce_job_value(name, declaration, once) == once diff --git a/tests/core/test_python_api_from_wic.py b/tests/core/test_python_api_from_wic.py index 48e856dcb..8a246d65c 100644 --- a/tests/core/test_python_api_from_wic.py +++ b/tests/core/test_python_api_from_wic.py @@ -24,7 +24,7 @@ from sophios.lang import Document, render from sophios.wic_types import Json, StepId, Tool, Tools -from .ast_strategies import SUBWORKFLOW_BODIES, compilable_documents +from .ast_strategies import SUBWORKFLOW_BODIES, documents from .budgets import budget from .cases import case_dirs, diagnostic, match from .equivalence import Strength, equivalent @@ -172,7 +172,7 @@ def _outcome(compile_it: Callable[[], tuple[Json, Json, list[str]]]) -> Any: @pytest.mark.fast -@given(compilable_documents().filter(_held_today).map(_files), st.just(False)) +@given(documents().filter(_held_today).map(_files), st.just(False)) # pylint: disable=no-member # A bare name is the workflow input, `!*` the producing step's output object and `!ii` a literal; the workflow output # is the step output it names. @example((CHAIN, {}), True) diff --git a/tests/core/test_reference_compatibility.py b/tests/core/test_reference_compatibility.py index 4286b934d..53125a90f 100644 --- a/tests/core/test_reference_compatibility.py +++ b/tests/core/test_reference_compatibility.py @@ -1,7 +1,6 @@ """The versioned, conservative boundary for user-authored references.""" import copy -from functools import partial from typing import Any, Final import pytest @@ -13,17 +12,14 @@ from sophios.lang.compatibility import TypeRelation, reference_relation from sophios.lang.diagnostics import SophiosError from sophios.lang.error_codes import SophiosErrorCode -from sophios.utils_cwl import desugar_into_canonical_normal_form from sophios.wic_types import StepId, Tool, Tools, Yaml from .synthetic_tools import clt from .budgets import budget -from .helpers import REPO_ROOT from .hermetic import ORACLE, compile_hermetic from .reference_model import ReferenceExpectation, reference_expectation from .strategies import cwl_types, pinned -from .wic_reading import read_wic _CASES: Final = ( ('same atom', 'string', 'string', ReferenceExpectation.OVERLAPS), @@ -102,16 +98,12 @@ def test_the_versioned_judge_matches_the_independent_model( if found is not TypeRelation.UNKNOWN and _loaded(source) and _loaded(sink): refused = check_types(copy.deepcopy(source), copy.deepcopy(sink), None, None, None) == 'exception' assert refused is (found is TypeRelation.DISJOINT) or refused and 'null' in repr((source, sink)), found + assert reference_relation(_RECURSIVE, _STR_ARR, lang_version='0.0.1') is TypeRelation.UNKNOWN -@pytest.mark.fast -def test_a_recursive_or_malformed_declaration_is_unknown_not_a_crash() -> None: - """A cyclic Python value cannot make the total raw judge recurse forever.""" - recursive: dict[str, Any] = {'type': 'array'} - recursive['items'] = recursive - assert reference_relation( - recursive, {'type': 'array', 'items': 'string'}, lang_version='0.0.1') \ - is TypeRelation.UNKNOWN +#: A cyclic Python value, which the total raw judge must call unknown rather than recurse on forever. +_RECURSIVE: Final[dict[str, Any]] = {'type': 'array'} +_RECURSIVE['items'] = _RECURSIVE @pytest.mark.fast @@ -139,148 +131,68 @@ def test_the_eager_api_check_defers_what_scatter_could_rescue( assert _python_api_types_match(sink, source) is accepted, claim -_ENDPOINTS: Final = ( - ('mk_file', 'name', 'string'), - ('count', 'file', 'File'), - ('scale', 'n', 'int'), - ('scale', 'factor', 'float'), - ('poly', 'value', ['int', 'string']), -) -_SOURCE_TYPES: Final = ( - 'string', 'File', 'int', 'float', 'Any', 'string[]', - {'type': 'array', 'items': 'Any'}, -) - - -@pytest.mark.slow -@given(st.sampled_from(_ENDPOINTS), st.sampled_from(_SOURCE_TYPES), st.booleans()) -@ORACLE -def test_workflow_input_references_follow_the_independent_outcome( - endpoint: tuple[str, str, Any], source_type: Any, scattered: bool) -> None: - """Unknown/overlapping references compile; only disjoint ones are wic023.""" - stem, argument, declared_sink = endpoint - sink_type = {'type': 'array', 'items': declared_sink} if scattered else declared_sink - expected = reference_expectation(source_type, sink_type) - step: Yaml = {'id': stem, 'in': {argument: 'wf_source'}} - if scattered: - step['scatter'] = [argument] - document: Yaml = {'inputs': {'wf_source': {'type': source_type}}, 'steps': [step]} - - if expected is ReferenceExpectation.DISJOINT: - with pytest.raises(SophiosError) as caught: - compile_hermetic(document, 'reference') - assert [diagnostic.code for diagnostic in caught.value.diagnostics] == [ - SophiosErrorCode.INCOMPATIBLE_INPUT_REFERENCE] - else: - compile_hermetic(document, 'reference') - - -#: `clt` in canonical normal form — the shape the inference and -#: explicit-edge paths read. -_clt = partial(clt, canonical=True) - - -def _edge_tools(source_type: Any, sink_type: Any) -> Tools: - """Return two tools exposing the requested raw endpoint declarations.""" - return { - StepId('typed_source', 'global'): Tool( - '/synthetic/typed_source.cwl', - _clt({'seed': {'type': 'string'}, - 'seed2': {'type': 'string', 'default': 'y'}}, - {'value': {'type': source_type}})), - StepId('typed_sink', 'global'): Tool( - '/synthetic/typed_sink.cwl', - _clt({'value': {'type': sink_type}}, {})), - } - - -#: A scatter as the test models it: the entries, and the method. Kept apart from -#: the production helpers so the expectations below are a restatement of CWL's -#: rule rather than a second call into the code under test. +#: Each sink a reference may reach, as `typed_sink` declares it: atoms, a union, and arrays one and two deep. _STR_ARR: Final[Yaml] = {'type': 'array', 'items': 'string'} _STR_ARR2: Final[Yaml] = {'type': 'array', 'items': _STR_ARR} +_SINKS: Final = ('string', 'File', 'int', 'float', ['int', 'string'], _STR_ARR, _STR_ARR2) +_SOURCES: Final = ('string', 'File', 'int', 'float', 'Any', 'string[]', {'type': 'array', 'items': 'Any'}, _STR_ARR2) +#: How `typed_source` scatters: the inputs it scatters, and the method. +_SCATTERS: Final = (((), ''), (('seed',), 'dotproduct'), (('seed', 'seed2'), 'nested_crossproduct'), + (('seed', 'seed2'), 'flat_crossproduct')) -def _model_output_rank(keys: tuple[str, ...], method: str) -> int: - """Array layers a scatter adds to every output of the step carrying it.""" - if not keys: - return 0 - return len(keys) if method == 'nested_crossproduct' else 1 - - -def _model_wrap(cwl_type: Any, layers: int) -> Any: +def _wrap(cwl_type: Any, layers: int) -> Any: for _ in range(layers): cwl_type = {'type': 'array', 'items': cwl_type} return cwl_type -@pytest.mark.fast -@pytest.mark.parametrize('source_type, sink_type, source_scatter, sink_scatter', [ - ('string', 'string', ((), ''), ()), - ('string', 'File', ((), ''), ()), - ('Any', 'string', ((), ''), ('value',)), - ({'type': 'array', 'items': 'Any'}, 'string', ((), ''), ('value',)), - ('string', 'string', (('seed',), 'dotproduct'), ('value',)), - ('File', 'string', (('seed',), 'dotproduct'), ('value',)), - # nested_crossproduct nests one level per scattered input, so a two-input - # scatter over a `string` output is `string[][]` and this sink is satisfied. - ('string', _STR_ARR2, (('seed', 'seed2'), 'nested_crossproduct'), ()), - # flat_crossproduct produces one flat array however many inputs it scatters. - ('string', _STR_ARR, (('seed', 'seed2'), 'flat_crossproduct'), ()), - # ... so against the same sink it is one layer short, and provably disjoint. - ('string', _STR_ARR2, (('seed', 'seed2'), 'flat_crossproduct'), ()), - # An input listed twice is scattered twice. - (_STR_ARR2, 'string', ((), ''), ('value', 'value')), -]) -def test_explicit_edges_follow_the_same_judgment( - source_type: Any, sink_type: Any, - source_scatter: tuple[tuple[str, ...], str], sink_scatter: tuple[str, ...]) -> None: - """Both endpoint scatter lifts occur before the shared judgment, at the rank - CWL gives them rather than one layer whenever any scatter is present.""" - source_keys, source_method = source_scatter - effective_source = _model_wrap(source_type, _model_output_rank(source_keys, source_method)) - effective_sink = _model_wrap(sink_type, sink_scatter.count('value')) - expected = reference_expectation(effective_source, effective_sink) - source: Yaml = { - 'id': 'typed_source', - 'in': {'seed': {'wic_inline_input': ['x'] if source_keys else 'x'}}, - 'out': [{'value': {'wic_anchor': 'edge'}}], +def _typed_tools(source_type: Any, sink_type: Any) -> Tools: + """`typed_source`, whose output is `source_type`, and `typed_sink`, whose input is `sink_type`.""" + return { + StepId('typed_source', 'global'): Tool('/synthetic/typed_source.cwl', clt( + {'seed': {'type': 'string'}, 'seed2': {'type': 'string', 'default': 'y'}}, + {'value': {'type': source_type}}, canonical=True)), + StepId('typed_sink', 'global'): Tool('/synthetic/typed_sink.cwl', clt( + {'value': {'type': sink_type}}, {}, canonical=True)), } - sink: Yaml = {'id': 'typed_sink', 'in': {'value': {'wic_alias': 'edge'}}} - if source_keys: - source['scatter'] = list(source_keys) - source['scatterMethod'] = source_method - if 'seed2' in source_keys: - source['in']['seed2'] = {'wic_inline_input': ['y']} - if sink_scatter: - sink['scatter'] = list(sink_scatter) - if expected is ReferenceExpectation.DISJOINT: - with pytest.raises(SophiosError) as caught: - compile_hermetic({'steps': [source, sink]}, 'edges', - tools=_edge_tools(source_type, sink_type)) - assert caught.value.diagnostics[0].code is SophiosErrorCode.INCOMPATIBLE_INPUT_REFERENCE - else: - compile_hermetic({'steps': [source, sink]}, 'edges', - tools=_edge_tools(source_type, sink_type)) +def _compiles(document: Yaml, tools: Tools) -> bool: + """Whether `document` compiles; a refusal must be wic023 alone.""" + try: + compile_hermetic(document, 'reference', tools=tools) + except SophiosError as error: + assert [d.code for d in error.diagnostics] == [SophiosErrorCode.INCOMPATIBLE_INPUT_REFERENCE] + return False + return True -@pytest.mark.fast -def test_echo_multi_scatter_keeps_any_at_the_cwl_boundary() -> None: - """The exact tutorial that exposed the old matcher's Any false positive.""" - path = REPO_ROOT / 'docs/tutorials/echo_multi_scatter.wic' - document = desugar_into_canonical_normal_form( - read_wic(path.read_text(encoding='utf-8'), path.name)) - tools: Tools = { - StepId('array_indices', 'global'): Tool( - '/synthetic/array_indices.cwl', - _clt( - {'input_array': {'type': 'string[]'}, 'input_indices': {'type': 'int[]'}}, - {'output_array': {'type': 'Any'}}, - )), - StepId('echo_3', 'global'): Tool( - '/synthetic/echo_3.cwl', - _clt({'message1': {'type': 'string'}, 'message2': {'type': 'string'}, - 'message3': {'type': 'string'}}, {})), - } - compile_hermetic(document, 'echo_multi_scatter', tools=tools) + +@pytest.mark.slow +@given(st.tuples(st.sampled_from(_SOURCES), st.sampled_from(_SINKS), st.sampled_from(_SCATTERS), st.integers(0, 2))) +@pinned(('string', 'string', _SCATTERS[0], 0), ('string', 'File', _SCATTERS[0], 0), ('Any', 'string', _SCATTERS[0], 1), + ({'type': 'array', 'items': 'Any'}, 'string', _SCATTERS[0], 1), ('string', 'string', _SCATTERS[1], 1), + ('File', 'string', _SCATTERS[1], 1), ('string', _STR_ARR2, _SCATTERS[2], 0), + ('string', _STR_ARR, _SCATTERS[3], 0), ('string', _STR_ARR2, _SCATTERS[3], 0), + (_STR_ARR2, 'string', _SCATTERS[0], 2)) +@ORACLE +def test_a_reference_compiles_unless_the_model_proves_it_disjoint(case: tuple[Any, Any, Any, int]) -> None: + """A workflow input of `source_type`, and `typed_source`'s output of that type by an edge, each feed + `typed_sink`'s input, scattered `layers` times: each compiles exactly when the independent model does not prove + the two disjoint, at the ranks CWL gives them. A scatter lifts the source one layer, or one per scattered input + under nested_crossproduct, and the sink once per time `scatter:` names it, before the shared judgment; unknown + and overlapping references compile, and only a disjoint one is wic023.""" + source_type, sink_type, (keys, method), layers = case + sink: Yaml = {'id': 'typed_sink', 'in': {'value': 'wf_source'}, + **({'scatter': ['value'] * layers} if layers else {})} + lifted = _wrap(sink_type, layers) + tools = _typed_tools(source_type, sink_type) + assert _compiles({'inputs': {'wf_source': {'type': source_type}}, 'steps': [sink]}, tools) is ( + reference_expectation(source_type, lifted) is not ReferenceExpectation.DISJOINT) + source: Yaml = {'id': 'typed_source', 'in': {'seed': {'wic_inline_input': ['x'] if keys else 'x'}, + **({'seed2': {'wic_inline_input': ['y']}} if 'seed2' in keys else {})}, + 'out': [{'value': {'wic_anchor': 'edge'}}], + **({'scatter': list(keys), 'scatterMethod': method} if keys else {})} + produced = _wrap(source_type, (len(keys) if method == 'nested_crossproduct' else 1) if keys else 0) + assert _compiles({'steps': [source, {**sink, 'in': {'value': {'wic_alias': 'edge'}}}]}, tools) is ( + reference_expectation(produced, lifted) is not ReferenceExpectation.DISJOINT) diff --git a/tests/core/test_resolve.py b/tests/core/test_resolve.py index 22929ed7c..467d72b8d 100644 --- a/tests/core/test_resolve.py +++ b/tests/core/test_resolve.py @@ -1,262 +1,51 @@ -"""Registry resolution and the direct typed front end, compared with the live compiler under an independent model of -scalar coercions. Blind spot: synthetic flat tools; nested sources, precedence, identities and raw CWL are examples.""" -import builtins -import copy +"""Contributions, judged on cases in files: a document contributes to a step of a subworkflow it calls by nesting +`wic:` blocks keyed `(index, name)` or by a bare id, and a contribution gone astray is named on stderr and ignored. +tests/core/data/contributions// is a workflow.wic and the child workflows it calls; the theme's +expected.yaml states what each case's steps bind once resolved. That resolution reads the registry and nothing else +is a law of test_emit.py's drawn workflows.""" from pathlib import Path from typing import Any, Final -from unittest.mock import patch import pytest -from hypothesis import example, given -from sophios.ir import ( - RegistryKey, - RegistrySnapshot, - ToolDefinition, - WorkflowSource, - front_end, - generated_process_id, - resolve, -) -from sophios.lang import (EdgeRef, InlineLiteral, RawCwlRef, SourceSpan, Step, - UnresolvedName, parse) -from sophios.lang.diagnostics import SophiosError -from sophios.lang.error_codes import SophiosErrorCode -from sophios.wic_types import StepId as LegacyStepId, Yaml +from sophios.ir import RegistrySnapshot, resolve +from sophios.lang import EdgeRef, InlineLiteral, RawCwlRef, UnresolvedName, parse -from . import ast_strategies as strat -from .cases import cases, match -from .hermetic import ORACLE, bundle, compile_hermetic, subworkflow_step -from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS, inputs_of, outputs_of +from .cases import DATA, match +from .helpers import stated +from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS - -def _typed(workflow: Yaml): # type: ignore[no-untyped-def] - model = bundle(workflow, 'oracle', SYNTHETIC_TOOLS) - result = front_end(model.parsed, model.registry, name='oracle') - assert result.resolved is not None and result.resolved.document is not None - assert result.graph is not None, list(result.diagnostics) - return result - - -def _assert_processes_match_the_registry(document: Any) -> None: - """Every non-generated process equals the tool the registry holds for it.""" - for step in document.steps: - process = step.process - if process.child is not None: - _assert_processes_match_the_registry(process.child) - continue - if process.generated: - continue - # The name the step authored, not the key the resolver returned: a - # resolver that answers every lookup with one tool reports that tool's - # key too, so comparing its own answer to itself proves nothing. - stem = step.source.id - assert process.key.name == stem - assert process.run_path == SYNTHETIC_TOOLS[LegacyStepId(stem, SYNTHETIC_NS)].run_path - assert tuple(port.name for port in process.inputs) == tuple(inputs_of(stem)) - assert tuple(port.name for port in process.outputs) == tuple(outputs_of(stem)) - - -@pytest.mark.skip_pypi_ci -@given(strat.workflows()) -@example({'steps': [{'id': 'join'}]}) # a resolver returning empty interfaces cannot satisfy this by accident -@ORACLE -def test_every_resolved_process_is_the_one_the_registry_holds(workflow: Yaml) -> None: - """Resolution is compared where the bridged differential cannot see it. - - Run path and both interfaces, per step and recursively through child - workflows, against an independent model of the same registry -- not - against the compiled bytes, which the source round-trip already fixes - whatever Resolve returned. - """ - model = bundle(copy.deepcopy(workflow), 'oracle', SYNTHETIC_TOOLS) - parsed = model.parsed - assert parsed.document is not None - resolved = resolve(parsed.document, - model.registry, - name='oracle') - assert resolved.document is not None, list(resolved.diagnostics) - _assert_processes_match_the_registry(resolved.document) - - -@pytest.mark.skip_pypi_ci -@given(strat.workflows()) -@ORACLE -def test_resolution_depends_only_on_the_registry(workflow: Yaml) -> None: - """Filesystem and ambient environment are unavailable during resolution.""" - model = bundle(workflow, 'oracle', SYNTHETIC_TOOLS) - parsed = model.parsed - assert parsed.document is not None - snapshot = model.registry - - def forbidden(*_args: Any, **_kwargs: Any) -> Any: - raise AssertionError('resolution attempted filesystem access') - - with patch.object(builtins, 'open', forbidden), patch.object(Path, 'read_text', forbidden): - result = resolve(parsed.document, snapshot, name='oracle') - assert result.document is not None, list(result.diagnostics) - - -@pytest.mark.fast -def test_snapshot_owns_tool_definitions() -> None: - """Mutating the caller's registry after snapshotting cannot change resolution.""" - tools = copy.deepcopy(SYNTHETIC_TOOLS) - snapshot = RegistrySnapshot.from_tools(tools) - tools[LegacyStepId('mk_file', SYNTHETIC_NS)].cwl['inputs'].clear() - parsed = parse('steps:\n- id: mk_file\n', 'probe.wic') - assert parsed.document is not None - result = resolve(parsed.document, snapshot) - assert result.document is not None - assert tuple(port.name for port in result.document.steps[0].process.inputs) == ('name',) - - -@pytest.mark.skip_pypi_ci -@given(strat.workflows()) -@ORACLE -def test_registry_order_cannot_change_resolution(workflow: Yaml) -> None: - """Lookup has no first-match semantics over registry iteration order.""" - model = bundle(workflow, 'oracle', SYNTHETIC_TOOLS) - parsed = model.parsed - assert parsed.document is not None - canonical = model.registry - reversed_snapshot = RegistrySnapshot(tuple(reversed(canonical.tools)), - tuple(reversed(canonical.workflows))) - left = resolve(parsed.document, canonical, name='oracle') - right = resolve(parsed.document, reversed_snapshot, name='oracle') - assert left.document == right.document - assert list(left.diagnostics) == list(right.diagnostics) - - -@pytest.mark.fast -def test_nested_workflow_source_is_resolved_from_the_snapshot() -> None: - """A child source is registry content, not a path Resolve may open.""" - child = 'steps:\n- id: mk_file\n in:\n name: !ii child.txt\n' - registry = RegistrySnapshot.from_tools( - SYNTHETIC_TOOLS, workflows={(SYNTHETIC_NS, 'child'): parse(child, 'child.wic')}) - result = front_end(parse('steps:\n- id: child.wic\n', 'root.wic'), registry, name='root') - assert result.resolved is not None and result.resolved.document is not None - assert result.graph is not None and len(result.graph.children) == 1 - assert result.resolved.document.steps[0].process.child is not None - - -@pytest.mark.fast -@pytest.mark.parametrize('key', ['inputs', 'outputs']) -@pytest.mark.parametrize('directive', ['$import', '$include']) -def test_a_called_workflow_listing_its_ports_with_an_import_is_reported(key: str, directive: str) -> None: - """The ports are in a file only cwltool reads, so no step can be checked against them. - - Calling such a workflow is reported at the call, not met with a `KeyError`. - """ - child = {key: [{directive: 'shared.yml'}], - 'steps': [{'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'x'}}}]} - with pytest.raises(SophiosError) as caught: - compile_hermetic({'steps': [subworkflow_step('child.wic', child)]}) - [diagnostic] = caught.value.diagnostics - assert diagnostic.code is SophiosErrorCode.SUBWORKFLOW_INVALID - assert f'workflow global/child lists its {key}:' in diagnostic.message - - -@pytest.mark.fast -def test_step_sidecar_namespace_selects_the_process() -> None: - """The closest sidecar namespace wins over the default global namespace.""" - global_tool = SYNTHETIC_TOOLS[LegacyStepId('mk_file', SYNTHETIC_NS)] - alt = ToolDefinition(RegistryKey('alt', 'mk_file'), '/alt/mk_file.cwl', - copy.deepcopy(global_tool.cwl)) - registry = RegistrySnapshot(RegistrySnapshot.from_tools(SYNTHETIC_TOOLS).tools + (alt,)) - source = ''' -wic: - steps: - (1, mk_file): - wic: - namespace: alt -steps: -- id: mk_file -''' - result = front_end(parse(source, 'workflow.wic'), registry) - assert result.resolved is not None and result.resolved.document is not None - assert result.resolved.document.steps[0].process.run_path == '/alt/mk_file.cwl' - - -@pytest.mark.fast -def test_explicit_implementation_overrides_the_default() -> None: - """Implementation selection is deterministic and uses the explicit choice first.""" - registry = RegistrySnapshot( - RegistrySnapshot.from_tools(SYNTHETIC_TOOLS).tools, - (WorkflowSource(RegistryKey('global', 'fast'), parse('steps:\n- id: mk_file\n')), - WorkflowSource(RegistryKey('global', 'safe'), parse('steps:\n- id: mk_text\n'))), - ) - source = ''' -wic: - implementations: {fast: {}, safe: {}} - default_implementation: safe - implementation: fast -''' - result = front_end(parse(source, 'choice.wic'), registry, name='choice') - assert result.resolved is not None and result.resolved.document is not None - assert result.resolved.document.steps[0].source.id == 'mk_file' - - -@pytest.mark.fast -def test_generated_process_identity_is_content_deterministic() -> None: - """Generated identities neither use uuid nor depend on source spans.""" - span = SourceSpan('probe.wic', 1, 1, 1, 1) - one = Step('python_script', inputs=(('script', InlineLiteral('a.py', span)),)) - same = Step('python_script', inputs=(('script', InlineLiteral('a.py', span)),)) - other = Step('python_script', inputs=(('script', InlineLiteral('b.py', span)),)) - assert generated_process_id(one) == generated_process_id(same) - assert generated_process_id(one) != generated_process_id(other) - - -@pytest.mark.fast -def test_raw_cwl_reference_needs_no_global_escape_hatch() -> None: - """The local tag reaches CWL unchanged while ordinary bare names stay governed.""" - workflow = {'inputs': {'wf_name': {'type': 'string'}}, - 'steps': [{'id': 'mk_file', 'in': {'name': {'wic_raw_cwl': 'wf_name'}}}]} - compiled = compile_hermetic(workflow).artifact.cwl - assert compiled['steps'][0]['in']['name'] == 'wf_name' +_PAYLOAD: Final = {InlineLiteral: 'value', EdgeRef: 'name', RawCwlRef: 'expression', UnresolvedName: 'name'} -def _resolved(source: str, **workflows: str) -> Any: - """Resolve `source` against the synthetic tools plus the named child sources.""" - parsed = parse(source, 'root.wic') +def _resolved(case: Path) -> Any: + """The case's workflow.wic resolved against the synthetic tools and the other `.wic` files beside it.""" + parsed = parse((case / 'workflow.wic').read_text(encoding='utf-8'), 'workflow.wic') assert parsed.document is not None, list(parsed.diagnostics) - registry = RegistrySnapshot.from_tools( - SYNTHETIC_TOOLS, - workflows={(SYNTHETIC_NS, name): parse(child, f'{name}.wic') - for name, child in workflows.items()}) - result = resolve(parsed.document, registry, name='root') + registry = RegistrySnapshot.from_tools(SYNTHETIC_TOOLS, workflows={ + (SYNTHETIC_NS, path.stem): parse(path.read_text(encoding='utf-8'), path.name) + for path in case.glob('*.wic') if path.name != 'workflow.wic'}) + result = resolve(parsed.document, registry, name='workflow') assert result.document is not None, list(result.diagnostics) return result.document -def _descend(document: Any, depth: int) -> Any: - """The document reached by entering each first step's subworkflow `depth` times.""" - for _ in range(depth): - child = document.steps[0].process.child - assert child is not None - document = child - return document - - -_PAYLOAD: Final = {InlineLiteral: 'value', EdgeRef: 'name', RawCwlRef: 'expression', UnresolvedName: 'name'} - - @pytest.mark.fast -@pytest.mark.parametrize('case', cases('contributions', 'root', 'children', 'expect', 'stderr')) -def test_contribution_case(case: dict[str, Any], capsys: pytest.CaptureFixture[str]) -> None: - """A document contributes to a step of a subworkflow it calls by nesting `wic:` blocks keyed `(index, name)`, - and a contribution gone astray deletes an edge rather than reporting anything. - - `root` and its `children` resolve; each `expect` entry names the step at `step` (default 0) of the document - `depth` calls below the root, and what it binds: `inputs` as `[construct, payload]` and `outputs` as - `[name, edge defined]`. `stderr` is what is printed. - """ - document = _resolved(case['root'], **case.get('children', {})) - for expected in case['expect']: - step = _descend(document, expected.get('depth', 0)).steps[expected.get('step', 0)].source - found = {**expected, 'outputs': [[out.name, out.edge_def and out.edge_def.name] for out in step.outputs], - 'inputs': {name: [type(value).__name__, getattr(value, _PAYLOAD[type(value)])] - for name, value in step.inputs}} - assert match(expected, found), (case['id'], found) - if 'stderr' in case: - assert match(case['stderr'], capsys.readouterr().err.splitlines()) +@pytest.mark.parametrize('theme', [pytest.param(path, id=path.name) + for path in sorted((DATA / 'contributions').iterdir()) if path.is_dir()]) +def test_a_contribution_binds_each_case_as_its_theme_states(theme: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Each `expect` entry names the step at `step` (default 0) of the document `depth` calls below the root, each + call its document's first step, and what it binds: `inputs` as `[construct, payload]` and `outputs` as + `[name, edge defined]`. `said` is every line printed on stderr (none, where it is left out).""" + for name, expected in stated(theme).items(): + document = _resolved(theme / name) + for entry in expected['expect']: + found = document + for _ in range(entry.get('depth', 0)): + found = found.steps[0].process.child + step = found.steps[entry.get('step', 0)].source + bound = {**entry, 'outputs': [[out.name, out.edge_def and out.edge_def.name] for out in step.outputs], + 'inputs': {port: [type(value).__name__, getattr(value, _PAYLOAD[type(value)])] + for port, value in step.inputs}} + assert match(entry, bound), (name, bound) + assert match(expected.get('said', []), capsys.readouterr().err.splitlines()), name diff --git a/tests/core/test_support_matrix.py b/tests/core/test_support_matrix.py index 9a98b79af..b90222241 100644 --- a/tests/core/test_support_matrix.py +++ b/tests/core/test_support_matrix.py @@ -13,20 +13,14 @@ @pytest.mark.fast -@pytest.mark.parametrize('class_name', sorted(SUPPORT_MATRIX)) -def test_every_schema_field_is_classified(class_name: str) -> None: - """A field the schema has and the matrix lacks, or one the schema dropped, fails here, and every row carries one - of the three classifications.""" - schema_fields = set(getattr(cwl_v1_2, class_name).attrs) - assert set(SUPPORT_MATRIX[class_name]) == schema_fields, ( - f'{class_name}: unclassified {schema_fields - set(SUPPORT_MATRIX[class_name])}, ' - f'stale {set(SUPPORT_MATRIX[class_name]) - schema_fields}') - assert all(row.support in Support for row in SUPPORT_MATRIX[class_name].values()) - - -@pytest.mark.fast -def test_every_row_is_pinned_by_a_test_that_exists() -> None: - """A row's `pinned_by` names a test function that exists under `tests/core`.""" +def test_every_schema_field_is_classified_and_pinned_by_a_test_that_exists() -> None: + """A field the CWL schema has and the matrix lacks, or one the schema dropped, fails here; every row carries one of + the three classifications, and its `pinned_by` names a test function that exists under `tests/core`.""" + for class_name, table in SUPPORT_MATRIX.items(): + schema_fields = set(getattr(cwl_v1_2, class_name).attrs) + assert set(table) == schema_fields, ( + f'{class_name}: unclassified {schema_fields - set(table)}, stale {set(table) - schema_fields}') + assert all(row.support in Support for row in table.values()) existing = {node.name for path in TESTS.glob('test_*.py') for node in ast.walk(ast.parse(path.read_text(encoding='utf-8'))) if isinstance(node, ast.FunctionDef) and node.name.startswith('test_')} diff --git a/tests/core/test_wic_defaults.py b/tests/core/test_wic_defaults.py index c7327f57d..cb6860f9d 100644 --- a/tests/core/test_wic_defaults.py +++ b/tests/core/test_wic_defaults.py @@ -1,6 +1,7 @@ """A `.wic` is read where it is and written elsewhere: a relative location in a `default:` names a file beside the `.wic` that wrote it.""" from pathlib import Path +import shutil import pytest @@ -9,6 +10,7 @@ from sophios.ir.artifacts import CompilationArtifact from sophios.ir.frontdoor import bundle_from_disk +from .cases import DATA from .synthetic_tools import SYNTHETIC_TOOLS pytestmark = pytest.mark.package @@ -22,21 +24,11 @@ def _compile_wic(wic: Path) -> CompilationArtifact: @pytest.mark.fast def test_a_wic_file_default_is_written_absolute_against_the_wic(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """A relative `default:` of a workflow input, a called one's and a step input's names a file beside the `.wic` - that wrote it, wherever Sophios runs and writes: a `location` as a URI, a `path` as a path.""" + """tests/core/data/defaults, copied elsewhere and compiled from another directory: a relative `default:` of a + workflow input, a called one's and a step input's names a file beside the `.wic` that wrote it, wherever Sophios + runs and writes: a `location` as a URI, a `path` as a path; an absolute one is left as it is.""" project = tmp_path / 'project' - (project / 'sub').mkdir(parents=True) - (project / 'sub' / 'child.wic').write_text( - 'inputs:\n cfg: {type: File, default: {class: File, location: other.txt}}\n' - 'steps:\n- id: xform\n in: {file: cfg, name: !ii out.txt}\n', encoding='utf-8') - (project / 'w.wic').write_text( - 'inputs:\n cfg: {type: File, default: {class: File, location: data/config.txt}}\n' - ' ref: {type: File, default: {class: File, path: data/ref.txt}}\n' - ' far: {type: File, default: {class: File, location: "file:///elsewhere/far.txt"}}\n' - 'steps:\n- id: xform\n in: {file: cfg, name: !ii a.txt}\n- id: again\n run: xform\n' - ' in: {file: ref, name: !ii b.txt}\n- id: third\n run: xform\n in: {file: far, name: !ii c.txt}\n' - '- id: call\n run: sub/child.wic\n- id: fourth\n run: xform\n' - ' in: {file: !cwl {default: {class: File, location: data/step.txt}}, name: !ii d.txt}\n', encoding='utf-8') + shutil.copytree(DATA / 'defaults', project) monkeypatch.chdir(tmp_path) artifact = _compile_wic(project / 'w.wic') inputs = artifact.cwl['inputs'] diff --git a/tests/core/transformations.py b/tests/core/transformations.py deleted file mode 100644 index fa0e2a294..000000000 --- a/tests/core/transformations.py +++ /dev/null @@ -1,172 +0,0 @@ -"""Rewrites that must not change what a workflow means, each with the strength it preserves and why (a field: it is -the claim the property checks). Not here: reordering steps, since inference takes the most recent match.""" -import copy -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Callable, Final, cast - -import yaml -from hypothesis.strategies import SearchStrategy - -from sophios.utils_yaml import Key -from sophios.wic_types import Yaml - -from .ast_strategies import partitionings -from .equivalence import Strength -from .hermetic import subworkflow_step - - -@dataclass(frozen=True, slots=True) -class Transformation: - """A rewrite of a `.wic` document, and the claim it makes about it.""" - - name: str - #: The strongest `Strength` a compilation of `apply(w)` shares with one of `w`. - preserves: Strength - apply: Callable[[Yaml], Yaml] - #: Why the claim is true: the claim the property checks, so a field. - rationale: str - - -def _text_roundtrip(document: Yaml) -> Yaml: - """`safe_dump` then `safe_load`, as a user writes a file and compiles it; `sort_keys=False`, since sorting reorders - keys and IDENTICAL compares key order.""" - return cast(Yaml, yaml.safe_load(yaml.safe_dump(document, sort_keys=False))) - - -def _bare_sources(inputs: Yaml, name: str) -> list[tuple[Any, Any]]: - """The bare-name references `inputs[name]` spells, as (container, key) slots: the string, or each string in a - wic_raw_cwl record's `source`.""" - value = inputs[name] - if isinstance(value, str): - return [(inputs, name)] - record = value.get(Key.RAW_CWL) if isinstance(value, dict) else None - if not isinstance(record, dict): - return [] - source = record.get('source') - if isinstance(source, str): - return [(record, 'source')] - if isinstance(source, list): - return [(source, index) for index, item in enumerate(source) if isinstance(item, str)] - return [] - - -def _declared_input_references(document: Yaml, steps: list[Yaml]) -> set[str]: - """The declared `inputs:` names `steps` reference by bare name.""" - declared = document.get('inputs') - if not declared: - return set() - referenced: set[str] = set() - for step in steps: - inputs = step.get('in', {}) - for name in inputs: - for container, key in _bare_sources(inputs, name): - if container[key] in declared: - referenced.add(container[key]) - return referenced - - -def _rewrite_workflow_input_references(steps: list[Yaml], formals: dict[str, str]) -> None: - """Rename bare workflow-input references in the new child scope; test-side, so a broken inverse can show.""" - for step in steps: - candidates = [step.get('in')] - parentargs = step.get('parentargs') - if isinstance(parentargs, dict): - candidates.append(parentargs.get('in')) - for inputs in candidates: - if not isinstance(inputs, dict): - continue - for name in inputs: - for container, key in _bare_sources(inputs, name): - if container[key] in formals: - container[key] = formals[container[key]] - - -def _subtree_for(document: Yaml, steps: list[Yaml], formals: dict[str, str]) -> Yaml: - """A subworkflow body of `steps`, redeclaring the top-level inputs they name bare: a bare name resolves against the - enclosing workflow's own `inputs:` only.""" - declared = document.get('inputs') or {} - _rewrite_workflow_input_references(steps, formals) - subtree: Yaml = {'steps': steps} - if formals: - subtree['inputs'] = {formal: copy.deepcopy(declared[actual]) - for actual, formal in formals.items()} - return subtree - - -def _wrap_steps(document: Yaml, groups: list[list[Yaml]], stems: list[str]) -> Yaml: - """`document`'s steps replaced by one subworkflow step per group, each wired through `parentargs['in']` (compilation - drops an `in:` on the step) to the inputs its group names: left unwired, inference may feed it from a sibling.""" - # `inputs:` stays outside too: the compiler emits a document's inputs whether used or not. - outer = {key: value for key, value in document.items() if key != 'steps'} - new_steps = [] - for stem, steps in zip(stems, groups): - referenced = _declared_input_references(document, steps) - formals = {actual: f'{Path(stem).stem}_input_{actual}' for actual in sorted(referenced)} - wrapper = subworkflow_step(stem, _subtree_for(document, steps, formals)) - if referenced: - wrapper['parentargs']['in'] = {formal: actual for actual, formal in formals.items()} - new_steps.append(wrapper) - outer['steps'] = new_steps - return outer - - -def _rename_workflow(document: Yaml) -> Yaml: - """Wrap every step in one subworkflow `renamed.wic`: the root's stem is outside the document, so nesting is how a - group of steps gets another first namespace segment.""" - return _wrap_steps(document, [copy.deepcopy(document.get('steps', []))], ['renamed.wic']) - - -TRANSFORMATIONS: Final[tuple[Transformation, ...]] = ( - # A copy, not the object: the compiler mutates its input, so a second compile would see what the first left. - Transformation( - name='identity', preserves=Strength.IDENTICAL, apply=copy.deepcopy, - rationale=( - 'Compiling the same input twice must give the same answer. Trivial to state and not ' - 'trivial to satisfy: the compiler mutates yaml_tree, inputs_workflow, ' - 'vars_workflow_output_internal, the graph, and the tools dict, so a second compilation ' - 'in the same process is a real test of whether any of that leaks.')), - Transformation( - name='text_roundtrip', preserves=Strength.IDENTICAL, apply=_text_roundtrip, - rationale=( - 'yaml.safe_dump then yaml.safe_load. Serialising a workflow and reading it ' - 'back is what every user does between writing a file and compiling it.')), - Transformation( - name='rename_workflow', preserves=Strength.UP_TO_RENAMING, apply=_rename_workflow, - rationale=( - "The workflow's stem is the first segment of every namespace. Changing it must move no " - "edge.")), -) - - -def split(cuts: tuple[tuple[int, ...], ...]) -> Transformation: - """A `split` for one drawn partitioning: each group, one step included, becomes its own subworkflow.""" - # Boundaries, not groups: `apply` rebuilds groups for the length of the document it gets. - points = tuple(group[0] for group in cuts[1:]) - - def apply(document: Yaml) -> Yaml: - steps: list[Yaml] = document.get('steps', []) - total = len(steps) - bounds = sorted({point for point in points if 0 < point < total}) - edges = [0, *bounds, total] - groups = [tuple(range(a, b)) for a, b in zip(edges, edges[1:])] or [tuple(range(total))] - step_groups = [[copy.deepcopy(steps[j]) for j in group] for group in groups] - stems = [f'part{i}.wic' for i in range(len(step_groups))] - return _wrap_steps(document, step_groups, stems) - - return Transformation( - name='split', preserves=Strength.UP_TO_RENAMING, apply=apply, - rationale=( - 'The first design principle. A subworkflow is the steps written in one file; grouping ' - 'them differently renames every port and moves no edge.')) - - -#: The widest document `workflows()` draws (4 tool steps and a subworkflow); `apply` clamps cuts, so generous will do. -_SPLIT_STEP_BOUND: Final = 5 - - -def split_transformations() -> SearchStrategy[Transformation]: - """A freshly drawn `split`. The property parametrises over the kinds instead of drawing one: Hypothesis favours - simple draws, so `identity` took half the budget and the thinnest rewrite about one example in fifty.""" - # pylint cannot see through `@st.composite`: it reads partitionings() as its element type, not a strategy. - return partitionings(_SPLIT_STEP_BOUND).map(split) # pylint: disable=no-member From d0536bbbea6a920a4f69f2da1616c64755652748 Mon Sep 17 00:00:00 2001 From: Vasu Jaganath Date: Fri, 13 Nov 2026 00:52:30 -0500 Subject: [PATCH 5/7] test(cli): scenarios, projects and timelines in files Preflight and CLI runs become seven scenario directories; packing, realtime, drawing, plain CWL and partial failure become projects; run handles, timelines. --- design_docs/one-target-table-design.md | 4 +- docs/dev/language_spec.md | 7 +- docs/validation.md | 4 +- tests/core/cases.py | 8 + tests/core/data/backends/write_into.cwl | 21 + tests/core/data/basepath/noop.cwl | 5 + tests/core/data/basepath/w.wic | 2 + .../core/data/compiler/literals/accepted.wic | 21 + .../core/data/compiler/literals/expected.yaml | 26 + tests/core/data/compiler/literals/forgot.wic | 5 + tests/core/data/compiler/literals/null.wic | 5 + tests/core/data/compiler/literals/octal.wic | 5 + tests/core/data/compiler/literals/quoted.wic | 5 + tests/core/data/compiler/literals/takes.cwl | 22 + tests/core/data/config/w.wic | 4 + tests/core/data/discovery/laid_out.cwl | 5 + tests/core/data/discovery/laid_out.wic | 1 + tests/core/data/drawing/drawn.wic | 42 + tests/core/data/drawing/expected.yaml | 61 + tests/core/data/drawing/inner.wic | 6 + tests/core/data/drawing/plain.wic | 9 + tests/core/data/drawing/sub.wic | 11 + tests/core/data/frontdoor/calls/child.wic | 5 + tests/core/data/frontdoor/calls/root.wic | 9 + .../frontdoor/cwl_workflow/adapters/echo.cwl | 5 + .../cwl_workflow/adapters/packed.cwl | 6 + .../frontdoor/cwl_workflow/adapters/say.cwl | 1 + .../core/data/frontdoor/cwl_workflow/echo.cwl | 5 + .../frontdoor/cwl_workflow/inline_body.wic | 4 + .../cwl_workflow/packed_on_search_paths.wic | 3 + .../frontdoor/cwl_workflow/run_packed.wic | 4 + .../data/frontdoor/cwl_workflow/run_path.wic | 4 + .../core/data/frontdoor/cwl_workflow/say.cwl | 1 + .../frontdoor/cwl_workflow/search_paths.wic | 3 + tests/core/data/frontdoor/forward.wic | 15 + tests/core/data/frontdoor/gate/probe.cwl | 6 + tests/core/data/frontdoor/gate/probe.wic | 6 + tests/core/data/frontdoor/gate/probe.yml | 6 + tests/core/data/frontdoor/own/child.wic | 7 + tests/core/data/frontdoor/own/root.wic | 2 + tests/core/data/frontdoor/paths/t.cwl | 1 + tests/core/data/frontdoor/paths/w.wic | 4 + .../examples/scripts/workflow_types.py | 1 + .../data/frontdoor/script/work/compile.wic | 5 + .../data/frontdoor/script/work/my_script.py | 10 + .../data/frontdoor/script/work/resolve.wic | 5 + tests/core/data/frontdoor/tutorial.wic | 10 + tests/core/data/packing/a/s.sh | 2 + tests/core/data/packing/a/w.wic | 13 + tests/core/data/packing/b/inner.wic | 10 + tests/core/data/packing/b/s.sh | 2 + tests/core/data/packing/broken/broken.cwl | 9 + tests/core/data/packing/broken/echo.cwl | 6 + tests/core/data/packing/broken/unused.wic | 3 + tests/core/data/packing/broken/used.wic | 3 + tests/core/data/packing/built.wic | 2 + tests/core/data/packing/dataA/config.txt | 1 + tests/core/data/packing/dataA/echo.cwl | 9 + tests/core/data/packing/dataB/config.txt | 1 + tests/core/data/packing/dataB/echo.cwl | 9 + tests/core/data/packing/live.wic | 9 + tests/core/data/packing/make_use.wic | 6 + tests/core/data/packing/one.wic | 3 + tests/core/data/packing/ontology.wic | 2 + tests/core/data/packing/pair.wic | 6 + tests/core/data/packing/relcat.wic | 5 + tests/core/data/packing/relcat_and_config.wic | 5 + tests/core/data/packing/schemadef.wic | 4 + tests/core/data/packing/schemadef.yml | 9 + .../core/data/packing/tools/Dockerfile_built | 2 + tests/core/data/packing/tools/built.cwl | 11 + tests/core/data/packing/tools/data.txt | 1 + tests/core/data/packing/tools/make.cwl | 10 + tests/core/data/packing/tools/ontology.cwl | 8 + tests/core/data/packing/tools/relcat.cwl | 18 + tests/core/data/packing/tools/s.sh | 2 + tests/core/data/packing/tools/seed.txt | 1 + tests/core/data/packing/tools/slow_log.cwl | 5 + tests/core/data/packing/tools/use.cwl | 9 + tests/core/data/packing/two.wic | 6 + tests/core/data/partial_failure/cases.yaml | 101 -- tests/core/data/partial_failure/err.cwl | 6 + tests/core/data/partial_failure/expected.yaml | 45 + tests/core/data/partial_failure/look.cwl | 6 + tests/core/data/partial_failure/make.cwl | 14 + tests/core/data/partial_failure/pair.cwl | 5 + tests/core/data/partial_failure/pull.cwl | 9 + tests/core/data/partial_failure/say.cwl | 7 + tests/core/data/partial_failure/tell.cwl | 5 + tests/core/data/partial_failure/w.wic | 39 + tests/core/data/plain_cwl/copy.cwl | 10 + tests/core/data/plain_cwl/job.yml | 1 + tests/core/data/plain_cwl/list_steps.cwl | 19 + tests/core/data/plain_cwl/missing.yml | 2 + tests/core/data/plain_cwl/no_version.cwl | 6 + .../core/data/plain_cwl/packed_hash_main.cwl | 14 + tests/core/data/plain_cwl/packed_main.cwl | 14 + tests/core/data/plain_cwl/packed_tool.cwl | 14 + tests/core/data/plain_cwl/plain.cwl | 19 + tests/core/data/plain_cwl/plain.wic | 2 + tests/core/data/plain_cwl/say.cwl | 10 + tests/core/data/plain_cwl/sidecar.cwl | 10 + tests/core/data/plain_cwl/tagged.cwl | 7 + tests/core/data/preflight/cli/bad.wic | 2 + tests/core/data/preflight/cli/echo.wic | 5 + tests/core/data/preflight/cli/expected.yaml | 65 + tests/core/data/preflight/cli/two_touches.wic | 8 + tests/core/data/preflight/engine/docker.sock | 0 .../core/data/preflight/engine/expected.yaml | 55 + tests/core/data/preflight/engine/touch.wic | 5 + .../core/data/preflight/images/expected.yaml | 41 + tests/core/data/preflight/images/image.tar | 0 tests/core/data/preflight/images/images.wic | 7 + tests/core/data/preflight/images/load.wic | 2 + .../data/preflight/images/local_import.wic | 2 + tests/core/data/preflight/images/nope.wic | 2 + tests/core/data/preflight/images/rootfs.tar | 0 tests/core/data/preflight/images/search.json | 1 + .../data/preflight/images/tools/download.cwl | 9 + .../data/preflight/images/tools/import.cwl | 10 + .../core/data/preflight/images/tools/load.cwl | 9 + .../preflight/images/tools/local_import.cwl | 10 + .../core/data/preflight/images/tools/nope.cwl | 9 + .../data/preflight/images/tools/pinned.cwl | 10 + .../core/data/preflight/images/tools/pull.cwl | 9 + tests/core/data/preflight/inputs/absent.wic | 7 + tests/core/data/preflight/inputs/absent.yml | 4 + tests/core/data/preflight/inputs/beside.wic | 8 + .../core/data/preflight/inputs/cat_input.wic | 7 + .../core/data/preflight/inputs/expected.yaml | 42 + tests/core/data/preflight/inputs/in x.txt | 1 + .../data/preflight/inputs/jobs/data/a.txt | 1 + tests/core/data/preflight/inputs/jobs/job.yml | 7 + tests/core/data/preflight/inputs/list.yml | 2 + tests/core/data/preflight/inputs/literal.wic | 5 + tests/core/data/preflight/inputs/locked.txt | 1 + tests/core/data/preflight/inputs/locked.wic | 6 + tests/core/data/preflight/inputs/named.wic | 2 + tests/core/data/preflight/inputs/named.yml | 2 + tests/core/data/preflight/inputs/search.json | 1 + tests/core/data/preflight/inputs/shared/a.txt | 1 + .../data/preflight/inputs/tools/write_dir.cwl | 17 + tests/core/data/preflight/inputs/uri.yml | 4 + tests/core/data/preflight/modes/absent.wic | 7 + .../data/preflight/modes/earlier/notes.txt | 1 + .../data/preflight/modes/earlier/touch.cwl | 1 + tests/core/data/preflight/modes/echo.wic | 5 + tests/core/data/preflight/modes/expected.yaml | 25 + tests/core/data/preflight/modes/touch.wic | 5 + .../earlier/nextflow_made/nextflow.config | 1 + .../nextflow_made/nextflow_params.json | 1 + .../nextflow_made/nextflow_workflow.json | 1 + .../earlier/nextflow_made/workflow.nf | 1 + .../data/preflight/nextflow/expected.yaml | 17 + tests/core/data/preflight/nextflow/made.wic | 5 + .../core/data/preflight/nextflow/search.json | 1 + .../preflight/nextflow/tools/write_into.cwl | 26 + tests/core/data/preflight/programs/echo.wic | 5 + .../data/preflight/programs/expected.yaml | 49 + tests/core/data/preflight/programs/touch.wic | 5 + tests/core/data/provenance_runs/edam_root.wic | 6 + tests/core/data/provenance_runs/edam_tool.wic | 4 + tests/core/data/provenance_runs/greeting.wic | 9 + tests/core/data/provenance_runs/other.wic | 6 + tests/core/data/provenance_runs/outer.wic | 6 + tests/core/data/provenance_runs/pair.wic | 7 + tests/core/data/provenance_runs/say.cwl | 6 + tests/core/data/provenance_runs/say_edam.cwl | 9 + tests/core/data/quiet/fail.wic | 4 + tests/core/data/quiet/local/local.cwl | 9 + tests/core/data/quiet/pair.wic | 4 + tests/core/data/quiet/probe.cwl | 7 + tests/core/data/quiet/probe.wic | 3 + tests/core/data/quiet/tools/own.cwl | 7 + tests/core/data/quiet/tools/say.cwl | 9 + tests/core/data/quiet/w.wic | 15 + tests/core/data/realtime/declared.wic | 39 + tests/core/data/realtime/expected.yaml | 29 + tests/core/data/realtime/live.wic | 21 + tests/core/data/realtime/measure.wic | 4 + tests/core/data/realtime/refused.wic | 9 + .../core/data/realtime/tools/Dockerfile_count | 1 + .../core/data/realtime/tools/count_lines.cwl | 9 + tests/core/data/realtime/tools/counted.cwl | 13 + tests/core/data/realtime/tools/fail_lines.cwl | 9 + tests/core/data/realtime/tools/slow_log.cwl | 7 + tests/core/data/realtime/tools/tag.cwl | 9 + tests/core/data/realtime/touched.wic | 3 + tests/core/data/realtime/watch.wic | 11 + tests/core/test_backends.py | 279 ++--- tests/core/test_basepath.py | 222 ++-- tests/core/test_ci_coverage.py | 10 +- tests/core/test_compute.py | 326 ++--- tests/core/test_config.py | 62 +- tests/core/test_diagnostics.py | 1113 +++-------------- tests/core/test_entry_points.py | 7 - tests/core/test_frontdoor.py | 420 ++----- tests/core/test_graph_features.py | 314 +---- tests/core/test_input_output.py | 15 +- tests/core/test_packing.py | 466 ++----- tests/core/test_plain_cwl.py | 345 ++--- tests/core/test_plugins.py | 107 +- tests/core/test_provenance.py | 67 +- tests/core/test_python_api_from_wic.py | 18 +- tests/core/test_quiet.py | 175 +-- tests/core/test_realtime.py | 506 +++----- tests/core/test_release.py | 11 +- tests/core/test_run_local.py | 871 +++++-------- tests/core/test_run_on_windows.py | 56 +- tests/core/test_settings_boundary.py | 65 +- 210 files changed, 3176 insertions(+), 4053 deletions(-) create mode 100644 tests/core/data/backends/write_into.cwl create mode 100644 tests/core/data/basepath/noop.cwl create mode 100644 tests/core/data/basepath/w.wic create mode 100644 tests/core/data/compiler/literals/accepted.wic create mode 100644 tests/core/data/compiler/literals/expected.yaml create mode 100644 tests/core/data/compiler/literals/forgot.wic create mode 100644 tests/core/data/compiler/literals/null.wic create mode 100644 tests/core/data/compiler/literals/octal.wic create mode 100644 tests/core/data/compiler/literals/quoted.wic create mode 100644 tests/core/data/compiler/literals/takes.cwl create mode 100644 tests/core/data/config/w.wic create mode 100644 tests/core/data/discovery/laid_out.cwl create mode 100644 tests/core/data/discovery/laid_out.wic create mode 100644 tests/core/data/drawing/drawn.wic create mode 100644 tests/core/data/drawing/expected.yaml create mode 100644 tests/core/data/drawing/inner.wic create mode 100644 tests/core/data/drawing/plain.wic create mode 100644 tests/core/data/drawing/sub.wic create mode 100644 tests/core/data/frontdoor/calls/child.wic create mode 100644 tests/core/data/frontdoor/calls/root.wic create mode 100644 tests/core/data/frontdoor/cwl_workflow/adapters/echo.cwl create mode 100644 tests/core/data/frontdoor/cwl_workflow/adapters/packed.cwl create mode 100644 tests/core/data/frontdoor/cwl_workflow/adapters/say.cwl create mode 100644 tests/core/data/frontdoor/cwl_workflow/echo.cwl create mode 100644 tests/core/data/frontdoor/cwl_workflow/inline_body.wic create mode 100644 tests/core/data/frontdoor/cwl_workflow/packed_on_search_paths.wic create mode 100644 tests/core/data/frontdoor/cwl_workflow/run_packed.wic create mode 100644 tests/core/data/frontdoor/cwl_workflow/run_path.wic create mode 100644 tests/core/data/frontdoor/cwl_workflow/say.cwl create mode 100644 tests/core/data/frontdoor/cwl_workflow/search_paths.wic create mode 100644 tests/core/data/frontdoor/forward.wic create mode 100644 tests/core/data/frontdoor/gate/probe.cwl create mode 100644 tests/core/data/frontdoor/gate/probe.wic create mode 100644 tests/core/data/frontdoor/gate/probe.yml create mode 100644 tests/core/data/frontdoor/own/child.wic create mode 100644 tests/core/data/frontdoor/own/root.wic create mode 100644 tests/core/data/frontdoor/paths/t.cwl create mode 100644 tests/core/data/frontdoor/paths/w.wic create mode 100644 tests/core/data/frontdoor/script/sophios/examples/scripts/workflow_types.py create mode 100644 tests/core/data/frontdoor/script/work/compile.wic create mode 100644 tests/core/data/frontdoor/script/work/my_script.py create mode 100644 tests/core/data/frontdoor/script/work/resolve.wic create mode 100644 tests/core/data/frontdoor/tutorial.wic create mode 100644 tests/core/data/packing/a/s.sh create mode 100644 tests/core/data/packing/a/w.wic create mode 100644 tests/core/data/packing/b/inner.wic create mode 100644 tests/core/data/packing/b/s.sh create mode 100644 tests/core/data/packing/broken/broken.cwl create mode 100644 tests/core/data/packing/broken/echo.cwl create mode 100644 tests/core/data/packing/broken/unused.wic create mode 100644 tests/core/data/packing/broken/used.wic create mode 100644 tests/core/data/packing/built.wic create mode 100644 tests/core/data/packing/dataA/config.txt create mode 100644 tests/core/data/packing/dataA/echo.cwl create mode 100644 tests/core/data/packing/dataB/config.txt create mode 100644 tests/core/data/packing/dataB/echo.cwl create mode 100644 tests/core/data/packing/live.wic create mode 100644 tests/core/data/packing/make_use.wic create mode 100644 tests/core/data/packing/one.wic create mode 100644 tests/core/data/packing/ontology.wic create mode 100644 tests/core/data/packing/pair.wic create mode 100644 tests/core/data/packing/relcat.wic create mode 100644 tests/core/data/packing/relcat_and_config.wic create mode 100644 tests/core/data/packing/schemadef.wic create mode 100644 tests/core/data/packing/schemadef.yml create mode 100644 tests/core/data/packing/tools/Dockerfile_built create mode 100644 tests/core/data/packing/tools/built.cwl create mode 100644 tests/core/data/packing/tools/data.txt create mode 100644 tests/core/data/packing/tools/make.cwl create mode 100644 tests/core/data/packing/tools/ontology.cwl create mode 100644 tests/core/data/packing/tools/relcat.cwl create mode 100644 tests/core/data/packing/tools/s.sh create mode 100644 tests/core/data/packing/tools/seed.txt create mode 100644 tests/core/data/packing/tools/slow_log.cwl create mode 100644 tests/core/data/packing/tools/use.cwl create mode 100644 tests/core/data/packing/two.wic delete mode 100644 tests/core/data/partial_failure/cases.yaml create mode 100644 tests/core/data/partial_failure/err.cwl create mode 100644 tests/core/data/partial_failure/expected.yaml create mode 100644 tests/core/data/partial_failure/look.cwl create mode 100644 tests/core/data/partial_failure/make.cwl create mode 100644 tests/core/data/partial_failure/pair.cwl create mode 100644 tests/core/data/partial_failure/pull.cwl create mode 100644 tests/core/data/partial_failure/say.cwl create mode 100644 tests/core/data/partial_failure/tell.cwl create mode 100644 tests/core/data/partial_failure/w.wic create mode 100644 tests/core/data/plain_cwl/copy.cwl create mode 100644 tests/core/data/plain_cwl/job.yml create mode 100644 tests/core/data/plain_cwl/list_steps.cwl create mode 100644 tests/core/data/plain_cwl/missing.yml create mode 100644 tests/core/data/plain_cwl/no_version.cwl create mode 100644 tests/core/data/plain_cwl/packed_hash_main.cwl create mode 100644 tests/core/data/plain_cwl/packed_main.cwl create mode 100644 tests/core/data/plain_cwl/packed_tool.cwl create mode 100644 tests/core/data/plain_cwl/plain.cwl create mode 100644 tests/core/data/plain_cwl/plain.wic create mode 100644 tests/core/data/plain_cwl/say.cwl create mode 100644 tests/core/data/plain_cwl/sidecar.cwl create mode 100644 tests/core/data/plain_cwl/tagged.cwl create mode 100644 tests/core/data/preflight/cli/bad.wic create mode 100644 tests/core/data/preflight/cli/echo.wic create mode 100644 tests/core/data/preflight/cli/expected.yaml create mode 100644 tests/core/data/preflight/cli/two_touches.wic create mode 100644 tests/core/data/preflight/engine/docker.sock create mode 100644 tests/core/data/preflight/engine/expected.yaml create mode 100644 tests/core/data/preflight/engine/touch.wic create mode 100644 tests/core/data/preflight/images/expected.yaml create mode 100644 tests/core/data/preflight/images/image.tar create mode 100644 tests/core/data/preflight/images/images.wic create mode 100644 tests/core/data/preflight/images/load.wic create mode 100644 tests/core/data/preflight/images/local_import.wic create mode 100644 tests/core/data/preflight/images/nope.wic create mode 100644 tests/core/data/preflight/images/rootfs.tar create mode 100644 tests/core/data/preflight/images/search.json create mode 100644 tests/core/data/preflight/images/tools/download.cwl create mode 100644 tests/core/data/preflight/images/tools/import.cwl create mode 100644 tests/core/data/preflight/images/tools/load.cwl create mode 100644 tests/core/data/preflight/images/tools/local_import.cwl create mode 100644 tests/core/data/preflight/images/tools/nope.cwl create mode 100644 tests/core/data/preflight/images/tools/pinned.cwl create mode 100644 tests/core/data/preflight/images/tools/pull.cwl create mode 100644 tests/core/data/preflight/inputs/absent.wic create mode 100644 tests/core/data/preflight/inputs/absent.yml create mode 100644 tests/core/data/preflight/inputs/beside.wic create mode 100644 tests/core/data/preflight/inputs/cat_input.wic create mode 100644 tests/core/data/preflight/inputs/expected.yaml create mode 100644 tests/core/data/preflight/inputs/in x.txt create mode 100644 tests/core/data/preflight/inputs/jobs/data/a.txt create mode 100644 tests/core/data/preflight/inputs/jobs/job.yml create mode 100644 tests/core/data/preflight/inputs/list.yml create mode 100644 tests/core/data/preflight/inputs/literal.wic create mode 100644 tests/core/data/preflight/inputs/locked.txt create mode 100644 tests/core/data/preflight/inputs/locked.wic create mode 100644 tests/core/data/preflight/inputs/named.wic create mode 100644 tests/core/data/preflight/inputs/named.yml create mode 100644 tests/core/data/preflight/inputs/search.json create mode 100644 tests/core/data/preflight/inputs/shared/a.txt create mode 100644 tests/core/data/preflight/inputs/tools/write_dir.cwl create mode 100644 tests/core/data/preflight/inputs/uri.yml create mode 100644 tests/core/data/preflight/modes/absent.wic create mode 100644 tests/core/data/preflight/modes/earlier/notes.txt create mode 100644 tests/core/data/preflight/modes/earlier/touch.cwl create mode 100644 tests/core/data/preflight/modes/echo.wic create mode 100644 tests/core/data/preflight/modes/expected.yaml create mode 100644 tests/core/data/preflight/modes/touch.wic create mode 100644 tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow.config create mode 100644 tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow_params.json create mode 100644 tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow_workflow.json create mode 100644 tests/core/data/preflight/nextflow/earlier/nextflow_made/workflow.nf create mode 100644 tests/core/data/preflight/nextflow/expected.yaml create mode 100644 tests/core/data/preflight/nextflow/made.wic create mode 100644 tests/core/data/preflight/nextflow/search.json create mode 100644 tests/core/data/preflight/nextflow/tools/write_into.cwl create mode 100644 tests/core/data/preflight/programs/echo.wic create mode 100644 tests/core/data/preflight/programs/expected.yaml create mode 100644 tests/core/data/preflight/programs/touch.wic create mode 100644 tests/core/data/provenance_runs/edam_root.wic create mode 100644 tests/core/data/provenance_runs/edam_tool.wic create mode 100644 tests/core/data/provenance_runs/greeting.wic create mode 100644 tests/core/data/provenance_runs/other.wic create mode 100644 tests/core/data/provenance_runs/outer.wic create mode 100644 tests/core/data/provenance_runs/pair.wic create mode 100644 tests/core/data/provenance_runs/say.cwl create mode 100644 tests/core/data/provenance_runs/say_edam.cwl create mode 100644 tests/core/data/quiet/fail.wic create mode 100644 tests/core/data/quiet/local/local.cwl create mode 100644 tests/core/data/quiet/pair.wic create mode 100644 tests/core/data/quiet/probe.cwl create mode 100644 tests/core/data/quiet/probe.wic create mode 100644 tests/core/data/quiet/tools/own.cwl create mode 100644 tests/core/data/quiet/tools/say.cwl create mode 100644 tests/core/data/quiet/w.wic create mode 100644 tests/core/data/realtime/declared.wic create mode 100644 tests/core/data/realtime/expected.yaml create mode 100644 tests/core/data/realtime/live.wic create mode 100644 tests/core/data/realtime/measure.wic create mode 100644 tests/core/data/realtime/refused.wic create mode 100644 tests/core/data/realtime/tools/Dockerfile_count create mode 100644 tests/core/data/realtime/tools/count_lines.cwl create mode 100644 tests/core/data/realtime/tools/counted.cwl create mode 100644 tests/core/data/realtime/tools/fail_lines.cwl create mode 100644 tests/core/data/realtime/tools/slow_log.cwl create mode 100644 tests/core/data/realtime/tools/tag.cwl create mode 100644 tests/core/data/realtime/touched.wic create mode 100644 tests/core/data/realtime/watch.wic diff --git a/design_docs/one-target-table-design.md b/design_docs/one-target-table-design.md index f32e722dc..65edf088b 100644 --- a/design_docs/one-target-table-design.md +++ b/design_docs/one-target-table-design.md @@ -194,7 +194,7 @@ the reading port must declare (`nf-s048`) or Link refuses (`wic023`), and one sc which lowers (`tests/core/data/nextflow/refused/scatter`, step `reads_pairs`). Each stays its own code: the scatter is its own construct, and a target that learns nested arrays still refuses it. -**The list** is `docs/error_codes.md`; `test_the_error_codes_page_says_what_the_code_says` keeps it equal to the +**The list** is `docs/error_codes.md`; `tests/core/test_diagnostics.py` keeps it equal to the catalog. A source written as text has two codes: `nf-s027`, a nested call's output, valid CWL as `tests/core/data/python_api_pairs/re_export.wic` shows; `nf-s028`, a step that is not there, the document's mistake. @@ -254,7 +254,7 @@ Literal["cwl", "nextflow"]`; `--target` and every other flag; `NotLowered` a `Va value is not the text it stands for) and `nf-s055` (CWL cwltool would not run) are the workflow's problems, which under `--target cwl` the compile writes and the runner meets. Kept as nf-s codes of kind `document`: only the Nextflow target reads those fields closely enough to find them. `SophiosErrorCode.is_language` counts them with - the `wic` codes, as describing the document, which `test_every_code_is_explained` holds kind `document` to. + the `wic` codes, as describing the document, which `tests/core/test_diagnostics.py` holds kind `document` to. Moving them to `wic` codes for both targets would make CWL compiles that succeed today fail, and for `nf-s028` it would stop `re_export.wic`'s valid shape too. 2. **`nf-s011`**, a `when` reading an input its step does not bind, stays kind `target`: cwltool reads `undefined`, diff --git a/docs/dev/language_spec.md b/docs/dev/language_spec.md index c445b07e9..b28aacf0d 100644 --- a/docs/dev/language_spec.md +++ b/docs/dev/language_spec.md @@ -86,7 +86,7 @@ step's tool is passthrough wholesale: Sophios does not classify | `label` | passthrough | | `test_leak_boundary.py` | | `out` | native | | `test_a_construct_reads_alike_in_either_spelling_and_position` (`test_lang_parser.py`) | | `requirements` | passthrough | | `test_leak_boundary.py` | -| `run` | native | a registry stem, a path relative to the document, or an inline body | `test_each_step_runs_the_tool_its_run_names` (`test_frontdoor.py`) | +| `run` | native | a registry stem, a path relative to the document, or an inline body | `tests/core/data/run_paths` (`test_frontdoor.py`) | | `scatter` | native | | `test_leak_boundary.py` | | `scatterMethod` | native | | `test_leak_boundary.py` | | `when` | native | | `test_leak_boundary.py` | @@ -363,9 +363,8 @@ Every member is provoked, in one of two ways: a document under (`COMPILED`). `tests/core/test_lang_parser.py` fails for a member neither provokes, so a new code lands with its provocation in the same commit. Every member has an `Explanation` in `EXPLANATIONS` (kind, meaning, fix); -`test_every_code_is_explained` fails for one without, and -`test_the_error_codes_page_says_what_the_code_says` keeps the -[error codes page](../error_codes.md) equal to it. +`tests/core/test_diagnostics.py` fails for one without, and keeps the +[error codes page](../error_codes.md) and `sophios --explain` equal to it. | Code | Member | Provoked in | |---|---|---| diff --git a/docs/validation.md b/docs/validation.md index de1795e12..0d7bc540e 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -55,8 +55,8 @@ Three kinds of test carry the promises the documentation makes: directory's `config_ci.json` lists as `fragments` (they read an input or edge a parent supplies) or `intensive` (the weekly lane runs those); those named `run_partial_failures` run with `--partial_failure_enable`. `tests/core/test_examples.py` drives it. -- **The catalog.** `test_the_error_codes_page_says_what_the_code_says` keeps - `docs/error_codes.md` equal to `EXPLANATIONS`; every code has a provocation, +- **The catalog.** `tests/core/test_diagnostics.py` keeps + `docs/error_codes.md` and `sophios --explain` equal to `EXPLANATIONS`; every code has a provocation, a document under `tests/core/data/parse` or a callable in `tests/core/provocations.py`, and an explanation, or the suite fails. diff --git a/tests/core/cases.py b/tests/core/cases.py index d167cc314..fd7f9f02a 100644 --- a/tests/core/cases.py +++ b/tests/core/cases.py @@ -17,6 +17,7 @@ The loaders raise ValueError, a collection error of the calling module, for no cases, a repeated id, or a key the test does not read: pytest skips an empty parametrize silently, and a misspelled key would go unread. """ +import json import re from pathlib import Path from typing import Any @@ -25,6 +26,7 @@ import yaml from sophios.lang.diagnostics import Diagnostic +from sophios.lang.error_codes import SophiosErrorCode DATA = Path(__file__).resolve().parent / 'data' @@ -89,6 +91,12 @@ def diagnostic(found: Diagnostic) -> dict[str, Any]: return {**found.to_json(), 'code': found.code.name} +def printed(err: str) -> list[dict[str, Any]]: + """The diagnostics `--diagnostics json` printed on `err`, each with its code by name, as cases write it.""" + return [{**found, 'code': SophiosErrorCode(found['code']).name} + for found in map(json.loads, (line for line in err.splitlines() if line.startswith('{')))] + + def match(expected: Any, actual: Any) -> bool: # pylint: disable=too-many-return-statements # one per form """Whether `actual` is what `expected` says, in the forms the module docstring lists.""" if isinstance(expected, dict) and len(expected) == 1: diff --git a/tests/core/data/backends/write_into.cwl b/tests/core/data/backends/write_into.cwl new file mode 100644 index 000000000..11be9f8a7 --- /dev/null +++ b/tests/core/data/backends/write_into.cwl @@ -0,0 +1,21 @@ +# Writes into the output-target Directory `outDir`, an entry it may write, captured as its output; reads `source`. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: touch +requirements: + InitialWorkDirRequirement: + listing: + - entry: $(inputs.outDir) + writable: true +inputs: + outDir: + type: Directory + source: + type: File +outputs: + outDir: + type: Directory + outputBinding: + glob: $(inputs.outDir.basename) +arguments: +- $(inputs.outDir.basename)/result.txt diff --git a/tests/core/data/basepath/noop.cwl b/tests/core/data/basepath/noop.cwl new file mode 100644 index 000000000..f6c56eb4f --- /dev/null +++ b/tests/core/data/basepath/noop.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: echo +inputs: {} +outputs: {} diff --git a/tests/core/data/basepath/w.wic b/tests/core/data/basepath/w.wic new file mode 100644 index 000000000..e4809b774 --- /dev/null +++ b/tests/core/data/basepath/w.wic @@ -0,0 +1,2 @@ +steps: +- id: noop diff --git a/tests/core/data/compiler/literals/accepted.wic b/tests/core/data/compiler/literals/accepted.wic new file mode 100644 index 000000000..33e935144 --- /dev/null +++ b/tests/core/data/compiler/literals/accepted.wic @@ -0,0 +1,21 @@ +# Each literal as the author wrote it, in the job: quoted, a number on a text input is its text as written, and plain, +# the number YAML read, as text. A scalar given to a union with an array takes the scalar member whose type it already +# is, and is wrapped into the array otherwise: biobb's pdb takes `filter` as `boolean | string[]`, and `!ii False` +# reached it as ['false'], so it kept only the lines starting with "false". +steps: +- id: takes + in: + text_quoted: !ii '7' + text_quoted_octal: !ii '007' + text_plain: !ii 7 + text_plain_octal: !ii 007 + flag_or_words: !ii False + count_or_counts: !ii 3 + word_or_words: !ii a + file_or_files: !ii + class: File + location: x + real_or_counts: !ii 3 + word_or_counts: !ii 3 + word_or_nested_counts: !ii 3 + letter_or_letters: !ii a diff --git a/tests/core/data/compiler/literals/expected.yaml b/tests/core/data/compiler/literals/expected.yaml new file mode 100644 index 000000000..9ea63843d --- /dev/null +++ b/tests/core/data/compiler/literals/expected.yaml @@ -0,0 +1,26 @@ +# Each root's job values as written, or its refusals by code, severity, line, step and port. +accepted.wic: + written: + accepted_inputs.yml: + takes~text_quoted: '7' + takes~text_quoted_octal: '007' + takes~text_plain: '7' + takes~text_plain_octal: '7' + takes~flag_or_words: false + takes~count_or_counts: 3 + takes~word_or_words: a + takes~file_or_files: {class: File, location: x} + takes~real_or_counts: [3] + takes~word_or_counts: [3] + takes~word_or_nested_counts: [[3]] + takes~letter_or_letters: [a] +quoted.wic: + refused: [{code: LITERAL_TYPE_MISMATCH, severity: error, line: 5, step: scale, index: 1, port: n}] +octal.wic: + refused: [{code: LITERAL_TYPE_MISMATCH, severity: error, line: 5, step: scale, index: 1, port: n}] +null.wic: + refused: [{code: MISSING_REQUIRED_INPUT, severity: error, line: 5, step: scale, index: 1, port: n}] +forgot.wic: + refused: + - {code: UNRESOLVED_INPUT, severity: error, line: 5, step: mk_file, index: 1, port: name, + message: 'Did you forget to use !ii before x?'} diff --git a/tests/core/data/compiler/literals/forgot.wic b/tests/core/data/compiler/literals/forgot.wic new file mode 100644 index 000000000..539b8f3cf --- /dev/null +++ b/tests/core/data/compiler/literals/forgot.wic @@ -0,0 +1,5 @@ +# A step input written without `!ii` names an edge or a workflow input, and `x` is neither. +steps: +- id: mk_file + in: + name: x diff --git a/tests/core/data/compiler/literals/null.wic b/tests/core/data/compiler/literals/null.wic new file mode 100644 index 000000000..a08293e1c --- /dev/null +++ b/tests/core/data/compiler/literals/null.wic @@ -0,0 +1,5 @@ +# A required input bound to null has no value, refused at the line of the literal. +steps: +- id: scale + in: + n: !ii null diff --git a/tests/core/data/compiler/literals/octal.wic b/tests/core/data/compiler/literals/octal.wic new file mode 100644 index 000000000..75dfd21a8 --- /dev/null +++ b/tests/core/data/compiler/literals/octal.wic @@ -0,0 +1,5 @@ +# Quoted, an octal-looking number is text too, not the int YAML would read it as. +steps: +- id: scale + in: + n: !ii '007' diff --git a/tests/core/data/compiler/literals/quoted.wic b/tests/core/data/compiler/literals/quoted.wic new file mode 100644 index 000000000..5cb6208cb --- /dev/null +++ b/tests/core/data/compiler/literals/quoted.wic @@ -0,0 +1,5 @@ +# A quoted `!ii` scalar is its text, and text is not an int: `!ii 7` binds `n`. +steps: +- id: scale + in: + n: !ii "7" diff --git a/tests/core/data/compiler/literals/takes.cwl b/tests/core/data/compiler/literals/takes.cwl new file mode 100644 index 000000000..3b13487e6 --- /dev/null +++ b/tests/core/data/compiler/literals/takes.cwl @@ -0,0 +1,22 @@ +# One input of each type a literal is bound to: text, and a scalar or an array of it, for a literal to pick from. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + text_quoted: string + text_quoted_octal: string + text_plain: string + text_plain_octal: string + flag_or_words: {type: ['null', boolean, {type: array, items: string}]} + count_or_counts: {type: ['null', int, {type: array, items: int}]} + word_or_words: {type: ['null', string, {type: array, items: string}]} + file_or_files: {type: ['null', File, {type: array, items: File}]} + real_or_counts: {type: ['null', float, {type: array, items: int}]} + word_or_counts: {type: ['null', string, {type: array, items: int}]} + word_or_nested_counts: {type: ['null', string, {type: array, items: {type: array, items: int}}]} + letter_or_letters: + type: + - 'null' + - {type: enum, name: letter, symbols: [a, b]} + - {type: array, items: {type: enum, name: letters, symbols: [a, b]}} +outputs: {} diff --git a/tests/core/data/config/w.wic b/tests/core/data/config/w.wic new file mode 100644 index 000000000..1bfd0842a --- /dev/null +++ b/tests/core/data/config/w.wic @@ -0,0 +1,4 @@ +steps: + - id: touch + in: + filename: !ii empty.txt diff --git a/tests/core/data/discovery/laid_out.cwl b/tests/core/data/discovery/laid_out.cwl new file mode 100644 index 000000000..6c5e2c021 --- /dev/null +++ b/tests/core/data/discovery/laid_out.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: "true" +inputs: {} +outputs: {} diff --git a/tests/core/data/discovery/laid_out.wic b/tests/core/data/discovery/laid_out.wic new file mode 100644 index 000000000..5e36f0c20 --- /dev/null +++ b/tests/core/data/discovery/laid_out.wic @@ -0,0 +1 @@ +steps: {} diff --git a/tests/core/data/drawing/drawn.wic b/tests/core/data/drawing/drawn.wic new file mode 100644 index 000000000..668d469fe --- /dev/null +++ b/tests/core/data/drawing/drawn.wic @@ -0,0 +1,42 @@ +# Every graphviz setting a document gives: the root's title and ranks, a step's label by its index and its style by its +# id, a subworkflow called twice, each call drawn as a cluster of its own with the look its call gives it, a +# subworkflow with no look of its own, and edges written (`!&`, `!*`), into a subworkflow too, beside inferred ones. +wic: + graphviz: + label: My Pipeline + ranksame: ['(1, touch)', '(2, echo)'] + steps: + (1, touch): + wic: + graphviz: + label: Make\nit + echo: + wic: + graphviz: + style: dashed, bold + (4, sub.wic): + wic: + graphviz: + label: Called + (5, sub.wic): + wic: + graphviz: + style: invis +steps: +- id: touch + in: + filename: !ii a.txt + out: + - file: !& made +- id: echo + in: + message: !ii hi +- id: cat + in: + file: !* made +- id: sub.wic + run: sub.wic +- id: sub.wic + run: sub.wic +- id: plain.wic + run: plain.wic diff --git a/tests/core/data/drawing/expected.yaml b/tests/core/data/drawing/expected.yaml new file mode 100644 index 000000000..d41864377 --- /dev/null +++ b/tests/core/data/drawing/expected.yaml @@ -0,0 +1,61 @@ +# What `sophios --yaml drawn.wic --generate_cwl_workflow --graphviz ` draws in autogenerated/drawn.wic.gv, +# for each set of flags: the clusters, by name, with their attributes; the boxes, each with its label and style; the +# edges, from and to, with their attributes; and each rank=same group, with its depth: 2 in the root's cluster, 3 in +# one within it. The drawing's text, box outlines, inferred edges and edge labels take one colour, black or, with +# --graph_dark_theme, white; an edge the document wrote is blue, or a lighter blue on a dark background. No box is +# filled, and the background is transparent either way, so a slide gives it its colour. The first row states every +# box; another states some, and its clusters are all the clusters drawn, and the boxes it calls `absent` are not. +- flags: [] + palette: black + clusters: + cluster_drawn.wic: {label: My Pipeline} + cluster_sub@4: {label: Called} + cluster_sub@4~inner: {label: inner.wic} + cluster_sub@5: {label: Own, style: invis} + cluster_sub@5~inner: {label: inner.wic} + cluster_plain: {label: plain.wic} + boxes: + touch: [Make\nit, rounded] + echo: [echo, 'rounded, dashed, bold'] + cat: [cat, rounded] + sub@4: [sub.wic, rounded] + sub@5: [sub.wic, 'rounded, invis'] + plain: [plain.wic, rounded] + sub@4~cat: [cat, rounded] + sub@4~inner: [inner.wic, rounded] + sub@4~inner~touch: [touch, rounded] + sub@4~inner~cat: [cat, rounded] + sub@5~cat: [cat, rounded] + sub@5~inner: [inner.wic, rounded] + sub@5~inner~touch: [touch, rounded] + sub@5~inner~cat: [cat, rounded] + plain~echo: [echo, rounded] + edges: + - [touch, cat, {color: blue}] + - [touch, sub@4~cat, {color: blue}] + - [touch, sub@5~cat, {color: blue}] + - [sub@4~inner~touch, sub@4~inner~cat, {color: black}] + - [sub@5~inner~touch, sub@5~inner~cat, {color: black}] + ranks: [[3, [sub@4~cat, sub@4~inner]], [3, [sub@5~cat, sub@5~inner]], [2, [touch, echo]]] + said: ['Warning! plain.wic: wic: graphviz: ranksame entry (2, echo) addresses no step of', + there is no step 2; the document has 1 step. The entry is ignored.] +- flags: [--graph_label_stepname] + palette: black + boxes: {touch: [touch, rounded], sub@4: [sub@4, rounded], plain: [plain, rounded], sub@4~inner: [inner, rounded]} +- flags: [--graph_label_edges, --graph_dark_theme] + palette: white + edges: + - [touch, cat, {label: file, color: lightskyblue, fontcolor: white}] + - [touch, sub@4~cat, {label: file, color: lightskyblue, fontcolor: white}] + - [touch, sub@5~cat, {label: file, color: lightskyblue, fontcolor: white}] + - [sub@4~inner~touch, sub@4~inner~cat, {label: file, color: white, fontcolor: white}] + - [sub@5~inner~touch, sub@5~inner~cat, {label: file, color: white, fontcolor: white}] +- flags: [--graph_inline_depth, '0'] + palette: black + clusters: {cluster_drawn.wic: {label: My Pipeline}} + absent: [sub@4~cat] + ranks: [[2, [touch, echo]]] +- flags: [--graph_inline_depth, '1'] + palette: black + clusters: {cluster_drawn.wic: {}, cluster_sub@4: {}, cluster_sub@5: {}, cluster_plain: {}} + absent: [sub@4~inner~touch] diff --git a/tests/core/data/drawing/inner.wic b/tests/core/data/drawing/inner.wic new file mode 100644 index 000000000..f97b2eafd --- /dev/null +++ b/tests/core/data/drawing/inner.wic @@ -0,0 +1,6 @@ +# Two levels down, with an edge inference made. +steps: +- id: touch + in: + filename: !ii b.txt +- id: cat diff --git a/tests/core/data/drawing/plain.wic b/tests/core/data/drawing/plain.wic new file mode 100644 index 000000000..f0d4cd88e --- /dev/null +++ b/tests/core/data/drawing/plain.wic @@ -0,0 +1,9 @@ +# No look of its own: its cluster is titled with the id of the step that calls it. A rank of fewer than two steps +# that exist is not drawn, and an entry that addresses no step is named on stderr. +wic: + graphviz: + ranksame: ['(1, echo)', '(2, echo)'] +steps: +- id: echo + in: + message: !ii there diff --git a/tests/core/data/drawing/sub.wic b/tests/core/data/drawing/sub.wic new file mode 100644 index 000000000..a46b9ba27 --- /dev/null +++ b/tests/core/data/drawing/sub.wic @@ -0,0 +1,11 @@ +# Titled by its own label unless its call gives one; its ranks are drawn in its own cluster. +wic: + graphviz: + label: Own + ranksame: ['(1, cat)', '(2, inner.wic)'] +steps: +- id: cat + in: + file: !* made +- id: inner.wic + run: inner.wic diff --git a/tests/core/data/frontdoor/calls/child.wic b/tests/core/data/frontdoor/calls/child.wic new file mode 100644 index 000000000..18d365806 --- /dev/null +++ b/tests/core/data/frontdoor/calls/child.wic @@ -0,0 +1,5 @@ +# the child keeps its comments too +steps: +- id: mk_file + in: + name: child.txt diff --git a/tests/core/data/frontdoor/calls/root.wic b/tests/core/data/frontdoor/calls/root.wic new file mode 100644 index 000000000..90f4f5207 --- /dev/null +++ b/tests/core/data/frontdoor/calls/root.wic @@ -0,0 +1,9 @@ +# Calls child.wic twice, the second time under the namespace gpu. +steps: +- id: child.wic +- id: child.wic +wic: + steps: + (2, child.wic): + wic: + namespace: gpu diff --git a/tests/core/data/frontdoor/cwl_workflow/adapters/echo.cwl b/tests/core/data/frontdoor/cwl_workflow/adapters/echo.cwl new file mode 100644 index 000000000..bb00490b1 --- /dev/null +++ b/tests/core/data/frontdoor/cwl_workflow/adapters/echo.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: echo +inputs: {text: {type: string, inputBinding: {position: 1}}} +outputs: {out: stdout} diff --git a/tests/core/data/frontdoor/cwl_workflow/adapters/packed.cwl b/tests/core/data/frontdoor/cwl_workflow/adapters/packed.cwl new file mode 100644 index 000000000..8b5829f86 --- /dev/null +++ b/tests/core/data/frontdoor/cwl_workflow/adapters/packed.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +$graph: + - {id: main, class: Workflow, inputs: {text: string}, + outputs: {said: {type: File, outputSource: echo/out}}, + steps: {echo: {run: "#echo", in: {text: text}, out: [out]}}} + - {id: echo, class: CommandLineTool, baseCommand: echo, inputs: {text: string}, outputs: {out: stdout}} diff --git a/tests/core/data/frontdoor/cwl_workflow/adapters/say.cwl b/tests/core/data/frontdoor/cwl_workflow/adapters/say.cwl new file mode 100644 index 000000000..661f85f0e --- /dev/null +++ b/tests/core/data/frontdoor/cwl_workflow/adapters/say.cwl @@ -0,0 +1 @@ +{class: Workflow, cwlVersion: v1.2, inputs: {text: string}, outputs: {said: {type: File, outputSource: echo/out}}, steps: {echo: {run: echo.cwl, in: {text: text}, out: [out]}}} diff --git a/tests/core/data/frontdoor/cwl_workflow/echo.cwl b/tests/core/data/frontdoor/cwl_workflow/echo.cwl new file mode 100644 index 000000000..bb00490b1 --- /dev/null +++ b/tests/core/data/frontdoor/cwl_workflow/echo.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: echo +inputs: {text: {type: string, inputBinding: {position: 1}}} +outputs: {out: stdout} diff --git a/tests/core/data/frontdoor/cwl_workflow/inline_body.wic b/tests/core/data/frontdoor/cwl_workflow/inline_body.wic new file mode 100644 index 000000000..df1364f74 --- /dev/null +++ b/tests/core/data/frontdoor/cwl_workflow/inline_body.wic @@ -0,0 +1,4 @@ +steps: + - id: s + run: {class: Workflow, cwlVersion: v1.2, inputs: {text: string}, outputs: {said: {type: File, outputSource: echo/out}}, steps: {echo: {run: echo.cwl, in: {text: text}, out: [out]}}} + in: {text: !ii hi} diff --git a/tests/core/data/frontdoor/cwl_workflow/packed_on_search_paths.wic b/tests/core/data/frontdoor/cwl_workflow/packed_on_search_paths.wic new file mode 100644 index 000000000..ef92c817b --- /dev/null +++ b/tests/core/data/frontdoor/cwl_workflow/packed_on_search_paths.wic @@ -0,0 +1,3 @@ +steps: + - id: packed + in: {text: !ii hi} diff --git a/tests/core/data/frontdoor/cwl_workflow/run_packed.wic b/tests/core/data/frontdoor/cwl_workflow/run_packed.wic new file mode 100644 index 000000000..0b3e1fd3d --- /dev/null +++ b/tests/core/data/frontdoor/cwl_workflow/run_packed.wic @@ -0,0 +1,4 @@ +steps: + - id: s + run: packed.cwl + in: {text: !ii hi} diff --git a/tests/core/data/frontdoor/cwl_workflow/run_path.wic b/tests/core/data/frontdoor/cwl_workflow/run_path.wic new file mode 100644 index 000000000..1ca533f48 --- /dev/null +++ b/tests/core/data/frontdoor/cwl_workflow/run_path.wic @@ -0,0 +1,4 @@ +steps: + - id: s + run: say.cwl + in: {text: !ii hi} diff --git a/tests/core/data/frontdoor/cwl_workflow/say.cwl b/tests/core/data/frontdoor/cwl_workflow/say.cwl new file mode 100644 index 000000000..661f85f0e --- /dev/null +++ b/tests/core/data/frontdoor/cwl_workflow/say.cwl @@ -0,0 +1 @@ +{class: Workflow, cwlVersion: v1.2, inputs: {text: string}, outputs: {said: {type: File, outputSource: echo/out}}, steps: {echo: {run: echo.cwl, in: {text: text}, out: [out]}}} diff --git a/tests/core/data/frontdoor/cwl_workflow/search_paths.wic b/tests/core/data/frontdoor/cwl_workflow/search_paths.wic new file mode 100644 index 000000000..de60b3bd4 --- /dev/null +++ b/tests/core/data/frontdoor/cwl_workflow/search_paths.wic @@ -0,0 +1,3 @@ +steps: + - id: say + in: {text: !ii hi} diff --git a/tests/core/data/frontdoor/forward.wic b/tests/core/data/frontdoor/forward.wic new file mode 100644 index 000000000..9e0426d0e --- /dev/null +++ b/tests/core/data/frontdoor/forward.wic @@ -0,0 +1,15 @@ +# A workflow that references an edge before defining it. +# +# These comment lines are load-bearing: a YAML round trip drops them, which +# is exactly what moves every construct below them onto a different line. +# +steps: +- id: xform + in: + file: !* later + name: out.txt +- id: mk_file + in: + name: made.txt + out: + - file: !& later diff --git a/tests/core/data/frontdoor/gate/probe.cwl b/tests/core/data/frontdoor/gate/probe.cwl new file mode 100644 index 000000000..ca691d182 --- /dev/null +++ b/tests/core/data/frontdoor/gate/probe.cwl @@ -0,0 +1,6 @@ +wic: + nonsense_key: 1 +steps: +- id: mk_file + in: + name: !ii a diff --git a/tests/core/data/frontdoor/gate/probe.wic b/tests/core/data/frontdoor/gate/probe.wic new file mode 100644 index 000000000..ca691d182 --- /dev/null +++ b/tests/core/data/frontdoor/gate/probe.wic @@ -0,0 +1,6 @@ +wic: + nonsense_key: 1 +steps: +- id: mk_file + in: + name: !ii a diff --git a/tests/core/data/frontdoor/gate/probe.yml b/tests/core/data/frontdoor/gate/probe.yml new file mode 100644 index 000000000..ca691d182 --- /dev/null +++ b/tests/core/data/frontdoor/gate/probe.yml @@ -0,0 +1,6 @@ +wic: + nonsense_key: 1 +steps: +- id: mk_file + in: + name: !ii a diff --git a/tests/core/data/frontdoor/own/child.wic b/tests/core/data/frontdoor/own/child.wic new file mode 100644 index 000000000..e01c5b87a --- /dev/null +++ b/tests/core/data/frontdoor/own/child.wic @@ -0,0 +1,7 @@ +# A namespace a child declares for itself does not move where its caller looks for it. +wic: + namespace: gpu +steps: +- id: mk_file + in: + name: c.txt diff --git a/tests/core/data/frontdoor/own/root.wic b/tests/core/data/frontdoor/own/root.wic new file mode 100644 index 000000000..fe8d5e94e --- /dev/null +++ b/tests/core/data/frontdoor/own/root.wic @@ -0,0 +1,2 @@ +steps: +- id: child.wic diff --git a/tests/core/data/frontdoor/paths/t.cwl b/tests/core/data/frontdoor/paths/t.cwl new file mode 100644 index 000000000..377a9490c --- /dev/null +++ b/tests/core/data/frontdoor/paths/t.cwl @@ -0,0 +1 @@ +{class: CommandLineTool, cwlVersion: v1.2, baseCommand: echo, inputs: {a: string}, outputs: {}} diff --git a/tests/core/data/frontdoor/paths/w.wic b/tests/core/data/frontdoor/paths/w.wic new file mode 100644 index 000000000..b9ddd9a69 --- /dev/null +++ b/tests/core/data/frontdoor/paths/w.wic @@ -0,0 +1,4 @@ +steps: + - id: s + run: t.cwl + in: {a: !ii x} diff --git a/tests/core/data/frontdoor/script/sophios/examples/scripts/workflow_types.py b/tests/core/data/frontdoor/script/sophios/examples/scripts/workflow_types.py new file mode 100644 index 000000000..e3f5ba8c4 --- /dev/null +++ b/tests/core/data/frontdoor/script/sophios/examples/scripts/workflow_types.py @@ -0,0 +1 @@ +string = {'type': 'string', 'format': 'edam:format_2330'} diff --git a/tests/core/data/frontdoor/script/work/compile.wic b/tests/core/data/frontdoor/script/work/compile.wic new file mode 100644 index 000000000..2438681a3 --- /dev/null +++ b/tests/core/data/frontdoor/script/work/compile.wic @@ -0,0 +1,5 @@ +steps: +- id: python_script + in: + script: !ii my_script.py + name: !ii made.txt diff --git a/tests/core/data/frontdoor/script/work/my_script.py b/tests/core/data/frontdoor/script/work/my_script.py new file mode 100644 index 000000000..3acefdf67 --- /dev/null +++ b/tests/core/data/frontdoor/script/work/my_script.py @@ -0,0 +1,10 @@ +"""A script whose annotations are all the generator reads: it writes the file its input names.""" +from pathlib import Path + +inputs = {'name': {'type': 'string', 'format': 'edam:format_2330'}} +outputs = {'file': ('$(inputs.name)', {'type': 'File', 'format': 'edam:format_2330'})} + + +def main(name: str) -> None: + """Write the empty file `name`.""" + Path(name).touch() diff --git a/tests/core/data/frontdoor/script/work/resolve.wic b/tests/core/data/frontdoor/script/work/resolve.wic new file mode 100644 index 000000000..8f4d61a69 --- /dev/null +++ b/tests/core/data/frontdoor/script/work/resolve.wic @@ -0,0 +1,5 @@ +steps: +- id: python_script + in: + script: my_script.py + name: made.txt diff --git a/tests/core/data/frontdoor/tutorial.wic b/tests/core/data/frontdoor/tutorial.wic new file mode 100644 index 000000000..82e0c0623 --- /dev/null +++ b/tests/core/data/frontdoor/tutorial.wic @@ -0,0 +1,10 @@ +# a leading comment + +wic: + graphviz: + label: Root + +steps: +- id: mk_file + in: + name: made.txt diff --git a/tests/core/data/packing/a/s.sh b/tests/core/data/packing/a/s.sh new file mode 100644 index 000000000..0264b8822 --- /dev/null +++ b/tests/core/data/packing/a/s.sh @@ -0,0 +1,2 @@ +#!/bin/sh +echo a diff --git a/tests/core/data/packing/a/w.wic b/tests/core/data/packing/a/w.wic new file mode 100644 index 000000000..b03803bf5 --- /dev/null +++ b/tests/core/data/packing/a/w.wic @@ -0,0 +1,13 @@ +# The same inline body in two `.wic` files in two directories: each includes its own directory's `s.sh`. +steps: +- id: say + run: + class: CommandLineTool + requirements: + InitialWorkDirRequirement: + listing: [{entryname: s.sh, entry: {$include: s.sh}}] + baseCommand: [sh, s.sh] + inputs: {} + outputs: {} +- id: inner + run: ../b/inner.wic diff --git a/tests/core/data/packing/b/inner.wic b/tests/core/data/packing/b/inner.wic new file mode 100644 index 000000000..1d8a1ed7e --- /dev/null +++ b/tests/core/data/packing/b/inner.wic @@ -0,0 +1,10 @@ +steps: +- id: say + run: + class: CommandLineTool + requirements: + InitialWorkDirRequirement: + listing: [{entryname: s.sh, entry: {$include: s.sh}}] + baseCommand: [sh, s.sh] + inputs: {} + outputs: {} diff --git a/tests/core/data/packing/b/s.sh b/tests/core/data/packing/b/s.sh new file mode 100644 index 000000000..c4ced2b4e --- /dev/null +++ b/tests/core/data/packing/b/s.sh @@ -0,0 +1,2 @@ +#!/bin/sh +echo b diff --git a/tests/core/data/packing/broken/broken.cwl b/tests/core/data/packing/broken/broken.cwl new file mode 100644 index 000000000..c77bed059 --- /dev/null +++ b/tests/core/data/packing/broken/broken.cwl @@ -0,0 +1,9 @@ +# Its `$include` names nothing. +cwlVersion: v1.2 +class: CommandLineTool +requirements: + InitialWorkDirRequirement: + listing: [{entryname: s.sh, entry: {$include: missing.sh}}] +baseCommand: [sh, s.sh] +inputs: {} +outputs: {} diff --git a/tests/core/data/packing/broken/echo.cwl b/tests/core/data/packing/broken/echo.cwl new file mode 100644 index 000000000..afc03a40d --- /dev/null +++ b/tests/core/data/packing/broken/echo.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: echo +inputs: {message: {type: string, default: hi, inputBinding: {position: 1}}} +outputs: {out: {type: stdout}} +stdout: out.txt diff --git a/tests/core/data/packing/broken/unused.wic b/tests/core/data/packing/broken/unused.wic new file mode 100644 index 000000000..3b59fe907 --- /dev/null +++ b/tests/core/data/packing/broken/unused.wic @@ -0,0 +1,3 @@ +# The broken tool beside it is on the search path, and no step runs it. +steps: +- id: echo diff --git a/tests/core/data/packing/broken/used.wic b/tests/core/data/packing/broken/used.wic new file mode 100644 index 000000000..4bc67723e --- /dev/null +++ b/tests/core/data/packing/broken/used.wic @@ -0,0 +1,3 @@ +steps: +- id: echo +- id: broken diff --git a/tests/core/data/packing/built.wic b/tests/core/data/packing/built.wic new file mode 100644 index 000000000..b53980b65 --- /dev/null +++ b/tests/core/data/packing/built.wic @@ -0,0 +1,2 @@ +steps: +- id: built diff --git a/tests/core/data/packing/dataA/config.txt b/tests/core/data/packing/dataA/config.txt new file mode 100644 index 000000000..1d12df3b1 --- /dev/null +++ b/tests/core/data/packing/dataA/config.txt @@ -0,0 +1 @@ +config of A diff --git a/tests/core/data/packing/dataA/echo.cwl b/tests/core/data/packing/dataA/echo.cwl new file mode 100644 index 000000000..973a48d59 --- /dev/null +++ b/tests/core/data/packing/dataA/echo.cwl @@ -0,0 +1,9 @@ +# Prints its `config.txt` default, beside it. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: cat +stdout: out.txt +inputs: + config: {type: File, default: {class: File, location: config.txt}, inputBinding: {position: 1}} +outputs: + out: {type: stdout} diff --git a/tests/core/data/packing/dataB/config.txt b/tests/core/data/packing/dataB/config.txt new file mode 100644 index 000000000..ba33a75d7 --- /dev/null +++ b/tests/core/data/packing/dataB/config.txt @@ -0,0 +1 @@ +config of B diff --git a/tests/core/data/packing/dataB/echo.cwl b/tests/core/data/packing/dataB/echo.cwl new file mode 100644 index 000000000..973a48d59 --- /dev/null +++ b/tests/core/data/packing/dataB/echo.cwl @@ -0,0 +1,9 @@ +# Prints its `config.txt` default, beside it. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: cat +stdout: out.txt +inputs: + config: {type: File, default: {class: File, location: config.txt}, inputBinding: {position: 1}} +outputs: + out: {type: stdout} diff --git a/tests/core/data/packing/live.wic b/tests/core/data/packing/live.wic new file mode 100644 index 000000000..02fb97c51 --- /dev/null +++ b/tests/core/data/packing/live.wic @@ -0,0 +1,9 @@ +# relcat declared as a real-time analysis. +steps: +- id: slow_log +- id: cwl_subinterpreter + in: + file_pattern: !ii out.log + cwl_tool: !ii relcat + max_times: !ii '1' + config: !ii {in: {}} diff --git a/tests/core/data/packing/make_use.wic b/tests/core/data/packing/make_use.wic new file mode 100644 index 000000000..2cda98dcb --- /dev/null +++ b/tests/core/data/packing/make_use.wic @@ -0,0 +1,6 @@ +# make, packed, feeds use, as written, through the edge inference makes. +steps: +- id: make + run: tools/make.cwl +- id: use + run: tools/use.cwl diff --git a/tests/core/data/packing/one.wic b/tests/core/data/packing/one.wic new file mode 100644 index 000000000..aa7d50cec --- /dev/null +++ b/tests/core/data/packing/one.wic @@ -0,0 +1,3 @@ +steps: +- id: relcat + run: tools/relcat.cwl diff --git a/tests/core/data/packing/ontology.wic b/tests/core/data/packing/ontology.wic new file mode 100644 index 000000000..f2c51fa10 --- /dev/null +++ b/tests/core/data/packing/ontology.wic @@ -0,0 +1,2 @@ +steps: +- id: ontology diff --git a/tests/core/data/packing/pair.wic b/tests/core/data/packing/pair.wic new file mode 100644 index 000000000..c85706f9d --- /dev/null +++ b/tests/core/data/packing/pair.wic @@ -0,0 +1,6 @@ +# Two tools both called echo.cwl, each with its own config.txt default. +steps: +- id: a + run: dataA/echo.cwl +- id: b + run: dataB/echo.cwl diff --git a/tests/core/data/packing/relcat.wic b/tests/core/data/packing/relcat.wic new file mode 100644 index 000000000..e3f1798ca --- /dev/null +++ b/tests/core/data/packing/relcat.wic @@ -0,0 +1,5 @@ +# relcat from the tool search path, three times. +steps: +- id: relcat +- id: relcat +- id: relcat diff --git a/tests/core/data/packing/relcat_and_config.wic b/tests/core/data/packing/relcat_and_config.wic new file mode 100644 index 000000000..0e64f2d19 --- /dev/null +++ b/tests/core/data/packing/relcat_and_config.wic @@ -0,0 +1,5 @@ +steps: +- id: relcat + run: tools/relcat.cwl +- id: a + run: dataA/echo.cwl diff --git a/tests/core/data/packing/schemadef.wic b/tests/core/data/packing/schemadef.wic new file mode 100644 index 000000000..5923854e5 --- /dev/null +++ b/tests/core/data/packing/schemadef.wic @@ -0,0 +1,4 @@ +# The conformance tool whose record type is `$import`ed from a file beside it. +steps: +- id: sd + run: ../cwl-v1.2/tests/schemadef_types_with_import-tool.cwl diff --git a/tests/core/data/packing/schemadef.yml b/tests/core/data/packing/schemadef.yml new file mode 100644 index 000000000..0777444ee --- /dev/null +++ b/tests/core/data/packing/schemadef.yml @@ -0,0 +1,9 @@ +# The conformance job, its bam read from the conformance suite. +message: + bam: + class: File + format: edam:format_2572 + location: ../cwl-v1.2/tests/schemadef_types_with_import-test.bam + readgroup_meta_list: + - {CN: UNKNOWN, DT: '1970-01-01T00:00:00Z', ID: SRR622461, LB: Illumina NA12878, PI: '250', PL: ILLUMINA, + SM: NA12878} diff --git a/tests/core/data/packing/tools/Dockerfile_built b/tests/core/data/packing/tools/Dockerfile_built new file mode 100644 index 000000000..95d0bb27b --- /dev/null +++ b/tests/core/data/packing/tools/Dockerfile_built @@ -0,0 +1,2 @@ +FROM alpine:3.20 +RUN echo built diff --git a/tests/core/data/packing/tools/built.cwl b/tests/core/data/packing/tools/built.cwl new file mode 100644 index 000000000..487b46dc0 --- /dev/null +++ b/tests/core/data/packing/tools/built.cwl @@ -0,0 +1,11 @@ +# Like extract_pdbbind_refined.cwl: its image is built from a Dockerfile beside it, and it keeps its own version. +cwlVersion: v1.0 +class: CommandLineTool +hints: + DockerRequirement: + dockerImageId: built_here + dockerFile: + $include: Dockerfile_built +baseCommand: echo +inputs: {} +outputs: {} diff --git a/tests/core/data/packing/tools/data.txt b/tests/core/data/packing/tools/data.txt new file mode 100644 index 000000000..83de37ada --- /dev/null +++ b/tests/core/data/packing/tools/data.txt @@ -0,0 +1 @@ +data beside the tool diff --git a/tests/core/data/packing/tools/make.cwl b/tests/core/data/packing/tools/make.cwl new file mode 100644 index 000000000..3e8393559 --- /dev/null +++ b/tests/core/data/packing/tools/make.cwl @@ -0,0 +1,10 @@ +# A relative default, and an output whose format inference reads as written: `edam:format_2330`. +cwlVersion: v1.2 +class: CommandLineTool +$namespaces: {edam: https://edamontology.org/} +baseCommand: cat +stdout: made.txt +inputs: + seed: {type: File, default: {class: File, location: seed.txt}, inputBinding: {position: 1}} +outputs: + out: {type: File, format: edam:format_2330, outputBinding: {glob: made.txt}} diff --git a/tests/core/data/packing/tools/ontology.cwl b/tests/core/data/packing/tools/ontology.cwl new file mode 100644 index 000000000..41e01c5c4 --- /dev/null +++ b/tests/core/data/packing/tools/ontology.cwl @@ -0,0 +1,8 @@ +# Its `$schemas` stay as written: packing never goes to the network for an ontology. +cwlVersion: v1.2 +class: CommandLineTool +$schemas: ['http://schemas.invalid/ontology.owl'] +baseCommand: echo +inputs: {message: {type: string, default: hi, inputBinding: {position: 1}}} +outputs: {out: {type: stdout}} +stdout: out.txt diff --git a/tests/core/data/packing/tools/relcat.cwl b/tests/core/data/packing/tools/relcat.cwl new file mode 100644 index 000000000..5681d699d --- /dev/null +++ b/tests/core/data/packing/tools/relcat.cwl @@ -0,0 +1,18 @@ +# Its script by `$include`, its data by a relative default: both beside it. It prints `from-include`, then the data. +cwlVersion: v1.2 +class: CommandLineTool +requirements: + InitialWorkDirRequirement: + listing: + - entryname: s.sh + entry: + $include: s.sh +baseCommand: [sh, s.sh] +inputs: + extra: + type: File + default: {class: File, location: data.txt} + inputBinding: {position: 1} +outputs: + out: {type: stdout} +stdout: out.txt diff --git a/tests/core/data/packing/tools/s.sh b/tests/core/data/packing/tools/s.sh new file mode 100644 index 000000000..8a1e33fe2 --- /dev/null +++ b/tests/core/data/packing/tools/s.sh @@ -0,0 +1,2 @@ +#!/bin/sh +echo from-include; cat "$1" diff --git a/tests/core/data/packing/tools/seed.txt b/tests/core/data/packing/tools/seed.txt new file mode 100644 index 000000000..e31de1f3a --- /dev/null +++ b/tests/core/data/packing/tools/seed.txt @@ -0,0 +1 @@ +seed diff --git a/tests/core/data/packing/tools/slow_log.cwl b/tests/core/data/packing/tools/slow_log.cwl new file mode 100644 index 000000000..58de206c4 --- /dev/null +++ b/tests/core/data/packing/tools/slow_log.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: [touch, out.log] +inputs: {} +outputs: {log: {type: File, outputBinding: {glob: out.log}}} diff --git a/tests/core/data/packing/tools/use.cwl b/tests/core/data/packing/tools/use.cwl new file mode 100644 index 000000000..ace7e9f6a --- /dev/null +++ b/tests/core/data/packing/tools/use.cwl @@ -0,0 +1,9 @@ +cwlVersion: v1.2 +class: CommandLineTool +$namespaces: {edam: https://edamontology.org/} +baseCommand: cat +stdout: used.txt +inputs: + file: {type: File, format: edam:format_2330, inputBinding: {position: 1}} +outputs: + out: {type: File, outputBinding: {glob: used.txt}} diff --git a/tests/core/data/packing/two.wic b/tests/core/data/packing/two.wic new file mode 100644 index 000000000..5cc6c4dfb --- /dev/null +++ b/tests/core/data/packing/two.wic @@ -0,0 +1,6 @@ +# Two steps run relcat by its path. +steps: +- id: one + run: tools/relcat.cwl +- id: two + run: tools/relcat.cwl diff --git a/tests/core/data/partial_failure/cases.yaml b/tests/core/data/partial_failure/cases.yaml deleted file mode 100644 index 5d0a235f0..000000000 --- a/tests/core/data/partial_failure/cases.yaml +++ /dev/null @@ -1,101 +0,0 @@ -# Each case is a project: `tools`, each .cwl over a stub CommandLineTool (`baseCommand: 'true'`, no ports), -# and `workflows`, each .wic, beside a config that searches the directory. `sophios --yaml w.wic -# --generate_cwl_workflow` compiles it with `flags` (--partial_failure_enable unless the case names them), and -# `written` is what files under autogenerated/ hold, in the forms of tests/core/cases.py; `refused`, what the -# command line says instead. Expected by hand from docs/partial-failures.md, never filled from a run. -- id: codes-listed-and-ranged - why: successCodes is emitted CWL, so no set's iteration order may reach it; these codes are chosen so that a set's - order is not the sorted one - flags: [--partial_failure_enable, --partial_failure_success_codes, 9, 4, 1, 32, --partial_failure_success_codes_range, 3, 6] - tools: {make: {}} - workflows: {w: "steps:\n- id: make\n"} - written: {w~make.cwl: {successCodes: [0, 1, 3, 4, 5, 9, 32]}} -- id: codes-zero-alone - why: 0 always counts, and a range keeps its lower bound and excludes its upper - flags: [--partial_failure_enable, --partial_failure_success_codes, --partial_failure_success_codes_range, 0, 1] - tools: {make: {}} - workflows: {w: "steps:\n- id: make\n"} - written: {w~make.cwl: {successCodes: [0]}} -- id: a-range-upside-down - why: a range whose lower bound is above its upper names no code, a usage error whatever else is given; with the flag - it stopped the command line with an AssertionError, and without it it was never read - flags: [--partial_failure_success_codes_range, 5, 2] - tools: {make: {}} - workflows: {w: "steps:\n- id: make\n"} - refused: '--partial_failure_success_codes_range 5 2: the lower bound is above the upper' -- id: codes-the-tool-declares - why: a tool's own successCodes are kept beside the policy's; they were replaced, so a code the tool counts as success - failed its step - tools: {make: {successCodes: [3, 0]}} - workflows: {w: "steps:\n- id: make\n"} - written: {w~make.cwl: {successCodes: [0, 1, 3]}} -- id: an-output-written-as-its-type - why: an output written as its type alone stopped the compile with a TypeError; a stream becomes a File? that globs - the file the tool names - tools: {say: {stdout: said.txt, outputs: {said: stdout}}} - workflows: {w: "steps:\n- id: say\n"} - written: {w~say.cwl: {stdout: said.txt, outputs: {exact: {said: {type: 'File?', outputBinding: {glob: said.txt}}}}}} -- id: a-stream-the-tool-does-not-name - why: stderr? is no CWL type, and cwltool refuses it; a stream the tool does not name is written to a file named by - the sha1 of the tool, cwltool's scheme for it, and globbed from there - tools: {say: {outputs: {err: {type: stderr}}}} - workflows: {w: "steps:\n- id: say\n"} - written: {w~say.cwl: {stderr: {re: '^[0-9a-f]{40}$'}, outputs: {err: {type: 'File?', - outputBinding: {glob: {re: '^[0-9a-f]{40}$'}}}}}} -- id: every-type-form - why: only a type written as one string was made optional; an array or a record written in full, and a union without - null, stayed required, so a job that left them out failed its step - tools: - make: - outputs: - listed: {type: 'File[]', outputBinding: {glob: '*.txt'}} - files: {type: {type: array, items: File}, outputBinding: {glob: '*.txt'}} - either: {type: [File, Directory], outputBinding: {glob: out}} - maybe: {type: ['null', File], outputBinding: {glob: out}} - pair: {type: {type: record, fields: {left: {type: File, outputBinding: {glob: left}}}}} - workflows: {w: "steps:\n- id: make\n"} - written: - w~make.cwl: - outputs: - listed: {type: 'File[]?'} - files: {type: ['null', {exact: {type: array, items: File}}]} - either: {type: ['null', File, Directory]} - maybe: {type: ['null', File]} - pair: {type: ['null', {exact: {type: record, fields: {left: {type: File, outputBinding: {glob: left}}}}}]} -- id: a-real-time-analysis - why: an analysis is compiled under the workflow's options, so its steps took the null checks, but its tools never - took the success codes or the optional outputs, which only the root's tree was given - tools: - make: {outputs: {made: {type: File, outputBinding: {glob: made.txt}}}} - look: {inputs: {file: File}, outputs: {seen: {type: File, outputBinding: {glob: seen.txt}}}} - workflows: - w: | - steps: - - id: make - - id: cwl_subinterpreter - in: - file_pattern: !ii made.txt - cwl_tool: !ii look - max_times: !ii 1 - config: !ii {in: {file: made.txt}} - written: - realtime/w/look_only.cwl: {steps: [{id: look, when: '$(inputs["file"] != null)'}]} - realtime/w/look_only~look.cwl: {successCodes: [0, 1], outputs: {seen: {type: 'File?'}}} -- id: no-when-of-its-own - why: a step with no when of its own runs only when every required input arrived, in the text it always had - tools: {pair: {inputs: {left: string, right: string}}} - workflows: {w: "steps:\n- id: pair\n in:\n left: !ii a\n right: !ii b\n"} - written: {w.cwl: {steps: [{id: pair, when: '$(inputs["left"] != null && inputs["right"] != null)'}]}} -- id: a-when-of-its-own - why: a step's own when was replaced by the null checks, so a step its author switched off ran; it is evaluated - after them, once, and a when written as a function body returns false first unless every required input arrived - tools: {say: {inputs: {message: string}}, tell: {inputs: {message: string}}} - workflows: {w: "steps:\n- id: say\n when: '$(inputs.message != \"skip\")'\n in:\n message: !ii skip\n- id: tell\n when: '${ return inputs.message != \"skip\"; }'\n in:\n message: !ii skip\n"} - written: {w.cwl: {steps: [{id: say, when: '$(inputs["message"] != null && (inputs.message != "skip"))'}, - {id: tell, when: '${if (!(inputs["message"] != null)) { return false; } return inputs.message != "skip"; }'}]}} -- id: a-when-that-is-not-one-expression - why: a when that is not one $(...) or ${...} evaluates to no boolean, so cwltool refuses it as a when, and the null - checks were written over it; it is written as the author wrote it - tools: {say: {inputs: {message: string}}, tell: {inputs: {message: string}}} - workflows: {w: "steps:\n- id: say\n when: 'on $(inputs.message)'\n in:\n message: !ii a\n- id: tell\n when: true\n in:\n message: !ii b\n"} - written: {w.cwl: {steps: [{id: say, when: 'on $(inputs.message)'}, {id: tell, when: true}]}} diff --git a/tests/core/data/partial_failure/err.cwl b/tests/core/data/partial_failure/err.cwl new file mode 100644 index 000000000..dc827b735 --- /dev/null +++ b/tests/core/data/partial_failure/err.cwl @@ -0,0 +1,6 @@ +# A stream the tool does not name. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: {err: {type: stderr}} diff --git a/tests/core/data/partial_failure/expected.yaml b/tests/core/data/partial_failure/expected.yaml new file mode 100644 index 000000000..53a4441cf --- /dev/null +++ b/tests/core/data/partial_failure/expected.yaml @@ -0,0 +1,45 @@ +# What `sophios --yaml w.wic ` writes under autogenerated/, in the forms of tests/core/cases.py, or what it +# refuses with; stated by hand from docs/partial-failures.md, never filled from a run. +- why: each output accepts null in whichever form it is written; a stream becomes a File? that globs the file the tool + names, or a file named by the sha1 of the tool, cwltool's scheme for it, since stderr? is no CWL type; a tool's own + success codes are kept beside the policy's; an analysis's tools take the codes and the optional outputs as the + workflow's do. A step runs only when every required input arrived, then its own when, evaluated once; a when + written as a function body returns false first unless every required input arrived; and a when that is not one + $(...) or ${...} is written as its author wrote it. + flags: [--generate_cwl_workflow, --partial_failure_enable] + written: + w~make.cwl: + successCodes: [0, 1, 3] + outputs: + listed: {type: 'File[]?'} + files: {type: ['null', {exact: {type: array, items: File}}]} + either: {type: ['null', File, Directory]} + maybe: {type: ['null', File]} + pair: {type: ['null', {exact: {type: record, fields: {left: {type: File, outputBinding: {glob: left}}}}}]} + w~say.cwl: {stdout: said.txt, outputs: {exact: {said: {type: 'File?', outputBinding: {glob: said.txt}}}}} + w~err.cwl: {stderr: {re: '^[0-9a-f]{40}$'}, outputs: {err: {type: 'File?', outputBinding: {glob: {re: '^[0-9a-f]{40}$'}}}}} + w.cwl: + steps: + contains: + - {id: pair, when: '$(inputs["left"] != null && inputs["right"] != null)'} + - {id: say_skip, when: '$(inputs["message"] != null && (inputs.message != "skip"))'} + - {id: tell_skip, when: '${if (!(inputs["message"] != null)) { return false; } return inputs.message != "skip"; }'} + - {id: say_on, when: 'on $(inputs.message)'} + - {id: tell_true, when: true} + realtime/w/look_only.cwl: {steps: [{id: look, when: '$(inputs["file"] != null)'}]} + realtime/w/look_only~look.cwl: {successCodes: [0, 1], outputs: {seen: {type: 'File?'}}} +- why: successCodes is emitted CWL, so no set's iteration order may reach it; these codes are chosen so that a set's + order is not the sorted one; a range keeps its lower bound and excludes its upper + flags: [--generate_cwl_workflow, --partial_failure_enable, --partial_failure_success_codes, '9', '4', '1', '32', + --partial_failure_success_codes_range, '3', '6'] + written: {w~say.cwl: {successCodes: [0, 1, 3, 4, 5, 9, 32]}} +- why: 0 always counts + flags: [--generate_cwl_workflow, --partial_failure_enable, --partial_failure_success_codes, + --partial_failure_success_codes_range, '0', '1'] + written: {w~say.cwl: {successCodes: [0]}} +- why: a range whose lower bound is above its upper names no code, a usage error whatever else is given + flags: [--generate_cwl_workflow, --partial_failure_success_codes_range, '5', '2'] + refused: '--partial_failure_success_codes_range 5 2: the lower bound is above the upper' +- why: under --docker_remove_entrypoints the image the runner pulls is the one built without its entrypoint + flags: [--generate_run_script, --docker_remove_entrypoints] + written: {w~pull.cwl: {requirements: {DockerRequirement: {dockerPull: 'docker.io/library/debian:bookworm-slim-noentrypoint'}}}} diff --git a/tests/core/data/partial_failure/look.cwl b/tests/core/data/partial_failure/look.cwl new file mode 100644 index 000000000..75e6a6bad --- /dev/null +++ b/tests/core/data/partial_failure/look.cwl @@ -0,0 +1,6 @@ +# A real-time analysis, compiled under the workflow's options. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {file: File} +outputs: {seen: {type: File, outputBinding: {glob: seen.txt}}} diff --git a/tests/core/data/partial_failure/make.cwl b/tests/core/data/partial_failure/make.cwl new file mode 100644 index 000000000..f1b94a47e --- /dev/null +++ b/tests/core/data/partial_failure/make.cwl @@ -0,0 +1,14 @@ +# Its own success codes, kept beside the policy's; and an output in each form CWL writes a type in: one string, an +# array or a record in full, a union with and without null. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +successCodes: [3, 0] +inputs: {} +outputs: + listed: {type: 'File[]', outputBinding: {glob: '*.txt'}} + files: {type: {type: array, items: File}, outputBinding: {glob: '*.txt'}} + either: {type: [File, Directory], outputBinding: {glob: out}} + maybe: {type: ['null', File], outputBinding: {glob: out}} + pair: {type: {type: record, fields: {left: {type: File, outputBinding: {glob: left}}}}} + made: {type: File, outputBinding: {glob: made.txt}} diff --git a/tests/core/data/partial_failure/pair.cwl b/tests/core/data/partial_failure/pair.cwl new file mode 100644 index 000000000..7d5fa059b --- /dev/null +++ b/tests/core/data/partial_failure/pair.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {left: string, right: string} +outputs: {} diff --git a/tests/core/data/partial_failure/pull.cwl b/tests/core/data/partial_failure/pull.cwl new file mode 100644 index 000000000..b84b036a9 --- /dev/null +++ b/tests/core/data/partial_failure/pull.cwl @@ -0,0 +1,9 @@ +# Runs in an image the runner pulls. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +requirements: + DockerRequirement: + dockerPull: docker.io/library/debian:bookworm-slim +inputs: {} +outputs: {} diff --git a/tests/core/data/partial_failure/say.cwl b/tests/core/data/partial_failure/say.cwl new file mode 100644 index 000000000..57759b10a --- /dev/null +++ b/tests/core/data/partial_failure/say.cwl @@ -0,0 +1,7 @@ +# An output written as its type alone, a stream the tool names. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +stdout: said.txt +inputs: {message: string} +outputs: {said: stdout} diff --git a/tests/core/data/partial_failure/tell.cwl b/tests/core/data/partial_failure/tell.cwl new file mode 100644 index 000000000..4a13451a3 --- /dev/null +++ b/tests/core/data/partial_failure/tell.cwl @@ -0,0 +1,5 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {message: string} +outputs: {} diff --git a/tests/core/data/partial_failure/w.wic b/tests/core/data/partial_failure/w.wic new file mode 100644 index 000000000..95a451ea4 --- /dev/null +++ b/tests/core/data/partial_failure/w.wic @@ -0,0 +1,39 @@ +# Every form a tool's outputs and a step's `when` take, and a real-time analysis, as --partial_failure_enable writes +# them (docs/partial-failures.md). +steps: +- id: make +- id: say + in: + message: !ii a +- id: err +- id: pair + in: + left: !ii a + right: !ii b +- id: say_skip + run: say.cwl + when: '$(inputs.message != "skip")' + in: + message: !ii skip +- id: tell_skip + run: tell.cwl + when: '${ return inputs.message != "skip"; }' + in: + message: !ii skip +- id: say_on + run: say.cwl + when: 'on $(inputs.message)' + in: + message: !ii a +- id: tell_true + run: tell.cwl + when: true + in: + message: !ii b +- id: cwl_subinterpreter + in: + file_pattern: !ii made.txt + cwl_tool: !ii look + max_times: !ii 1 + config: !ii {in: {file: made.txt}} +- id: pull diff --git a/tests/core/data/plain_cwl/copy.cwl b/tests/core/data/plain_cwl/copy.cwl new file mode 100644 index 000000000..0151546c6 --- /dev/null +++ b/tests/core/data/plain_cwl/copy.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: cat +inputs: + text: + type: File + inputBinding: {position: 1} +stdout: copied.txt +outputs: + copied: stdout diff --git a/tests/core/data/plain_cwl/job.yml b/tests/core/data/plain_cwl/job.yml new file mode 100644 index 000000000..0279c7bf6 --- /dev/null +++ b/tests/core/data/plain_cwl/job.yml @@ -0,0 +1 @@ +message: hello diff --git a/tests/core/data/plain_cwl/list_steps.cwl b/tests/core/data/plain_cwl/list_steps.cwl new file mode 100644 index 000000000..5b01be5ad --- /dev/null +++ b/tests/core/data/plain_cwl/list_steps.cwl @@ -0,0 +1,19 @@ +cwlVersion: v1.2 +class: Workflow +inputs: + message: string +outputs: + copied: + type: File + outputSource: copy/copied +steps: +- id: say + run: say.cwl + in: + message: message + out: [said] +- id: copy + run: copy.cwl + in: + text: say/said + out: [copied] diff --git a/tests/core/data/plain_cwl/missing.yml b/tests/core/data/plain_cwl/missing.yml new file mode 100644 index 000000000..97b9b7c35 --- /dev/null +++ b/tests/core/data/plain_cwl/missing.yml @@ -0,0 +1,2 @@ +message: hello +file: {class: File, location: nope.txt} diff --git a/tests/core/data/plain_cwl/no_version.cwl b/tests/core/data/plain_cwl/no_version.cwl new file mode 100644 index 000000000..1c78a6ada --- /dev/null +++ b/tests/core/data/plain_cwl/no_version.cwl @@ -0,0 +1,6 @@ +# No cwlVersion: not a CWL workflow, so a document to compile. +class: Workflow +inputs: {message: string} +outputs: {} +steps: + say: {run: say.cwl, in: {message: message}, out: [said]} diff --git a/tests/core/data/plain_cwl/packed_hash_main.cwl b/tests/core/data/plain_cwl/packed_hash_main.cwl new file mode 100644 index 000000000..cb1a25cb5 --- /dev/null +++ b/tests/core/data/plain_cwl/packed_hash_main.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +$graph: +- id: say + class: CommandLineTool + baseCommand: echo + inputs: {message: {type: string, inputBinding: {position: 1}}} + stdout: said.txt + outputs: {said: stdout} +- id: '#main' + class: Workflow + inputs: {message: string} + outputs: {said: {type: File, outputSource: say/said}} + steps: + say: {run: '#say', in: {message: message}, out: [said]} diff --git a/tests/core/data/plain_cwl/packed_main.cwl b/tests/core/data/plain_cwl/packed_main.cwl new file mode 100644 index 000000000..1cceba0ee --- /dev/null +++ b/tests/core/data/plain_cwl/packed_main.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +$graph: +- id: say + class: CommandLineTool + baseCommand: echo + inputs: {message: {type: string, inputBinding: {position: 1}}} + stdout: said.txt + outputs: {said: stdout} +- id: main + class: Workflow + inputs: {message: string} + outputs: {said: {type: File, outputSource: say/said}} + steps: + say: {run: '#say', in: {message: message}, out: [said]} diff --git a/tests/core/data/plain_cwl/packed_tool.cwl b/tests/core/data/plain_cwl/packed_tool.cwl new file mode 100644 index 000000000..730415358 --- /dev/null +++ b/tests/core/data/plain_cwl/packed_tool.cwl @@ -0,0 +1,14 @@ +cwlVersion: v1.2 +$graph: +- id: say + class: CommandLineTool + baseCommand: echo + inputs: {message: {type: string, inputBinding: {position: 1}}} + stdout: said.txt + outputs: {said: stdout} +- id: main + class: CommandLineTool + inputs: {message: string} + outputs: {said: {type: File, outputSource: say/said}} + steps: + say: {run: '#say', in: {message: message}, out: [said]} diff --git a/tests/core/data/plain_cwl/plain.cwl b/tests/core/data/plain_cwl/plain.cwl new file mode 100644 index 000000000..5742b6b37 --- /dev/null +++ b/tests/core/data/plain_cwl/plain.cwl @@ -0,0 +1,19 @@ +cwlVersion: v1.2 +class: Workflow +inputs: + message: string +outputs: + copied: + type: File + outputSource: copy/copied +steps: + say: + run: say.cwl + in: + message: message + out: [said] + copy: + run: copy.cwl + in: + text: say/said + out: [copied] diff --git a/tests/core/data/plain_cwl/plain.wic b/tests/core/data/plain_cwl/plain.wic new file mode 100644 index 000000000..cc3323741 --- /dev/null +++ b/tests/core/data/plain_cwl/plain.wic @@ -0,0 +1,2 @@ +steps: +- id: say diff --git a/tests/core/data/plain_cwl/say.cwl b/tests/core/data/plain_cwl/say.cwl new file mode 100644 index 000000000..05ec7a049 --- /dev/null +++ b/tests/core/data/plain_cwl/say.cwl @@ -0,0 +1,10 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: echo +inputs: + message: + type: string + inputBinding: {position: 1} +stdout: said.txt +outputs: + said: stdout diff --git a/tests/core/data/plain_cwl/sidecar.cwl b/tests/core/data/plain_cwl/sidecar.cwl new file mode 100644 index 000000000..85f4f811f --- /dev/null +++ b/tests/core/data/plain_cwl/sidecar.cwl @@ -0,0 +1,10 @@ +# A `wic:` block makes this a document to compile. +wic: + graphviz: + label: x +cwlVersion: v1.2 +class: Workflow +inputs: {message: string} +outputs: {} +steps: + say: {run: say.cwl, in: {message: message}, out: [said]} diff --git a/tests/core/data/plain_cwl/tagged.cwl b/tests/core/data/plain_cwl/tagged.cwl new file mode 100644 index 000000000..7464ec4f7 --- /dev/null +++ b/tests/core/data/plain_cwl/tagged.cwl @@ -0,0 +1,7 @@ +# A Sophios tag makes this a document to compile. +cwlVersion: v1.2 +class: Workflow +inputs: {} +outputs: {} +steps: + say: {run: say.cwl, in: {message: !ii hello}, out: [said]} diff --git a/tests/core/data/preflight/cli/bad.wic b/tests/core/data/preflight/cli/bad.wic new file mode 100644 index 000000000..82cd4bbb2 --- /dev/null +++ b/tests/core/data/preflight/cli/bad.wic @@ -0,0 +1,2 @@ +steps: +- id: "" diff --git a/tests/core/data/preflight/cli/echo.wic b/tests/core/data/preflight/cli/echo.wic new file mode 100644 index 000000000..2155c1dee --- /dev/null +++ b/tests/core/data/preflight/cli/echo.wic @@ -0,0 +1,5 @@ +# No container: nothing to ask of an engine. +steps: +- id: echo + in: + message: !ii hello diff --git a/tests/core/data/preflight/cli/expected.yaml b/tests/core/data/preflight/cli/expected.yaml new file mode 100644 index 000000000..368958149 --- /dev/null +++ b/tests/core/data/preflight/cli/expected.yaml @@ -0,0 +1,65 @@ +# What the command line says, and its exit code: 1 for a failure, 2 for a usage error, with no traceback. +runs: +- why: the failure a scientist sees names the file, line, column and code on stderr + argv: [--yaml, bad.wic, --generate_cwl_workflow] + exit: 1 + stderr: {contains: [Failed to compile bad.wic, 'bad.wic:2:7: error [wic007]']} + lacks: [Traceback] +- why: or one JSON object a line + argv: [--yaml, bad.wic, --generate_cwl_workflow, --diagnostics, json] + exit: 1 + diagnostics: [{severity: error, code: EMPTY_STEP_ID, kind: document, file: bad.wic, line: 2, column: 7}] +- why: a guessed edge is a note, the compile succeeds, and the note says to draw the workflow + argv: [--yaml, two_touches.wic, --generate_cwl_workflow] + stderr: {contains: ['note [wic043] 1 edge was guessed; draw the workflow', + 'two_touches.wic:8:3 cat.file <- touch@2.file (1 other fits)']} +- argv: [--yaml, two_touches.wic, --generate_cwl_workflow, --diagnostics, json] + diagnostics: [{severity: note, code: INFERENCE_GUESS, message: cat.file <- touch@2.file (1 other fits), step: cat, + index: 3, port: file}] +- why: --inference_strict makes the guess an error, with nothing to draw + argv: [--yaml, two_touches.wic, --generate_cwl_workflow, --inference_strict] + exit: 1 + stderr: {contains: ['error [wic043] cat.file <- touch@2.file was guessed, 1 other fits']} + lacks: [draw the workflow] +- why: a flag Sophios does not know is an error, not a silent gift to the runner + argv: [--yaml, echo.wic, --generate_cwl_workflow, --no_such_flag] + exit: 2 + stderr: {contains: [--no_such_flag]} + lacks: [Traceback] +- argv: [--yaml, echo.wic, --generate_run_script, --no_such_flag] + exit: 2 + stderr: {contains: [--no_such_flag]} +- why: --passthrough_flags yes with no runner to send the arguments to + argv: [--yaml, echo.wic, --generate_cwl_workflow, --passthrough_flags, 'yes', --debug] + exit: 2 + stderr: {contains: [--run_local]} +- argv: [--yaml, nope.wic, --generate_cwl_workflow] + exit: 2 + stderr: {contains: [no workflow file at nope.wic]} + lacks: [Traceback] +- argv: [--yaml, echo.wic, --inputs_file, nope.yml, --generate_cwl_workflow] + exit: 2 + stderr: {contains: [no inputs file at nope.yml]} +- argv: [--explain, wic999] + exit: 2 + stderr: {contains: [wic999 is not a Sophios error code]} + lacks: [Traceback] +- why: a failure Sophios did not expect says so in one line; the file holds the traceback with its frames + machine: {crash: true} + argv: [--yaml, two_touches.wic, --generate_cwl_workflow] + exit: 1 + stderr: {contains: ['Sophios stopped on an unexpected RuntimeError: boom. The traceback is in error_two_touches.txt']} + lacks: [Traceback] + texts: {error_two_touches.txt: {contains: [Traceback (most recent call last), in crash]}} +- why: a working directory where autogenerated/ cannot be made is one wic021, not a PermissionError + cwd: locked + posix_user: true + argv: [--yaml, ../echo.wic, --generate_cwl_workflow, --diagnostics, json] + exit: 1 + diagnostics: [{code: DIRECTORY_NOT_WRITABLE, severity: error, + message: {contains: [Sophios writes the compiled workflow to, give --basepath a directory you can write to]}}] +- why: and a --basepath that is a file names the path given + argv: [--yaml, echo.wic, --generate_cwl_workflow, --basepath, echo.wic, --diagnostics, json] + exit: 1 + diagnostics: [{code: DIRECTORY_NOT_WRITABLE, severity: error, + message: {contains: ['{tmp}/echo.wic is a file: give --basepath a directory you can write to']}}] diff --git a/tests/core/data/preflight/cli/two_touches.wic b/tests/core/data/preflight/cli/two_touches.wic new file mode 100644 index 000000000..af273cd4d --- /dev/null +++ b/tests/core/data/preflight/cli/two_touches.wic @@ -0,0 +1,8 @@ +steps: +- id: touch + in: + filename: !ii a.txt +- id: touch + in: + filename: !ii b.txt +- id: cat diff --git a/tests/core/data/preflight/engine/docker.sock b/tests/core/data/preflight/engine/docker.sock new file mode 100644 index 000000000..e69de29bb diff --git a/tests/core/data/preflight/engine/expected.yaml b/tests/core/data/preflight/engine/expected.yaml new file mode 100644 index 000000000..72bed4898 --- /dev/null +++ b/tests/core/data/preflight/engine/expected.yaml @@ -0,0 +1,55 @@ +# A step that runs in a container needs a usable engine: one wic015 says why this one is not, and nothing is pulled. +# The flag that waives the check skips it, and the images are pulled. +runs: +- machine: {engine: missing} + argv: [--yaml, touch.wic, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: CONTAINER_ENGINE_UNAVAILABLE, severity: error, message: {contains: [ + 'docker is not installed (it is not on PATH), and this workflow runs tools in containers + (docker.io/library/debian:bookworm-slim): install docker, or name an installed engine with --container_engine']}}] +- why: a socket DOCKER_HOST names that is not there is named, and the engine quoted + machine: {engine: fails, said: "failed to connect to the docker API\nsecond line", docker_host: 'unix:///nonexistent/sophios.sock'} + argv: [--yaml, touch.wic, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: CONTAINER_ENGINE_UNAVAILABLE, severity: error, message: {contains: [ + 'the socket /nonexistent/sophios.sock does not exist (failed to connect to the docker API): start the engine']}}] +- why: a stopped engine with no socket of its own is not blamed on permissions + machine: {engine: fails, said: 'Is the docker daemon running?'} + argv: [--yaml, touch.wic, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: CONTAINER_ENGINE_UNAVAILABLE, severity: error, message: {contains: [ + '`docker info` exited with status 1 (Is the docker daemon running?): run `docker info` to see why']}}] +- why: a socket that is not yours is + machine: {engine: fails, said: denied, docker_host: 'unix://{tmp}/docker.sock', unreadable: [docker.sock]} + posix_user: true + argv: [--yaml, touch.wic, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: CONTAINER_ENGINE_UNAVAILABLE, severity: error, message: {contains: [ + 'you may not use its socket {tmp}/docker.sock (denied): add your user to the docker group']}}] +- why: an engine that fails for another reason is quoted with its status + machine: {engine: fails, said: " whatever the engine said\n", docker_host: 'tcp://engine.invalid:2375'} + argv: [--yaml, touch.wic, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: CONTAINER_ENGINE_UNAVAILABLE, severity: error, message: {contains: [ + '`docker info` exited with status 1 (whatever the engine said)']}}] +- machine: {engine: fails, said: whatever the engine said, docker_host: 'tcp://engine.invalid:2375'} + argv: [--yaml, touch.wic, --generate_run_script, --ignore_docker_install] + pulled: true +- why: too many docker processes is one line, unless ignored + machine: {processes: 1001} + argv: [--yaml, touch.wic, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: CONTAINER_ENGINE_UNAVAILABLE, severity: error, message: {contains: [ + 1001 docker processes are running, ', or pass --ignore_docker_processes.']}}] +- machine: {processes: 1001} + argv: [--yaml, touch.wic, --generate_run_script, --ignore_docker_processes] + pulled: true +- why: a Nextflow run is not told of options only a CWL run takes + machine: {engine: missing} + argv: [--yaml, touch.wic, --target, nextflow, --check, --diagnostics, json] + exit: 1 + diagnostics: [{code: CONTAINER_ENGINE_UNAVAILABLE, severity: error, message: {re: 'install docker\.$'}}] +- machine: {processes: 1001} + argv: [--yaml, touch.wic, --target, nextflow, --check, --diagnostics, json] + exit: 1 + diagnostics: [{code: CONTAINER_ENGINE_UNAVAILABLE, severity: error, message: {re: 'pkill Docker\)\.$'}}] diff --git a/tests/core/data/preflight/engine/touch.wic b/tests/core/data/preflight/engine/touch.wic new file mode 100644 index 000000000..5049115d2 --- /dev/null +++ b/tests/core/data/preflight/engine/touch.wic @@ -0,0 +1,5 @@ +# touch runs in docker.io/library/debian:bookworm-slim. +steps: +- id: touch + in: + filename: !ii a.txt diff --git a/tests/core/data/preflight/images/expected.yaml b/tests/core/data/preflight/images/expected.yaml new file mode 100644 index 000000000..c209e0eaa --- /dev/null +++ b/tests/core/data/preflight/images/expected.yaml @@ -0,0 +1,41 @@ +# The images a run uses are fetched before it starts, with the chosen engine: pulled through cwl-docker-extract, and +# a dockerLoad loaded and a dockerImport imported as cwltool does. What fails is one wic037 naming it and quoting the +# engine's error line. --check fetches nothing. +runs: +- argv: [--yaml, images.wic, --config_file, search.json, --generate_run_script] + pulled: true + commands: {contains: [[docker, load, -i, image.tar], [docker, import, 'https://example.org/rootfs.tar', 'rootfs:1'], + [docker, load, -i, {re: image.tar$}]]} +- argv: [--yaml, images.wic, --config_file, search.json, --generate_run_script, --container_engine, podman] + pulled: true + commands: {contains: [[cwl-docker-extract, --force-download, --container-engine, podman, {re: images.cwl$}], + [podman, load, -i, image.tar], [podman, import, 'https://example.org/rootfs.tar', 'rootfs:1']]} +- argv: [--yaml, images.wic, --config_file, search.json, --check] + commands: {exact: [[docker, info], [pgrep, com.docker]]} +- machine: {fails: [[cwl-docker-extract]], said: "first line\nError: pull access denied\n"} + argv: [--yaml, nope.wic, --config_file, search.json, --generate_run_script, --diagnostics, json] + exit: 1 + pulled: true + diagnostics: [{code: IMAGE_UNAVAILABLE, severity: error, message: {contains: [ + 'docker could not pull docker.io/nope:1 (cwl-docker-extract exited with status 1: Error: pull access denied)']}}] +- why: cwl-docker-extract re-raises the engine's output as `SubprocessError()`, which is read + machine: {fails: [[cwl-docker-extract]], said: "Traceback (most recent call last):\n File \"extract.py\", line 1, + in \nsubprocess.SubprocessError: b'Trying to pull docker.io/nope:1... \\r\\nError: requested access to + the resource is denied \\r\\n'\n"} + argv: [--yaml, nope.wic, --config_file, search.json, --generate_run_script, --diagnostics, json] + exit: 1 + pulled: true + diagnostics: [{code: IMAGE_UNAVAILABLE, severity: error, message: {contains: [ + '(cwl-docker-extract exited with status 1: Error: requested access to the resource is denied)']}}] +- machine: {fails: [[docker, load]], said: "first line\nError: no such archive\n"} + argv: [--yaml, load.wic, --config_file, search.json, --generate_run_script, --diagnostics, json] + exit: 1 + pulled: true + diagnostics: [{code: IMAGE_UNAVAILABLE, severity: error, message: {contains: [ + 'docker could not load image.tar (docker exited with status 1: Error: no such archive)']}}] +- machine: {fails: [[docker, import]], said: "Error: not an archive\n"} + argv: [--yaml, local_import.wic, --config_file, search.json, --generate_run_script, --diagnostics, json] + exit: 1 + pulled: true + diagnostics: [{code: IMAGE_UNAVAILABLE, severity: error, message: {contains: [ + 'docker could not import rootfs:1 from rootfs.tar (docker exited with status 1: Error: not an archive)']}}] diff --git a/tests/core/data/preflight/images/image.tar b/tests/core/data/preflight/images/image.tar new file mode 100644 index 000000000..e69de29bb diff --git a/tests/core/data/preflight/images/images.wic b/tests/core/data/preflight/images/images.wic new file mode 100644 index 000000000..d208f6a96 --- /dev/null +++ b/tests/core/data/preflight/images/images.wic @@ -0,0 +1,7 @@ +# Every form a DockerRequirement fetches its image in. +steps: +- id: pull +- id: pinned +- id: load +- id: download +- id: import diff --git a/tests/core/data/preflight/images/load.wic b/tests/core/data/preflight/images/load.wic new file mode 100644 index 000000000..75a41b066 --- /dev/null +++ b/tests/core/data/preflight/images/load.wic @@ -0,0 +1,2 @@ +steps: +- id: load diff --git a/tests/core/data/preflight/images/local_import.wic b/tests/core/data/preflight/images/local_import.wic new file mode 100644 index 000000000..a722703a0 --- /dev/null +++ b/tests/core/data/preflight/images/local_import.wic @@ -0,0 +1,2 @@ +steps: +- id: local_import diff --git a/tests/core/data/preflight/images/nope.wic b/tests/core/data/preflight/images/nope.wic new file mode 100644 index 000000000..b35841f0b --- /dev/null +++ b/tests/core/data/preflight/images/nope.wic @@ -0,0 +1,2 @@ +steps: +- id: nope diff --git a/tests/core/data/preflight/images/rootfs.tar b/tests/core/data/preflight/images/rootfs.tar new file mode 100644 index 000000000..e69de29bb diff --git a/tests/core/data/preflight/images/search.json b/tests/core/data/preflight/images/search.json new file mode 100644 index 000000000..fc8d0b484 --- /dev/null +++ b/tests/core/data/preflight/images/search.json @@ -0,0 +1 @@ +{"search_paths_cwl": {"global": ["tools"]}, "search_paths_wic": {"global": ["."]}} diff --git a/tests/core/data/preflight/images/tools/download.cwl b/tests/core/data/preflight/images/tools/download.cwl new file mode 100644 index 000000000..9964da66c --- /dev/null +++ b/tests/core/data/preflight/images/tools/download.cwl @@ -0,0 +1,9 @@ +# An image downloaded, then loaded. +cwlVersion: v1.2 +class: CommandLineTool +requirements: + DockerRequirement: + dockerLoad: https://example.org/image.tar +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/preflight/images/tools/import.cwl b/tests/core/data/preflight/images/tools/import.cwl new file mode 100644 index 000000000..0b04d5150 --- /dev/null +++ b/tests/core/data/preflight/images/tools/import.cwl @@ -0,0 +1,10 @@ +# An image imported under its id. +cwlVersion: v1.2 +class: CommandLineTool +requirements: + DockerRequirement: + dockerImport: https://example.org/rootfs.tar + dockerImageId: rootfs:1 +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/preflight/images/tools/load.cwl b/tests/core/data/preflight/images/tools/load.cwl new file mode 100644 index 000000000..8e88f4248 --- /dev/null +++ b/tests/core/data/preflight/images/tools/load.cwl @@ -0,0 +1,9 @@ +# An image loaded from the archive beside the run. +cwlVersion: v1.2 +class: CommandLineTool +requirements: + DockerRequirement: + dockerLoad: image.tar +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/preflight/images/tools/local_import.cwl b/tests/core/data/preflight/images/tools/local_import.cwl new file mode 100644 index 000000000..5b36bf18f --- /dev/null +++ b/tests/core/data/preflight/images/tools/local_import.cwl @@ -0,0 +1,10 @@ +# An image imported from the archive beside the run. +cwlVersion: v1.2 +class: CommandLineTool +requirements: + DockerRequirement: + dockerImport: rootfs.tar + dockerImageId: rootfs:1 +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/preflight/images/tools/nope.cwl b/tests/core/data/preflight/images/tools/nope.cwl new file mode 100644 index 000000000..ccae1f2a6 --- /dev/null +++ b/tests/core/data/preflight/images/tools/nope.cwl @@ -0,0 +1,9 @@ +# An image no registry has. +cwlVersion: v1.2 +class: CommandLineTool +requirements: + DockerRequirement: + dockerPull: docker.io/nope:1 +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/preflight/images/tools/pinned.cwl b/tests/core/data/preflight/images/tools/pinned.cwl new file mode 100644 index 000000000..406b04e7e --- /dev/null +++ b/tests/core/data/preflight/images/tools/pinned.cwl @@ -0,0 +1,10 @@ +# Pulled, so nothing is loaded or imported for it. +cwlVersion: v1.2 +class: CommandLineTool +requirements: + DockerRequirement: + dockerPull: docker.io/bash:4.4 + dockerImageId: bash:4.4 +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/preflight/images/tools/pull.cwl b/tests/core/data/preflight/images/tools/pull.cwl new file mode 100644 index 000000000..5f6f17d0a --- /dev/null +++ b/tests/core/data/preflight/images/tools/pull.cwl @@ -0,0 +1,9 @@ +# An image pulled by name. +cwlVersion: v1.2 +class: CommandLineTool +requirements: + DockerRequirement: + dockerPull: docker.io/bash:4.4 +baseCommand: 'true' +inputs: {} +outputs: {} diff --git a/tests/core/data/preflight/inputs/absent.wic b/tests/core/data/preflight/inputs/absent.wic new file mode 100644 index 000000000..3b69a239a --- /dev/null +++ b/tests/core/data/preflight/inputs/absent.wic @@ -0,0 +1,7 @@ +# cat reads a file that is not there. +steps: +- id: cat + in: + file: !ii + class: File + location: absent.txt diff --git a/tests/core/data/preflight/inputs/absent.yml b/tests/core/data/preflight/inputs/absent.yml new file mode 100644 index 000000000..2a8d9122b --- /dev/null +++ b/tests/core/data/preflight/inputs/absent.yml @@ -0,0 +1,4 @@ +file: + class: File + location: absent.txt +n: 3 diff --git a/tests/core/data/preflight/inputs/beside.wic b/tests/core/data/preflight/inputs/beside.wic new file mode 100644 index 000000000..cbec5b7f6 --- /dev/null +++ b/tests/core/data/preflight/inputs/beside.wic @@ -0,0 +1,8 @@ +# A directory beside the workflow, which the run reads in place, however large: nothing is copied. +steps: +- id: subdirectory + in: + directory: !ii + class: Directory + location: shared + glob_pattern: !ii a.txt diff --git a/tests/core/data/preflight/inputs/cat_input.wic b/tests/core/data/preflight/inputs/cat_input.wic new file mode 100644 index 000000000..629e6b451 --- /dev/null +++ b/tests/core/data/preflight/inputs/cat_input.wic @@ -0,0 +1,7 @@ +# cat reads the workflow input `file`, whose value an inputs file gives. +inputs: + file: File +steps: +- id: cat + in: + file: file diff --git a/tests/core/data/preflight/inputs/expected.yaml b/tests/core/data/preflight/inputs/expected.yaml new file mode 100644 index 000000000..36a49faa2 --- /dev/null +++ b/tests/core/data/preflight/inputs/expected.yaml @@ -0,0 +1,42 @@ +# An input the run cannot use is one wic016 naming the input, where its relative paths are read from, and the fix, +# before any image is pulled. An output-target Directory names what the step creates: it is not looked for, nor made +# absolute against the inputs file; a Directory that is an input is read where it is. +runs: +- argv: [--yaml, absent.wic, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: MISSING_INPUT_FILE, severity: error, message: {contains: [ + "input 'cat~file' (from the workflow, whose relative paths are read from {tmp})", + "names 'absent.txt', which does not exist at {tmp}/absent.txt: correct the path, or create the file"]}}] +- argv: [--yaml, cat_input.wic, --generate_run_script, --inputs_file, absent.yml, --diagnostics, json] + exit: 1 + diagnostics: [{code: MISSING_INPUT_FILE, severity: error, message: {contains: [ + "input 'file' (from --inputs_file, whose relative paths are read from {tmp})"]}}] +- posix_user: true + machine: {unreadable: [locked.txt]} + argv: [--yaml, locked.wic, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: MISSING_INPUT_FILE, severity: error, message: {contains: [ + 'which you may not read ({tmp}/locked.txt): give yourself access (chmod u+r {tmp}/locked.txt)']}}] +- why: a missing input and a stopped engine are reported together + machine: {engine: fails, said: stopped, docker_host: 'tcp://engine.invalid:2375'} + argv: [--yaml, absent.wic, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: MISSING_INPUT_FILE, severity: error}, {code: CONTAINER_ENGINE_UNAVAILABLE, severity: error}] +- argv: [--yaml, cat_input.wic, --generate_run_script, --inputs_file, jobs/job.yml] + pulled: true + files: + autogenerated/cat_input_inputs.yml: + file: {location: '{tmp_uri}/jobs/data/a.txt', secondaryFiles: [{path: '{tmp}/jobs/data/a.txt'}]} +- argv: [--yaml, cat_input.wic, --check, --inputs_file, uri.yml] + stdout: {contains: ['Checked cat_input: ']} +- argv: [--yaml, cat_input.wic, --generate_run_script, --inputs_file, list.yml, --diagnostics, json] + exit: 1 + diagnostics: [{code: NOT_A_MAPPING, severity: error, message: {contains: [ + must be a mapping of input names to values, not a list]}}] +- argv: [--yaml, literal.wic, --generate_run_script, --config_file, search.json] +- argv: [--yaml, named.wic, --generate_run_script, --config_file, search.json, --inputs_file, named.yml] + files: {autogenerated/named_inputs.yml: {write_dir~outDir: result.outDir}} +- argv: [--yaml, beside.wic, --generate_run_script] + files: {autogenerated/beside_inputs.yml: {subdirectory~directory: {class: Directory, location: '{tmp_uri}/shared'}}} + written: {exact: [autogenerated/beside.cwl, autogenerated/beside_inputs.yml, autogenerated/beside~subdirectory.cwl, + run.sh]} diff --git a/tests/core/data/preflight/inputs/in x.txt b/tests/core/data/preflight/inputs/in x.txt new file mode 100644 index 000000000..587be6b4c --- /dev/null +++ b/tests/core/data/preflight/inputs/in x.txt @@ -0,0 +1 @@ +x diff --git a/tests/core/data/preflight/inputs/jobs/data/a.txt b/tests/core/data/preflight/inputs/jobs/data/a.txt new file mode 100644 index 000000000..587be6b4c --- /dev/null +++ b/tests/core/data/preflight/inputs/jobs/data/a.txt @@ -0,0 +1 @@ +x diff --git a/tests/core/data/preflight/inputs/jobs/job.yml b/tests/core/data/preflight/inputs/jobs/job.yml new file mode 100644 index 000000000..128e6bb3e --- /dev/null +++ b/tests/core/data/preflight/inputs/jobs/job.yml @@ -0,0 +1,7 @@ +# Read from beside this file, at any depth: CWL v1.2 section 5.1.5, the base IRI of the inputs document. +file: + class: File + location: data/a.txt + secondaryFiles: + - class: File + path: data/a.txt diff --git a/tests/core/data/preflight/inputs/list.yml b/tests/core/data/preflight/inputs/list.yml new file mode 100644 index 000000000..4068906cb --- /dev/null +++ b/tests/core/data/preflight/inputs/list.yml @@ -0,0 +1,2 @@ +- a +- b diff --git a/tests/core/data/preflight/inputs/literal.wic b/tests/core/data/preflight/inputs/literal.wic new file mode 100644 index 000000000..881466ebe --- /dev/null +++ b/tests/core/data/preflight/inputs/literal.wic @@ -0,0 +1,5 @@ +# The directory the step creates, by name: no such directory exists yet. +steps: +- id: write_dir + in: + outDir: !ii result.outDir diff --git a/tests/core/data/preflight/inputs/locked.txt b/tests/core/data/preflight/inputs/locked.txt new file mode 100644 index 000000000..587be6b4c --- /dev/null +++ b/tests/core/data/preflight/inputs/locked.txt @@ -0,0 +1 @@ +x diff --git a/tests/core/data/preflight/inputs/locked.wic b/tests/core/data/preflight/inputs/locked.wic new file mode 100644 index 000000000..b5eeb07f1 --- /dev/null +++ b/tests/core/data/preflight/inputs/locked.wic @@ -0,0 +1,6 @@ +steps: +- id: cat + in: + file: !ii + class: File + location: locked.txt diff --git a/tests/core/data/preflight/inputs/named.wic b/tests/core/data/preflight/inputs/named.wic new file mode 100644 index 000000000..9420ff8b2 --- /dev/null +++ b/tests/core/data/preflight/inputs/named.wic @@ -0,0 +1,2 @@ +steps: +- id: write_dir diff --git a/tests/core/data/preflight/inputs/named.yml b/tests/core/data/preflight/inputs/named.yml new file mode 100644 index 000000000..aa6fad541 --- /dev/null +++ b/tests/core/data/preflight/inputs/named.yml @@ -0,0 +1,2 @@ +# Written as CWL writes a Directory, it still names the directory the step creates. +write_dir~outDir: {class: Directory, location: result.outDir} diff --git a/tests/core/data/preflight/inputs/search.json b/tests/core/data/preflight/inputs/search.json new file mode 100644 index 000000000..fc8d0b484 --- /dev/null +++ b/tests/core/data/preflight/inputs/search.json @@ -0,0 +1 @@ +{"search_paths_cwl": {"global": ["tools"]}, "search_paths_wic": {"global": ["."]}} diff --git a/tests/core/data/preflight/inputs/shared/a.txt b/tests/core/data/preflight/inputs/shared/a.txt new file mode 100644 index 000000000..587be6b4c --- /dev/null +++ b/tests/core/data/preflight/inputs/shared/a.txt @@ -0,0 +1 @@ +x diff --git a/tests/core/data/preflight/inputs/tools/write_dir.cwl b/tests/core/data/preflight/inputs/tools/write_dir.cwl new file mode 100644 index 000000000..c33728985 --- /dev/null +++ b/tests/core/data/preflight/inputs/tools/write_dir.cwl @@ -0,0 +1,17 @@ +# Creates the directory `outDir` names, and writes into it. +cwlVersion: v1.2 +class: CommandLineTool +requirements: + InitialWorkDirRequirement: + listing: + - entry: $(inputs.outDir) + writable: true + InlineJavascriptRequirement: {} +baseCommand: [mkdir] +inputs: + outDir: Directory +outputs: + outDir: + type: Directory + outputBinding: + glob: $(inputs.outDir.basename) diff --git a/tests/core/data/preflight/inputs/uri.yml b/tests/core/data/preflight/inputs/uri.yml new file mode 100644 index 000000000..a68ad33fe --- /dev/null +++ b/tests/core/data/preflight/inputs/uri.yml @@ -0,0 +1,4 @@ +# A file: location in this platform's own spelling: on Windows a drive path, not /C:/... +file: + class: File + location: '{tmp_uri}/in%20x.txt' diff --git a/tests/core/data/preflight/modes/absent.wic b/tests/core/data/preflight/modes/absent.wic new file mode 100644 index 000000000..646573d15 --- /dev/null +++ b/tests/core/data/preflight/modes/absent.wic @@ -0,0 +1,7 @@ +# cat runs in a container too, and reads a file that is not there. +steps: +- id: cat + in: + file: !ii + class: File + location: absent.txt diff --git a/tests/core/data/preflight/modes/earlier/notes.txt b/tests/core/data/preflight/modes/earlier/notes.txt new file mode 100644 index 000000000..78013fad9 --- /dev/null +++ b/tests/core/data/preflight/modes/earlier/notes.txt @@ -0,0 +1 @@ +an earlier note diff --git a/tests/core/data/preflight/modes/earlier/touch.cwl b/tests/core/data/preflight/modes/earlier/touch.cwl new file mode 100644 index 000000000..0a5c89cc1 --- /dev/null +++ b/tests/core/data/preflight/modes/earlier/touch.cwl @@ -0,0 +1 @@ +an earlier touch.cwl diff --git a/tests/core/data/preflight/modes/echo.wic b/tests/core/data/preflight/modes/echo.wic new file mode 100644 index 000000000..2155c1dee --- /dev/null +++ b/tests/core/data/preflight/modes/echo.wic @@ -0,0 +1,5 @@ +# No container: nothing to ask of an engine. +steps: +- id: echo + in: + message: !ii hello diff --git a/tests/core/data/preflight/modes/expected.yaml b/tests/core/data/preflight/modes/expected.yaml new file mode 100644 index 000000000..58b34b047 --- /dev/null +++ b/tests/core/data/preflight/modes/expected.yaml @@ -0,0 +1,25 @@ +# What each mode asks of this machine: --check asks the engine and stops, writing, pulling and running nothing, whether +# it passes, fails or is refused; a run script needs an engine only for containers, and pulls their images. +runs: +- argv: [--yaml, touch.wic, --check, --basepath, earlier] + stdout: {contains: ['Checked touch: ']} + asked: true + unchanged: true +- why: it finds every problem a run would hit, one diagnostic each, in one pass + machine: {engine: missing} + argv: [--yaml, absent.wic, --check, --basepath, earlier, --diagnostics, json] + exit: 1 + diagnostics: [{code: MISSING_INPUT_FILE, severity: error}, {code: CONTAINER_ENGINE_UNAVAILABLE, severity: error}] + unchanged: true +- why: a drawing would be written, so it is refused + argv: [--yaml, touch.wic, --check, --basepath, earlier, --graphviz] + exit: 2 + unchanged: true +- machine: {engine: missing} + argv: [--yaml, echo.wic, --generate_run_script] + written: {contains: [run.sh]} + asked: false +- argv: [--yaml, touch.wic, --generate_run_script] + written: {contains: [run.sh]} + asked: true + pulled: true diff --git a/tests/core/data/preflight/modes/touch.wic b/tests/core/data/preflight/modes/touch.wic new file mode 100644 index 000000000..5049115d2 --- /dev/null +++ b/tests/core/data/preflight/modes/touch.wic @@ -0,0 +1,5 @@ +# touch runs in docker.io/library/debian:bookworm-slim. +steps: +- id: touch + in: + filename: !ii a.txt diff --git a/tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow.config b/tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow.config new file mode 100644 index 000000000..94bf5a3eb --- /dev/null +++ b/tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow.config @@ -0,0 +1 @@ +an earlier nextflow.config diff --git a/tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow_params.json b/tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow_params.json new file mode 100644 index 000000000..078724f67 --- /dev/null +++ b/tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow_params.json @@ -0,0 +1 @@ +an earlier nextflow_params.json diff --git a/tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow_workflow.json b/tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow_workflow.json new file mode 100644 index 000000000..b656ad73b --- /dev/null +++ b/tests/core/data/preflight/nextflow/earlier/nextflow_made/nextflow_workflow.json @@ -0,0 +1 @@ +an earlier nextflow_workflow.json diff --git a/tests/core/data/preflight/nextflow/earlier/nextflow_made/workflow.nf b/tests/core/data/preflight/nextflow/earlier/nextflow_made/workflow.nf new file mode 100644 index 000000000..e85c805c0 --- /dev/null +++ b/tests/core/data/preflight/nextflow/earlier/nextflow_made/workflow.nf @@ -0,0 +1 @@ +an earlier workflow.nf diff --git a/tests/core/data/preflight/nextflow/expected.yaml b/tests/core/data/preflight/nextflow/expected.yaml new file mode 100644 index 000000000..c15fbc7fd --- /dev/null +++ b/tests/core/data/preflight/nextflow/expected.yaml @@ -0,0 +1,17 @@ +# A --check of the Nextflow target asks for Nextflow, reports the lowering's notes and stops: Nextflow is not started, +# nothing is written into the base path, passing or failing, and the output directory a tool writes into is not made. +runs: +- argv: [--yaml, made.wic, --config_file, search.json, --target, nextflow, --check, --diagnostics, json] + stdout: {contains: ['Checked made: nothing in the way of a local run on this machine. Nothing was written, pulled or + run.']} + diagnostics: + - {code: UNCHECKED_CUDA_FIELD, severity: note, step: write_into, message: {contains: [cudaVersionMin '11.4']}} + - {code: UNCHECKED_CUDA_FIELD, severity: note, step: write_into, message: {contains: [cudaComputeCapability '3.0']}} + commands: {exact: [[/usr/bin/nextflow, -version]]} + absent: [made, autogenerated] +- argv: [--yaml, made.wic, --config_file, search.json, --target, nextflow, --check, --basepath, earlier] + unchanged: true +- machine: {missing: [nextflow]} + argv: [--yaml, made.wic, --config_file, search.json, --target, nextflow, --check, --basepath, earlier] + exit: 1 + unchanged: true diff --git a/tests/core/data/preflight/nextflow/made.wic b/tests/core/data/preflight/nextflow/made.wic new file mode 100644 index 000000000..edde16735 --- /dev/null +++ b/tests/core/data/preflight/nextflow/made.wic @@ -0,0 +1,5 @@ +# One step writing into the output-target Directory `made`. +steps: +- id: write_into + in: + outDir: !ii made diff --git a/tests/core/data/preflight/nextflow/search.json b/tests/core/data/preflight/nextflow/search.json new file mode 100644 index 000000000..fc8d0b484 --- /dev/null +++ b/tests/core/data/preflight/nextflow/search.json @@ -0,0 +1 @@ +{"search_paths_cwl": {"global": ["tools"]}, "search_paths_wic": {"global": ["."]}} diff --git a/tests/core/data/preflight/nextflow/tools/write_into.cwl b/tests/core/data/preflight/nextflow/tools/write_into.cwl new file mode 100644 index 000000000..a7259b35d --- /dev/null +++ b/tests/core/data/preflight/nextflow/tools/write_into.cwl @@ -0,0 +1,26 @@ +# Writes into the output-target Directory `outDir`, with two CUDA fields the Nextflow target notes it does not check. +cwlVersion: v1.2 +class: CommandLineTool +$namespaces: + cwltool: http://commonwl.org/cwltool# +baseCommand: touch +requirements: + InitialWorkDirRequirement: + listing: + - entry: $(inputs.outDir) + writable: true +hints: + cwltool:CUDARequirement: + cudaVersionMin: '11.4' + cudaComputeCapability: '3.0' + cudaDeviceCountMin: 1 +inputs: + outDir: + type: Directory +outputs: + outDir: + type: Directory + outputBinding: + glob: $(inputs.outDir.basename) +arguments: +- $(inputs.outDir.basename)/result.txt diff --git a/tests/core/data/preflight/programs/echo.wic b/tests/core/data/preflight/programs/echo.wic new file mode 100644 index 000000000..73b79a02f --- /dev/null +++ b/tests/core/data/preflight/programs/echo.wic @@ -0,0 +1,5 @@ +# No container: the only program the run calls is its runner. +steps: +- id: echo + in: + message: !ii hello diff --git a/tests/core/data/preflight/programs/expected.yaml b/tests/core/data/preflight/programs/expected.yaml new file mode 100644 index 000000000..ac84545a3 --- /dev/null +++ b/tests/core/data/preflight/programs/expected.yaml @@ -0,0 +1,49 @@ +# A program the run calls that is not here is one wic029 naming it and how to install it, before anything is pulled or +# started; and so is a runner that cannot run on this platform. +runs: +- machine: {missing: [cwltool_filterlog]} + argv: [--yaml, echo.wic, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: PROGRAM_MISSING, severity: error, message: {contains: [ + 'run.sh calls cwltool_filterlog, which is not on PATH: install Sophios']}}] + written: {exact: [autogenerated/echo.cwl, autogenerated/echo_inputs.yml, autogenerated/echo~echo.cwl]} +- machine: {missing: [toil-cwl-runner]} + argv: [--yaml, echo.wic, --run_local, --cwl_runner, toil-cwl-runner, --diagnostics, json] + exit: 1 + diagnostics: [{code: PROGRAM_MISSING, severity: error, message: {contains: [ + 'the run calls toil-cwl-runner, which is neither in this Python environment nor on PATH: install Toil']}}] +- machine: {missing: [cwl-docker-extract]} + argv: [--yaml, touch.wic, --generate_run_script, --container_engine, singularity, --diagnostics, json] + exit: 1 + diagnostics: [{code: PROGRAM_MISSING, severity: error, message: {contains: [ + pulling the images for singularity needs cwl-docker-extract]}}] +- machine: {windows: Windows has no pwd module} + argv: [--yaml, echo.wic, --run_local, --diagnostics, json] + exit: 1 + diagnostics: [{code: PROGRAM_MISSING, severity: error, message: {contains: [ + 'cwltool cannot run here (Windows has no pwd module): run Sophios inside WSL']}}] +- why: --graphviz without dot draws nothing, and says so as a note + machine: {missing: [dot]} + argv: [--yaml, echo.wic, --generate_cwl_workflow, --graphviz, --diagnostics, json] + diagnostics: [{code: PROGRAM_MISSING, severity: note, message: {contains: [--graphviz needs the dot program]}}] +- machine: {missing: [nextflow]} + argv: [--yaml, echo.wic, --target, nextflow, --check, --diagnostics, json] + exit: 1 + diagnostics: [{code: PROGRAM_MISSING, severity: error, message: {contains: [ + 'the run calls nextflow, which is neither in this Python environment nor on PATH: install Nextflow']}}] +- machine: {missing: [nextflow]} + argv: [--yaml, echo.wic, --target, nextflow, --generate_run_script, --diagnostics, json] + exit: 1 + diagnostics: [{code: PROGRAM_MISSING, severity: error, message: {contains: [ + 'run.sh calls nextflow, which is not on PATH: install Nextflow']}}] +- why: the launcher colours what it prints; the first line, without colour, is quoted + machine: {nextflow_exit: 1, said: "\e[31mERROR: Cannot find Java or it's a wrong version\e(B\e[m\n"} + argv: [--yaml, echo.wic, --target, nextflow, --check, --diagnostics, json] + exit: 1 + diagnostics: [{code: PROGRAM_MISSING, severity: error, message: {contains: [ + "nextflow -version exited with status 1 (ERROR: Cannot find Java or it's a wrong version): Nextflow needs a Java"]}}] +- machine: {windows: Windows has no pwd module} + argv: [--yaml, echo.wic, --target, nextflow, --check, --diagnostics, json] + exit: 1 + diagnostics: [{code: PROGRAM_MISSING, severity: error, message: {contains: [ + 'nextflow cannot run here (Nextflow needs a POSIX system, which Windows is not)']}}] diff --git a/tests/core/data/preflight/programs/touch.wic b/tests/core/data/preflight/programs/touch.wic new file mode 100644 index 000000000..d453ed9d5 --- /dev/null +++ b/tests/core/data/preflight/programs/touch.wic @@ -0,0 +1,5 @@ +# touch runs in docker.io/library/debian:bookworm-slim, so its image is pulled. +steps: +- id: touch + in: + filename: !ii a.txt diff --git a/tests/core/data/provenance_runs/edam_root.wic b/tests/core/data/provenance_runs/edam_root.wic new file mode 100644 index 000000000..03ba6fa73 --- /dev/null +++ b/tests/core/data/provenance_runs/edam_root.wic @@ -0,0 +1,6 @@ +# Declares EDAM from edamontology's default branch: a URL Sophios never wrote, with the basename of the one it did. +$schemas: ['https://raw.githubusercontent.com/edamontology/edamontology/main/EDAM_dev.owl'] +steps: +- id: hi + run: say.cwl + in: {message: !ii hi} diff --git a/tests/core/data/provenance_runs/edam_tool.wic b/tests/core/data/provenance_runs/edam_tool.wic new file mode 100644 index 000000000..d3da8d3cf --- /dev/null +++ b/tests/core/data/provenance_runs/edam_tool.wic @@ -0,0 +1,4 @@ +steps: +- id: hi + run: say_edam.cwl + in: {message: !ii hi} diff --git a/tests/core/data/provenance_runs/greeting.wic b/tests/core/data/provenance_runs/greeting.wic new file mode 100644 index 000000000..ce424880b --- /dev/null +++ b/tests/core/data/provenance_runs/greeting.wic @@ -0,0 +1,9 @@ +# Calls pair.wic directly and through outer.wic. +steps: +- id: hello + run: say.cwl + in: {message: !ii hi} +- id: pair + run: pair.wic +- id: outer + run: outer.wic diff --git a/tests/core/data/provenance_runs/other.wic b/tests/core/data/provenance_runs/other.wic new file mode 100644 index 000000000..1d88838dc --- /dev/null +++ b/tests/core/data/provenance_runs/other.wic @@ -0,0 +1,6 @@ +steps: +- id: hello + run: say.cwl + in: {message: !ii there} +- id: pair + run: pair.wic diff --git a/tests/core/data/provenance_runs/outer.wic b/tests/core/data/provenance_runs/outer.wic new file mode 100644 index 000000000..199f92092 --- /dev/null +++ b/tests/core/data/provenance_runs/outer.wic @@ -0,0 +1,6 @@ +steps: +- id: pair + run: pair.wic +- id: b + run: say.cwl + in: {message: !ii c} diff --git a/tests/core/data/provenance_runs/pair.wic b/tests/core/data/provenance_runs/pair.wic new file mode 100644 index 000000000..aee110ed8 --- /dev/null +++ b/tests/core/data/provenance_runs/pair.wic @@ -0,0 +1,7 @@ +steps: +- id: hello + run: say.cwl + in: {message: !ii a} +- id: shout + run: say.cwl + in: {message: !ii b} diff --git a/tests/core/data/provenance_runs/say.cwl b/tests/core/data/provenance_runs/say.cwl new file mode 100644 index 000000000..ac85357d8 --- /dev/null +++ b/tests/core/data/provenance_runs/say.cwl @@ -0,0 +1,6 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: echo +stdout: out.txt +inputs: {message: {type: string, inputBinding: {position: 1}}} +outputs: {out: {type: File, outputBinding: {glob: out.txt}}} diff --git a/tests/core/data/provenance_runs/say_edam.cwl b/tests/core/data/provenance_runs/say_edam.cwl new file mode 100644 index 000000000..e6d7769c5 --- /dev/null +++ b/tests/core/data/provenance_runs/say_edam.cwl @@ -0,0 +1,9 @@ +# Declares EDAM from edamontology's default branch: a URL Sophios never wrote, with the basename of the one it did. +$namespaces: {edam: https://edamontology.org/} +$schemas: ['https://raw.githubusercontent.com/edamontology/edamontology/main/EDAM_dev.owl'] +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: echo +stdout: out.txt +inputs: {message: {type: string, inputBinding: {position: 1}}} +outputs: {out: {type: File, outputBinding: {glob: out.txt}}} diff --git a/tests/core/data/quiet/fail.wic b/tests/core/data/quiet/fail.wic new file mode 100644 index 000000000..9d82a077c --- /dev/null +++ b/tests/core/data/quiet/fail.wic @@ -0,0 +1,4 @@ +steps: +- id: say + run: local/local.cwl + in: {word: !ii boom, status: !ii 3} diff --git a/tests/core/data/quiet/local/local.cwl b/tests/core/data/quiet/local/local.cwl new file mode 100644 index 000000000..2fdd0238b --- /dev/null +++ b/tests/core/data/quiet/local/local.cwl @@ -0,0 +1,9 @@ +# Prints a line on each stream, and fails when told to. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: [sh, -c] +arguments: ['echo "$0 out"; echo "$0 err" >&2; exit $1'] +inputs: + word: {type: string, default: say, inputBinding: {position: 1}} + status: {type: int, default: 0, inputBinding: {position: 2}} +outputs: {} diff --git a/tests/core/data/quiet/pair.wic b/tests/core/data/quiet/pair.wic new file mode 100644 index 000000000..ac2c08f80 --- /dev/null +++ b/tests/core/data/quiet/pair.wic @@ -0,0 +1,4 @@ +steps: +- id: say +- id: local + run: local/local.cwl diff --git a/tests/core/data/quiet/probe.cwl b/tests/core/data/quiet/probe.cwl new file mode 100644 index 000000000..83b86b467 --- /dev/null +++ b/tests/core/data/quiet/probe.cwl @@ -0,0 +1,7 @@ +# Writes system.pdb itself, and also names it as its empty stdout. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: [sh, -c, 'printf "ATOM 1\n" > "$0"'] +inputs: {output_pdb_path: {type: string, default: system.pdb, inputBinding: {position: 1}}} +outputs: {output_pdb_path: {type: File, outputBinding: {glob: $(inputs.output_pdb_path)}}} +stdout: $(inputs.output_pdb_path) diff --git a/tests/core/data/quiet/probe.wic b/tests/core/data/quiet/probe.wic new file mode 100644 index 000000000..d78599612 --- /dev/null +++ b/tests/core/data/quiet/probe.wic @@ -0,0 +1,3 @@ +steps: +- id: probe + run: probe.cwl diff --git a/tests/core/data/quiet/tools/own.cwl b/tests/core/data/quiet/tools/own.cwl new file mode 100644 index 000000000..ef7ed289f --- /dev/null +++ b/tests/core/data/quiet/tools/own.cwl @@ -0,0 +1,7 @@ +# Names its own stdout. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: echo +stdout: own.txt +inputs: {} +outputs: {out: {type: File, outputBinding: {glob: own.txt}}} diff --git a/tests/core/data/quiet/tools/say.cwl b/tests/core/data/quiet/tools/say.cwl new file mode 100644 index 000000000..2fdd0238b --- /dev/null +++ b/tests/core/data/quiet/tools/say.cwl @@ -0,0 +1,9 @@ +# Prints a line on each stream, and fails when told to. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: [sh, -c] +arguments: ['echo "$0 out"; echo "$0 err" >&2; exit $1'] +inputs: + word: {type: string, default: say, inputBinding: {position: 1}} + status: {type: int, default: 0, inputBinding: {position: 2}} +outputs: {} diff --git a/tests/core/data/quiet/w.wic b/tests/core/data/quiet/w.wic new file mode 100644 index 000000000..b08f81b8a --- /dev/null +++ b/tests/core/data/quiet/w.wic @@ -0,0 +1,15 @@ +# A search-path tool (`say`, `own`), a tool named by a `run:` path, an inline body and a call. +steps: +- id: say +- id: local + run: local/local.cwl +- id: inline + run: + cwlVersion: v1.2 + class: CommandLineTool + baseCommand: echo + inputs: {} + outputs: {} +- id: pair + run: pair.wic +- id: own diff --git a/tests/core/data/realtime/declared.wic b/tests/core/data/realtime/declared.wic new file mode 100644 index 000000000..5b4e3df84 --- /dev/null +++ b/tests/core/data/realtime/declared.wic @@ -0,0 +1,39 @@ +# A producer and the analyses declared beside it, which are taken out of the workflow and compiled on their own. +steps: +- id: slow_log +# A tool, its `config: in:` every one a literal of the analysis: a plain file name as the corpus npt_amber.wic +# writes it (read as written, an edge, wic011), and a nested `!ii`. +- id: cwl_subinterpreter + in: + file_pattern: !ii '*.log' + cwl_tool: !ii tag + max_times: !ii '3' + config: !ii + in: + file: a.txt + name: !ii b.txt +# A .wic, configured per step as `wic: steps:`, as cwl_subinterpreter_protein.wic is; a nested literal in either +# spelling. +- id: cwl_subinterpreter + in: + file_pattern: !ii '*.log' + cwl_tool: !ii measure.wic + max_times: !ii 1 + config: !ii + (1, count_lines): + in: + log: a.txt + (2, count_lines): + in: + log: {wic_inline_input: b.txt} +# A tool whose image is built from the Dockerfile beside it, wherever the analysis is written. +- id: cwl_subinterpreter + in: + file_pattern: !ii out.log + cwl_tool: !ii counted + max_times: !ii 2 + interval: !ii 5 + config: !ii + in: + log: out.log +- id: watch.wic diff --git a/tests/core/data/realtime/expected.yaml b/tests/core/data/realtime/expected.yaml new file mode 100644 index 000000000..5f2d58317 --- /dev/null +++ b/tests/core/data/realtime/expected.yaml @@ -0,0 +1,29 @@ +# What `sophios --yaml declared.wic --generate_cwl_workflow` writes under autogenerated/: the workflow as it is without +# its declarations, and each analysis compiled on its own under realtime//, a repeated document name given a +# suffix, every analysis named in the manifest with where it was declared. `refused.wic` fails at its declaration. +files: + realtime/declared: [tag_only.cwl, tag_only_inputs.yml, tag_only~tag.cwl] + realtime/declared_2: [measure_only.cwl, measure_only_inputs.yml, measure_only~measure.cwl, + measure_only~measure~count_lines@1.cwl, measure_only~measure~count_lines@2.cwl] + realtime/declared_3: [counted_only.cwl, counted_only_inputs.yml, counted_only~counted.cwl] + realtime/watch: [count_lines_only.cwl, count_lines_only_inputs.yml, count_lines_only~count_lines.cwl] +written: + declared.cwl: {steps: [{id: slow_log}, {id: watch}]} + declared~watch.cwl: {steps: []} + declared.realtime.json: + - {name: declared, analysis: tag, file_pattern: '*.log', max_times: 3, interval: 60, + cwl: realtime/declared/tag_only.cwl, inputs: realtime/declared/tag_only_inputs.yml, root_dir: '{tmp}', + declared_at: 'declared.wic:6:3'} + - {name: declared_2, analysis: measure.wic, file_pattern: '*.log', max_times: 1, interval: 60, + cwl: realtime/declared_2/measure_only.cwl, declared_at: 'declared.wic:17:3'} + - {name: declared_3, analysis: counted, file_pattern: out.log, max_times: 2, interval: 5, + declared_at: 'declared.wic:30:3'} + - {name: watch, analysis: count_lines, max_times: 2, interval: 5, declared_at: 'watch.wic:3:3'} + realtime/declared/tag_only_inputs.yml: {exact: {tag~file: {class: File, location: a.txt}, tag~name: b.txt}} + realtime/declared_2/measure_only_inputs.yml: {exact: {measure~count_lines@1~log: {class: File, location: a.txt}, + measure~count_lines@2~log: {class: File, location: b.txt}}} + realtime/declared_3/counted_only.cwl: {steps: [{run: counted_only~counted.cwl}]} + realtime/declared_3/counted_only~counted.cwl: + hints: [{exact: {class: DockerRequirement, dockerPull: counted, dockerFile: "FROM alpine:3.20\n"}}] +refused: [{code: REALTIME_DECLARATION, severity: error, file: refused.wic, line: 4, + message: {contains: ["real-time analysis 'nope' does not compile"]}}] diff --git a/tests/core/data/realtime/live.wic b/tests/core/data/realtime/live.wic new file mode 100644 index 000000000..02e13902b --- /dev/null +++ b/tests/core/data/realtime/live.wic @@ -0,0 +1,21 @@ +# Two analyses of the log slow_log writes: one that succeeds and one that fails. +steps: +- id: slow_log +- id: cwl_subinterpreter + in: + file_pattern: !ii out.log + cwl_tool: !ii count_lines + max_times: !ii '5' + interval: !ii 1 + config: !ii + in: + log: out.log +- id: cwl_subinterpreter + in: + file_pattern: !ii out.log + cwl_tool: !ii fail_lines + max_times: !ii '5' + interval: !ii 1 + config: !ii + in: + log: out.log diff --git a/tests/core/data/realtime/measure.wic b/tests/core/data/realtime/measure.wic new file mode 100644 index 000000000..f5a74fced --- /dev/null +++ b/tests/core/data/realtime/measure.wic @@ -0,0 +1,4 @@ +# An analysis written as a workflow: each step is configured by the declaration, as `wic: steps:` would. +steps: +- id: count_lines +- id: count_lines diff --git a/tests/core/data/realtime/refused.wic b/tests/core/data/realtime/refused.wic new file mode 100644 index 000000000..8f97b8f1d --- /dev/null +++ b/tests/core/data/realtime/refused.wic @@ -0,0 +1,9 @@ +# An analysis that does not compile fails the compile at its declaration, before anything runs. +steps: +- id: slow_log +- id: cwl_subinterpreter + in: + file_pattern: !ii '*.log' + cwl_tool: !ii nope + max_times: !ii 1 + config: !ii {in: {}} diff --git a/tests/core/data/realtime/tools/Dockerfile_count b/tests/core/data/realtime/tools/Dockerfile_count new file mode 100644 index 000000000..abf8b7c7b --- /dev/null +++ b/tests/core/data/realtime/tools/Dockerfile_count @@ -0,0 +1 @@ +FROM alpine:3.20 diff --git a/tests/core/data/realtime/tools/count_lines.cwl b/tests/core/data/realtime/tools/count_lines.cwl new file mode 100644 index 000000000..409c44d7a --- /dev/null +++ b/tests/core/data/realtime/tools/count_lines.cwl @@ -0,0 +1,9 @@ +# Counts the lines of a log. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: [wc, -l] +inputs: + log: {type: File, inputBinding: {position: 1}} +stdout: count.txt +outputs: + count: {type: stdout} diff --git a/tests/core/data/realtime/tools/counted.cwl b/tests/core/data/realtime/tools/counted.cwl new file mode 100644 index 000000000..8ccca0e6d --- /dev/null +++ b/tests/core/data/realtime/tools/counted.cwl @@ -0,0 +1,13 @@ +# Counts the lines of a log in an image built from the Dockerfile beside it. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: [wc, -l] +hints: + DockerRequirement: + dockerPull: counted + dockerFile: {$include: Dockerfile_count} +inputs: + log: {type: File, inputBinding: {position: 1}} +stdout: count.txt +outputs: + count: {type: stdout} diff --git a/tests/core/data/realtime/tools/fail_lines.cwl b/tests/core/data/realtime/tools/fail_lines.cwl new file mode 100644 index 000000000..9a83d9be1 --- /dev/null +++ b/tests/core/data/realtime/tools/fail_lines.cwl @@ -0,0 +1,9 @@ +# Fails, given a log. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: ['false'] +inputs: + log: {type: File, inputBinding: {position: 1}} +stdout: count.txt +outputs: + count: {type: stdout} diff --git a/tests/core/data/realtime/tools/slow_log.cwl b/tests/core/data/realtime/tools/slow_log.cwl new file mode 100644 index 000000000..c66afaf3f --- /dev/null +++ b/tests/core/data/realtime/tools/slow_log.cwl @@ -0,0 +1,7 @@ +# Writes out.log one line a second for six seconds: long enough to be watched while it grows. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: [bash, -c, 'for i in 1 2 3 4 5 6; do echo $i >> out.log; sleep 1; done'] +inputs: {} +outputs: + log: {type: File, outputBinding: {glob: out.log}} diff --git a/tests/core/data/realtime/tools/tag.cwl b/tests/core/data/realtime/tools/tag.cwl new file mode 100644 index 000000000..b4847b70a --- /dev/null +++ b/tests/core/data/realtime/tools/tag.cwl @@ -0,0 +1,9 @@ +# Copies a file under a name. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: cp +inputs: + file: {type: File, inputBinding: {position: 1}} + name: {type: string, inputBinding: {position: 2}} +outputs: + tagged: {type: File, outputBinding: {glob: $(inputs.name)}} diff --git a/tests/core/data/realtime/touched.wic b/tests/core/data/realtime/touched.wic new file mode 100644 index 000000000..5d9b9f36b --- /dev/null +++ b/tests/core/data/realtime/touched.wic @@ -0,0 +1,3 @@ +# An analysis written as a workflow of the shipped touch, for the Python API to find. +steps: +- id: touch diff --git a/tests/core/data/realtime/watch.wic b/tests/core/data/realtime/watch.wic new file mode 100644 index 000000000..135a9e45f --- /dev/null +++ b/tests/core/data/realtime/watch.wic @@ -0,0 +1,11 @@ +# A subworkflow whose only step is a declaration: emitted with no steps. +steps: +- id: cwl_subinterpreter + in: + file_pattern: !ii '*.log' + cwl_tool: !ii count_lines + max_times: !ii 2 + interval: !ii 5 + config: !ii + in: + log: out.log diff --git a/tests/core/test_backends.py b/tests/core/test_backends.py index 23c260f7b..ee5b1dbdb 100644 --- a/tests/core/test_backends.py +++ b/tests/core/test_backends.py @@ -2,7 +2,6 @@ import json import os import signal -import subprocess import tempfile from dataclasses import replace from pathlib import Path @@ -23,6 +22,7 @@ from sophios.lang.error_codes import SophiosErrorCode from .budgets import budget +from .cases import DATA from .helpers import adapter_step, write_tree from .nextflow.testkit import runtime_workflow @@ -44,7 +44,9 @@ def now(cls, tz: Any = None) -> '_Frozen': 'cwltool': [(('--parallel',), 'parallel', True), (('--timestamps',), 'timestamps', True), (('--no-read-only',), 'no_read_only', True)], 'toil-cwl-runner': [(('--maxCores', '2'), 'maxCores', 2), (('--retryCount', '3'), 'retryCount', 3), - (('--logLevel', 'DEBUG'), 'logLevel', 'DEBUG')]} + (('--logLevel', 'DEBUG'), 'logLevel', 'DEBUG'), + (('--batchSystem', 'slurm'), 'batchSystem', 'slurm'), + (('--batchSystem=slurm',), 'batchSystem', 'slurm')]} #: What a request leaves out, as RunRequest's docstring says. _DEFAULTS: dict[str, Any] = {'outdir': '', 'cachedir': '', 'quiet': True, 'provenance': True, 'container_engine': 'docker', 'documents': None} @@ -58,7 +60,9 @@ def now(cls, tz: Any = None) -> '_Frozen': 'outdir': st.one_of(st.just(''), _PATHS), 'cachedir': st.one_of(st.just(''), _PATHS), 'quiet': st.booleans(), 'provenance': st.booleans(), 'container_engine': st.sampled_from(['docker', 'singularity', 'podman', 'udocker']), - 'documents': st.lists(_PATHS, min_size=1, max_size=2).map(tuple)})) + 'documents': st.lists(_PATHS, min_size=1, max_size=2).map(tuple), + 'env': st.dictionaries(st.sampled_from(['SOPHIOS_TEST_KEPT', 'SOPHIOS_TEST_ADDED']), + st.text('ab', max_size=2))})) @pytest.mark.fast @@ -72,17 +76,27 @@ def now(cls, tz: Any = None) -> '_Frozen': @example(('bbbc', 'base', ('toil-cwl-runner', []), {})) @example(('python_script_demo', 'base', ('toil-cwl-runner', []), {})) @example(('wf', 'base', ('cwltool', []), {'quiet': False, 'cachedir': 'cache'})) +@example(('wf', 'base', ('toil-cwl-runner', [(('--batchSystem', 'slurm'), 'batchSystem', 'slurm')]), {})) +@example(('wf', 'base', ('toil-cwl-runner', [(('--batchSystem=slurm',), 'batchSystem', 'slurm')]), {})) +@example(('wf', 'base', ('cwltool', []), {'env': {'SOPHIOS_TEST_KEPT': 'new'}, 'container_engine': 'podman'})) +@example(('wf', 'base', ('toil-cwl-runner', []), {'container_engine': 'singularity'})) +# pylint: disable-next=too-many-locals def test_each_cwl_runner_reads_its_command_line_as_the_request_says( drawn: tuple[str, str, tuple[str, list[Any]], dict[str, Any]]) -> None: """As each runner's own parser reads it. The default outdir is named after the workflow, as provenance, the summary and the job store are, so two workflows started in the same second from one basepath never share it. `--quiet` is on for callers that say nothing and off when `quiet=False`, so `--debug` can be heard; Toil is never - quiet. The passthrough arguments come before the documents.""" + quiet, and writes no provenance under Slurm, which an argument that is exactly `slurm` asks for. The passthrough + arguments come before the documents. The runner gets this process's environment with the request's on top.""" name, basepath, (runner, passthrough), fields = drawn asked = _DEFAULTS | fields - with mock.patch.object(backends, 'datetime', _Frozen): - argv = _argv(RunRequest(name, Path(basepath), runner=runner, passthrough_args=tuple( - argument for arguments, _, _ in passthrough for argument in arguments), **fields)) + arguments = tuple(argument for given, _, _ in passthrough for argument in given) + with mock.patch.object(backends, 'datetime', _Frozen), \ + mock.patch.dict(os.environ, {'SOPHIOS_TEST_KEPT': 'kept', 'SOPHIOS_TEST_ELSE': 'else'}): + request = RunRequest(name, Path(basepath), runner=runner, passthrough_args=arguments, **fields) + launch = targets.backend('cwl', runner).launch(request) + assert launch.env == {**os.environ, **fields.get('env', {})} + argv = list(launch.argv) import cwltool.argparser # pylint: disable=import-outside-toplevel # it and Toil import `pwd` from toil.cwl.cwltoil import get_options # pylint: disable=import-outside-toplevel read = {'cwltool': cwltool.argparser.arg_parser().parse_args, 'toil-cwl-runner': get_options}[runner]( @@ -93,7 +107,8 @@ def test_each_cwl_runner_reads_its_command_line_as_the_request_says( f"{base}/outdir_{'cwltool' if cwl else 'toil'}_{name}_2026_10_09_12.02.16") assert read.quiet is (cwl and asked['quiet']) assert (read.cachedir or None) == (os.path.abspath(asked['cachedir']) if cwl and asked['cachedir'] else None) - assert read.provenance == (f'{base}/provenance/{name}' if asked['provenance'] else None) + assert read.provenance == (f'{base}/provenance/{name}' if asked['provenance'] and 'slurm' not in arguments + else None) docker = read.user_space_docker_cmd or ('podman' if read.podman else 'docker') assert (read.singularity, 'singularity' if read.singularity else docker) == ( asked['container_engine'] == 'singularity', asked['container_engine']) @@ -104,26 +119,6 @@ def test_each_cwl_runner_reads_its_command_line_as_the_request_says( (f'{base}/output_{name}.json',) if cwl else (f'file:{base}/jobStore_{name}', 'always')) -@pytest.mark.fast -@pytest.mark.parametrize(('passthrough', 'provenance'), [ - ((), True), (('--batchSystem', 'slurm'), False), (('--batchSystem=slurm',), True)]) -def test_toil_keeps_no_provenance_when_an_argument_is_slurm(tmp_path: Path, passthrough: tuple[str, ...], - provenance: bool) -> None: - """Toil writes no provenance under Slurm: an argument that is exactly `slurm` drops the flag.""" - cmd = _argv(RunRequest('wf', tmp_path, runner='toil-cwl-runner', passthrough_args=passthrough)) - assert ('--provenance' in cmd) is provenance - - -@pytest.mark.fast -def test_the_runner_gets_this_processs_environment_with_the_users_on_top( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - monkeypatch.setenv('SOPHIOS_TEST_KEPT', 'kept') - monkeypatch.setenv('SOPHIOS_TEST_REPLACED', 'old') - launch = targets.backend('cwl', 'cwltool').launch( - RunRequest('wf', tmp_path, env={'SOPHIOS_TEST_REPLACED': 'new'})) - assert launch.env['SOPHIOS_TEST_KEPT'] == 'kept' and launch.env['SOPHIOS_TEST_REPLACED'] == 'new' - - #: Lines that end no run: any text with no `[` (cwltool's lines start with one) and no line break. _TEXT = st.text(st.characters(exclude_characters='[\n\r'), max_size=20) @@ -222,7 +217,7 @@ def test_toil_writes_the_output_object_it_printed_last_and_no_other(printed: lis def _nextflow_request(tmp_path: Path, **fields: Any) -> RunRequest: """A Nextflow run of `wf` from `tmp_path`, whose names file `prepare` would have written.""" - (tmp_path / 'nextflow_wf').mkdir() + (tmp_path / 'nextflow_wf').mkdir(parents=True, exist_ok=True) (tmp_path / 'nextflow_wf' / 'nextflow_names.json').write_text(json.dumps({ 'processes': {'bad_step': 'bad-step', 'copy': 'child~copy'}, 'outputs': {'copy_result': 'copy~result', 'grid': 'grid', 'text': 'text', 'skipped': 'skipped'}, @@ -260,72 +255,13 @@ def test_failed_nextflow_processes_are_read_from_its_log_lines(log: tuple[list[s assert list(backends.nextflow_failed_steps(lines).items()) == list(failed.items()) -@pytest.mark.fast -def test_a_nextflow_run_reports_the_outputs_its_pipeline_recorded_by_their_sophios_names(tmp_path: Path) -> None: - """Each recorded path becomes a CWL object, the summary holds the output object, and only a run that - succeeded has one.""" - file = tmp_path / 'nextflow_wf' / 'work' / 'ab' / 'copy.txt' - cells = [[{'class': 'File', 'path': f'/w/{a}{b}/cell.txt'} for b in 'xy'] for a in 'ab'] - stdout = ''.join(f'{line}\n' for line in [ - '[PROCESS ab/cdef12] wf:copy', - 'sophios-output ' + json.dumps(['copy_result', {'class': 'File', 'path': str(file)}]), - 'sophios-output ' + json.dumps(['grid', cells]), - 'sophios-output ' + json.dumps(['text', 'a "line"\n']), - 'sophios-output ' + json.dumps(['skipped', None]), - ]) - backend = targets.backend('nextflow', 'nextflow') - outcome = backend.outcome(_nextflow_request(tmp_path), 0, stdout, tmp_path / 'absent.log') - assert outcome.outputs == { - 'copy~result': {'class': 'File', 'location': file.as_uri(), 'path': str(file), 'basename': 'copy.txt'}, - 'grid': [[{'class': 'File', 'location': f'file:///w/{a}{b}/cell.txt', 'path': f'/w/{a}{b}/cell.txt', - 'basename': 'cell.txt'} for b in 'xy'] for a in 'ab'], - 'text': 'a "line"\n', - 'skipped': None, - } - assert outcome.summary == tmp_path.resolve() / 'output_wf.json' - assert json.loads(outcome.summary.read_text(encoding='utf-8')) == outcome.outputs - assert outcome.failed == {} - - -@pytest.mark.fast -def test_a_failed_nextflow_run_names_each_failed_step_and_no_outputs(tmp_path: Path) -> None: - log = tmp_path / 'run_wf.log' - log.write_text('\n'.join(_NEXTFLOW_FAILED_LOG) + '\n', encoding='utf-8') - stdout = 'sophios-output ' + json.dumps(['grid', []]) + '\n' - outcome = targets.backend('nextflow', 'nextflow').outcome(_nextflow_request(tmp_path), 1, stdout, log) - assert (outcome.outputs, outcome.summary) == (None, None) - assert outcome.failed == {'bad-step': 7, 'child~copy': None} - assert not (tmp_path / 'output_wf.json').exists() +#: A tool that writes into an output-target Directory: an entry it may write, captured as its output. +_WRITE_INTO = DATA / 'backends' / 'write_into.cwl' -#: A tool that writes into an output-target Directory: an entry it may write, captured as its output. -_WRITE_INTO = '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: touch -requirements: - InitialWorkDirRequirement: - listing: - - entry: $(inputs.outDir) - writable: true -inputs: - outDir: - type: Directory - source: - type: File -outputs: - outDir: - type: Directory - outputBinding: - glob: $(inputs.outDir.basename) -arguments: -- $(inputs.outDir.basename)/result.txt -''' - - -def _write_into(tmp_path: Path) -> Any: +def _write_into() -> Any: """The compilation of a one-step workflow `wf` whose step `write-into` writes into `made`, beside `source.txt`.""" - write_tree(tmp_path, {'write_into.cwl': _WRITE_INTO}) - step = Step(clt_path=tmp_path / 'write_into.cwl', step_name='write-into') + step = Step(clt_path=_WRITE_INTO, step_name='write-into') step.inputs.outDir = Path('made') step.inputs.source = Path('source.txt') return compile_workflow_result(Workflow([step], 'wf')) @@ -341,22 +277,36 @@ def _lowered(result: CompilationResult, root: Path) -> run_setup.Lowered[Any]: @pytest.mark.fast -@pytest.mark.parametrize('check', [False, True]) -def test_nextflow_prepare_writes_the_pipeline_from_absolute_paths_and_makes_each_output_directory( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, check: bool) -> None: - """A relative path is read from the root directory; an output-target Directory that names nothing yet is - made; and each Nextflow name maps back to its Sophios one. A check writes none of it under the base path, - and makes no directory, as a CWL check does.""" +# pylint: disable-next=too-many-locals,too-many-statements +def test_a_nextflow_run_is_checked_prepared_and_read_back_by_its_sophios_names( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """As the CWL pre-flight does, a check reports a missing input before Nextflow starts, and makes and writes + nothing; an output-target Directory is made, not looked for. Prepared, a relative path is read from the root + directory, an output-target Directory that names nothing yet is made, and each Nextflow name maps back to its + Sophios one, in each workflow's own names file, as its summary is. The engine is asked about only when a process + has a container, its image read from the pipeline Nextflow runs, not from `nextflow_workflow.json`. Read back, + each recorded path becomes a CWL object, the first record read even on the line the standalone launcher printed + its download notice on, with no newline; the summary holds the output object, and only a run that succeeded has + one. A failed run names each failed step from Nextflow's log by its Sophios name, and has no outputs.""" monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: []) root = tmp_path / 'root' root.mkdir() + backend = targets.backend('nextflow', 'nextflow') + check = run_setup.Settings(_NEXTFLOW_SETTINGS, root, check=True) + with pytest.raises(SophiosError) as raised: + backend.prepare(_lowered(_write_into(), root), (), tmp_path / 'base', check) + (missing,) = raised.value.diagnostics + assert missing.code is SophiosErrorCode.MISSING_INPUT_FILE + assert f"input 'write-into~source' (from the workflow, whose relative paths are read from {root}) names " \ + f"'{root / 'source.txt'}', which does not exist" in missing.message write_tree(root, {'source.txt': ''}) - settings = run_setup.Settings(_NEXTFLOW_SETTINGS, root, check=check) - prepared = targets.backend('nextflow', 'nextflow').prepare(_lowered(_write_into(root), root), (), - tmp_path / 'base', settings) - if check: - assert not (tmp_path / 'base').exists() and not (root / 'made').exists() - return + backend.prepare(_lowered(_write_into(), root), (), tmp_path / 'base', check) + assert not (tmp_path / 'base').exists() and not (root / 'made').exists() + + settings = run_setup.Settings(_NEXTFLOW_SETTINGS, root) + prepared = backend.prepare(_lowered(_write_into(), root), (), tmp_path / 'base', settings) + backend.prepare(_lowered(compile_workflow_result(Workflow([adapter_step('echo', message='hello')], 'other')), + root), (), tmp_path / 'base', settings) base = tmp_path / 'base' / 'nextflow_wf' assert prepared.documents == tuple(base / name for name in ( 'nextflow_workflow.json', 'workflow.nf', 'nextflow.config', 'nextflow_params.json')) @@ -364,55 +314,17 @@ def test_nextflow_prepare_writes_the_pipeline_from_absolute_paths_and_makes_each assert params == {'write_into_outDir': {'class': 'Directory', 'path': str(root / 'made')}, 'write_into_source': {'class': 'File', 'path': str(root / 'source.txt')}} assert (root / 'made').is_dir() - assert json.loads((base / 'nextflow_names.json').read_text(encoding='utf-8')) == { - 'processes': {'write_into': 'write-into'}, 'outputs': {'write_into_outDir': 'write-into~outDir'}} - - -@pytest.mark.fast -def test_the_nextflow_check_reports_a_missing_input_and_not_an_output_directory_it_makes( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """As the CWL pre-flight does, before Nextflow starts; an output-target Directory is made, not looked for.""" - monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: []) - settings = run_setup.Settings(_NEXTFLOW_SETTINGS, tmp_path, check=True) - with pytest.raises(SophiosError) as raised: - targets.backend('nextflow', 'nextflow').prepare(_lowered(_write_into(tmp_path), tmp_path), (), - tmp_path / 'base', settings) - (missing,) = raised.value.diagnostics - assert missing.code is SophiosErrorCode.MISSING_INPUT_FILE - assert f"input 'write-into~source' (from the workflow, whose relative paths are read from {tmp_path}) names " \ - f"'{tmp_path / 'source.txt'}', which does not exist" in missing.message - - -@pytest.mark.fast -def test_a_nextflow_run_reads_its_own_names_after_another_workflow_is_prepared_in_its_base_path( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """Each workflow's names are its own file, as its summary is.""" - monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: []) - write_tree(tmp_path, {'source.txt': ''}) - settings = run_setup.Settings(_NEXTFLOW_SETTINGS, tmp_path) - backend = targets.backend('nextflow', 'nextflow') - backend.prepare(_lowered(_write_into(tmp_path), tmp_path), (), tmp_path / 'base', settings) - echo = adapter_step('echo', message='hello') - backend.prepare(_lowered(compile_workflow_result(Workflow([echo], 'other')), tmp_path), (), tmp_path / 'base', - settings) stdout = 'sophios-output ' + json.dumps(['write_into_outDir', 'made']) + '\n' request = RunRequest('wf', tmp_path / 'base', runner='nextflow', target='nextflow') assert backend.outcome(request, 0, stdout, tmp_path / 'absent.log').outputs == {'write-into~outDir': 'made'} - -@pytest.mark.fast -def test_the_nextflow_check_asks_for_the_engine_only_when_a_process_has_a_container( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """Each process's image is read from the pipeline Nextflow runs, not from `nextflow_workflow.json`.""" asked: list[list[str]] = [] engine_down = Diagnostic(Severity.ERROR, SophiosErrorCode.CONTAINER_ENGINE_UNAVAILABLE, 'docker is down.') def engine_problems(images: list[str], _settings: preflight.RunSettings) -> list[Diagnostic]: asked.append(images) return [engine_down] - monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: []) monkeypatch.setattr(preflight, 'engine_problems', engine_problems) - backend = targets.backend('nextflow', 'nextflow') host = runtime_workflow() contained = replace(host, processes=[replace(process, container='docker.io/bash:4.4') for process in host.processes]) @@ -424,58 +336,31 @@ def engine_problems(images: list[str], _settings: preflight.RunSettings) -> list assert asked == [['docker.io/bash:4.4', 'docker.io/bash:4.4']] assert list(raised.value.diagnostics) == [engine_down] - -@pytest.mark.fast -@pytest.mark.parametrize(('platform', 'script', 'run_script', 'expected'), [ - (None, None, False, 'error [wic029] the run calls nextflow, which is neither in this Python environment nor on ' - 'PATH: install Nextflow (https://www.nextflow.io/docs/latest/install.html).'), - (None, 'printf "\\033[31mERROR: Cannot find Java or it\'s a wrong version\\033(B\\033[m\\n"; exit 1', False, - "error [wic029] nextflow -version exited with status 1 (ERROR: Cannot find Java or it's a wrong version): " - 'Nextflow needs a Java it can run; install one and point JAVA_HOME at it.'), - (None, 'echo "nextflow version 26.04.2"', False, None), - (None, 'echo "nextflow version 26.04.2"', True, 'error [wic029] run.sh calls nextflow, which is not on PATH: ' - 'install Nextflow (https://www.nextflow.io/docs/latest/install.html).'), - ('Windows', 'echo "nextflow version 26.04.2"', False, 'error [wic029] nextflow cannot run here (Nextflow needs a ' - 'POSIX system, which Windows is not): run Sophios inside WSL (https://learn.microsoft.com/windows/wsl/install).'), -], ids=['missing', 'no-java', 'starts', 'run-script-not-on-path', 'windows']) -# pylint: disable-next=too-many-arguments,too-many-positional-arguments -def test_nextflow_must_start_for_a_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, platform: str | None, - script: str | None, run_script: bool, expected: str | None) -> None: - """A run looks where `runner_program` looks; `run.sh` calls the `nextflow` on PATH; and, as for a CWL run, - Sophios runs a runner on POSIX only, so a Nextflow that starts is no help on Windows.""" - program = tmp_path / 'nextflow' - program.write_text(f'#!/bin/sh\n{script}\n', encoding='utf-8') - program.chmod(0o755) - monkeypatch.setattr(preflight, 'runner_program', lambda _name: None if script is None else str(program)) - monkeypatch.setattr(preflight, 'PLATFORM_LACKS_RUNNERS', platform) - monkeypatch.setenv('PATH', str(tmp_path / 'empty')) - settings = replace(_NEXTFLOW_SETTINGS, run_script=run_script) - assert [str(problem) for problem in preflight.nextflow_problems(settings)] == ([expected] if expected else []) - - -@pytest.mark.fast -@pytest.mark.parametrize('runner', ['cwltool', 'nextflow']) -def test_the_engine_remedies_name_only_the_options_the_runs_target_takes( - monkeypatch: pytest.MonkeyPatch, runner: str) -> None: - """`--container_engine` and `--ignore_docker_processes` are a CWL run's: a Nextflow run is not told to pass - them.""" - def absent(*_args: Any, **_kwargs: Any) -> Any: - raise FileNotFoundError('docker') - settings = preflight.RunSettings('docker', '', runner=runner) - monkeypatch.setattr(preflight.sub, 'run', absent) - (missing,) = preflight.engine_problems(['docker.io/bash:4.4'], settings) - monkeypatch.setattr(preflight.sub, 'run', lambda *_args, **_kwargs: subprocess.CompletedProcess([], 0, b'', b'')) - monkeypatch.setattr(preflight, '_docker_processes', lambda: preflight.MAX_DOCKER_PROCESSES + 1) - (busy,) = preflight.engine_problems(['docker.io/bash:4.4'], settings) - cwl = runner != 'nextflow' - assert str(missing).endswith('install docker, or name an installed engine with --container_engine.' if cwl - else 'install docker.') - assert str(busy).endswith('or pass --ignore_docker_processes.' if cwl else '(sudo pkill com.docker && sudo ' - 'pkill Docker).') - - -def test_a_recorded_output_is_read_after_the_launchers_download_notice() -> None: - """The standalone launcher prints its notice with no newline, so the first record shares its line.""" - stdout = ('Downloading nextflow dependencies. It may require a few seconds, please wait .. \r\x1b[K' - 'sophios-output ["a", 1]\nsophios-output ["b", {"class": "File", "path": "/x"}]\nnot a record\n') - assert list(backends.recorded_outputs(stdout)) == [("a", 1), ("b", {"class": "File", "path": "/x"})] + file = tmp_path / 'read' / 'nextflow_wf' / 'work' / 'ab' / 'copy.txt' + cells = [[{'class': 'File', 'path': f'/w/{a}{b}/cell.txt'} for b in 'xy'] for a in 'ab'] + stdout = ''.join(f'{line}\n' for line in [ + '[PROCESS ab/cdef12] wf:copy', + 'Downloading nextflow dependencies. It may require a few seconds, please wait .. \r\x1b[K' + 'sophios-output ' + json.dumps(['copy_result', {'class': 'File', 'path': str(file)}]), + 'sophios-output ' + json.dumps(['grid', cells]), + 'not a record', + 'sophios-output ' + json.dumps(['text', 'a "line"\n']), + 'sophios-output ' + json.dumps(['skipped', None]), + ]) + outcome = backend.outcome(_nextflow_request(tmp_path / 'read'), 0, stdout, tmp_path / 'read' / 'absent.log') + assert outcome.outputs == { + 'copy~result': {'class': 'File', 'location': file.as_uri(), 'path': str(file), 'basename': 'copy.txt'}, + 'grid': [[{'class': 'File', 'location': f'file:///w/{a}{b}/cell.txt', 'path': f'/w/{a}{b}/cell.txt', + 'basename': 'cell.txt'} for b in 'xy'] for a in 'ab'], + 'text': 'a "line"\n', + 'skipped': None, + } + assert outcome.summary == (tmp_path / 'read').resolve() / 'output_wf.json' + assert json.loads(outcome.summary.read_text(encoding='utf-8')) == outcome.outputs + assert outcome.failed == {} + outcome.summary.unlink() + log = tmp_path / 'read' / 'run_wf.log' + log.write_text('\n'.join(_NEXTFLOW_FAILED_LOG) + '\n', encoding='utf-8') + failed = backend.outcome(_nextflow_request(tmp_path / 'read'), 1, stdout, log) + assert (failed.outputs, failed.summary, failed.failed) == (None, None, {'bad-step': 7, 'child~copy': None}) + assert not (tmp_path / 'read' / 'output_wf.json').exists() diff --git a/tests/core/test_basepath.py b/tests/core/test_basepath.py index cbbbfef84..162ab9aa9 100644 --- a/tests/core/test_basepath.py +++ b/tests/core/test_basepath.py @@ -1,85 +1,45 @@ -"""`--basepath` and `Workflow.run(basepath=)` are one setting: where Sophios writes what it generates.""" +"""`--basepath` and `Workflow.run(basepath=)` are one setting: where Sophios writes what it generates. The project is +tests/core/data/basepath: the tool `noop` and the workflow `w.wic` that calls it.""" import json import shlex +import shutil import sys from pathlib import Path -from types import SimpleNamespace from typing import Final import pytest import sophios.plugins -from sophios import main, run_local +from sophios import run_local from sophios.api.python.workflow import Step, Workflow -from .helpers import EACH_RUNNER, no_preflight, run_cli, search_config, write_tree +from .cases import DATA +from .helpers import EACH_RUNNER, no_preflight, run_cli, search_config pytestmark = pytest.mark.package -TOOL: Final = 'cwlVersion: v1.2\nclass: CommandLineTool\nbaseCommand: echo\ninputs: {}\noutputs: {}\n' -WORKFLOW: Final = 'steps:\n- id: noop\n' - @pytest.fixture(name='project') def _project(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: - """A working directory holding the tool `noop`, the workflow `w.wic` that calls it and a config that - searches the directory. Nothing is pulled, and the runner command is captured instead of written.""" + """A working directory holding a copy of the project and a config that searches it. Nothing is pulled, and the + runner command is captured instead of written.""" root = tmp_path / 'project' - write_tree(root, {'noop.cwl': TOOL, 'w.wic': WORKFLOW}) + shutil.copytree(DATA / 'basepath', root) search_config(root / 'config.json', [root], [root]) no_preflight(monkeypatch) monkeypatch.chdir(root) return root -def _sophios(monkeypatch: pytest.MonkeyPatch, *flags: str, code: int | None = None) -> None: - """`sophios --yaml w.wic --config_file config.json `, from the working directory; it exits with code.""" - assert run_cli(monkeypatch, '--yaml', 'w.wic', '--config_file', 'config.json', *flags) == code +def _sophios(monkeypatch: pytest.MonkeyPatch, *flags: str) -> None: + """`sophios --yaml w.wic --config_file config.json `, from the working directory.""" + assert run_cli(monkeypatch, '--yaml', 'w.wic', '--config_file', 'config.json', *flags) is None def _files(base: Path) -> set[str]: return {path.relative_to(base).as_posix() for path in base.rglob('*') if path.is_file()} -@pytest.mark.fast -@pytest.mark.parametrize('spelled', ['out/generated', 'absolute']) -@pytest.mark.parametrize('mode', ['--generate_cwl_workflow', '--generate_run_script']) -def test_the_cli_writes_under_the_basepath_and_nowhere_else( - project: Path, monkeypatch: pytest.MonkeyPatch, spelled: str, mode: str) -> None: - """The compiled workflow and job file are under `--basepath`, relative to the working directory or absolute; - the run script names it for every path the run writes; no `autogenerated/` appears.""" - base = project / 'out' / 'generated' - cmdlines: list[str] = [] - monkeypatch.setattr(run_local, 'generate_run_script', cmdlines.append) - _sophios(monkeypatch, mode, '--basepath', str(base) if spelled == 'absolute' else spelled) - assert {'w.cwl', 'w_inputs.yml'} <= _files(base) - assert not (project / 'autogenerated').exists() - if mode == '--generate_run_script': - resolved = str(base.resolve()) - assert all(resolved in cmdline for cmdline in cmdlines) and len(cmdlines) == 1 - assert f'--provenance {shlex.quote(f"{resolved}/provenance/w")}' in cmdlines[0] - - -@pytest.mark.fast -def test_the_cli_draws_under_the_basepath(project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """`--graphviz` writes its drawings beside the compiled workflow, and names the same directory to `dot`.""" - commands: list[list[str]] = [] - written: list[bool] = [] - - def run(command: list[str], *_args: object, **_kwargs: object) -> SimpleNamespace: - commands.append(command) - if '--print-dot' in command: - written.append((project / 'out' / 'w.cwl').is_file()) - return SimpleNamespace(stdout=b'') - - monkeypatch.setattr(main.shutil, 'which', lambda _name: '/usr/bin/dot') - monkeypatch.setattr(main, 'sub', SimpleNamespace(run=run)) - _sophios(monkeypatch, '--generate_cwl_workflow', '--graphviz', '--basepath', 'out') - assert (project / 'out' / 'w.wic.gv').is_file() and not (project / 'autogenerated').exists() - assert len(commands) == 3 and all(any(str(Path('out', 'w')) in arg for arg in command) for command in commands) - assert written == [True], 'cwltool reads the compiled workflow, so this compile has written it by then' - - #: Stands in for Graphviz's `dot`: `-Tsvg -o ` writes the drawing source it reads on stdin to . FAKE_DOT: Final = '''#!{python} import sys @@ -90,44 +50,48 @@ def run(command: list[str], *_args: object, **_kwargs: object) -> SimpleNamespac @pytest.mark.fast -@pytest.mark.skipif(sys.platform == 'win32', reason='the stand-in for dot is a script with a shebang') -def test_graphviz_draws_with_only_dot_on_the_path(project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """`--graphviz` needs `dot` and nothing else of the environment: cwltool runs through the interpreter that - runs Sophios, and what it prints for the workflow is what `dot` is given to draw.""" - tools = project.parent / 'tools' - tools.mkdir() - dot = tools / 'dot' - dot.write_text(FAKE_DOT.format(python=sys.executable), encoding='utf-8') - dot.chmod(0o755) - monkeypatch.setenv('PATH', str(tools)) - _sophios(monkeypatch, '--generate_cwl_workflow', '--graphviz') - drawn = (project / 'autogenerated' / 'w.svg').read_text(encoding='utf-8') - assert drawn.startswith('digraph') and 'Workflow Outputs' in drawn - - -@pytest.mark.fast -def test_generate_schemas_follows_the_basepath(project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """The schema is something Sophios generates: it goes under the base path like the rest.""" - assert run_cli(monkeypatch, '--generate_schemas', '--basepath', 'out') == 0 - assert (project / 'out' / 'schemas' / 'wic.json').is_file() and not (project / 'autogenerated').exists() - - -@pytest.mark.fast -def test_a_basepath_that_cannot_be_written_is_wic021_naming_the_flag( - project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: - """A file where the directory should be: the message names the path given and tells the user to change it.""" - write_tree(project, {'taken': ''}) - _sophios(monkeypatch, '--generate_cwl_workflow', '--basepath', 'taken', code=1) - printed = capsys.readouterr().err - assert 'error [wic021] Sophios writes the compiled workflow to' in printed - assert str(project / 'taken') in printed and 'give --basepath a directory you can write to' in printed +@pytest.mark.parametrize(('flags', 'written'), [ + (['--generate_cwl_workflow', '--basepath', 'out/generated'], {'w.cwl', 'w_inputs.yml'}), + (['--generate_run_script', '--basepath', '{base}'], {'w.cwl', 'w_inputs.yml'}), + (['--generate_cwl_workflow', '--graphviz', '--basepath', 'out/generated'], {'w.svg', 'w.wic.gv'}), + (['--generate_schemas', '--basepath', 'out/generated'], {'schemas/wic.json'}), +], ids=['relative', 'absolute', 'drawings', 'schemas']) +def test_the_cli_writes_under_the_basepath_and_nowhere_else(project: Path, monkeypatch: pytest.MonkeyPatch, + flags: list[str], written: set[str]) -> None: + """Under `--basepath`, relative to the working directory or absolute: the compiled workflow and job file; the run + script names it for every path the run writes; the drawings, which need `dot` and nothing else of the environment, + as cwltool runs through the interpreter that runs Sophios and draws the workflow this compile has written; and the + schema, which is something Sophios generates. No `autogenerated/` appears.""" + base = project / 'out' / 'generated' + cmdlines: list[str] = [] + monkeypatch.setattr(run_local, 'generate_run_script', cmdlines.append) + if '--graphviz' in flags: + if sys.platform == 'win32': + pytest.skip('the stand-in for dot is a script with a shebang') + (dot := project.parent / 'tools' / 'dot').parent.mkdir() + dot.write_text(FAKE_DOT.format(python=sys.executable), encoding='utf-8') + dot.chmod(0o755) + monkeypatch.setenv('PATH', str(dot.parent)) + if '--generate_schemas' in flags: + assert run_cli(monkeypatch, *flags) == 0 + else: + _sophios(monkeypatch, *(flag.format(base=base) for flag in flags)) + assert written <= _files(base) and not (project / 'autogenerated').exists() + if '--graphviz' in flags: + drawn = (base / 'w.svg').read_text(encoding='utf-8') + assert drawn.startswith('digraph') and 'Workflow Outputs' in drawn + if '--generate_run_script' in flags: + resolved = str(base.resolve()) + assert all(resolved in cmdline for cmdline in cmdlines) and len(cmdlines) == 1 + assert f'--provenance {shlex.quote(f"{resolved}/provenance/w")}' in cmdlines[0] @pytest.mark.fast -def test_what_the_cli_generates_under_a_search_path_is_not_read_as_a_tool( - project: Path, monkeypatch: pytest.MonkeyPatch) -> None: +def test_what_the_cli_generates_under_a_search_path_is_not_read_as_a_tool(project: Path, + monkeypatch: pytest.MonkeyPatch) -> None: """A base path below a search path is generated output, so a second run, and a scan from Python given the - same base path, find only the tool and the workflow that are there.""" + same base path, find only the tool and the workflow that are there; a base path outside or at a search path is + no output inside it, and hides nothing.""" _sophios(monkeypatch, '--generate_cwl_workflow', '--basepath', 'out') _sophios(monkeypatch, '--generate_cwl_workflow', '--basepath', 'out') assert (project / 'out' / 'w.cwl').is_file() @@ -135,72 +99,42 @@ def test_what_the_cli_generates_under_a_search_path_is_not_read_as_a_tool( assert [key.stem for key in sophios.plugins.get_tools_cwl(config, basepath='out')] == ['noop'] assert sorted(sophios.plugins.get_yml_paths(config, basepath=project / 'out')['global']) == ['w'] assert 'w' in [key.stem for key in sophios.plugins.get_tools_cwl(config)] # without it, it is read + for basepath in (project.parent / 'elsewhere', project): + assert 'w' in [key.stem for key in sophios.plugins.get_tools_cwl(config, basepath=basepath)], basepath @pytest.mark.fast -def test_a_basepath_outside_or_at_a_search_path_hides_nothing(tmp_path: Path) -> None: - """Only a directory below the search path can be generated output inside it.""" - root = tmp_path / 'root' - write_tree(root, {'a/a.cwl': TOOL}) - config = {'search_paths_cwl': {'global': [str(root)]}} - for basepath in (tmp_path / 'elsewhere', root): - assert [key.stem for key in sophios.plugins.get_tools_cwl(config, basepath=basepath)] == ['a'] - - -@pytest.mark.fast -def test_the_cli_and_python_write_a_run_to_the_same_places( - project: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: +@EACH_RUNNER +def test_the_cli_and_python_write_a_run_to_the_same_places(project: Path, monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, runner: str) -> None: """The same workflow run with the same base path leaves its root and job there and a runner command that writes provenance, the summary and the outputs there, from `--basepath` and from `run(basepath=)`. The - command line writes the tree beside the root; Python, one document.""" - commands: dict[str, str] = {} - monkeypatch.setattr(run_local, 'generate_run_script', lambda cmdline: commands.update(last=cmdline)) - + command line writes the tree beside the root; Python, one document. `--no_provenance`, and `no_provenance: yes` + in `run()`'s run arguments, give the runner no `--provenance`; without them it has one.""" + commands: list[str] = [] + monkeypatch.setattr(run_local, 'generate_run_script', commands.append) cli_base, python_base = tmp_path / 'cli out', tmp_path / 'python out' - _sophios(monkeypatch, '--generate_run_script', '--basepath', str(cli_base)) - from_cli = commands['last'] (project / 'python').mkdir() - monkeypatch.chdir(project / 'python') - Workflow([Step(clt_path=project / 'noop.cwl')], 'w').run( - basepath=str(python_base), run_args_dict={'generate_run_script': 'yes'}) - from_python = commands['last'] + def run(entry: str, base: Path, *no_provenance: str) -> list[str]: + if entry == 'cli': + monkeypatch.chdir(project) + _sophios(monkeypatch, '--generate_run_script', '--cwl_runner', runner, '--basepath', str(base), + *no_provenance) + else: + monkeypatch.chdir(project / 'python') + run_args = {'generate_run_script': 'yes', 'cwl_runner': runner} + if no_provenance: + run_args['no_provenance'] = 'yes' + Workflow([Step(clt_path=project / 'noop.cwl')], 'w').run(basepath=str(base), run_args_dict=run_args) + return shlex.split(commands[-1]) + + for entry, base in (('cli', cli_base), ('python', python_base)): + words, resolved = run(entry, base), base.resolve() + assert words[words.index('--provenance') + 1] == f'{resolved}/provenance/w' + assert words[words.index('--outdir') + 1].startswith(f"{resolved}/outdir_{runner.split('-')[0]}_w_") + assert runner != 'cwltool' or words[words.index('--write-summary') + 1] == f'{resolved}/output_w.json' + assert '--provenance' not in run(entry, base, '--no_provenance') assert _files(cli_base) == {'w.cwl', 'w_inputs.yml', 'w~noop.cwl'} assert _files(python_base) == {'w.cwl', 'w_inputs.yml'} - for base, cmdline in ((cli_base, from_cli), (python_base, from_python)): - resolved = base.resolve() - assert f'--provenance {shlex.quote(f"{resolved}/provenance/w")}' in cmdline - assert f'--write-summary {shlex.quote(f"{resolved}/output_w.json")}' in cmdline - words = shlex.split(cmdline) - outdir = words[words.index('--outdir') + 1] - assert outdir.startswith(f'{resolved}/outdir_cwltool_w_') - assert f'--outdir {shlex.quote(outdir)}' in cmdline assert not (project / 'autogenerated').exists() and not (project / 'python' / 'autogenerated').exists() - - -def _provenance_flags(cmdline: str) -> list[str]: - return [word for word in shlex.split(cmdline) if word == '--provenance'] - - -@pytest.mark.fast -@EACH_RUNNER -@pytest.mark.parametrize('entry', ['cli', 'python']) -def test_no_provenance_drops_the_runners_provenance_flag( - project: Path, monkeypatch: pytest.MonkeyPatch, entry: str, runner: str) -> None: - """`--no_provenance`, and `no_provenance: yes` in `run()`'s run arguments, give the runner no `--provenance`; - without them it has one.""" - commands: list[str] = [] - monkeypatch.setattr(run_local, 'generate_run_script', commands.append) - - def run(no_provenance: bool) -> str: - if entry == 'cli': - _sophios(monkeypatch, '--generate_run_script', '--cwl_runner', runner, - *(('--no_provenance',) if no_provenance else ())) - else: - run_args = {'generate_run_script': 'yes', 'cwl_runner': runner, - **({'no_provenance': 'yes'} if no_provenance else {})} - Workflow([Step(clt_path=project / 'noop.cwl')], 'w').run(run_args_dict=run_args) - return commands[-1] - - assert _provenance_flags(run(no_provenance=False)) == ['--provenance'] - assert not _provenance_flags(run(no_provenance=True)) diff --git a/tests/core/test_ci_coverage.py b/tests/core/test_ci_coverage.py index ef77a6555..ed7244998 100644 --- a/tests/core/test_ci_coverage.py +++ b/tests/core/test_ci_coverage.py @@ -363,8 +363,7 @@ def _tests_importing(module: str, path: Path) -> set[str]: # and twelve conformance workflows, each also run by cwltool directly, in # about four seconds. The file's other tests check what the runner is # given and run on Windows. - 'tests/core/test_plain_cwl.py::test_a_plain_cwl_workflow_runs_as_it_is', - 'tests/core/test_plain_cwl.py::test_a_conformance_workflow_runs_through_sophios_as_cwltool_runs_it', + 'tests/core/test_plain_cwl.py::test_a_plain_cwl_workflow_runs_through_sophios_as_cwltool_runs_it', # One `Workflow.run()` of a one-step echo, by cwltool, from a script run by a new # interpreter, under a second. 'tests/core/test_python_api_workflow.py::test_workflow_run_runs_a_workflow_from_a_users_script', @@ -391,16 +390,13 @@ def _tests_importing(module: str, path: Path) -> set[str]: # and that the compile reads no file it should not, is checked on every leg by the file's # other tests; only a runner shows that the written description runs. 'tests/core/test_packing.py::test_a_packed_tool_runs_from_the_tree_and_embedded_twice', - 'tests/core/test_packing.py::test_a_schemadef_tool_with_an_import_is_written_runnable', - 'tests/core/test_packing.py::test_a_packed_tool_keeps_the_partial_failure_rewrite_written_and_embedded', + 'tests/core/test_packing.py::test_a_packed_project_runs_under_cwltool_and_changes_nothing_beside_it', 'tests/core/test_packing.py::test_a_packed_tool_and_one_as_written_run_wired_by_inference', 'tests/core/test_packing.py::test_one_basepath_runs_two_echo_cwl_and_two_config_txt_with_provenance', - 'tests/core/test_packing.py::test_nothing_outside_the_basepath_is_written_or_changed', # Two quiet runs through the command line by cwltool, a failing step in a call and a tool that names # the file it writes as its stdout, in a few seconds together. What a quiet run writes and gives the # runner is checked on every leg by the file's other tests. - 'tests/core/test_quiet.py::test_a_failing_step_is_named_with_its_status_below_its_own_messages', - 'tests/core/test_quiet.py::test_a_quiet_run_keeps_a_file_the_tool_names_as_its_stdout', + 'tests/core/test_quiet.py::test_a_quiet_run_prints_each_steps_messages_and_keeps_the_files_it_names', # One six-step workflow run under Nextflow and under cwltool, and one one-step tool cwltool fails, in about six # seconds. Only Lint And Test's Linux Nextflow step collects it, so the Windows leg gives up nothing it ran; which # references the target refuses is checked on every leg by the staging family of test_capabilities.py. diff --git a/tests/core/test_compute.py b/tests/core/test_compute.py index ec9a199e2..19705ef1b 100644 --- a/tests/core/test_compute.py +++ b/tests/core/test_compute.py @@ -28,7 +28,6 @@ from sophios.api.python.workflow import Step, Workflow from sophios.lang.diagnostics import SophiosError from sophios.lang.error_codes import SophiosErrorCode -from sophios.run_local import RunHandle from sophios.run_status import RunState, RunStatus from sophios.wic_types import Yaml @@ -85,42 +84,6 @@ def test_the_request_carries_the_compiled_workflow_and_every_path_as_written(out f'{named}model': {'class': 'File', 'location': model}} -@pytest.mark.fast -def test_an_output_folder_is_sent_as_a_folder_not_as_the_local_runs_bare_name(tmp_path: Path) -> None: - """`compile()` gives a local runner an output folder as a bare name, and refuses an absolute one; the service - is sent the folder where the input names it, for it to check and write on the cluster.""" - tool = tmp_path / 'writes_in.cwl' - tool.write_text("""cwlVersion: v1.2 -class: CommandLineTool -requirements: - InlineJavascriptRequirement: {} - InitialWorkDirRequirement: - listing: - - entry: $(inputs.out) - writable: true -inputs: - out: - type: Directory -outputs: - result: - type: Directory - outputBinding: - glob: $(inputs.out.basename) -baseCommand: touch -""", encoding='utf-8') - step = Step(clt_path=tool, step_name='write') - step.inputs.out = 'results' - workflow = Workflow([step], 'writes') - assert workflow.compile().cwl_job_inputs['write~out'] == 'results' - request = compute.build_request(workflow) - assert request['inputs']['write~out'] == {'class': 'Directory', 'location': 'results'} - (run,) = (step['run'] for step in request['workflow']['steps']) - declared = run['inputs'] if isinstance(run['inputs'], dict) else {i['id']: i for i in run['inputs']} - assert declared['out']['type'] == 'Directory' - step.inputs.out = '/projects/lab/results' - assert compute.build_request(workflow)['inputs']['write~out']['location'] == '/projects/lab/results' - - #: The service's id rule, and the fit of each name outside it a case pins, by hand from the rule. _ID: typing.Final = Draft202012Validator(compute.SCHEMA['$defs']['Id']) _FITTED: typing.Final = {'a b/c': 'a-b-c', '...': 'run'} @@ -157,33 +120,6 @@ def test_a_run_id_is_the_workflow_name_the_time_and_four_hex_digits_within_the_s assert len({compute.new_run_id(name, now) for _ in range(8)}) > 1 -@pytest.mark.fast -def test_every_field_the_schema_refuses_is_a_line_in_the_schemas_words() -> None: - """All at once, each where it is and what the field is.""" - with pytest.raises(compute.RequestRefused) as refused: - compute.build_request(_workflow(), RunConfig('results').leader(time='3 days', memory='8GB') - .log_level('LOUD') # type: ignore[arg-type] - .steps(partition='a b')) - assert sorted(refused.value.messages) == [ - "leader.memory: '8GB' is not the leader's memory, as Slurm writes it: a whole number with K, M, G or T, " - 'such as 8G', - "leader.time: '3 days' is not a Slurm time limit: M, M:S, H:M:S, D-H, D-H:M or D-H:M:S, such as 3-00:00:00", - "logLevel: 'LOUD' is not Toil's log level: DEBUG, INFO (the default), WARNING or ERROR", - "steps.partition: 'a b' is not a Slurm partition of this cluster: letters, digits, '_', '.' or '-'"] - request = compute.build_request(_workflow(), RunConfig('results') - .leader(partition='normal', time='1-00:00:00', memory='8G') - .steps(partition='normal', gpu_partition='gpu', time='10').log_level('DEBUG')) - assert (request['leader']['time'], request['steps']['gpuPartition'], request['logLevel']) == ( - '1-00:00:00', 'gpu', 'DEBUG') - - -@pytest.mark.fast -def test_a_workflow_with_a_real_time_analysis_is_refused_the_service_never_runs_one() -> None: - """Refused before sending, naming the analysis, rather than dropped.""" - with pytest.raises(compute.RequestRefused, match="real-time analysis 'touch', which the compute service never"): - compute.build_request(live_workflow('live')) - - def _camel(name: str) -> str: first, *rest = name.split('_') return first + ''.join(word.capitalize() for word in rest) @@ -214,12 +150,35 @@ def _set_every_field(config: RunConfig) -> RunConfig: @pytest.mark.fast -def test_run_config_reaches_every_field_of_the_request_but_its_workflow_and_inputs_as_the_schema_says() -> None: - """The constructor and every setter, each given a valid value, reach exactly the vendored schema's top-level - properties but id, workflow and inputs, each under its own name; the keywords of `leader` and `steps` are the - properties of the schema's Leader and Steps, camelCased; the folder is left out of the request without one, for - the run's own folder, so `basepath`, which requires it, is then refused before sending, saying what to do; and no - setter touches where the outputs go. The vendored schema and RunConfig cannot drift apart.""" +def test_a_request_is_refused_or_sent_as_the_vendored_schema_says() -> None: + """The vendored schema is a JSON Schema 2020-12 document that takes its own example. Every field it refuses is a + line in its words, all at once, each where it is and what the field is; a workflow with a real-time analysis is + refused before sending, naming the analysis, rather than dropped. The constructor and every setter of RunConfig, + each given a valid value, reach exactly the schema's top-level properties but id, workflow and inputs, each under + its own name; the keywords of `leader` and `steps` are the properties of its Leader and Steps, camelCased; the + folder is left out of the request without one, for the run's own folder, so `basepath`, which requires it, is then + refused before sending, saying what to do; and no setter touches where the outputs go. Called again, a setter + replaces what it is passed again and keeps the rest; what no setter sets is left out of the request, for the + service's own settings. The vendored schema and RunConfig cannot drift apart.""" + Draft202012Validator.check_schema(compute.SCHEMA) + assert Draft202012Validator(compute.SCHEMA).is_valid(compute.SCHEMA['examples'][0]) + with pytest.raises(compute.RequestRefused) as refused: + compute.build_request(_workflow(), RunConfig('results').leader(time='3 days', memory='8GB') + .log_level('LOUD') # type: ignore[arg-type] + .steps(partition='a b')) + assert sorted(refused.value.messages) == [ + "leader.memory: '8GB' is not the leader's memory, as Slurm writes it: a whole number with K, M, G or T, " + 'such as 8G', + "leader.time: '3 days' is not a Slurm time limit: M, M:S, H:M:S, D-H, D-H:M or D-H:M:S, such as 3-00:00:00", + "logLevel: 'LOUD' is not Toil's log level: DEBUG, INFO (the default), WARNING or ERROR", + "steps.partition: 'a b' is not a Slurm partition of this cluster: letters, digits, '_', '.' or '-'"] + request = compute.build_request(_workflow(), RunConfig('results') + .leader(partition='normal', time='1-00:00:00', memory='8G') + .steps(partition='normal', gpu_partition='gpu', time='10').log_level('DEBUG')) + assert (request['leader']['time'], request['steps']['gpuPartition'], request['logLevel']) == ( + '1-00:00:00', 'gpu', 'DEBUG') + with pytest.raises(compute.RequestRefused, match="real-time analysis 'touch', which the compute service never"): + compute.build_request(live_workflow('live')) properties, defs = compute.SCHEMA['properties'], compute.SCHEMA['$defs'] workflow = {'class': 'Workflow', 'cwlVersion': 'v1.2'} core = {'id': 'r1', 'workflow': workflow, 'inputs': {}} @@ -237,12 +196,6 @@ def test_run_config_reaches_every_field_of_the_request_but_its_workflow_and_inpu assert keywords == set(defs[name.capitalize()]['properties']), name levels = typing.get_args(typing.get_type_hints(RunConfig.log_level)['level']) assert set(levels) == set(properties['logLevel']['enum']) - - -@pytest.mark.fast -def test_each_setter_sets_just_what_it_is_passed_and_leaves_the_rest() -> None: - """Called again, a setter replaces what it is passed again and keeps the rest; what no setter sets is left out - of the request, for the service's own settings.""" config = RunConfig('results').basepath('/shared/lab').leader(time='2:00:00', memory='4G') config.steps(time='30:00').leader(memory='8G', partition='normal').basepath('/shared/lab2') request = compute.request_for('r1', {'class': 'Workflow', 'cwlVersion': 'v1.2'}, {}, config) @@ -252,42 +205,6 @@ def test_each_setter_sets_just_what_it_is_passed_and_leaves_the_rest() -> None: 'steps': {'time': '30:00'}} -@pytest.mark.fast -def test_the_compute_codes_are_the_clients_own_and_never_a_sophios_errors() -> None: - """cmp001 and cmp002 belong to sophios.compute: a ComputeError is not a SophiosError, no SophiosErrorCode is - one of them, docs/compute.md documents exactly them, and the message is every line under its code.""" - errors = compute.ComputeError.__subclasses__() - assert [(error, error.code) for error in errors] == [ - (compute.RequestRefused, 'cmp001'), (compute.ServiceUnavailable, 'cmp002')] - assert not issubclass(compute.ComputeError, SophiosError) - assert not {error.code for error in errors} & {str(code) for code in SophiosErrorCode} - documented = set(re.findall(r'\bcmp\d{3}\b', (DOCS / 'compute.md').read_text('utf-8'))) - assert documented == {error.code for error in errors} - refused = compute.RequestRefused('one', 'two') - assert (refused.messages, str(refused)) == (('one', 'two'), '[cmp001] one\n[cmp001] two') - - -@pytest.mark.fast -def test_a_workflow_that_does_not_compile_is_a_sophios_error_and_nothing_is_sent( - monkeypatch: pytest.MonkeyPatch) -> None: - """The compile is Sophios's, so its failure is a SophiosError with Sophios's own code, before the service is - asked anything: the one failure of `submit` that is not a ComputeError.""" - calls = _serving(monkeypatch, {}) - step = Step(CommandLineTool('count', Inputs(n=Input(cwl.int, position=1)), Outputs()).base_command('echo')) - step.inputs.n = 'not an int' - with pytest.raises(SophiosError) as raised: - compute.Service('unix:///api.sock').submit(Workflow([step], 'count')) - assert [diagnostic.code for diagnostic in raised.value.diagnostics] == [SophiosErrorCode.LITERAL_TYPE_MISMATCH] - assert not calls - - -@pytest.mark.fast -def test_the_vendored_schema_is_a_json_schema_2020_12_document_and_its_example_a_request() -> None: - """The copy the requests are checked with is itself valid, and takes its own example.""" - Draft202012Validator.check_schema(compute.SCHEMA) - assert Draft202012Validator(compute.SCHEMA).is_valid(compute.SCHEMA['examples'][0]) - - #: The header the service names itself in, on every answer. _SERVICE: typing.Final = {'Server': 'slurm-driver/3.0.0'} @@ -360,17 +277,47 @@ def _seen(value: object) -> object: @pytest.mark.fast -@pytest.mark.parametrize('case', cases('compute-service', 'do', 'answers', 'raises', 'returns', 'stdout', 'stderr', - 'pauses', 'calls', 'patience')) -def test_a_run_makes_of_the_services_answers_what_its_contract_says( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], case: Yaml) -> None: +def test_a_run_makes_of_the_services_answers_what_its_contract_says(monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str]) -> None: """Each case of data/compute-service: each call answered from `answers` by 'METHOD path', over `_SPOKEN`, a list's answers one per call in turn, so a call past them or answered nothing fails the case; then `raises` ({exception: [message, ...]}, nothing by default), and those it gives of `returns` (what each verb returned), `stdout`, `stderr`, `pauses` and `calls` ([method, path, connect and read timeouts]). A key the test does not - read, or a case that expects none of these, fails.""" + read, or a case that expects none of these, fails. cmp001 and cmp002 belong to sophios.compute: a ComputeError is + not a SophiosError, no SophiosErrorCode is one of them, docs/compute.md documents exactly them, and the message is + every line under its code. A workflow that does not compile is a SophiosError with Sophios's own code, before the + service is asked anything: the one failure of `submit` that is not a ComputeError.""" expected = {'raises', 'returns', 'stdout', 'stderr', 'pauses', 'calls'} - assert case.keys() - {'id', 'why', 'do', 'patience', 'answers'} <= expected and case.keys() & expected, case.keys() + for case in (param.values[0] for param in cases('compute-service', 'do', 'answers', 'raises', 'returns', 'stdout', + 'stderr', 'pauses', 'calls', 'patience')): + assert case.keys() - {'id', 'why', 'do', 'patience', 'answers'} <= expected and case.keys() & expected, case + with monkeypatch.context() as patches: + seen = _answered(patches, capsys, case) + for key in case.keys() & seen.keys() | {'raises'}: + assert match(case.get(key), seen[key]), (case['id'], key, seen[key]) + + errors = compute.ComputeError.__subclasses__() + assert [(error, error.code) for error in errors] == [ + (compute.RequestRefused, 'cmp001'), (compute.ServiceUnavailable, 'cmp002')] + assert not issubclass(compute.ComputeError, SophiosError) + assert not {error.code for error in errors} & {str(code) for code in SophiosErrorCode} + documented = set(re.findall(r'\bcmp\d{3}\b', (DOCS / 'compute.md').read_text('utf-8'))) + assert documented == {error.code for error in errors} + refused = compute.RequestRefused('one', 'two') + assert (refused.messages, str(refused)) == (('one', 'two'), '[cmp001] one\n[cmp001] two') + + calls = _serving(monkeypatch, {}) + step = Step(CommandLineTool('count', Inputs(n=Input(cwl.int, position=1)), Outputs()).base_command('echo')) + step.inputs.n = 'not an int' + with pytest.raises(SophiosError) as raised: + compute.Service('unix:///api.sock').submit(Workflow([step], 'count')) + assert [diagnostic.code for diagnostic in raised.value.diagnostics] == [SophiosErrorCode.LITERAL_TYPE_MISMATCH] + assert not calls + + +def _answered(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], case: Yaml) -> dict[str, typing.Any]: + """What a run did with the answers of `case`: what each verb returned or the run raised, what it printed, the + pauses it made and the calls.""" pauses: list[float] = [] monkeypatch.setattr(compute.time, 'sleep', pauses.append) monkeypatch.setattr(compute, 'PATIENCE', float(case.get('patience', compute.PATIENCE))) @@ -385,20 +332,8 @@ def test_a_run_makes_of_the_services_answers_what_its_contract_says( except (compute.ComputeError, TimeoutError, KeyboardInterrupt) as error: raised = {type(error).__name__: list(getattr(error, 'messages', [str(error)]))} printed = capsys.readouterr() - seen = {'returns': [_seen(value) for value in returned], 'stdout': printed.out, 'stderr': printed.err, + return {'returns': [_seen(value) for value in returned], 'stdout': printed.out, 'stderr': printed.err, 'raises': raised, 'pauses': pauses, 'calls': [[method, path, *limits] for method, path, limits in calls]} - for key in case.keys() & seen.keys() | {'raises'}: - assert match(case.get(key), seen[key]), (key, seen[key]) - - -@pytest.mark.fast -def test_a_compute_run_is_the_local_handle_but_for_what_each_has_alone() -> None: - """Each method both have takes and returns the same; `slurm_job` and `warnings` are the compute run's alone, and - `collect` the local handle's, as docs/compute.md's table says.""" - run, handle = ({name for name in dir(kind) if not name.startswith('_')} for kind in (compute.Run, RunHandle)) - assert (run - handle, handle - run) == ({'slurm_job', 'warnings'}, {'collect'}) - for name in run & handle: - assert inspect.signature(getattr(compute.Run, name)) == inspect.signature(getattr(RunHandle, name)), name class _Driver(BaseHTTPRequestHandler): @@ -507,43 +442,37 @@ def _ended(pid: int) -> bool: @pytest.mark.fast -def test_a_service_on_this_host_is_reached_at_its_socket(driver: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """unix:///socket: every call goes over the socket, the Server header read as from any service, and never by - way of the proxy the environment names.""" +@pytest.mark.skipif(sys.platform == 'win32', reason=_WINDOWS) +# pylint: disable-next=too-many-locals,too-many-statements +def test_the_service_is_reached_at_its_socket_or_through_an_ssh_forward_that_never_outlives_it( + driver: Path, ssh_calls: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """unix:///socket: every call goes over the socket, the Server header read as from any service, and never by way of + the proxy the environment names; a cancel the service refuses (403, a run another account submitted) is raised in + its words, never taken for a run that ended. http:// and https:// need an HTTPS gateway in front of the service, + which there is not yet. ssh:// is the user's own ssh, its prompts left to the terminal (no BatchMode), on a + connection no ControlMaster holds, deaf to the Ctrl-C the terminal sends Python too: a socket in a directory only + its owner may open, no TCP port, forwarded to the socket the URL names. Closed, ssh has ended, the directory is + gone, and a run of it is refused at once, never asked again for PATIENCE seconds as a service that cannot be + reached is; so is a call after ssh ended, a dropped connection or a laptop asleep, in ssh's own words. Ctrl-C + before ssh forwards, at a password prompt say, ends ssh, which ignores it; Python exiting closes every Service it + left open. An unreachable host, a refused key, or nothing on the socket the URL names, by default the service + node's, is ssh's own words, no ssh left running and no directory left; and with no ssh on PATH, cmp002 names ssh, + never a bare FileNotFoundError.""" monkeypatch.setenv('HTTP_PROXY', 'http://proxy.invalid:3128') with compute.Service(f'unix://{driver}') as service: assert service.attach('r1').status().state is RunState.RUNNING - - -@pytest.mark.fast -def test_a_cancel_the_service_refuses_is_raised_in_its_words(driver: Path) -> None: - """403, a run another account submitted: refused in the service's words, never taken for a run that ended.""" - with pytest.raises(compute.RequestRefused) as refused: - compute.Service(f'unix://{driver}').attach('r1').cancel() + with pytest.raises(compute.RequestRefused) as refused: + service.attach('r1').cancel() assert refused.value.messages == ('run r1 was submitted by alice: only alice, or the service account, may ' 'cancel it',) + for url in ('http://cluster:7998', 'https://compute.example.org', 'cluster'): + with pytest.raises(compute.ServiceUnavailable) as unavailable: + compute.Service(url) + assert unavailable.value.messages == ( + f'{url} is not where the compute service is: it is reached over SSH, as ssh://[user@]host[:port][/socket] ' + '(the socket by default /run/slurm-driver/api.sock), or on its own host, as unix:///socket; http:// and ' + 'https:// need an HTTPS gateway in front of the service, which there is not yet',) - -@pytest.mark.fast -@pytest.mark.skipif(sys.platform == 'win32', reason=_WINDOWS) -@pytest.mark.parametrize('url', ['http://cluster:7998', 'https://compute.example.org', 'cluster']) -def test_a_url_but_ssh_and_unix_is_refused_there_being_no_https_gateway(url: str) -> None: - """http:// and https:// need an HTTPS gateway in front of the service, which there is not yet.""" - with pytest.raises(compute.ServiceUnavailable) as unavailable: - compute.Service(url) - assert unavailable.value.messages == ( - f'{url} is not where the compute service is: it is reached over SSH, as ssh://[user@]host[:port][/socket] ' - '(the socket by default /run/slurm-driver/api.sock), or on its own host, as unix:///socket; http:// and ' - 'https:// need an HTTPS gateway in front of the service, which there is not yet',) - - -@pytest.mark.fast -def test_ssh_forwards_a_private_socket_to_the_services_until_the_service_is_closed( - ssh_calls: Path, driver: Path) -> None: - """The user's own ssh, its prompts left to the terminal (no BatchMode), on a connection no ControlMaster holds, - deaf to the Ctrl-C the terminal sends Python too: a socket in a directory only its owner may open, no TCP port, - forwarded to the socket the URL names; closed, ssh has ended, the directory is gone, and a run of it is refused at - once, never asked again for PATIENCE seconds as a service that cannot be reached is.""" with compute.Service(f'ssh://alice@cluster:2222{driver}') as service: run = service.attach('r1') assert run.status().state is RunState.RUNNING @@ -552,87 +481,64 @@ def test_ssh_forwards_a_private_socket_to_the_services_until_the_service_is_clos assert arguments == ['-N', '-o', 'ExitOnForwardFailure=yes', '-o', 'StreamLocalBindUnlink=yes', '-o', 'ControlPath=none', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=4', '-L', f'{directory / "api.sock"}:{driver}', 'ssh://alice@cluster:2222'] - assert ignores_ctrl_c - assert _ended(pid) and not directory.exists() + assert ignores_ctrl_c and _ended(pid) and not directory.exists() with pytest.raises(compute.ServiceUnavailable) as unavailable: run.status() assert unavailable.value.messages == ( f"Service('ssh://alice@cluster:2222{driver}') is closed: a new one follows its runs again, as " f"Service('ssh://alice@cluster:2222{driver}').attach(run id)",) - -@pytest.mark.fast -@pytest.mark.usefixtures('ssh_calls') -def test_a_forward_that_ended_fails_the_next_call_at_once_and_says_so(driver: Path) -> None: - """ssh gone, a dropped connection or a laptop asleep: nothing reaches the service through it again, and the call - says so with ssh's own words, without asking again for PATIENCE seconds.""" + ssh_calls.unlink() with compute.Service(f'ssh://cluster{driver}') as service: forward = service._client.forward # pylint: disable=protected-access assert forward is not None - ssh, directory = forward + ssh, held = forward ssh.kill() ssh.wait() - (Path(directory) / 'ssh.log').write_text('Timeout, server cluster not responding.\n', 'utf-8') + (Path(held) / 'ssh.log').write_text('Timeout, server cluster not responding.\n', 'utf-8') with pytest.raises(compute.ServiceUnavailable) as unavailable: service.attach('r1') assert unavailable.value.messages == ( f'the compute service at ssh://cluster{driver} could not be reached: ssh ended, and its forward with it; a ' 'new Service forwards it again', 'Timeout, server cluster not responding.') - assert not Path(directory).exists() - + assert not Path(held).exists() -@pytest.mark.fast -def test_ctrl_c_before_ssh_forwards_ends_it_and_leaves_nothing(ssh_calls: Path, - monkeypatch: pytest.MonkeyPatch) -> None: - """At a password prompt, say: ssh, which ignores the Ctrl-C, would otherwise go on asking.""" + ssh_calls.unlink() sleep = compute.time.sleep def interrupted(_: float) -> None: while not ssh_calls.exists() or not ssh_calls.read_text('utf-8'): # until ssh is up, and asks sleep(0.01) raise KeyboardInterrupt - monkeypatch.setattr(compute.time, 'sleep', interrupted) - with pytest.raises(KeyboardInterrupt): - compute.Service('ssh://slow') + with monkeypatch.context() as patches: + patches.setattr(compute.time, 'sleep', interrupted) + with pytest.raises(KeyboardInterrupt): + compute.Service('ssh://slow') pid, _, _, directory = _ssh_run(ssh_calls) assert _ended(pid) and not directory.exists() - -@pytest.mark.fast -def test_a_forward_a_process_never_closes_ends_as_the_process_does(ssh_calls: Path, driver: Path) -> None: - """Python exiting closes every Service it left open.""" + ssh_calls.unlink() python_process('-c', f"from sophios.compute import Service; Service('ssh://cluster{driver}')", check=True, timeout=60) pid, _, _, directory = _ssh_run(ssh_calls) assert _ended(pid) and not directory.exists() + for url, said in (('ssh://alice@nowhere', 'ssh: Could not resolve hostname nowhere: Name or service not known'), + ('ssh://cluster', 'channel 2: open failed: connect failed: No such file or directory')): + ssh_calls.unlink() + with pytest.raises(compute.ServiceUnavailable) as unavailable: + compute.Service(url) + pid, _, arguments, directory = _ssh_run(ssh_calls) + assert unavailable.value.messages == ( + f"ssh to {url.removeprefix('ssh://')} did not forward the compute service's socket " + '/run/slurm-driver/api.sock:', said) + assert arguments[-2] == f'{directory / "api.sock"}:/run/slurm-driver/api.sock' + assert _ended(pid) and not directory.exists() -@pytest.mark.fast -@pytest.mark.parametrize(('url', 'said'), [ - ('ssh://alice@nowhere', 'ssh: Could not resolve hostname nowhere: Name or service not known'), - ('ssh://cluster', 'channel 2: open failed: connect failed: No such file or directory')]) -def test_ssh_that_does_not_forward_fails_at_once_with_its_own_error_and_leaves_nothing( - ssh_calls: Path, url: str, said: str) -> None: - """An unreachable host, a refused key, or nothing on the socket the URL names, by default the service node's, - /run/slurm-driver/api.sock: ssh's own words, no ssh left running and no directory left.""" - with pytest.raises(compute.ServiceUnavailable) as unavailable: - compute.Service(url) - pid, _, arguments, directory = _ssh_run(ssh_calls) - assert unavailable.value.messages == ( - f"ssh to {url.removeprefix('ssh://')} did not forward the compute service's socket /run/slurm-driver/api.sock:", - said) - assert arguments[-2] == f'{directory / "api.sock"}:/run/slurm-driver/api.sock' - assert _ended(pid) and not directory.exists() - - -@pytest.mark.fast -@pytest.mark.skipif(sys.platform == 'win32', reason=_WINDOWS) -def test_an_ssh_that_cannot_be_run_is_unavailable_in_the_systems_words_and_leaves_nothing( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """None on PATH: cmp002 naming ssh, never a bare FileNotFoundError, and no directory left of its forward.""" monkeypatch.setenv('PATH', str(tmp_path / 'bin')) - monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path)) + monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path / 'temp')) + (tmp_path / 'temp').mkdir() with pytest.raises(compute.ServiceUnavailable) as unavailable: compute.Service('ssh://cluster') assert unavailable.value.messages == ("ssh could not be run: [Errno 2] No such file or directory: 'ssh'",) - assert not list(tmp_path.iterdir()) + assert not list((tmp_path / 'temp').iterdir()) diff --git a/tests/core/test_config.py b/tests/core/test_config.py index 265effaaa..f7ef4763e 100644 --- a/tests/core/test_config.py +++ b/tests/core/test_config.py @@ -1,29 +1,53 @@ """The discovery config: a file the user names is only read; the default is generated once.""" +import json +import shutil from pathlib import Path import pytest from sophios import input_output as io -from .helpers import run_cli, write_tree +from .cases import DATA +from .helpers import run_cli pytestmark = pytest.mark.package @pytest.mark.fast -def test_a_config_file_that_does_not_exist_leaves_the_users_config_alone( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: - """A typo in --config_file used to write a fresh default config over the user's own.""" +def test_an_explicit_config_file_is_only_read(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, + capsys: pytest.CaptureFixture[str]) -> None: + """An explicit config keeps its path semantics, relative to the working directory, and creates no default + installation, nor anything it names. One that does not exist is a usage error naming it: a typo in --config_file + used to write a fresh default config over the user's own. A search path given as a string is a type error naming + its key, not iterated into characters.""" monkeypatch.setenv('HOME', str(tmp_path)) monkeypatch.chdir(tmp_path) - write_tree(tmp_path, {'wic/global_config.json': '{"mine": true}', 'w.wic': 'steps:\n touch:\n'}) users_config = tmp_path / 'wic' / 'global_config.json' - + users_config.parent.mkdir() + users_config.write_text('{"mine": true}', encoding='utf-8') + shutil.copy(DATA / 'config' / 'w.wic', tmp_path / 'w.wic') assert run_cli(monkeypatch, '--yaml', 'w.wic', '--generate_cwl_workflow', '--homedir', tmp_path, '--config_file', 'typo.json') == 2 assert 'typo.json' in capsys.readouterr().err assert users_config.read_text(encoding='utf-8') == '{"mine": true}' + config_file = tmp_path / 'config' / 'custom.json' + absolute_examples = tmp_path / 'absolute-examples' + io.write_config_to_disk({'search_paths_cwl': {'global': ['relative-adapters']}, + 'search_paths_wic': {'global': [str(absolute_examples)]}}, config_file) + before = config_file.read_bytes() + config = io.get_config(config_file, tmp_path / 'unused-home') + assert config['search_paths_cwl']['global'] == [str(tmp_path / 'relative-adapters')] + assert config['search_paths_wic']['global'] == [str(absolute_examples)] + assert config_file.read_bytes() == before + assert not [path for path in (tmp_path / 'unused-home', tmp_path / 'relative-adapters', absolute_examples) + if path.exists()] + for tag in ('search_paths_cwl', 'search_paths_wic'): + config_file.write_text(json.dumps({'search_paths_cwl': {'global': []}, 'search_paths_wic': {'global': []}, + tag: {'global': '/whole/disk'}}), encoding='utf-8') + with pytest.raises(TypeError, match=f'{tag}.global'): + io.read_config_from_disk(config_file) + @pytest.mark.fast @pytest.mark.parametrize('generate_explicitly,relative_homedir', [(False, True), (True, False)], @@ -42,7 +66,7 @@ def test_selected_home_is_provisioned_once_without_touching_an_existing_installa if generate_explicitly: assert run_cli(monkeypatch, '--homedir', homedir, '--generate_config') == 0 else: - write_tree(tmp_path, {'w.wic': 'steps:\n - id: touch\n in:\n filename: !ii empty.txt\n'}) + shutil.copy(DATA / 'config' / 'w.wic', tmp_path / 'w.wic') assert run_cli(monkeypatch, '--homedir', homedir, '--yaml', 'w.wic', '--generate_cwl_workflow') is None assert (tmp_path / 'autogenerated' / 'w.cwl').is_file() @@ -59,27 +83,3 @@ def test_selected_home_is_provisioned_once_without_touching_an_existing_installa assert io.get_config(None, homedir) == {'search_paths_cwl': {}, 'search_paths_wic': {}} assert {path.relative_to(process_home): path.read_bytes() for path in process_home.rglob('*') if path.is_file()} == before - - -@pytest.mark.fast -def test_explicit_config_paths_stay_relative_to_cwd_without_provisioning( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """An explicit config keeps its path semantics and does not create a default installation.""" - monkeypatch.chdir(tmp_path) - config_file = tmp_path / 'config' / 'custom.json' - absolute_examples = tmp_path / 'absolute-examples' - io.write_config_to_disk({ - 'search_paths_cwl': {'global': ['relative-adapters']}, - 'search_paths_wic': {'global': [str(absolute_examples)]}, - }, config_file) - before = config_file.read_bytes() - homedir = tmp_path / 'unused-home' - - config = io.get_config(config_file, homedir) - - assert config['search_paths_cwl']['global'] == [str(tmp_path / 'relative-adapters')] - assert config['search_paths_wic']['global'] == [str(absolute_examples)] - assert config_file.read_bytes() == before - assert not homedir.exists() - assert not (tmp_path / 'relative-adapters').exists() - assert not absolute_examples.exists() diff --git a/tests/core/test_diagnostics.py b/tests/core/test_diagnostics.py index be2655cdd..585ab7f68 100644 --- a/tests/core/test_diagnostics.py +++ b/tests/core/test_diagnostics.py @@ -1,5 +1,7 @@ -"""The library reports failures; only the CLI adapter exits: compilation never terminates the process, every failure -yields a diagnostic, exit codes are unchanged. The no-exit claim's dynamic half is test_emit.py's laws.""" +"""The library reports failures; only the CLI adapter exits: every failure is a coded diagnostic, a run is checked +against this machine before anything is pulled or started, and each scenario of tests/core/data/preflight says what +the command line gives back. A document's own refusals by line, step and port are tests/core/data/compiler/literals; +the no-exit claim's dynamic half is test_emit.py's laws.""" import datetime import json import math @@ -9,73 +11,29 @@ import string import subprocess import sys -from collections.abc import Callable, Sequence -from functools import partial +from collections.abc import Callable from pathlib import Path -from types import ModuleType -from typing import Any, Final, NamedTuple +from typing import Any, Final import pytest import yaml from hypothesis import assume, example, given, strategies as st -from sophios import main as cli -from sophios import preflight, run_local -from sophios.ir.complete import coerce_job_value -from sophios.ir.declarations import port_declaration -from sophios.ir.types import AuthoredName +from sophios import compiler, preflight from sophios.lang.diagnostics import Diagnostic, Diagnostics, Locator, Severity, SophiosError from sophios.lang.error_codes import EXPLANATIONS, Kind, SophiosErrorCode from sophios.lang.spans import SourceSpan -from sophios.python_cwl_adapter import check_args_match_inputs from .budgets import budget -from .cases import match -from .fake_runner import POSIX_ONLY -from .helpers import HELLOWORLD, REPO_ROOT, no_preflight, run_cli, search_config, write_tree +from .cases import case_dirs, match, printed +from .helpers import REPO_ROOT, run_cli from .hermetic import compile_hermetic, compile_hermetic_source -from .provocations import _provoke_duplicate_document_name from .strategies import author_names, pinned from .synthetic_tools import clt, registered from .test_lang_parser import FAST pytestmark = pytest.mark.package - -@pytest.mark.fast -def test_an_error_with_no_diagnostics_is_unrepresentable() -> None: - """By construction: the exception cannot exist empty.""" - with pytest.raises(ValueError): - SophiosError([]) - - -@pytest.mark.fast -def test_str_carries_every_message() -> None: - """What an embedder logs by default includes each diagnostic, so catching - without inspecting `.diagnostics` still loses nothing.""" - error = SophiosError.error(SophiosErrorCode.UNRESOLVED_INPUT, 'first', 'second') - assert 'first' in str(error) and 'second' in str(error) - assert len(error.diagnostics) == 2 - - -# --- the converted sites, one by one --------------------------------------- - - -@pytest.mark.fast -def test_script_argument_mismatch_reports(tmp_path: Path) -> None: - """`python_cwl_adapter` reports the mismatch it used to print-and-exit.""" - module = ModuleType('fake_workflow_script') - module.inputs = {'expected_arg': int} # type: ignore[attr-defined] - - with pytest.raises(SophiosError) as caught: - check_args_match_inputs(module, {'unexpected_arg': 1}, check=True) - - messages = [d.message for d in caught.value.diagnostics] - assert any('unexpected_arg' in m for m in messages) - assert any('expected_arg' in m for m in messages) - assert all(d.code is SophiosErrorCode.SCRIPT_ARGUMENT_MISMATCH for d in caught.value.diagnostics) - - _TYPES: Final = {'int': int, 'long': int, 'float': float, 'double': float, 'boolean': bool, 'string': str} _TEXTS = st.text('07.e+-:axy', max_size=4) _READ_BACK: Final[dict[type, Callable[[str], Any]]] = {str: str, int: int, float: float, @@ -104,6 +62,15 @@ def _binds(name: str, value: Any) -> bool: return value.__class__ is wanted or wanted is str and isinstance(value, (int, float, datetime.date)) +def _job_value(declared: object, literal: object) -> object: + """The job value `!ii literal` gives the one input of a tool that declares `declared`.""" + tool = clt({'x': {'type': declared, 'inputBinding': {'position': 1}}}, {}, canonical=True) + compiled = compile_hermetic({'steps': [{'id': 'probe', 'in': {'x': {'wic_inline_input': literal}}}]}, + tools=registered({'probe': tool}, {})) + (value,) = compiled.artifact.job_inputs.values() + return value + + @pytest.mark.fast @given(_PORTS_AND_LITERALS) @pinned(('int', 2.9), ('int', '007'), ('int', True), ('long', 2.9), ('boolean', 'yes'), ('boolean', 2), @@ -111,7 +78,7 @@ def _binds(name: str, value: Any) -> bool: ('string', {'seen': datetime.date(2024, 1, 15)}), ({'type': 'array', 'items': 'string'}, ['a', None]), ('string', 20), ('string', 1.5), ('string', True), ('string', False), ('string', datetime.date(2024, 1, 15)), ('string', {'seen': 'a'}), ('float', 1), ('double', 2**53), ('float', 1.0e-5), ('int', 3), ('long', 3), - ('boolean', False), ('float', math.nan), ({'type': 'array', 'items': 'int'}, [1, None])) + ('boolean', False), ('float', math.nan), ({'type': 'array', 'items': 'int'}, [1, None]), ('string', b'abc')) @FAST def test_a_literal_binds_only_as_the_value_it_is(case: Any) -> None: """`int('007')` and `bool('yes')` used to succeed, an int above 2**53 rounded silently, and a null inside an array @@ -139,70 +106,6 @@ def test_a_literal_binds_only_as_the_value_it_is(case: Any) -> None: assert held.__class__ is _TYPES[name] and repr(held) == repr(_TYPES[name](item)), held -def _job_value(declared: object, literal: object) -> object: - """The job value `!ii literal` gives the one input of a tool that declares `declared`.""" - tool = clt({'x': {'type': declared, 'inputBinding': {'position': 1}}}, {}, canonical=True) - compiled = compile_hermetic({'steps': [{'id': 'probe', 'in': {'x': {'wic_inline_input': literal}}}]}, - tools=registered({'probe': tool}, {})) - (value,) = compiled.artifact.job_inputs.values() - return value - - -def _job_value_written(declared: object, spelling: str) -> object: - """The job value `!ii `, written in a `.wic` file, gives the one input of a tool that declares - `declared`. Only the text can say whether the literal is quoted.""" - tool = clt({'x': {'type': declared, 'inputBinding': {'position': 1}}}, {}, canonical=True) - compiled = compile_hermetic_source(f'steps:\n- id: probe\n in:\n x: !ii {spelling}\n', - tools=registered({'probe': tool}, {})) - (value,) = compiled.artifact.job_inputs.values() - return value - - -@pytest.mark.fast -@pytest.mark.parametrize('spelling', ["'7'", '"7"', "'007'"], ids=['single', 'double', 'octal']) -def test_a_quoted_number_on_an_int_input_is_wic020(spelling: str) -> None: - """A quoted `!ii` scalar is its text, and text is not an int; `!ii 7` is what binds the port.""" - with pytest.raises(SophiosError) as caught: - _job_value_written('int', spelling) - assert caught.value.diagnostics[0].code is SophiosErrorCode.LITERAL_TYPE_MISMATCH - - -@pytest.mark.fast -@pytest.mark.parametrize('spelling, expected', [("'7'", '7'), ("'007'", '007'), ('7', '7'), ('007', '7')], - ids=['quoted', 'quoted-octal', 'plain', 'plain-octal']) -def test_a_number_on_a_string_input_is_its_text_quoted_or_not(spelling: str, expected: str) -> None: - """Quoted, the literal is the text as written; plain, it is the number YAML read, as text.""" - assert _job_value_written('string', spelling) == expected - - -_ENUM: Final = {'type': 'enum', 'symbols': ['a', 'b']} -_BOOL_OR_STRINGS: Final = ['null', 'boolean', {'type': 'array', 'items': 'string'}] - - -@pytest.mark.fast -@pytest.mark.parametrize('declared, literal, expected', [ - (_BOOL_OR_STRINGS, False, False), - (['null', 'int', {'type': 'array', 'items': 'int'}], 3, 3), - (['null', 'string', {'type': 'array', 'items': 'string'}], 'a', 'a'), - (['null', 'File', {'type': 'array', 'items': 'File'}], {'class': 'File', 'location': 'x'}, - {'class': 'File', 'location': 'x'}), - (['null', 'float', {'type': 'array', 'items': 'int'}], 3, [3]), - (['null', 'string', {'type': 'array', 'items': 'int'}], 3, [3]), - (['null', 'string', {'type': 'array', 'items': {'type': 'array', 'items': 'int'}}], 3, [[3]]), - (['null', _ENUM, {'type': 'array', 'items': _ENUM}], 'a', ['a']), -], ids=['bool-stays-a-bool', 'int-stays-an-int', 'text-stays-text', 'file-stays-a-file', - 'int-is-not-widened-to-the-float', 'int-is-not-made-text', 'int-is-not-made-text-nested', - 'enum-member-is-not-a-type-name']) -def test_a_scalar_given_to_a_union_with_an_array_takes_the_scalar_member( - declared: object, literal: object, expected: object) -> None: - """biobb's `pdb` takes `filter` as `boolean | string[]`; `filter: !ii False` - reached it as `['false']`, so it kept only the lines starting with "false" - and wrote a PDB with no coordinates. A scalar takes the scalar member whose - type it already is; any other scalar is wrapped into the array, as before.""" - value = _job_value(declared, literal) - assert (value, type(value)) == (expected, type(expected)) - - @pytest.mark.fast @given(st.from_regex(r'[-+]?[0-9]+(\.[0-9]*)?[eE][-+]?[0-9]+', fullmatch=True)) @pinned('1e-5', '1E3', '2.5e10') @@ -212,304 +115,15 @@ def test_a_scalar_given_to_a_union_with_an_array_takes_the_scalar_member( def test_scientific_notation_yaml_reads_as_text_says_how_to_write_a_float(text: str) -> None: """YAML reads a float with no signed exponent as text, so it is wic020. The message gives the spelling YAML, and so the parser, reads as a float, with the value the author meant: the same float, infinity included.""" + tool = clt({'x': {'type': 'float', 'inputBinding': {'position': 1}}}, {}, canonical=True) assume(isinstance(yaml.safe_load(text), str)) with pytest.raises(SophiosError) as caught: - _job_value('float', text) + compile_hermetic_source(f'steps:\n- id: probe\n in:\n x: !ii {text}\n', + tools=registered({'probe': tool}, {})) advised = re.search(r'Write (\S+)\.$', caught.value.diagnostics[0].message) assert advised is not None and yaml.safe_load(advised[1]) == float(text), caught.value.diagnostics[0].message -@pytest.mark.fast -def test_a_literal_of_another_python_type_says_which_python_type_the_port_wants() -> None: - """`b'abc'` is a YAML binary scalar; the message names the Python type the port holds.""" - with pytest.raises(SophiosError) as caught: - _job_value('string', b'abc') - assert caught.value.diagnostics[0].message.endswith("its literal b'abc' is of type bytes, not a Python str.") - - -_BAD = 'steps:\n- id: ""\n' -_TWO_TOUCHES = ('steps:\n- id: touch\n in:\n filename: !ii a.txt\n' - '- id: touch\n in:\n filename: !ii b.txt\n- id: cat\n') -_JSON = ('--diagnostics', 'json') - - -class _CliRow(NamedTuple): - source: str - name: str - flags: tuple[str, ...] - code: int | None - expected: list[Any] - draws: bool | None - - -@pytest.mark.fast -@pytest.mark.parametrize('row', [ - pytest.param(_CliRow(_BAD, 'bad.wic', (), 1, - [{'re': 'Failed to compile .*bad[.]wic'}, {'re': r'bad[.]wic:2:7: error \[wic007\]'}], None), - id='error'), - pytest.param(_CliRow(_BAD, 'bad.wic', _JSON, 1, - [{'severity': 'error', 'code': 'wic007', 'kind': 'document', 'line': 2, 'column': 7, - 'file': {'re': 'bad[.]wic$'}, 'fix': SophiosErrorCode.EMPTY_STEP_ID.explanation.fix}], None), - id='error-json'), - pytest.param(_CliRow(_TWO_TOUCHES, 'two_touches.wic', (), None, - [{'re': '^' + re.escape('note [wic043] 1 edge was guessed; draw the workflow to check it ' - '(--graphviz, or Workflow.draw() in Python)') + '$'}, - {'re': r'^ .*two_touches\.wic:8:3 cat\.file <- touch@2\.file \(1 other fits\)$'}], True), - id='note'), - pytest.param(_CliRow(_TWO_TOUCHES, 'two_touches.wic', ('--inference_strict',), 1, - [{'re': 'Failed to compile .*two_touches[.]wic'}, - {'re': r'^.*error \[wic043\] cat\.file <- touch@2\.file was guessed, ' - '1 other fits; write the edge it should read$'}], False), - id='strict'), - pytest.param(_CliRow(_TWO_TOUCHES, 'two_touches.wic', _JSON, None, - [{'severity': 'note', 'code': 'wic043', 'message': 'cat.file <- touch@2.file (1 other fits)', - 'step': 'cat', 'index': 3, 'port': 'file'}], None), - id='note-json')]) -def test_the_cli_reports_each_diagnostic_on_stderr( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], row: _CliRow) -> None: - """The failure a scientist sees names the file, line, column and code on stderr, as text or one JSON object a - line. A guessed edge is a note and the compile succeeds; `--inference_strict` makes it an error, with nothing to - draw. `code` is None where main returns; `draws` is None where unchecked.""" - path = write_tree(tmp_path, {row.name: row.source}) / row.name - monkeypatch.chdir(tmp_path) - assert run_cli(monkeypatch, '--yaml', path, '--generate_cwl_workflow', *row.flags) == row.code - out, err = capsys.readouterr() - assert row.code != 1 or row.flags == _JSON or f'Failed to compile {path}' in err - if row.flags == _JSON: - found = [json.loads(line) for line in err.splitlines() if line.startswith('{')] - else: - found = [line for line in err.splitlines() if re.search(r'\[wic|^Failed to compile| <- ', line)] - assert match(row.expected, found), found - assert 'wic0' not in out and 'Failed to compile' not in out - if row.draws is not None: - assert ('draw the workflow' in err) is row.draws - - -@pytest.mark.fast -def test_cli_reports_a_crash_in_one_line_and_keeps_the_whole_traceback( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: - """A failure Sophios did not expect says so in one line; the file holds the traceback with its frames.""" - workflow = write_tree(tmp_path, {'crash.wic': 'steps:\n- id: touch\n'}) / 'crash.wic' - - def crash(*_args: object, **_kwargs: object) -> None: - raise RuntimeError('boom') - - monkeypatch.setattr(cli.compiler, 'compile_source', crash) - monkeypatch.chdir(tmp_path) - - assert run_cli(monkeypatch, '--yaml', workflow, '--generate_cwl_workflow') == 1 - captured = capsys.readouterr() - assert 'Sophios stopped on an unexpected RuntimeError: boom. The traceback is in error_crash.txt' in captured.err - assert 'Traceback' not in captured.err and 'boom' not in captured.out - kept = (tmp_path / 'error_crash.txt').read_text(encoding='utf-8') - assert 'Traceback (most recent call last)' in kept and 'in crash' in kept - - -@pytest.mark.fast -def test_the_failure_type_is_importable_from_the_package() -> None: - """`from sophios.lang import SophiosError` works. - - This is the type an embedder writes an `except` clause against, so it is - the one name in the layer that must be reachable from the package root. - It was reachable only as `sophios.lang.diagnostics.SophiosError`, which - asks callers to import from a private module for the sake of the one - thing the refactor exists to give them. - """ - from sophios.lang import SophiosError as exported - assert exported is SophiosError - - -@pytest.mark.fast -def test_every_exported_name_resolves() -> None: - """Everything `__all__` promises can be imported. - - `__all__` is a claim about the package's surface, and nothing checks a - claim like that until a caller writes the import and it fails. - """ - import sophios.lang as lang - - missing = [name for name in lang.__all__ if not hasattr(lang, name)] - assert not missing, f'exported but not importable: {missing}' - - -_Cli = Callable[..., int | str | None] - - -@pytest.fixture(name='cli_on_helloworld') -def _cli_on_helloworld(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> _Cli: - """Run the CLI on the helloworld tutorial from a scratch directory, container engine replaced; compiling, arguments - and exit code are real.""" - no_preflight(monkeypatch) - monkeypatch.chdir(tmp_path) - return partial(run_cli, monkeypatch, '--yaml', HELLOWORLD) - - -@pytest.mark.fast -@pytest.mark.parametrize(('argv', 'said'), [ - (['--yaml', '{hello}', '--generate_cwl_workflow', '--no_such_flag'], '--no_such_flag'), - (['--yaml', '{hello}', '--generate_run_script', '--no_such_flag'], '--no_such_flag'), - (['--yaml', '{hello}', '--generate_cwl_workflow', '--passthrough_flags', 'yes', '--debug'], '--run_local'), - (['--yaml', '{tmp}/nope.wic', '--generate_cwl_workflow'], 'no workflow file at'), - (['--yaml', '{hello}', '--inputs_file', '{tmp}/nope.yml', '--generate_cwl_workflow'], 'no inputs file at'), - (['--explain', 'wic999'], 'wic999 is not a Sophios error code'), -], ids=['an unknown flag compiling', 'an unknown flag writing run.sh', 'passthrough flags with no runner', - 'no such workflow file', 'no such inputs file', 'no such code']) -def test_a_usage_error_exits_2_naming_it_without_a_traceback( - argv: list[str], said: str, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capsys: pytest.CaptureFixture[str]) -> None: - """A flag Sophios does not know is an error, not a silent gift to the runner, and `--passthrough_flags yes` - with no runner to send the arguments to is one too. A mistyped `--yaml` or `--inputs_file`, or a code Sophios - does not report, is a usage error that names it and exit 2, not a traceback.""" - monkeypatch.chdir(tmp_path) - code = run_cli(monkeypatch, *(arg.format(hello=HELLOWORLD, tmp=tmp_path) for arg in argv)) - printed = capsys.readouterr().err - assert code == 2 and said in printed and 'Traceback' not in printed - - -@pytest.mark.fast -@pytest.mark.parametrize(('flags', 'token', 'present'), [ - (['--passthrough_flags', 'yes', '--debug'], '--debug', True), - (['--passthrough_flags', 'yes', '--validate'], '--validate', True), - ([], '--quiet', False), - (['--quiet'], '--quiet', True), -], ids=['passthrough sends an unrecognised argument to the runner', - 'runner --validate is not a prefix of --validate_plugins', 'no --quiet', '--quiet']) -def test_run_sh_carries_a_runner_flag_exactly_when_asked(cli_on_helloworld: _Cli, flags: list[str], - token: str, present: bool) -> None: - """cwltool's `--validate` reaches the runner; it is not a prefix of `--validate_plugins`. Without `--quiet` the - runner keeps its own log level, so `--debug` can be heard.""" - cli_on_helloworld('--generate_run_script', *flags) - assert (token in Path('run.sh').read_text(encoding='utf-8').split()) is present - - -@pytest.mark.fast -@pytest.mark.parametrize(('outcome', 'cwl_runner', 'code'), [ - (3, 'cwltool', 3), (KeyboardInterrupt, 'cwltool', 130), (KeyboardInterrupt, 'toil-cwl-runner', 130), -], ids=['the runners exit code', 'ctrl-c under cwltool', 'ctrl-c under toil']) -def test_run_local_exits_with_the_runners_code_or_130_on_ctrl_c( - monkeypatch: pytest.MonkeyPatch, cli_on_helloworld: _Cli, outcome: object, cwl_runner: str, - code: int) -> None: - """The CLI turns the interrupt the run lets through into the shell's SIGINT code, whichever runner ran. - - KeyboardInterrupt is listed so a regression fails this test instead of aborting the session.""" - def run(_request: object) -> object: - if outcome is KeyboardInterrupt: - raise KeyboardInterrupt - return outcome - - monkeypatch.setattr(run_local, 'run', run) - try: - assert cli_on_helloworld('--run_local', '--cwl_runner', cwl_runner) == code - except KeyboardInterrupt: - pytest.fail('the interrupt escaped the CLI') - - -@pytest.mark.fast -@POSIX_ONLY -@pytest.mark.parametrize('flags', [[], ['--cachedir', 'mycache']]) -def test_a_runner_that_cannot_start_says_why_with_or_without_a_cachedir( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path, - cli_on_helloworld: _Cli, flags: list[str]) -> None: - """The traceback goes to error_.txt; the message itself is printed, whatever the cache.""" - monkeypatch.setattr(preflight, 'runner_program', lambda _name: str(tmp_path / 'no_such_runner')) - assert cli_on_helloworld('--run_local', *flags) == 1 - out, err = capsys.readouterr() - assert 'no_such_runner' in out and 'See error_helloworld.txt for detailed technical information.' in out - assert 'or the error the runner itself raised' in err - kept = (tmp_path / 'error_helloworld.txt').read_text(encoding='utf-8') - assert 'Traceback (most recent call last)' in kept and 'FileNotFoundError' in kept - - -@pytest.mark.fast -@pytest.mark.parametrize('step, code, message', [ - ({'id': 'mk_file', 'in': {'name': 'x'}}, SophiosErrorCode.UNRESOLVED_INPUT, 'Did you forget to use !ii before x?'), - ({'id': 'scale', 'in': {'n': {'wic_inline_input': 'x'}}}, SophiosErrorCode.LITERAL_TYPE_MISMATCH, None)], - ids=['unresolved input', 'literal type mismatch']) -def test_a_compile_error_names_its_line_step_and_port(step: dict[str, Any], code: SophiosErrorCode, - message: str | None) -> None: - """wic011 carried a message and nothing else, the parser had the span all along; it is one line, with no - `Warning!` in front and no advice to compile anyway. wic020 names the line of the `!ii` literal and the step - and port it binds.""" - with pytest.raises(SophiosError) as caught: - compile_hermetic({'steps': [step]}) - first = caught.value.diagnostics[0] - assert first.code is code - assert first.span is not None and first.span.file == 'oracle.wic' and first.span.start_line > 0 - assert first.locator == Locator(step=step['id'], index=1, port=next(iter(step['in']))) - if message is not None: - assert [(d.code, d.message) for d in caught.value.diagnostics] == [(code, message)] - - -@pytest.mark.fast -def test_a_missing_required_job_value_carries_its_position() -> None: - """wic012 is raised where the value is coerced, at the span and step its caller names.""" - span = SourceSpan('x.wic', 3, 1, 3, 1) - locator = Locator(step='scale', index=2, port='n') - with pytest.raises(SophiosError) as caught: - coerce_job_value(AuthoredName('n'), port_declaration({'type': 'int'}), None, - span=span, locator=locator) - diagnostic = caught.value.diagnostics[0] - assert diagnostic.code is SophiosErrorCode.MISSING_REQUIRED_INPUT - assert (diagnostic.span, diagnostic.locator) == (span, locator) - assert str(diagnostic).startswith('x.wic:3:1: ') - - -@pytest.mark.fast -def test_a_duplicate_document_name_names_its_document() -> None: - """wic031 has no port to point at, so it points at the document that binds a prefix twice.""" - with pytest.raises(SophiosError) as caught: - _provoke_duplicate_document_name() - diagnostic = caught.value.diagnostics[0] - assert diagnostic.code is SophiosErrorCode.DUPLICATE_DOCUMENT_NAME - assert diagnostic.span is not None and diagnostic.span.file == 'provoke.wic' - - -@pytest.mark.fast -def test_every_code_is_explained() -> None: - """A code an agent cannot look up is a code it cannot act on. - - A document's mistake carries a language code and a call's mistake does not, - so a caller can route on `is_language` and land on the right reference. - """ - assert set(EXPLANATIONS) == set(SophiosErrorCode) - for code, explanation in EXPLANATIONS.items(): - text = explanation.meaning + explanation.fix - assert explanation.meaning and explanation.fix and '|' not in text and '\n' not in text, code - if explanation.kind in (Kind.DOCUMENT, Kind.CALL): - assert code.is_language == (explanation.kind is Kind.DOCUMENT), code - - -@pytest.mark.fast -def test_explain_prints_what_a_code_means_and_the_fix(monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str]) -> None: - """`--explain` answers from the catalog, with no workflow, and exits 0.""" - assert run_cli(monkeypatch, '--explain', 'WIC011') == 0 - printed = capsys.readouterr().out - assert printed.startswith('wic011 (document): ') and '\nFix: ' in printed and '!ii' in printed - - -@pytest.mark.fast -def test_explain_says_what_a_nextflow_support_code_means(monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str]) -> None: - """An nf-s code is looked up as any other, and its kind says nothing is wrong with the workflow: the target - cannot run it yet.""" - assert run_cli(monkeypatch, '--explain', 'nf-s007') == 0 - assert capsys.readouterr().out.startswith( - 'nf-s007 (target): A `nested_crossproduct` result read by a later step.\nFix: ') - - -_ROW = re.compile(r'^\| `(?P[a-z]{3}\d{3}|nf-s\d{3})` \| (?P[a-z]+) \| (?P.+) \| (?P.+) \|$') - - -@pytest.mark.fast -def test_the_error_codes_page_says_what_the_code_says() -> None: - """docs/error_codes.md is the catalog, written out.""" - page = REPO_ROOT / 'docs' / 'error_codes.md' - rows = {found['code']: (found['kind'], found['meaning'], found['fix']) - for found in map(_ROW.match, page.read_text(encoding='utf-8').splitlines()) if found} - assert rows == {str(code): (str(e.kind), e.meaning, e.fix) for code, e in EXPLANATIONS.items()} - - _SPANS = st.builds(SourceSpan, st.text('aw.', min_size=1, max_size=4), *[st.integers(1, 9)] * 4) @@ -528,7 +142,8 @@ def test_a_diagnostic_is_one_json_object_it_can_be_rebuilt_from( """The object `--diagnostics json` prints has every key docs/cli-reference.md lists, null where Sophios does not know the value, so a reader never tests for a key; it carries the position, the step and port, and the catalog's kind and fix, so a reader rebuilds the diagnostic from it. The text form reads where, how serious, the code and - the message, and a compile-phase failure that knows no line invents none. A note does not fail anything.""" + the message, and a compile-phase failure that knows no line invents none. A note does not fail anything; an + error holds at least one diagnostic, and says each of them.""" diagnostics = Diagnostics() (diagnostics.error if severity is Severity.ERROR else diagnostics.note)(code, message, span, locator) [found] = list(diagnostics) @@ -544,524 +159,8 @@ def test_a_diagnostic_is_one_json_object_it_can_be_rebuilt_from( said = f'{where[0]}:{where[1]}:{where[2]}: ' * (span is not None) + f'{severity} [{code}] {message}' assert str(found) == said if locator is None else str(found).startswith(said) assert diagnostics.has_errors is (severity is Severity.ERROR) - - -@pytest.mark.fast -@pytest.mark.skipif(sys.platform == 'win32' or os.geteuid() == 0, - reason='directory modes do not stop Windows or root') -def test_a_directory_sophios_cannot_write_is_wic021(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capsys: pytest.CaptureFixture[str]) -> None: - """A working directory where `autogenerated/` cannot be created is one `wic021` line, not a PermissionError.""" - locked = tmp_path / 'locked' - locked.mkdir(mode=0o555) - monkeypatch.chdir(locked) - assert run_cli(monkeypatch, '--yaml', HELLOWORLD, '--generate_cwl_workflow') == 1 - printed = capsys.readouterr().err - assert 'error [wic021] Sophios writes the compiled workflow to' in printed - assert 'give --basepath a directory you can write to' in printed - - -# touch.cwl runs in docker.io/library/debian:bookworm-slim -_TOUCH = 'steps:\n- id: touch\n in:\n filename: !ii a.txt\n' - - -@pytest.fixture(name='machine') -def _machine(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Callable[..., list[object]]: - """Replace `subprocess.run` with a machine whose `docker` is 'running', 'missing' or answers an exit status, with - `processes` Docker Desktop processes and the programs in `missing` off PATH; returns the commands it was given.""" - monkeypatch.chdir(tmp_path) - - def install(engine: str = 'running', processes: int = 0, said: bytes = b'', - missing: tuple[str, ...] = ()) -> list[object]: - calls: list[object] = [] - - def run(cmd: list[str], *_args: object, **_kwargs: object) -> subprocess.CompletedProcess[bytes]: - calls.append(cmd) - if cmd[0] == 'pgrep': - return subprocess.CompletedProcess(cmd, 0, stdout=b'1\n' * processes, stderr=b'') - if cmd[0] == 'docker' and engine == 'missing': - raise FileNotFoundError('docker') - if cmd[0] == 'docker' and engine == 'fails': - return subprocess.CompletedProcess(cmd, 1, stdout=b'', stderr=said) - return subprocess.CompletedProcess(cmd, 0, stdout=b'', stderr=b'') - monkeypatch.setattr(subprocess, 'run', run) - monkeypatch.setattr(sys, 'platform', 'linux') - which = shutil.which - monkeypatch.setattr(shutil, 'which', lambda name, *a, **k: None if name in missing else which(name, *a, **k)) - return calls - return install - - -def _pulled(calls: Sequence[object]) -> bool: - return any(isinstance(cmd, list) and cmd[0] == 'cwl-docker-extract' for cmd in calls) - - -def _w(tmp_path: Path, source: str | None) -> Path: - """The workflow to run: helloworld when source is None, else source written as tmp_path/w.wic.""" - return HELLOWORLD if source is None else write_tree(tmp_path, {'w.wic': source}) / 'w.wic' - - -def _wic015(err: str) -> list[str]: - return [line for line in err.splitlines() if '[wic015]' in line] - - -class _ModeRow(NamedTuple): - engine: str - source: str | None - mode: str - written: Any - asked: bool | None - pulled: bool - - -@pytest.mark.fast -@pytest.mark.parametrize('row', [ - pytest.param(_ModeRow('missing', None, '--generate_run_script', {'contains': ['run.sh']}, False, False), - id='no-containers'), - pytest.param(_ModeRow('running', _TOUCH, '--generate_run_script', {'contains': ['run.sh']}, None, True), - id='run-script'), - pytest.param(_ModeRow('running', _TOUCH, '--check', ['w.wic'], True, False), id='check')]) -def test_what_each_mode_does_to_the_machine( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capsys: pytest.CaptureFixture[str], row: _ModeRow) -> None: - """A workflow without containers needs no engine, and still gets its run.sh. With containers, - `--generate_run_script` asks the engine and pulls the images; `--check` asks it, then stops without writing, - pulling or running. `asked` is None where the engine is not checked.""" - calls = machine(row.engine) - if row.mode == '--check': - monkeypatch.setattr(run_local, 'run', lambda _request: pytest.fail('--check must not run the workflow')) - assert run_cli(monkeypatch, '--yaml', _w(tmp_path, row.source), row.mode) is None - assert match(row.written, sorted(path.name for path in tmp_path.iterdir())) - assert row.asked is None or (['docker', 'info'] in calls) is row.asked - assert _pulled(calls) is row.pulled - assert row.mode != '--check' or 'Checked w: ' in capsys.readouterr().out - - -@pytest.mark.fast -@pytest.mark.parametrize('row', [ - ({'engine': 'missing'}, None, None, ['docker is not installed (it is not on PATH), and this workflow runs tools in ' - 'containers (docker.io/library/debian:bookworm-slim): install docker'], []), - ({'engine': 'fails', 'said': b'failed to connect to the docker API\nsecond line'}, - 'unix:///nonexistent/sophios.sock', None, - ['its engine is not reachable: the socket /nonexistent/sophios.sock does not exist ', - '(failed to connect to the docker API): start the engine'], []), - ({'engine': 'fails', 'said': b'Is the docker daemon running?'}, None, None, - ['`docker info` exited with status 1 (Is the docker daemon running?)'], ['usermod']), - ({'engine': 'fails', 'said': b' whatever the engine said\n'}, 'tcp://engine.invalid:2375', - '--ignore_docker_install', - ['`docker info` exited with status 1 (whatever the engine said): run `docker info` to see why'], []), - ({'processes': 1001}, None, '--ignore_docker_processes', - ['1001 docker processes are running', '--ignore_docker_processes'], ['Warning']), -], ids=['a missing engine names the image that needs it', 'a missing socket is named and the engine quoted', - 'a stopped engine with no default socket is not blamed on permissions', - 'an engine that fails for another reason is quoted with its status, unless ignored', - 'too many docker processes is one line, unless ignored']) -def test_an_engine_that_cannot_be_used_is_one_wic015_line( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capsys: pytest.CaptureFixture[str], row: tuple[Any, ...]) -> None: - """A step running in a container needs a usable engine; the line says why this one is not, and nothing is pulled. - The flag that waives the check skips it, and the images are still pulled.""" - machine_is, host, waiver, says, never = row - calls = machine(**machine_is) - monkeypatch.delenv('DOCKER_HOST', raising=False) - if host: - monkeypatch.setenv('DOCKER_HOST', host) - monkeypatch.setattr(preflight, 'DEFAULT_DOCKER_SOCKET', tmp_path / 'absent.sock') - code = run_cli(monkeypatch, '--yaml', _w(tmp_path, _TOUCH), '--generate_run_script') - line, = _wic015(capsys.readouterr().err) - assert code == 1 and not _pulled(calls) - assert all(text in line for text in says) and not any(text in line for text in never), line - if waiver: - assert run_cli(monkeypatch, '--yaml', _w(tmp_path, _TOUCH), '--generate_run_script', waiver) is None - assert _pulled(calls) - - -@pytest.mark.fast -def test_a_file_uri_in_the_inputs_file_is_read_as_this_platforms_path( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """A `file:` location names the file in this platform's own spelling: on Windows a drive path, not `/C:/...`.""" - machine('running') - monkeypatch.setattr(preflight, 'PLATFORM_LACKS_RUNNERS', None) - data = tmp_path / 'in x.txt' - write_tree(tmp_path, {data.name: 'x', 'job.yml': f"file:\n class: File\n location: '{data.as_uri()}'\n"}) - # returns: the file is found where the URI names it - assert run_cli(monkeypatch, '--yaml', _w(tmp_path, _CAT_INPUT), - '--check', '--inputs_file', tmp_path / 'job.yml') is None - - -@pytest.mark.fast -@pytest.mark.skipif(sys.platform == 'win32' or os.geteuid() == 0, reason='file modes do not stop Windows or root') -def test_an_engine_whose_socket_is_not_yours_says_so( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capsys: pytest.CaptureFixture[str]) -> None: - machine('fails', said=b'denied') - socket = tmp_path / 'docker.sock' - socket.write_text('', encoding='utf-8') - socket.chmod(0) - monkeypatch.setenv('DOCKER_HOST', f'unix://{socket}') - assert run_cli(monkeypatch, '--yaml', _w(tmp_path, _TOUCH), '--generate_run_script') == 1 - line, = _wic015(capsys.readouterr().err) - assert f'you may not use its socket {socket} (denied): add your user to the docker group' in line - - -@pytest.mark.skipif(shutil.which('docker') is None, reason='needs the docker CLI') -def test_the_docker_cli_with_no_daemon_is_named_not_reachable(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - tool = tmp_path / 'tool.cwl' - tool.write_text('cwlVersion: v1.2\nclass: CommandLineTool\nrequirements:\n DockerRequirement:\n' - ' dockerPull: docker.io/bash:4.4\nbaseCommand: [echo]\ninputs: {}\noutputs: {}\n', - encoding='utf-8') - # short: socket paths max out near 100 bytes - monkeypatch.setenv('DOCKER_HOST', 'unix:///nonexistent/no-daemon.sock') - with pytest.raises(SophiosError) as caught: - preflight.check(preflight.needs([tool]), preflight.RunSettings('docker', str(tmp_path), ignore_processes=True)) - found, = caught.value.diagnostics - assert found.code is SophiosErrorCode.CONTAINER_ENGINE_UNAVAILABLE - assert 'the socket /nonexistent/no-daemon.sock does not exist' in found.message - - -_CAT = 'steps:\n- id: cat\n in:\n file: !ii\n class: File\n location: {}\n' -_CAT_INPUT = 'inputs:\n file: File\nsteps:\n- id: cat\n in:\n file: file\n' - - -def _wic016(err: str) -> list[str]: - return [line for line in err.splitlines() if '[wic016]' in line] - - -@pytest.mark.fast -@pytest.mark.parametrize('row', [ - (_CAT.format('absent.txt'), None, ["input 'cat~file' (from the workflow, whose relative paths are read from ", - "names 'absent.txt', which does not exist at ", 'create the file']), - (_CAT_INPUT, 'file:\n class: File\n location: absent.txt\nn: 3\n', - ["input 'file' (from --inputs_file, whose relative paths are read from "]), -], ids=['a missing input is named before any image is pulled', 'a missing path in the inputs file is named']) -def test_a_missing_input_is_one_wic016_line_naming_where_it_was_read( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capsys: pytest.CaptureFixture[str], row: tuple[Any, ...]) -> None: - source, job, said = row - calls = machine('running') - if job: - (tmp_path / 'job.yml').write_text(job, encoding='utf-8') - code = run_cli(monkeypatch, '--yaml', _w(tmp_path, source), '--generate_run_script', - *(('--inputs_file', tmp_path / 'job.yml') if job else ())) - line, = _wic016(capsys.readouterr().err) - assert code == 1 and all(text in line for text in said) and not _pulled(calls) - - -@pytest.mark.fast -def test_a_relative_path_in_the_inputs_file_is_read_beside_the_inputs_file( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """CWL v1.2 section 5.1.5: the base IRI of the inputs document, not the working directory, at any depth.""" - machine('running') - jobs = tmp_path / 'jobs' - write_tree(jobs, {'data/a.txt': 'x', 'job.yml': 'file:\n class: File\n location: data/a.txt\n' - ' secondaryFiles:\n - class: File\n path: data/a.txt\n'}) - (tmp_path / 'cwd').mkdir() - monkeypatch.chdir(tmp_path / 'cwd') - # returns: nothing missing - assert run_cli(monkeypatch, '--yaml', _w(tmp_path / 'cwd', _CAT_INPUT), '--generate_run_script', - '--inputs_file', jobs / 'job.yml') is None - written = yaml.safe_load((tmp_path / 'cwd' / 'autogenerated' / 'w_inputs.yml').read_text(encoding='utf-8')) - assert written['file']['location'] == (jobs / 'data' / 'a.txt').as_uri() - assert written['file']['secondaryFiles'][0]['path'] == str(jobs / 'data' / 'a.txt') - - -def _output_target_project(tmp_path: Path) -> Path: - """A config whose search path holds `write_dir`, a tool that creates the directory `outDir` names.""" - write_tree(tmp_path, {'write_dir.cwl': ( - 'cwlVersion: v1.2\nclass: CommandLineTool\nrequirements:\n InitialWorkDirRequirement:\n' - ' listing:\n - entry: $(inputs.outDir)\n writable: true\n InlineJavascriptRequirement: {}\n' - 'baseCommand: [mkdir]\ninputs:\n outDir: Directory\n' - 'outputs:\n outDir:\n type: Directory\n outputBinding:\n glob: $(inputs.outDir.basename)\n')}) - return search_config(tmp_path / 'config.json', [tmp_path], [tmp_path]) - - -@pytest.mark.fast -def test_an_output_target_directory_is_not_a_missing_input( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """The runner gets it as the name of a directory the step creates, which does not exist yet.""" - machine('running') - source = 'steps:\n- id: write_dir\n in:\n outDir: !ii result.outDir\n' - # returns: nothing missing - assert run_cli(monkeypatch, '--yaml', _w(tmp_path, source), '--generate_run_script', - '--config_file', _output_target_project(tmp_path)) is None - - -@pytest.mark.fast -def test_an_output_target_directory_in_the_inputs_file_is_a_name( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """Written as CWL writes a Directory, it still names the directory the step creates: it is not made - absolute against the inputs file, and it is not looked for.""" - machine('running') - (tmp_path / 'job.yml').write_text( - 'write_dir~outDir: {class: Directory, location: result.outDir}\n', encoding='utf-8') - assert run_cli(monkeypatch, '--yaml', _w(tmp_path, 'steps:\n- id: write_dir\n'), '--generate_run_script', - '--config_file', _output_target_project(tmp_path), '--inputs_file', tmp_path / 'job.yml') is None - job = yaml.safe_load((tmp_path / 'autogenerated' / 'w_inputs.yml').read_text(encoding='utf-8')) - assert job['write_dir~outDir'] == 'result.outDir' - - -@pytest.mark.fast -def test_an_inputs_file_that_is_not_a_mapping_is_one_clear_error( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capsys: pytest.CaptureFixture[str]) -> None: - machine('running') - (tmp_path / 'job.yml').write_text('- a\n- b\n', encoding='utf-8') - assert run_cli(monkeypatch, '--yaml', _w(tmp_path, _CAT_INPUT), - '--generate_run_script', '--inputs_file', tmp_path / 'job.yml') == 1 - err = capsys.readouterr().err - assert 'must be a mapping of input names to values, not a list' in err and 'Traceback' not in err - - -@pytest.mark.fast -@pytest.mark.skipif(sys.platform == 'win32' or os.geteuid() == 0, reason='file modes do not stop Windows or root') -def test_an_unreadable_input_is_named_with_the_fix( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capsys: pytest.CaptureFixture[str]) -> None: - machine('running') - locked = tmp_path / 'locked.txt' - locked.write_text('x', encoding='utf-8') - locked.chmod(0) - assert run_cli(monkeypatch, '--yaml', _w(tmp_path, _CAT.format('locked.txt')), '--generate_run_script') == 1 - line, = _wic016(capsys.readouterr().err) - assert 'which you may not read' in line and 'chmod u+r' in line - - -@pytest.mark.fast -@pytest.mark.parametrize('row', [ - ({'engine': 'fails', 'said': b'stopped'}, 'tcp://engine.invalid:2375', '--generate_run_script'), - ({'engine': 'missing'}, None, '--check'), -], ids=['a missing input and a stopped engine are reported together', 'check reports what a run would hit']) -def test_a_missing_input_and_an_unusable_engine_are_reported_in_one_pass( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capsys: pytest.CaptureFixture[str], row: tuple[Any, ...]) -> None: - """Both problems are one line each, under --check as under a run.""" - machine_is, host, mode = row - machine(**machine_is) - if host: - monkeypatch.setenv('DOCKER_HOST', host) - code = run_cli(monkeypatch, '--yaml', _w(tmp_path, _CAT.format('absent.txt')), mode) - err = capsys.readouterr().err - assert code == 1 and len(_wic016(err)) == 1 and len(_wic015(err)) == 1 - - -@pytest.mark.fast -def test_a_directory_beside_the_workflow_reaches_the_run_where_it_is( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """The job names it beside the workflow, so the run reads it in place, however large; nothing is copied.""" - machine('running') - write_tree(tmp_path, {'data/a.txt': 'x'}) - source = ('steps:\n- id: subdirectory\n in:\n directory: !ii\n class: Directory\n' - ' location: data\n glob_pattern: !ii a.txt\n') - assert run_cli(monkeypatch, '--yaml', _w(tmp_path, source), '--generate_run_script') is None - job = yaml.safe_load((tmp_path / 'autogenerated' / 'w_inputs.yml').read_text(encoding='utf-8')) - directory, = [value for value in job.values() if isinstance(value, dict)] - assert directory['location'] == (tmp_path / 'data').as_uri() - assert not (tmp_path / 'autogenerated' / 'data').exists() - - -@pytest.mark.fast -@pytest.mark.parametrize('row', [ - ('cwltool_filterlog', None, '--generate_run_script', (), - 'error [wic029] run.sh calls cwltool_filterlog, which is not on PATH: install Sophios'), - ('toil-cwl-runner', None, '--run_local', ('--cwl_runner', 'toil-cwl-runner'), - 'error [wic029] the run calls toil-cwl-runner, which is neither in this Python environment nor on PATH: ' - 'install Toil'), - ('cwl-docker-extract', _TOUCH, '--generate_run_script', ('--container_engine', 'singularity'), - 'error [wic029] pulling the images for singularity needs cwl-docker-extract'), -], ids=['a run script whose runner is missing', 'a run whose runner is missing', 'a missing image puller']) -def test_a_program_the_run_calls_that_is_missing_is_wic029( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capsys: pytest.CaptureFixture[str], row: tuple[Any, ...]) -> None: - """The runner is a program: one that is not installed is named before anything is pulled or started.""" - program, source, mode, flags, said = row - calls = machine(missing=(program,)) - monkeypatch.setattr(preflight, 'PLATFORM_LACKS_RUNNERS', None) - code = run_cli(monkeypatch, '--yaml', _w(tmp_path, source), mode, *flags) - assert code == 1 and said in capsys.readouterr().err - assert not (tmp_path / 'run.sh').exists() and not _pulled(calls) - - -class _CheckRow(NamedTuple): - engine: str - source: str - flags: tuple[str, ...] - exit_code: int | None - - -@pytest.mark.fast -@pytest.mark.parametrize('row', [ - _CheckRow('running', _TOUCH, (), None), # the check passes - _CheckRow('missing', _CAT.format('absent.txt'), (), 1), # it finds what a run would hit - _CheckRow('running', _TOUCH, ('--graphviz',), 2), # a drawing would be written, so it is refused -], ids=['passes', 'fails', 'refused']) -def test_a_check_leaves_an_earlier_compile_as_it_was( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - row: _CheckRow) -> None: - """Passing, failing or refused, --check writes nothing into the base path.""" - machine(row.engine) - basepath = tmp_path / 'autogenerated' - basepath.mkdir() - for name in ('w.cwl', 'w_inputs.yml'): - (basepath / name).write_text(f'an earlier {name}\n', encoding='utf-8') - before = {path: path.read_bytes() for path in basepath.rglob('*')} - assert run_cli(monkeypatch, '--yaml', _w(tmp_path, row.source), '--check', *row.flags) == row.exit_code - assert {path: path.read_bytes() for path in basepath.rglob('*')} == before - - -@pytest.mark.fast -def test_graphviz_without_dot_is_a_note( - machine: Callable[..., list[object]], monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str]) -> None: - machine(missing=('dot',)) - assert run_cli(monkeypatch, '--yaml', HELLOWORLD, '--generate_cwl_workflow', '--graphviz') is None - captured = capsys.readouterr() - assert 'note [wic029] --graphviz needs the dot program' in captured.err - assert 'Warning: Cannot generate graphviz' not in captured.out - - -# The upfront image fetch is complete: podman pulls with podman, loaded and imported images are fetched, -# and a failure is one wic037 - - -def _tool(directory: Path, docker: dict[str, str]) -> Path: - """A CWL tool in `directory` whose DockerRequirement is `docker`.""" - path = directory / 'tool.cwl' - path.write_text(json.dumps({'cwlVersion': 'v1.2', 'class': 'CommandLineTool', 'baseCommand': 'true', - 'inputs': [], 'outputs': [], 'requirements': {'DockerRequirement': docker}}), - encoding='utf-8') - return path - - -@pytest.fixture(name='engine') -def _engine(monkeypatch: pytest.MonkeyPatch) -> Callable[..., list[list[str]]]: - """A machine on which every command succeeds, except those starting with `failing`, which exit 1 and say - `said` on stderr. Returns the list of commands it was given.""" - def install(failing: tuple[str, ...] = (), said: str = '') -> list[list[str]]: - calls: list[list[str]] = [] - - def run(cmd: list[str], *_args: object, **_kwargs: object) -> subprocess.CompletedProcess[str]: - calls.append(cmd) - if failing and tuple(cmd[:len(failing)]) == failing: - return subprocess.CompletedProcess(cmd, 1, stdout='', stderr=said) - return subprocess.CompletedProcess(cmd, 0, stdout='', stderr='') - monkeypatch.setattr(subprocess, 'run', run) - monkeypatch.setattr(sys, 'platform', 'linux') - monkeypatch.setattr(shutil, 'which', lambda name, *a, **k: f'/bin/{name}') - return calls - return install - - -def _prepare(tool: Path, tmp_path: Path, engine: str = 'docker') -> None: - """The pre-flight a local run makes: check, then fetch.""" - preflight.prepare([tool], preflight.RunSettings(engine, str(tmp_path))) - - -_PULL: Final = ['cwl-docker-extract', '--force-download', '--container-engine', '{engine}', '{tool}'] - - -@pytest.mark.fast -@pytest.mark.parametrize(('docker', 'engine_name', 'fetched'), [ - ({'dockerPull': 'docker.io/bash:4.4'}, 'docker', [_PULL]), - ({'dockerPull': 'docker.io/bash:4.4'}, 'podman', [_PULL]), - ({'dockerPull': 'docker.io/bash:4.4', 'dockerImageId': 'bash:4.4'}, 'docker', []), - ({'dockerLoad': '{archive}'}, 'docker', [['docker', 'load', '-i', '{archive}']]), - ({'dockerLoad': '{archive}'}, 'podman', [['podman', 'load', '-i', '{archive}']]), - ({'dockerImport': 'https://example.org/rootfs.tar', 'dockerImageId': 'rootfs:1'}, 'podman', - [['podman', 'import', 'https://example.org/rootfs.tar', 'rootfs:1']]), -], ids=['pull with docker', 'pull with podman', 'a pull loads and imports nothing', 'load with docker', - 'load with podman', 'import under its image id']) -def test_images_are_fetched_with_the_chosen_engine(engine: Callable[..., list[list[str]]], tmp_path: Path, - docker: dict[str, str], engine_name: str, - fetched: list[list[str]]) -> None: - """Podman pulls with podman: the engine reaches cwl-docker-extract. A dockerLoad file is loaded, and a - dockerImport imported as its dockerImageId, with the chosen engine; a dockerPull needs the pull and nothing else.""" - calls = engine() - archive = tmp_path / 'image.tar' - archive.write_bytes(b'') - tool = _tool(tmp_path, {key: value.format(archive=archive) for key, value in docker.items()}) - _prepare(tool, tmp_path, engine_name) - fetched = [[part.format(engine=engine_name, tool=tool, archive=archive) for part in cmd] for cmd in fetched] - assert all(cmd in calls for cmd in fetched) - loaded_or_imported = [cmd for cmd in calls if cmd[1:2] in (['load'], ['import'])] - assert loaded_or_imported == [cmd for cmd in fetched if cmd[0] != 'cwl-docker-extract'] - - -@pytest.mark.fast -def test_a_docker_load_url_is_downloaded_then_loaded(engine: Callable[..., list[list[str]]], - monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """A dockerLoad URL is downloaded, then loaded from the file.""" - calls = engine() - - class Response: - def __enter__(self) -> 'Response': - return self - - def __exit__(self, *_exc: object) -> None: - return None - - def raise_for_status(self) -> None: - """A successful response.""" - return None - - def iter_content(self, _size: int) -> list[bytes]: - """The body in one chunk.""" - return [b'image'] - - monkeypatch.setattr(preflight.requests, 'get', lambda *_a, **_k: Response()) - _prepare(_tool(tmp_path, {'dockerLoad': 'https://example.org/image.tar'}), tmp_path) - loads = [cmd for cmd in calls if cmd[:3] == ['docker', 'load', '-i']] - assert len(loads) == 1 - - -@pytest.mark.fast -@pytest.mark.parametrize('docker, failing, doing', [ - ({'dockerPull': 'docker.io/nope:1'}, ('cwl-docker-extract',), 'pull docker.io/nope:1'), - ({'dockerLoad': '{archive}'}, ('docker', 'load'), 'load {archive}'), - ({'dockerImport': 'rootfs.tar', 'dockerImageId': 'rootfs:1'}, ('docker', 'import'), - 'import rootfs:1 from rootfs.tar'), -]) -def test_a_failed_pull_load_or_import_is_one_wic037_quoting_the_engine( - engine: Callable[..., list[list[str]]], tmp_path: Path, docker: dict[str, str], failing: tuple[str, ...], - doing: str) -> None: - """One wic037 names what failed and quotes the last stderr line.""" - archive = tmp_path / 'image.tar' - archive.write_bytes(b'') - docker = {key: value.format(archive=archive) for key, value in docker.items()} - engine(failing, said='first line\nError: pull access denied\n') - tool = _tool(tmp_path, docker) - with pytest.raises(SophiosError) as raised: - _prepare(tool, tmp_path) - [diagnostic] = raised.value.diagnostics - assert diagnostic.code is SophiosErrorCode.IMAGE_UNAVAILABLE - assert doing.format(archive=archive) in diagnostic.message - assert 'Error: pull access denied' in diagnostic.message and 'first line' not in diagnostic.message - - -@pytest.mark.fast -def test_a_failed_pull_quotes_the_engines_error_line_not_the_extractors_traceback( - engine: Callable[..., list[list[str]]], tmp_path: Path) -> None: - """cwl-docker-extract re-raises the engine's output as `SubprocessError()`; wic037 quotes the - engine's `Error:` line, decoded.""" - traceback = ('Traceback (most recent call last):\n File "extract.py", line 1, in \n' - "subprocess.SubprocessError: b'Trying to pull docker.io/nope:1... \\r\\n" - "Error: requested access to the resource is denied \\r\\n'\n") - engine(('cwl-docker-extract',), said=traceback) - tool = _tool(tmp_path, {'dockerPull': 'docker.io/nope:1'}) - with pytest.raises(SophiosError) as raised: - _prepare(tool, tmp_path) - [diagnostic] = raised.value.diagnostics - assert 'Error: requested access to the resource is denied)' in diagnostic.message - assert 'SubprocessError' not in diagnostic.message and "b'" not in diagnostic.message - - -@pytest.mark.fast -def test_check_loads_and_imports_nothing(engine: Callable[..., list[list[str]]], tmp_path: Path) -> None: - """--check checks and fetches nothing.""" - calls = engine() - tool = _tool(tmp_path, {'dockerLoad': str(tmp_path / 'image.tar'), 'dockerImageId': 'x:1'}) - preflight.check(preflight.needs([tool]), preflight.RunSettings('docker', str(tmp_path))) - assert not [cmd for cmd in calls if len(cmd) > 1 and cmd[1] in ('load', 'import')] - assert not _pulled(calls) + assert found.message in str(SophiosError([found])) + pytest.raises(ValueError, SophiosError, []) #: Where a document writes a name, as text with a `{name}` slot, and what the refusal calls it. @@ -1105,3 +204,163 @@ def test_a_step_id_outside_the_allowed_characters_is_refused_at_its_line(case: t assert name[0] != '.' and not set(name) - set(string.ascii_letters + string.digits + '_.-'), name assert where not in ('step id', 'mapping step id') or [ step['id'] for step in compiled.artifact.cwl['steps']] == ['mk_file', name] + + +_ROW = re.compile(r'^\| `(?P[a-z]{3}\d{3}|nf-s\d{3})` \| (?P[a-z]+) \| (?P.+) \| (?P.+) \|$') + + +@pytest.mark.fast +def test_every_code_is_explained_alike_by_the_catalog_its_page_and_explain( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + """A code an agent cannot look up is a code it cannot act on. Each code has a meaning and a fix of one line, and + docs/error_codes.md and `sophios --explain `, in any case, with no workflow, say what the catalog says. A + document's mistake carries a language code and a call's mistake does not, so a caller can route on `is_language` + and land on the right reference.""" + assert set(EXPLANATIONS) == set(SophiosErrorCode) + for code, explanation in EXPLANATIONS.items(): + text = explanation.meaning + explanation.fix + assert explanation.meaning and explanation.fix and '|' not in text and '\n' not in text, code + if explanation.kind in (Kind.DOCUMENT, Kind.CALL): + assert code.is_language == (explanation.kind is Kind.DOCUMENT), code + assert run_cli(monkeypatch, '--explain', str(code).upper()) == 0 + said = f'{code} ({explanation.kind}): {explanation.meaning}\nFix: {explanation.fix}\n' + assert capsys.readouterr().out == said + page = REPO_ROOT / 'docs' / 'error_codes.md' + rows = {found['code']: (found['kind'], found['meaning'], found['fix']) + for found in map(_ROW.match, page.read_text(encoding='utf-8').splitlines()) if found} + assert rows == {str(code): (str(e.kind), e.meaning, e.fix) for code, e in EXPLANATIONS.items()} + + +class _Machine: + """This machine as a scenario's `machine` describes it: every program on PATH but those `missing`; `docker + info` and `docker` itself `running`, `missing` or exiting 1 having `said` something; `processes` Docker Desktop + processes; each command starting with one of `fails` exiting 1 having `said` it; `nextflow -version` exiting + `nextflow_exit` having `said` it; `DOCKER_HOST` as `docker_host` gives it, and no default socket; each of + `unreadable` mode 0; Windows when `windows` says so; the compile crashing when `crash` says so; and a dockerLoad + URL downloaded. Every command run is kept, in order.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch, root: Path, spec: dict[str, Any]) -> None: + self.spec = {'engine': 'running', 'said': '', 'processes': 0, 'missing': [], 'fails': [], **spec} + self.commands: list[list[str]] = [] + monkeypatch.setattr(subprocess, 'run', self.run) + monkeypatch.setattr(sys, 'platform', 'linux') + monkeypatch.setattr(shutil, 'which', lambda name, *_a, **_k: ( + None if name in self.spec['missing'] else f'/usr/bin/{name}')) + monkeypatch.setattr(preflight, 'PLATFORM_LACKS_RUNNERS', preflight.PLATFORM_LACKS_RUNNERS + if self.spec.get('windows') is None else self.spec['windows']) + monkeypatch.setattr(preflight, 'DEFAULT_DOCKER_SOCKET', root / 'absent.sock') + monkeypatch.delenv('DOCKER_HOST', raising=False) + if 'docker_host' in self.spec: + monkeypatch.setenv('DOCKER_HOST', self.spec['docker_host']) + for name in self.spec.get('unreadable', []): + (root / name).chmod(0) + if self.spec.get('crash'): + monkeypatch.setattr(compiler, 'compile_source', self.crash) + monkeypatch.setattr(preflight.requests, 'get', lambda *_a, **_k: _Download()) + + @staticmethod + def crash(*_args: object, **_kwargs: object) -> None: + """A failure Sophios did not expect.""" + raise RuntimeError('boom') + + def run(self, cmd: list[str], *_args: object, **options: object) -> subprocess.CompletedProcess[Any]: + """Each command as this machine answers it.""" + self.commands.append(list(map(str, cmd))) + code, said = 0, '' + if cmd[0] == 'pgrep': + said = '1\n' * self.spec['processes'] + elif cmd[0] == 'docker' and self.spec['engine'] == 'missing': + raise FileNotFoundError('docker') + elif cmd[:2] == ['docker', 'info'] and self.spec['engine'] == 'fails': + code, said = 1, self.spec['said'] + elif cmd[1:] == ['-version']: + code, said = self.spec.get('nextflow_exit', 0), self.spec['said'] + elif any(cmd[:len(prefix)] == prefix for prefix in self.spec['fails']): + code, said = 1, self.spec['said'] + text = said if options.get('text') else said.encode() + return subprocess.CompletedProcess(cmd, code, stdout=text, stderr=text) + + def pulled(self) -> bool: + """Whether an image was pulled.""" + return any(cmd[0] == 'cwl-docker-extract' for cmd in self.commands) + + +class _Download: + """A dockerLoad URL's answer: the image, in one chunk.""" + + def __enter__(self) -> '_Download': + return self + + def __exit__(self, *_exc: object) -> None: + return None + + def raise_for_status(self) -> None: + """It succeeded.""" + + def iter_content(self, _size: int) -> list[bytes]: + """The body.""" + return [b'image'] + + +def _files(root: Path) -> dict[str, bytes]: + return {path.relative_to(root).as_posix(): path.read_bytes() for path in sorted(root.rglob('*')) if path.is_file()} + + +@pytest.mark.fast +@pytest.mark.parametrize('scenario, expected', case_dirs('preflight', 'runs')) +# pylint: disable-next=too-many-locals +def test_the_command_line_on_this_machine_does_what_its_scenario_states( + scenario: Path, expected: dict[str, Any], tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str]) -> None: + """Each run of a scenario of tests/core/data/preflight (see its README), in a copy of the scenario, on the + machine it describes: what the command line exits with, the diagnostics it reports, what it prints, asks of the + engine, pulls, fetches, writes, leaves alone and never makes. Nothing is pulled or started once a check has + failed.""" + for number, run in enumerate(expected['runs'], start=1): + root = tmp_path / str(number) + shutil.copytree(scenario, root, ignore=shutil.ignore_patterns('expected.yaml')) + if run.get('posix_user') and (sys.platform == 'win32' or os.geteuid() == 0): + continue # file modes stop neither Windows nor root + for path in root.rglob('*'): + if path.suffix in ('.wic', '.yml', '.json'): + path.write_text(path.read_text(encoding='utf-8').replace('{tmp_uri}', root.as_uri()), encoding='utf-8') + cwd = root / run.get('cwd', '') + cwd.mkdir(exist_ok=True) + if run.get('cwd'): + cwd.chmod(0o555) + monkeypatch.chdir(cwd) + before = _files(root) + with monkeypatch.context() as machine_patches: + machine = _Machine(machine_patches, root, _placed(run.get('machine', {}), root)) + code = run_cli(monkeypatch, *_placed(run['argv'], root)) + for path in (cwd, *(root / name for name in run.get('machine', {}).get('unreadable', []))): + path.chmod(0o755) + out, err = capsys.readouterr() + after = _files(root) + said = f'run {number}: {" ".join(run["argv"])}\n{out}{err}' + expect = _placed(run, root) + assert code == expect.get('exit'), said + assert match(expect.get('diagnostics', []), printed(err)), said + for stream, text in (('stdout', out), ('stderr', err)): + assert stream not in expect or match(expect[stream], text), said + assert not [text for text in expect.get('lacks', []) if text in out + err], said + assert 'commands' not in expect or match(expect['commands'], machine.commands), (said, machine.commands) + assert expect.get('asked') is None or (['docker', 'info'] in machine.commands) is expect['asked'], said + assert machine.pulled() is expect.get('pulled', False), said + assert 'written' not in expect or match(expect['written'], sorted(after.keys() - before.keys())), ( + said, sorted(after)) + assert not expect.get('unchanged') or after == before, said + assert not [name for name in expect.get('absent', []) if (root / name).exists()], said + for name, value in expect.get('files', {}).items(): + assert match(value, yaml.safe_load(after[name])), (said, name, after[name]) + for name, value in expect.get('texts', {}).items(): + assert match(value, after[name].decode('utf-8')), (said, name, after[name]) + + +def _placed(value: Any, root: Path) -> Any: + """`value` with `{tmp}` and `{tmp_uri}` in each string the copy of the scenario, as a path and as a URI.""" + if isinstance(value, dict): + return {key: _placed(item, root) for key, item in value.items()} + if isinstance(value, list): + return [_placed(item, root) for item in value] + return value.replace('{tmp_uri}', root.as_uri()).replace('{tmp}', str(root)) if isinstance(value, str) else value diff --git a/tests/core/test_entry_points.py b/tests/core/test_entry_points.py index 39dd46996..a10923b9a 100644 --- a/tests/core/test_entry_points.py +++ b/tests/core/test_entry_points.py @@ -56,10 +56,3 @@ def test_each_entry_point_names_an_importable_module_and_attribute(declared: str except ModuleNotFoundError as exc: pytest.fail(f'{declared}, but {module} does not exist ({exc}): it would fail at startup.') assert hasattr(mod, attr), f'{declared}, but {module} has no attribute {attr!r}' - - -@pytest.mark.fast -def test_entry_point_scan_is_not_vacuous() -> None: - """Both scans must actually find targets, or the checks pass for free.""" - assert _console_scripts(), 'no console scripts discovered in pyproject.toml' - assert _container_targets(), 'no container entry points discovered in docker/' diff --git a/tests/core/test_frontdoor.py b/tests/core/test_frontdoor.py index a5134fd59..cfd59a467 100644 --- a/tests/core/test_frontdoor.py +++ b/tests/core/test_frontdoor.py @@ -1,6 +1,9 @@ """The file front door parses each file as written, so a reported span is a position a reader can open an editor at; -the round-tripped spelling of the same document reports another line (test_span_names_the_line_in_the_authored_file).""" +the round-tripped spelling of the same document reports another line. The documents are tests/core/data/frontdoor, +tests/core/data/run_paths and tests/core/data/packed_tools.""" +import shutil from pathlib import Path +from typing import Final import pytest import yaml @@ -26,51 +29,16 @@ parse, render, ) -from sophios.lang.diagnostics import SophiosError +from sophios.lang.diagnostics import Diagnostic, SophiosError from sophios.plugins import get_tools_cwl -from sophios.wic_types import Tools, Yaml +from sophios.wic_types import Yaml from .cases import DATA, case_dirs, cases -from .helpers import write_tree from .synthetic_tools import SYNTHETIC_TOOLS pytestmark = pytest.mark.package -#: A root whose failing construct sits well below the top of the file, so a -#: reported line that came from a re-dump cannot coincide with the real one. -FORWARD_EDGE = '''# A workflow that references an edge before defining it. -# -# These comment lines are load-bearing: a YAML round trip drops them, which -# is exactly what moves every construct below them onto a different line. -# -steps: -- id: xform - in: - file: !* later - name: out.txt -- id: mk_file - in: - name: made.txt - out: - - file: !& later -''' - -PYTHON_SCRIPT = ''' -inputs = {'name': {'type': 'string', 'format': 'edam:format_2330'}} -outputs = {'file': ('$(inputs.name)', {'type': 'File', 'format': 'edam:format_2330'})} - - -def main(name: str) -> None: - """A script whose annotations are all the generator reads.""" -''' - - -def _script_project(tmp_path: Path, wic: str) -> Path: - """The directory `root.wic` and `my_script.py` are written in, beside the `workflow_types` sibling the adapter - imports from a path relative to the working directory.""" - return write_tree(tmp_path, { - 'sophios/examples/scripts/workflow_types.py': "string = {'type': 'string', 'format': 'edam:format_2330'}\n", - 'work/my_script.py': PYTHON_SCRIPT, 'work/root.wic': wic}) / 'work' +DOOR: Final = DATA / 'frontdoor' def _line_of(text: str, needle: str) -> int: @@ -91,174 +59,83 @@ def _redump(text: str) -> str: return render(document) -@pytest.mark.fast -def test_source_is_the_file_verbatim(tmp_path: Path) -> None: - """The root is parsed from its own bytes, comments and blank lines included.""" - text = ('# a leading comment\n' - '\n' - 'wic:\n' - ' graphviz:\n' - ' label: Root\n' - '\n' - 'steps:\n' - '- id: mk_file\n' - ' in:\n' - ' name: made.txt\n') - root = write_tree(tmp_path, {'tutorial.wic': text}) / 'tutorial.wic' - - bundle = bundle_from_disk(root, {'global': {}}, SYNTHETIC_TOOLS) - - assert bundle.parsed.document == parse(text, 'tutorial.wic').document - assert bundle.name == 'tutorial' +def _undefined(diagnostics: Diagnostics) -> list[Diagnostic]: + return [item for item in diagnostics if item.code is SophiosErrorCode.UNDEFINED_EDGE] @pytest.mark.fast -def test_child_workflow_is_registered_as_its_own_parse(tmp_path: Path) -> None: - """A called `.wic` enters the registry parsed from the file, not from a re-dump.""" - child_text = ('# the child keeps its comments too\n' - 'steps:\n' - '- id: mk_file\n' - ' in:\n' - ' name: child.txt\n') - write_tree(tmp_path, {'child.wic': child_text, 'root.wic': 'steps:\n- id: child.wic\n'}) - - bundle = bundle_from_disk(tmp_path / 'root.wic', {'global': {'child': tmp_path / 'child.wic'}}, SYNTHETIC_TOOLS) - - entry = bundle.registry.workflow(RegistryKey('global', 'child')) - assert entry is not None - assert entry.parsed.document == parse(child_text, 'child.wic').document - assert entry.parsed.document != parse(_redump(child_text), 'child.wic').document +# pylint: disable-next=too-many-locals +def test_the_file_door_reads_each_file_as_written(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The root and each child it calls are parsed from their own bytes, comments and blank lines included, so a + diagnostic points at the line the construct occupies on disk; the same document through a YAML round trip, what the + legacy path did, reports a line that exists in the dump and means something else in the file. An in-memory + document has no span, so the locator is where the edge failed. A `wic:` key the language does not have is refused + as the file is read, at the key, by the parser, under the file's own name, whatever its extension, with no + environment involved. The caller's declaration files a child under each namespace a call site declares, and + nowhere else: a namespace the child declares for itself does not move where its caller looks. A Python script + step's tool is keyed as Resolve keys it and never reaches disk; it names the EDAM prefix its formats use and no + ontology, as a document depends only on what its author wrote, at the CWL version Sophios writes. + `python_cwl_adapter` imports `workflow_types` from a path relative to the working directory, so the project holds + both that directory and that sibling file; nothing here reads the repository's own examples.""" + text = (DOOR / 'tutorial.wic').read_text(encoding='utf-8') + bundle = bundle_from_disk(DOOR / 'tutorial.wic', {'global': {}}, SYNTHETIC_TOOLS) + assert bundle.parsed.document == parse(text, 'tutorial.wic').document and bundle.name == 'tutorial' + + child = DOOR / 'calls' / 'child.wic' + paths = {space: {'child': child} for space in ('global', 'gpu')} + bundle = bundle_from_disk(DOOR / 'calls' / 'root.wic', paths, SYNTHETIC_TOOLS) + for space in ('global', 'gpu'): + entry = bundle.registry.workflow(RegistryKey(space, 'child')) + assert entry is not None and entry.parsed.document == parse(child.read_text(encoding='utf-8'), + 'child.wic').document + assert entry.parsed.document != parse(_redump(child.read_text(encoding='utf-8')), 'child.wic').document assert front_end(bundle.parsed, bundle.registry, name=bundle.name).graph is not None - - -@pytest.mark.fast -@pytest.mark.parametrize('root, child, namespaces, registered', [ - # `resolve._resolve_process` builds its `RegistryKey` from the *step's* sidecar namespace, so a child that declares - # a namespace of its own does not move where its caller looks, and filing it there files it where nothing reads. - ('steps:\n- id: child.wic\n', 'wic:\n namespace: gpu\n', ['global'], {'global'}), - # The traversal skips a path it has already walked, which stops a cycle; a second call site under another - # namespace needs its own entry from the same text, and suppressing it left Resolve reporting a file as absent - # from the registry when the front door had read it moments before. - ('steps:\n- id: child.wic\n- id: child.wic\nwic:\n steps:\n (2, child.wic):\n wic:\n' - ' namespace: gpu\n', '', ['global', 'gpu'], {'global', 'gpu'}), -], ids=['declared-by-the-child', 'called-twice']) -def test_a_called_file_is_registered_under_each_namespace_its_call_sites_declare( - tmp_path: Path, root: str, child: str, namespaces: list[str], registered: set[str]) -> None: - """The caller's declaration files the child, under each namespace a call site declares, and nowhere else.""" - write_tree(tmp_path, {'child.wic': child + 'steps:\n- id: mk_file\n in:\n name: c.txt\n', 'root.wic': root}) - paths = {namespace: {'child': tmp_path / 'child.wic'} for namespace in namespaces} - registry = bundle_from_disk(tmp_path / 'root.wic', paths, SYNTHETIC_TOOLS).registry - assert {space for space in ('global', 'gpu') if registry.workflow(RegistryKey(space, 'child'))} == registered - - -@pytest.mark.fast -def test_span_names_the_line_in_the_authored_file(tmp_path: Path) -> None: - """A diagnostic points at the line the construct occupies on disk. - - The second assertion is the point of the first: feeding the same document - through a YAML round trip -- what the legacy path does -- reports a line - that exists in the dump and means something else in the file. - """ - root = write_tree(tmp_path, {'forward.wic': FORWARD_EDGE}) / 'forward.wic' - bundle = bundle_from_disk(root, {'global': {}}, SYNTHETIC_TOOLS) - - result = front_end(bundle.parsed, bundle.registry, name=bundle.name) - - undefined = [item for item in result.diagnostics - if item.code is SophiosErrorCode.UNDEFINED_EDGE] - assert len(undefined) == 1 - assert undefined[0].span is not None - assert undefined[0].span.start_line == _line_of(FORWARD_EDGE, '!* later') - - redumped = parse(_redump(FORWARD_EDGE), 'forward.wic') - dumped = [item for item in front_end(redumped, bundle.registry, name=bundle.name).diagnostics - if item.code is SophiosErrorCode.UNDEFINED_EDGE] - assert len(dumped) == 1 - assert dumped[0].span is not None - assert dumped[0].span.start_line != undefined[0].span.start_line - - -@pytest.mark.fast -def test_a_spanless_forward_edge_names_its_consuming_step() -> None: - """An in-memory document has no span, so the locator is where the edge failed.""" + own = bundle_from_disk(DOOR / 'own' / 'root.wic', {'global': {'child': DOOR / 'own' / 'child.wic'}}, + SYNTHETIC_TOOLS).registry + assert [space for space in ('global', 'gpu') if own.workflow(RegistryKey(space, 'child'))] == ['global'] + + forward = (DOOR / 'forward.wic').read_text(encoding='utf-8') + bundle = bundle_from_disk(DOOR / 'forward.wic', {'global': {}}, SYNTHETIC_TOOLS) + (undefined,) = _undefined(front_end(bundle.parsed, bundle.registry, name=bundle.name).diagnostics) + assert undefined.span is not None and undefined.span.start_line == _line_of(forward, '!* later') + (dumped,) = _undefined(front_end(parse(_redump(forward), 'forward.wic'), bundle.registry, + name=bundle.name).diagnostics) + assert dumped.span is not None and dumped.span.start_line != undefined.span.start_line document = Document(steps=( Step('xform', inputs=(('file', EdgeRef('later', None)),)), Step('mk_file', outputs=(OutputBinding('file', EdgeDef('later', None), None),)), )) - result = front_end(ParseResult(document, Diagnostics()), - RegistrySnapshot.from_tools(SYNTHETIC_TOOLS), name='memory') - - undefined = [item for item in result.diagnostics - if item.code is SophiosErrorCode.UNDEFINED_EDGE] - assert len(undefined) == 1 - assert undefined[0].span is None - assert undefined[0].locator is not None - assert undefined[0].locator.step == 'xform' - assert undefined[0].locator.index == 1 - assert undefined[0].locator.port == 'file' - - -@pytest.mark.fast -def test_python_script_resolves_without_writing_a_file(tmp_path: Path, - monkeypatch: pytest.MonkeyPatch) -> None: - """A generated tool is keyed as Resolve keys it and never reaches disk. - - `python_cwl_adapter` imports `workflow_types` from a path relative to the - working directory, so the fixture supplies both the directory and that - sibling file; nothing here reads the repository's own examples. - """ - text = 'steps:\n- id: python_script\n in:\n script: my_script.py\n name: made.txt\n' - work = _script_project(tmp_path, text) - root = work / 'root.wic' + (spanless,) = _undefined(front_end(ParseResult(document, Diagnostics()), + RegistrySnapshot.from_tools(SYNTHETIC_TOOLS), name='memory').diagnostics) + assert spanless.span is None and spanless.locator is not None + assert (spanless.locator.step, spanless.locator.index, spanless.locator.port) == ('xform', 1, 'file') + + for name in ('probe.wic', 'probe.cwl', 'probe.yml'): + diagnostics = bundle_from_disk(DOOR / 'gate' / name, {'global': {}}, {}).parsed.diagnostics + assert [(d.code, d.span and (d.span.file, d.span.start_line)) for d in diagnostics] == [ + (SophiosErrorCode.UNKNOWN_WIC_KEY, (name, 2))] + + shutil.copytree(DOOR / 'script', tmp_path / 'script') + work = tmp_path / 'script' / 'work' monkeypatch.chdir(work) - - bundle = bundle_from_disk(root, {'global': {}}, SYNTHETIC_TOOLS) - - document = parse(text, 'root.wic').document - assert document is not None - expected = RegistryKey('global', generated_process_id(document.steps[0])) + bundle = bundle_from_disk(work / 'resolve.wic', {'global': {}}, SYNTHETIC_TOOLS) + resolve = parse((work / 'resolve.wic').read_text(encoding='utf-8'), 'resolve.wic').document + assert resolve is not None + expected = RegistryKey('global', generated_process_id(resolve.steps[0])) assert bundle.registry.tool(expected) is not None - result = front_end(bundle.parsed, bundle.registry, name=bundle.name) assert result.resolved is not None and result.resolved.document is not None process = result.resolved.document.steps[0].process - assert process.key == expected - assert process.generated + assert process.key == expected and process.generated assert not (work / 'autogenerated').exists() - -@pytest.mark.fast -def test_a_python_script_tool_declares_no_schemas_of_sophios_own(tmp_path: Path, - monkeypatch: pytest.MonkeyPatch) -> None: - """The tool generated for a script names the EDAM prefix its formats use, and no ontology: a document - depends only on what its author wrote. It is at the CWL version Sophios writes.""" - work = _script_project(tmp_path, 'steps:\n- id: python_script\n in:\n script: !ii my_script.py\n' - ' name: !ii made.txt\n') - monkeypatch.chdir(work) - artifact = _compile(bundle_from_disk(work / 'root.wic', {'global': {}}, SYNTHETIC_TOOLS)).artifact + artifact = _compile(bundle_from_disk(work / 'compile.wic', {'global': {}}, SYNTHETIC_TOOLS)).artifact (tool,) = artifact.children assert tool.cwl['cwlVersion'] == CWL_VERSION, 'the script tool generator once wrote v1.0' assert tool.cwl['$namespaces'] == {'edam': 'https://edamontology.org/'} assert '$schemas' not in tool.cwl and '$schemas' not in artifact.cwl -@pytest.mark.fast -@pytest.mark.parametrize('name', ['probe.wic', 'probe.cwl', 'probe.yml']) -def test_the_parser_is_the_gate_a_file_passes_as_it_is_read(tmp_path: Path, name: str) -> None: - """A document with a `wic:` key the language does not have is refused as it is read, at the key, by the parser, - under the file's own name, whatever its extension. - - A generated jsonschema used to be applied here, and the parser let the key - through as opaque data. Nothing validates against a schema now, so the - refusal is the parser's -- positioned, and with no environment involved: - the registry is empty. - """ - write_tree(tmp_path, {name: 'wic:\n nonsense_key: 1\nsteps:\n- id: mk_file\n in:\n name: !ii a\n'}) - diagnostics = bundle_from_disk(tmp_path / name, {'global': {}}, {}).parsed.diagnostics - assert [(d.code, d.span and (d.span.file, d.span.start_line)) for d in diagnostics] == [ - (SophiosErrorCode.UNKNOWN_WIC_KEY, (name, 2))] - - def _assert_runs(artifact: CompilationArtifact, written: Yaml, directory: Path, expected: list[Yaml]) -> None: """Each step runs the `expected` tool, compiled and in the file its written `run:` names, at `CWL_VERSION`.""" files: list[str] = [] @@ -275,72 +152,65 @@ def _assert_runs(artifact: CompilationArtifact, written: Yaml, directory: Path, @pytest.mark.fast -@pytest.mark.parametrize('case, expected', case_dirs('run_paths', 'steps')) -def test_each_step_runs_the_tool_its_run_names(tmp_path: Path, case: Path, expected: Yaml) -> None: - """A `run:` path is read from beside the document that names it, else from the registry by its stem; an inline - body is a tool of its own. Each tool is the one its step runs, compiled and written out.""" - result = _compile(bundle_from_disk(case / 'w.wic', {}, SYNTHETIC_TOOLS)) - write_artifacts_to_disk(result.artifact, tmp_path) - _assert_runs(result.artifact, yaml.safe_load((tmp_path / 'w.cwl').read_text(encoding='utf-8')), tmp_path, - expected['steps']) - - -#: A plain CWL Workflow whose one step runs a tool file beside it. -_CWL_WORKFLOW = ('{class: Workflow, cwlVersion: v1.2, inputs: {text: string}, ' - 'outputs: {said: {type: File, outputSource: echo/out}}, ' - 'steps: {echo: {run: echo.cwl, in: {text: text}, out: [out]}}}') -_ECHO_TOOL = ('cwlVersion: v1.2\nclass: CommandLineTool\nbaseCommand: echo\n' - 'inputs: {text: {type: string, inputBinding: {position: 1}}}\noutputs: {out: stdout}\n') -_AS_WIC = ('Sophios cannot embed a CWL Workflow as a step: write it as a .wic subworkflow ' - '(on search_paths_wic, or beside this document as run: .wic)') -#: The advice for a CWL Workflow in a file, which --allow_raw_cwl can run on its own. -_ADVICE = _AS_WIC + ', or run the CWL Workflow on its own with --allow_raw_cwl' +def test_each_step_runs_the_tool_its_run_names(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """In each project of tests/core/data/run_paths, a `run:` path is read from beside the document that names it, + else from the registry by its stem; an inline body is a tool of its own. Each tool is the one its step runs, + compiled and written out. A root with no file of its own reads its `run:` paths from the working directory, and a + run path on another drive than the root is named by its absolute path, as `os.path.relpath` raises across Windows + drives.""" + for case, expected in (param.values for param in case_dirs('run_paths', 'steps')): + result = _compile(bundle_from_disk(case / 'w.wic', {}, SYNTHETIC_TOOLS)) + write_artifacts_to_disk(result.artifact, tmp_path / case.name) + _assert_runs(result.artifact, yaml.safe_load((tmp_path / case.name / 'w.cwl').read_text(encoding='utf-8')), + tmp_path / case.name, expected['steps']) + paths = DOOR / 'paths' + monkeypatch.chdir(paths) + (child,) = _compile(bundle_from_source((paths / 'w.wic').read_text(encoding='utf-8'), 'w', {}, + SYNTHETIC_TOOLS)).artifact.children + assert child.cwl['baseCommand'] == 'echo' + def across_drives(path: object, start: object = None) -> str: + raise ValueError("path is on mount 'C:', start on mount 'D:'") + monkeypatch.setattr('os.path.relpath', across_drives) + result = _compile(bundle_from_disk(paths / 'w.wic', {}, SYNTHETIC_TOOLS)) + assert result.artifact.children[0].cwl['baseCommand'] == 'echo' -def _cwl_workflow_step_diagnostic(tmp_path: Path, step: str, tools: Tools) -> str: - """Compile a root with `step` as its one step and return the error it is refused with.""" - write_tree(tmp_path, {'w.wic': 'steps:\n' + step + ' in: {text: !ii hi}\n'}) - with pytest.raises(SophiosError) as caught: - _compile(bundle_from_disk(tmp_path / 'w.wic', {}, tools)) - diagnostic, = caught.value.diagnostics - assert diagnostic.code is SophiosErrorCode.SUBWORKFLOW_INVALID - return diagnostic.message + +_AS_WIC: Final = ('Sophios cannot embed a CWL Workflow as a step: write it as a .wic subworkflow ' + '(on search_paths_wic, or beside this document as run: .wic)') +#: The advice for a CWL Workflow in a file, which --allow_raw_cwl can run on its own. +_ADVICE: Final = _AS_WIC + ', or run the CWL Workflow on its own with --allow_raw_cwl' @pytest.mark.fast -@pytest.mark.parametrize('step, refusal', [ - (' - id: say\n', "step 'say' runs {say}, a CWL Workflow from the tool search paths " - f'(search_paths_cwl). {_ADVICE}'), - (' - id: packed\n', "step 'packed' runs {packed}, a CWL Workflow from the tool search paths " +@pytest.mark.parametrize('root, refusal', [ + ('search_paths.wic', "step 'say' runs {adapters}/say.cwl, a CWL Workflow from the tool search paths " f'(search_paths_cwl). {_ADVICE}'), - (' - id: s\n run: say.cwl\n', f"step 's' runs run: say.cwl, a CWL Workflow. {_ADVICE}"), - (f' - id: s\n run: {_CWL_WORKFLOW}\n', f"step 's' runs an inline run: body that is a CWL Workflow. {_AS_WIC}"), -], ids=['search-paths', 'packed-on-search-paths', 'run-path', 'inline-body']) -def test_a_cwl_workflow_as_a_step_is_refused_with_advice_for_where_it_came_from(tmp_path: Path, step: str, - refusal: str) -> None: + ('packed_on_search_paths.wic', "step 'packed' runs {adapters}/packed.cwl, a CWL Workflow from the tool search " + f'paths (search_paths_cwl). {_ADVICE}'), + ('run_path.wic', f"step 's' runs run: say.cwl, a CWL Workflow. {_ADVICE}"), + ('inline_body.wic', f"step 's' runs an inline run: body that is a CWL Workflow. {_AS_WIC}"), +]) +def test_a_cwl_workflow_as_a_step_is_refused_with_advice_for_where_it_came_from(root: str, refusal: str) -> None: """Its copy would lose the tool file beside it, so the step is refused instead of emitted broken. A `$graph` whose `main` is a Workflow is one too; an inline body is no file --allow_raw_cwl could run on its own.""" - adapters = tmp_path / 'adapters' - packed = ( - 'cwlVersion: v1.2\n$graph:\n' - ' - {id: main, class: Workflow, inputs: {text: string},\n' - ' outputs: {said: {type: File, outputSource: echo/out}},\n' - ' steps: {echo: {run: "#echo", in: {text: text}, out: [out]}}}\n' - ' - {id: echo, class: CommandLineTool, baseCommand: echo, inputs: {text: string}, outputs: {out: stdout}}\n') - write_tree(tmp_path, {'say.cwl': _CWL_WORKFLOW, 'echo.cwl': _ECHO_TOOL, 'adapters/say.cwl': _CWL_WORKFLOW, - 'adapters/echo.cwl': _ECHO_TOOL, 'adapters/packed.cwl': packed}) + adapters = DOOR / 'cwl_workflow' / 'adapters' tools = get_tools_cwl({'search_paths_cwl': {'global': [str(adapters)]}}) - assert _cwl_workflow_step_diagnostic(tmp_path, step, tools) == refusal.format( - say=adapters / 'say.cwl', packed=adapters / 'packed.cwl') + with pytest.raises(SophiosError) as caught: + _compile(bundle_from_disk(DOOR / 'cwl_workflow' / root, {}, tools)) + diagnostic, = caught.value.diagnostics + assert (diagnostic.code, diagnostic.message) == (SophiosErrorCode.SUBWORKFLOW_INVALID, + refusal.format(adapters=adapters)) def _write_packed_tool_step(tmp_path: Path, where: str, packed: Path) -> Path: """Compile a root whose one step runs `packed`, copied `where` (beside the root, or on the tool search paths), and write it out; the directory written.""" directory = tmp_path if where == 'beside' else tmp_path / 'adapters' - step = ' - id: s\n run: packed.cwl\n' if where == 'beside' else ' - id: packed\n' - write_tree(directory, {'packed.cwl': packed.read_text(encoding='utf-8')}) - write_tree(tmp_path, {'w.wic': 'steps:\n' + step + ' in: {text: !ii hi}\n'}) + directory.mkdir(parents=True, exist_ok=True) + shutil.copy(packed, directory / 'packed.cwl') + shutil.copy(DOOR / 'cwl_workflow' / ('run_packed.wic' if where == 'beside' else 'packed_on_search_paths.wic'), + tmp_path / 'w.wic') tools = SYNTHETIC_TOOLS if where == 'beside' else get_tools_cwl({'search_paths_cwl': {'global': [str(directory)]}}) write_artifacts_to_disk(_compile(bundle_from_disk(tmp_path / 'w.wic', {}, tools)).artifact, tmp_path / 'out') return tmp_path / 'out' @@ -365,28 +235,29 @@ def _packed_step(door: str, packed: Path, tmp_path: Path) -> tuple[list[list[lis @pytest.mark.fast @pytest.mark.parametrize('door', ['clt_path', 'cwl_document', 'beside', 'search-paths']) -@pytest.mark.parametrize('case', cases('packed_tools', 'ports', 'refused')) -def test_a_packed_document_as_a_step_runs_its_main(tmp_path: Path, case: Yaml, door: str) -> None: - """A packed CommandLineTool, a `$graph`'s `main` or the one tool `cwltool --pack` writes, is that tool through each - door a step has, Python's and the file's: main's ports, and main alone as the step's CWL, with the document's - `$namespaces` and its `cwlVersion`, or written out, the one we emit. With no `main`, the document, as the door - names it, is refused with its processes and the fix.""" - packed = DATA / 'packed_tools' / f"{case['id']}.cwl" - if 'refused' in case: - with pytest.raises(SophiosError) as caught: - _packed_step(door, packed, tmp_path) - named = {'clt_path': packed, 'cwl_document': 'packed.cwl', 'beside': tmp_path / 'packed.cwl', - 'search-paths': tmp_path / 'adapters' / 'packed.cwl'}[door] - diagnostic, = caught.value.diagnostics - assert (diagnostic.code, diagnostic.message) == (SophiosErrorCode.SUBWORKFLOW_INVALID, - f"{named} {case['refused']}") - return - ports, tool = _packed_step(door, packed, tmp_path) - document = yaml.safe_load(packed.read_text(encoding='utf-8')) - assert ports == [case['ports']] * len(ports) - assert tool['class'] == 'CommandLineTool' and '$graph' not in tool and 'id' not in tool - assert (tool['cwlVersion'], tool['$namespaces']) == ( - document['cwlVersion'] if door in ('clt_path', 'cwl_document') else CWL_VERSION, document['$namespaces']) +def test_a_packed_document_as_a_step_runs_its_main(tmp_path: Path, door: str) -> None: + """Each packed CommandLineTool of tests/core/data/packed_tools, a `$graph`'s `main` or the one tool `cwltool --pack` + writes, is that tool through each door a step has, Python's and the file's: main's ports, and main alone as the + step's CWL, with the document's `$namespaces` and its `cwlVersion`, or written out, the one we emit. With no + `main`, the document, as the door names it, is refused with its processes and the fix.""" + for case in (param.values[0] for param in cases('packed_tools', 'ports', 'refused')): + packed, where = DATA / 'packed_tools' / f"{case['id']}.cwl", tmp_path / case['id'] + if 'refused' in case: + with pytest.raises(SophiosError) as caught: + _packed_step(door, packed, where) + named = {'clt_path': packed, 'cwl_document': 'packed.cwl', 'beside': where / 'packed.cwl', + 'search-paths': where / 'adapters' / 'packed.cwl'}[door] + diagnostic, = caught.value.diagnostics + assert (diagnostic.code, diagnostic.message) == (SophiosErrorCode.SUBWORKFLOW_INVALID, + f"{named} {case['refused']}"), case['id'] + continue + ports, tool = _packed_step(door, packed, where) + document = yaml.safe_load(packed.read_text(encoding='utf-8')) + assert ports == [case['ports']] * len(ports), case['id'] + assert tool['class'] == 'CommandLineTool' and '$graph' not in tool and 'id' not in tool, case['id'] + assert (tool['cwlVersion'], tool['$namespaces']) == ( + document['cwlVersion'] if door in ('clt_path', 'cwl_document') else CWL_VERSION, + document['$namespaces']), case['id'] @pytest.mark.needs_cwltool @@ -396,34 +267,3 @@ def test_a_packed_tool_step_validates_in_cwltool(tmp_path: Path) -> None: from .cwl_validation import validate_cwl # pylint: disable=import-outside-toplevel # no cwltool on Windows out = _write_packed_tool_step(tmp_path, 'beside', DATA / 'packed_tools' / 'single-tool.cwl') assert validate_cwl(str(out / 'w.cwl'), str(out / 'w_inputs.yml')) == 0 - - -_ECHO_FILE = ('{class: CommandLineTool, cwlVersion: v1.2, baseCommand: %s, ' - 'inputs: {a: string}, outputs: {}}') - - -@pytest.mark.fast -def test_a_run_path_on_another_drive_than_the_root_still_compiles(tmp_path: Path, - monkeypatch: pytest.MonkeyPatch) -> None: - """`os.path.relpath` raises across Windows drives; the tool is then named by its absolute path.""" - write_tree(tmp_path, {'t.cwl': _ECHO_FILE % 'echo', - 'w.wic': 'steps:\n - id: s\n run: t.cwl\n in: {a: !ii x}\n'}) - - def across_drives(path: object, start: object = None) -> str: - raise ValueError("path is on mount 'C:', start on mount 'D:'") - - monkeypatch.setattr('os.path.relpath', across_drives) - result = _compile(bundle_from_disk(tmp_path / 'w.wic', {}, SYNTHETIC_TOOLS)) - assert result.artifact.children[0].cwl['baseCommand'] == 'echo' - - -@pytest.mark.fast -def test_a_run_path_in_a_source_root_resolves_beside_the_working_directory( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """A root with no file of its own reads its `run:` paths from the working directory.""" - write_tree(tmp_path, {'t.cwl': _ECHO_FILE % 'echo'}) - monkeypatch.chdir(tmp_path) - result = _compile(bundle_from_source('steps:\n - id: s\n run: t.cwl\n in: {a: !ii x}\n', - 'w', {}, SYNTHETIC_TOOLS)) - child, = result.artifact.children - assert child.cwl['baseCommand'] == 'echo' diff --git a/tests/core/test_graph_features.py b/tests/core/test_graph_features.py index 0b45ee92f..aadae6bb5 100644 --- a/tests/core/test_graph_features.py +++ b/tests/core/test_graph_features.py @@ -1,53 +1,22 @@ -"""The graph Sophios draws: what each graph setting and the CLI's `--graphviz` do to its DOT source; no image is -rendered.""" +"""The graph Sophios draws: what a document's graph settings and the CLI's `--graphviz` flags do to its DOT source, as +tests/core/data/drawing states it; no image is rendered.""" import re -import sys -from collections.abc import Callable +import shutil from pathlib import Path from types import SimpleNamespace -from typing import Any, cast +from typing import Any, Final import pytest import yaml -from sophios import compiler, drawing, main -from sophios.cli import default_compilation_settings, get_args, get_dicts_for_compilation -from sophios.wic_types import Yaml +from sophios import main -from .helpers import no_preflight, run_cli, write_tree -from .hermetic import bundle, subworkflow_step -from .synthetic_tools import SYNTHETIC_TOOLS +from .cases import DATA, match +from .helpers import no_preflight, run_cli pytestmark = pytest.mark.package -#: `mk_file` feeds `xform` of a subworkflow, which feeds `count`, which feeds a -#: subworkflow of its own: two levels of nesting under the root. -_DOCUMENT: Yaml = {'steps': [ - {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a'}}, 'out': [{'file': {'wic_anchor': 'f'}}]}, - subworkflow_step('sub.wic', {'steps': [ - {'id': 'xform', 'in': {'file': {'wic_alias': 'f'}, 'name': {'wic_inline_input': 'b'}}}, - {'id': 'count'}, - subworkflow_step('inner.wic', {'steps': [ - {'id': 'mk_text', 'in': {'name': {'wic_inline_input': 'c'}}}]}), - ]}), -]} -#: The ids `_DOCUMENT`'s steps are written with. -_AUTHORED_IDS = {'mk_file', 'sub.wic', 'xform', 'count', 'inner.wic', 'mk_text'} - - -def _draw(document: Yaml = _DOCUMENT, *, label_edges: bool = False, label_stepname: bool = False, - inline_depth: int = sys.maxsize, dark_theme: bool = False) -> str: - """`document` compiled, then drawn with the given graph settings: the DOT source.""" - source = bundle(document, 'oracle', SYNTHETIC_TOOLS) - compiled = compiler.compile_source(source, default_compilation_settings(), quiet=True) - _options, settings = get_dicts_for_compilation(get_args()) - settings['graph_label_edges'] = label_edges - settings['graph_label_stepname'] = label_stepname - settings['graph_inline_depth'] = inline_depth - settings['graph_dark_theme'] = dark_theme - return cast(str, drawing.draw(compiled, source, settings, 'oracle', background=None).source) - - +DRAWING: Final = DATA / 'drawing' #: A node or edge name in DOT: quoted, or a bare word. _ID = r'"[^"]*"|\w+' #: A node or edge statement: its node or its two ends, and its attributes. @@ -59,237 +28,54 @@ def _unquoted(text: str) -> str: return text[1:-1] if text.startswith('"') else text -def _statements(dot: str) -> list[tuple[str, str, dict[str, str]]]: - """Each node (with an empty sink) and each edge `dot` draws, with its attributes.""" - return [(_unquoted(name), _unquoted(sink), {key: _unquoted(value) for key, value in _ATTRIBUTE.findall(attrs)}) - for name, sink, attrs in _STATEMENT.findall(dot)] - - -def _nodes(dot: str) -> dict[str, dict[str, str]]: - return {name: attrs for name, sink, attrs in _statements(dot) if not sink} - +def _attributes(text: str) -> dict[str, str]: + return {key: _unquoted(value) for key, value in _ATTRIBUTE.findall(text)} -def _edges(dot: str) -> list[tuple[str, str, dict[str, str]]]: - return [statement for statement in _statements(dot) if statement[1]] - -def _cluster(dot: str, name: str) -> dict[str, str]: - """The attributes of cluster `name`, written before its first node.""" - block = re.search(rf'subgraph "?{re.escape(name)}"? {{\n((?:\t+\w+=.*\n)*)', dot) - assert block is not None, f'{name} is not drawn' - return {key: _unquoted(value) for key, value in _ATTRIBUTE.findall(block.group(1))} - - -def _ranks(dot: str) -> list[tuple[int, list[str]]]: - """Each rank=same group, with its indent (2 in the root's cluster, 3 in a cluster within it) and its nodes.""" - return [(len(indent), [_unquoted(name) for name in names.split('; ')]) - for indent, names in re.findall(r'^(\t*)\{rank=same; (.*)\}$', dot, re.MULTILINE)] - - -@pytest.mark.fast -@pytest.mark.parametrize(('flag', 'edge', 'nodes'), [ - ({}, None, _AUTHORED_IDS), - ({'label_edges': True}, 'file', _AUTHORED_IDS), - ({'label_stepname': True}, None, {'mk_file', 'sub', 'xform', 'count', 'inner', 'mk_text'}), -], ids=['neither', 'graph_label_edges', 'graph_label_stepname']) -def test_each_graph_label_flag_labels_what_it_names(flag: dict[str, Any], edge: str | None, nodes: set[str]) -> None: - """With `--graph_label_edges` an edge is labelled with the output it carries. A node is labelled with the id the - document wrote; with `--graph_label_stepname` it is the generated step name instead, which a subworkflow's steps - carry relative to the subworkflow.""" - dot = _draw(**flag) - assert [attrs.get('label') for *_, attrs in _edges(dot)] == [edge] * 2 - assert ('label=file' in dot) is (edge is not None) - assert {attrs['label'] for attrs in _nodes(dot).values()} == nodes +def _clusters(dot: str) -> dict[str, dict[str, str]]: + """Each cluster, with the attributes written before its first node.""" + return {_unquoted(name): _attributes(block) for name, block in + re.findall(rf'subgraph ({_ID}) {{\n((?:\t+\w+=.*\n)*)', dot)} @pytest.mark.fast -@pytest.mark.parametrize(('depth', 'clusters'), [ - (0, {'cluster_oracle'}), - (1, {'cluster_oracle', 'cluster_sub'}), - (2, {'cluster_oracle', 'cluster_sub', - 'cluster_sub~inner'}), -]) -def test_graph_inline_depth_draws_that_many_levels_of_subworkflow(depth: int, clusters: set[str]) -> None: - """`--graph_inline_depth N` draws the subworkflows N levels down as clusters and leaves the steps of the - deeper ones out of the drawing.""" - dot = _draw(inline_depth=depth) - assert {_unquoted(name) for name in re.findall(rf'subgraph ({_ID})', dot)} == clusters - drawn = _nodes(dot) - assert ('sub~count' in drawn) is (depth >= 1) - assert ('sub~inner~mk_text' in drawn) is (depth >= 2) - - -@pytest.fixture(name='cli_graph') -def _cli_graph(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Callable[..., str]: - """Run the CLI on a workflow in `tmp_path` and return the `.gv` it wrote, with `dot` reported present and its - commands swallowed.""" +@pytest.mark.parametrize('drawn', yaml.safe_load((DRAWING / 'expected.yaml').read_text(encoding='utf-8')), + ids=lambda drawn: ' '.join(drawn['flags']) or 'default') +def test_the_drawing_is_what_its_example_states(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, + capsys: pytest.CaptureFixture[str], drawn: dict[str, Any]) -> None: + """`--graphviz` writes `autogenerated/.wic.gv`: a cluster per workflow, the subworkflows + `--graph_inline_depth` levels down and no deeper, a box per step labelled with the id the document wrote, or its + own `wic: graphviz:` label written under its `(index, name)` or its id, `\\n` and all, or with + `--graph_label_stepname` the generated step name; a step's style after `rounded`; an edge per dependency, + labelled with the output it carries under `--graph_label_edges`. A subworkflow's own label titles its cluster, + the calling step's entry wins over it, and without either the cluster is titled with the calling step's id; + `style: invis` hides the subworkflow, its cluster and the box that calls it, and each call is a cluster of its own. + A workflow's `ranksame` steps share one rank=same group in its own cluster, and an entry that addresses no step is + named on stderr, as for a stale `wic: steps:` key.""" + shutil.copytree(DRAWING, tmp_path / 'drawing', ignore=shutil.ignore_patterns('expected.yaml')) no_preflight(monkeypatch) monkeypatch.setattr(main.shutil, 'which', lambda _name: '/usr/bin/dot') monkeypatch.setattr(main, 'sub', SimpleNamespace(run=lambda *_a, **_k: SimpleNamespace(stdout=b''))) - monkeypatch.chdir(tmp_path) - - def run(source: str, *flags: str, sub: str | None = None) -> str: - write_tree(tmp_path, {'w.wic': source, **({} if sub is None else {'sub.wic': sub})}) - assert run_cli(monkeypatch, '--yaml', tmp_path / 'w.wic', '--generate_cwl_workflow', '--graphviz', - *flags) is None - return (tmp_path / 'autogenerated' / 'w.wic.gv').read_text(encoding='utf-8') - return run - - -_TWO_STEPS = """\ -steps: -- id: touch - in: - filename: !ii empty.txt -- id: cat -""" - - -@pytest.mark.fast -def test_graphviz_writes_the_graph_of_the_compiled_workflow(cli_graph: Callable[..., str]) -> None: - """`--graphviz` writes `autogenerated/.wic.gv` with a node per step and an edge per dependency.""" - drawn = cli_graph(_TWO_STEPS) - assert re.findall(r'^\s*(\w+) \[label=(\w+) ', drawn, re.MULTILINE) == [ - ('touch', 'touch'), ('cat', 'cat')] - assert re.findall(r'^\s*(\w+) -> (\w+) \[', drawn, re.MULTILINE) == [('touch', 'cat')] - - -@pytest.mark.fast -@pytest.mark.parametrize(('flags', 'font', 'blue'), [((), 'black', 'blue'), - (('--graph_dark_theme',), 'white', 'lightskyblue')]) -def test_the_drawing_takes_its_palette_from_the_theme( - cli_graph: Callable[..., str], flags: tuple[str, ...], font: str, blue: str) -> None: - """The drawing's text, its box outlines, its inferred edges and an edge's label take one colour: black, or white - with `--graph_dark_theme`. The background is transparent either way, so a slide gives it its colour; a box is - not filled, so it takes that colour too. An edge the document wrote is `blue`, whether it joins two steps of one - document or reaches into a subworkflow; that does not read on a dark background, so the dark theme draws it in a - lighter blue.""" - drawn = cli_graph(_TWO_STEPS, '--graph_label_edges', *flags) - assert 'bgcolor=transparent\n' in drawn - assert f'fontcolor={font}\n' in drawn - boxes = _nodes(drawn) - assert {(attrs['color'], attrs['fontcolor']) for attrs in boxes.values()} == {(font, font)} + monkeypatch.chdir(tmp_path / 'drawing') + assert run_cli(monkeypatch, '--yaml', 'drawn.wic', '--generate_cwl_workflow', '--graphviz', *drawn['flags']) is None + dot = Path('autogenerated/drawn.wic.gv').read_text(encoding='utf-8') + statements = [(_unquoted(name), _unquoted(sink), _attributes(attrs)) + for name, sink, attrs in _STATEMENT.findall(dot)] + boxes = {name: attrs for name, sink, attrs in statements if not sink} + edges = [[name, sink, attrs] for name, sink, attrs in statements if sink] + palette = drawn['palette'] + assert 'bgcolor=transparent\n' in dot and f'fontcolor={palette}\n' in dot + assert {(attrs['color'], attrs['fontcolor']) for attrs in boxes.values()} == {(palette, palette)} assert not any('filled' in attrs['style'] or 'fillcolor' in attrs for attrs in boxes.values()) - assert [(attrs['color'], attrs['fontcolor']) for *_, attrs in _edges(drawn)] == [(font, font)] - nested = _draw({'steps': [ - {'id': 'mk_file', 'in': {'name': {'wic_inline_input': 'a'}}, 'out': [{'file': {'wic_anchor': 'f'}}]}, - {'id': 'xform', 'in': {'file': {'wic_alias': 'f'}, 'name': {'wic_inline_input': 'b'}}}, - subworkflow_step('sub.wic', {'steps': [ - {'id': 'xform', 'in': {'file': {'wic_alias': 'f'}, 'name': {'wic_inline_input': 'c'}}}, - {'id': 'count'}, # file inferred from xform - ]}), - ]}, dark_theme='--graph_dark_theme' in flags) - assert {(source, sink): attrs.get('color') for source, sink, attrs in _edges(nested)} == { - ('mk_file', 'xform'): blue, - ('mk_file', 'sub~xform'): blue, - ('sub~xform', 'sub~count'): font, - } - - -@pytest.mark.fast -def test_the_root_graphviz_label_titles_the_drawing(cli_graph: Callable[..., str]) -> None: - """`wic: graphviz: label:` on the workflow is the title of the cluster that draws it.""" - drawn = cli_graph('wic:\n graphviz:\n label: My Pipeline\n' + _TWO_STEPS) - assert 'label="My Pipeline"' in drawn - assert 'label="My Pipeline"' not in cli_graph(_TWO_STEPS) - - -#: A workflow whose second step calls `sub.wic`, which the `cli_graph` fixture writes beside it. -_SUB_CLUSTER = 'cluster_sub' -_CALLS_SUB = """\ -steps: -- id: touch - in: - filename: !ii empty.txt -- id: sub.wic - run: sub.wic -""" - - -def _with(steps: str, graphviz: Yaml | None = None, entries: dict[str, Yaml] | None = None) -> str: - """`steps` under a `wic:` block whose own `graphviz:` is `graphviz`, and whose `steps:` entry - `key` has `entries[key]` as its `graphviz:`.""" - wic: Yaml = {'graphviz': graphviz} if graphviz else {} - if entries: - wic['steps'] = {key: {'wic': {'graphviz': value}} for key, value in entries.items()} - return (yaml.safe_dump({'wic': wic}, sort_keys=False) if wic else '') + steps - - -@pytest.mark.fast -@pytest.mark.parametrize('address', ['(1, touch)', 'touch']) -@pytest.mark.parametrize(('flags', 'labels'), [ - ((), ('Make\\nit', 'cat')), - (('--graph_label_stepname',), ('touch', 'cat')), -]) -def test_a_step_label_names_its_box_unless_the_flag_asks_for_generated_names( - cli_graph: Callable[..., str], address: str, flags: tuple[str, ...], labels: tuple[str, str]) -> None: - """A step's `wic: graphviz: label`, written under its `(index, name)` or its id, replaces the id on its - box, `\\n` and all; `--graph_label_stepname` replaces both with the generated step name.""" - nodes = _nodes(cli_graph(_with(_TWO_STEPS, entries={address: {'label': 'Make\\nit'}}), *flags)) - assert (nodes['touch']['label'], nodes['cat']['label']) == labels - - -@pytest.mark.fast -def test_a_step_style_is_appended_to_the_style_of_its_box(cli_graph: Callable[..., str]) -> None: - """A step's `wic: graphviz: style` follows `rounded`; a step without one keeps that alone.""" - nodes = _nodes(cli_graph(_with(_TWO_STEPS, entries={'touch': {'style': 'dashed, bold'}}))) - assert nodes['touch']['style'] == 'rounded, dashed, bold' - assert nodes['cat']['style'] == 'rounded' - - -@pytest.mark.fast -@pytest.mark.parametrize(('own', 'call', 'cluster', 'box'), [ - (None, None, ('label', 'sub.wic'), 'rounded'), - ({'label': 'Own'}, None, ('label', 'Own'), 'rounded'), - (None, {'label': 'Called'}, ('label', 'Called'), 'rounded'), - ({'label': 'Own'}, {'label': 'Called'}, ('label', 'Called'), 'rounded'), - ({'style': 'invis'}, None, ('style', 'invis'), 'rounded, invis'), - (None, {'style': 'invis'}, ('style', 'invis'), 'rounded, invis'), -], ids=['call-id', 'own-label', 'call-label', 'call-wins', 'own-invis', 'call-invis']) -def test_a_subworkflow_cluster_takes_the_label_and_style_of_its_call_else_its_own( - cli_graph: Callable[..., str], own: Yaml | None, call: Yaml | None, cluster: tuple[str, str], box: str) -> None: - """The subworkflow's own `wic: graphviz: label` titles its cluster, and the calling step's entry wins - over it; without either the cluster is titled with the calling step's id. `style: invis`, in its own file or - at the call, hides the whole subworkflow: its cluster and the box that calls it.""" - drawn = cli_graph(_with(_CALLS_SUB, entries={'sub.wic': call} if call else None), sub=_with(_TWO_STEPS, own)) - attr, value = cluster - assert _cluster(drawn, _SUB_CLUSTER)[attr] == value - nodes = _nodes(drawn) - assert (nodes['sub']['style'], nodes['touch']['style']) == (box, 'rounded') - - -@pytest.mark.fast -def test_two_calls_to_one_subworkflow_are_two_clusters_each_with_its_own_look( - cli_graph: Callable[..., str]) -> None: - """Each call to a subworkflow is a cluster named after the step that calls it, so the label and - style a call's `wic: steps:` entry gives belong to that call alone.""" - calls = _CALLS_SUB + "- id: sub.wic\n run: sub.wic\n" - entries = {'(2, sub.wic)': {'label': 'First'}, '(3, sub.wic)': {'label': 'Second', 'style': 'invis'}} - drawn = cli_graph(_with(calls, entries=entries), sub=_TWO_STEPS) - first, second = _cluster(drawn, 'cluster_sub@2'), _cluster(drawn, 'cluster_sub@3') - assert (first['label'], first.get('style'), second['label'], second['style']) == ('First', None, 'Second', 'invis') - assert _nodes(drawn)['sub@2']['style'] == 'rounded' - - -@pytest.mark.fast -@pytest.mark.parametrize(('root', 'sub', 'ranks'), [ - (['(1, touch)', '(2, sub.wic)'], [], [(2, ['touch', 'sub'])]), - ([], ['(1, touch)', '(2, cat)'], - [(3, ['sub~touch', 'sub~cat'])]), - (['(1, touch)', '(3, touch)'], [], []), -]) -def test_ranksame_puts_the_steps_it_names_on_one_rank_in_their_workflow_s_cluster( - cli_graph: Callable[..., str], root: list[str], sub: list[str], ranks: list[tuple[int, list[str]]]) -> None: - """A workflow's `ranksame` steps share one rank=same group in its own cluster, the root's included. - A group of fewer than two steps that exist is not drawn.""" - drawn = cli_graph(_with(_CALLS_SUB, {'ranksame': root}), sub=_with(_TWO_STEPS, {'ranksame': sub})) - assert _ranks(drawn) == ranks - - -@pytest.mark.fast -def test_a_ranksame_entry_that_addresses_no_step_is_named_on_stderr( - cli_graph: Callable[..., str], capsys: pytest.CaptureFixture[str]) -> None: - """The line names the file, the entry and the steps the document has, as for a stale `wic: steps:` key.""" - cli_graph(_with(_TWO_STEPS, {'ranksame': ['(1, touch)', '(3, touch)']})) - assert ("Warning! w.wic: wic: graphviz: ranksame entry (3, touch) addresses no step of 'w': " - 'there is no step 3; the document has 2 steps. The entry is ignored.') in capsys.readouterr().err + clusters = _clusters(dot) + assert 'clusters' not in drawn or set(clusters) == set(drawn['clusters']) + assert match(drawn.get('clusters', {}), clusters) + assert {name: [boxes[name]['label'], boxes[name]['style']] for name in drawn.get('boxes', {})} == drawn.get( + 'boxes', {}) + assert drawn['flags'] or set(boxes) == set(drawn['boxes']) + assert not [name for name in drawn.get('absent', []) if name in boxes] + assert 'edges' not in drawn or edges == drawn['edges'] + ranks = [[len(indent), [_unquoted(name) for name in names.split('; ')]] + for indent, names in re.findall(r'^(\t*)\{rank=same; (.*)\}$', dot, re.MULTILINE)] + assert 'ranks' not in drawn or ranks == drawn['ranks'] + assert match({'contains': drawn['said']} if 'said' in drawn else {'re': ''}, capsys.readouterr().err) diff --git a/tests/core/test_input_output.py b/tests/core/test_input_output.py index efdaf9833..9effcb732 100644 --- a/tests/core/test_input_output.py +++ b/tests/core/test_input_output.py @@ -1,5 +1,4 @@ -"""Behavioural coverage for `sophios.input_output` config handling, and for the paths a written job names.""" -import json +"""The paths a written job names; the config `sophios.input_output` reads is test_config.py's.""" import string from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath from typing import Any, NamedTuple @@ -7,23 +6,11 @@ import pytest from hypothesis import example, given, strategies as st -from sophios import input_output as io from sophios.ir.locations import absolute_paths from .budgets import budget -@pytest.mark.fast -@pytest.mark.parametrize('tag', ['search_paths_cwl', 'search_paths_wic']) -def test_a_search_path_given_as_a_string_is_a_type_error(tmp_path: Path, tag: str) -> None: - """A string is not iterated into characters; the error names the config key.""" - config = tmp_path / 'c.json' - config.write_text(json.dumps({'search_paths_cwl': {'global': []}, 'search_paths_wic': {'global': []}, - tag: {'global': '/whole/disk'}}), encoding='utf-8') - with pytest.raises(TypeError, match=f'{tag}.global'): - io.read_config_from_disk(config) - - class _At(NamedTuple): key: str path: str diff --git a/tests/core/test_packing.py b/tests/core/test_packing.py index 168ca6d60..2900cceb7 100644 --- a/tests/core/test_packing.py +++ b/tests/core/test_packing.py @@ -1,7 +1,8 @@ -"""A tool that refers to files beside it is written packed, so it means the same wherever it is written.""" +"""A tool that refers to files beside it is written packed, so it means the same wherever it is written. The project +is tests/core/data/packing, compiled and run where it is from a working directory of the test's own: what is packed +is checked on every leg, and the runs show that the written descriptions run.""" import hashlib import json -import os import subprocess import sys from pathlib import Path @@ -11,7 +12,7 @@ import yaml from schema_salad.fetcher import DefaultFetcher -from sophios import run_local, utils_cwl +from sophios import run_local from sophios.api.python.workflow import Step, Workflow from sophios.cli import default_compilation_settings from sophios.compiler import compile_source @@ -19,111 +20,19 @@ from sophios.ir.frontdoor import bundle_from_disk from sophios.lang.diagnostics import SophiosError from sophios.lang.error_codes import SophiosErrorCode -from sophios.wic_types import StepId, Tool, Tools +from sophios.plugins import get_tools_cwl +from sophios.wic_types import StepId, Tools -from .helpers import ADAPTERS, EACH_RUNNER, no_preflight, run_cli, run_local_process, search_config, write_tree +from .cases import DATA +from .helpers import ADAPTERS, EACH_RUNNER, no_preflight, run_cli, run_local_process, search_config pytestmark = pytest.mark.package -#: Its script by `$include`, its data by a relative default: both beside it. -RELCAT: Final = '''cwlVersion: v1.2 -class: CommandLineTool -requirements: - InitialWorkDirRequirement: - listing: - - entryname: s.sh - entry: - $include: s.sh -baseCommand: [sh, s.sh] -inputs: - extra: - type: File - default: {class: File, location: data.txt} - inputBinding: {position: 1} -outputs: - out: {type: stdout} -stdout: out.txt -''' -SCRIPT: Final = 'echo from-include; cat "$1"\n' -DATA: Final = 'data beside the tool\n' -#: What `relcat` prints. -PRINTED: Final = 'from-include\n' + DATA -PLAIN: Final = '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: echo -inputs: {message: {type: string, default: hi, inputBinding: {position: 1}}} -outputs: {out: {type: stdout}} -stdout: out.txt -''' -#: A relative default, and an output whose format inference reads as written: `edam:format_2330`. -MAKE: Final = '''cwlVersion: v1.2 -class: CommandLineTool -$namespaces: {edam: https://edamontology.org/} -baseCommand: cat -stdout: made.txt -inputs: - seed: {type: File, default: {class: File, location: seed.txt}, inputBinding: {position: 1}} -outputs: - out: {type: File, format: edam:format_2330, outputBinding: {glob: made.txt}} -''' -USE: Final = '''cwlVersion: v1.2 -class: CommandLineTool -$namespaces: {edam: https://edamontology.org/} -baseCommand: cat -stdout: used.txt -inputs: - file: {type: File, format: edam:format_2330, inputBinding: {position: 1}} -outputs: - out: {type: File, outputBinding: {glob: used.txt}} -''' -MAKE_USE_PROJECT: Final = { - 'tools/seed.txt': 'seed\n', 'tools/make.cwl': MAKE, 'tools/use.cwl': USE, - 'w.wic': 'steps:\n- id: make\n run: tools/make.cwl\n- id: use\n run: tools/use.cwl\n'} -#: A step `say` whose inline tool includes the `s.sh` beside the `.wic` that holds it. -INLINE_SAY: Final = '''- id: say - run: - class: CommandLineTool - requirements: - InitialWorkDirRequirement: - listing: [{entryname: s.sh, entry: {$include: s.sh}}] - baseCommand: [sh, s.sh] - inputs: {} - outputs: {} -''' -#: Like `extract_pdbbind_refined.cwl`: its image is built from a Dockerfile beside it. -DOCKERFILE_TOOL: Final = '''cwlVersion: v1.0 -class: CommandLineTool -hints: - DockerRequirement: - dockerImageId: built_here - dockerFile: - $include: Dockerfile_built -baseCommand: echo -inputs: {} -outputs: {} -''' -DOCKERFILE: Final = 'FROM alpine:3.20\nRUN echo built\n' -#: Its `$include` names nothing. -BROKEN: Final = '''cwlVersion: v1.2 -class: CommandLineTool -requirements: - InitialWorkDirRequirement: - listing: [{entryname: s.sh, entry: {$include: missing.sh}}] -baseCommand: [sh, s.sh] -inputs: {} -outputs: {} -''' - - -def _relcat(directory: Path, script: str = SCRIPT) -> Path: - """`relcat.cwl`, its script and its data, in `directory`.""" - return write_tree(directory, {'s.sh': script, 'data.txt': DATA, 'relcat.cwl': RELCAT}) / 'relcat.cwl' - - -def _registry(*tools: Path) -> Tools: - """Each file as a search-path tool, read as the loader reads it.""" - return {StepId(tool.stem, 'global'): Tool(str(tool), yaml.safe_load(tool.read_text(encoding='utf-8'))) - for tool in tools} +PROJECT: Final = DATA / 'packing' +TOOLS: Final = PROJECT / 'tools' +#: What `relcat` includes and prints. +SCRIPT: Final = (TOOLS / 's.sh').read_text(encoding='utf-8') +PRINTED: Final = 'from-include\n' + (TOOLS / 'data.txt').read_text(encoding='utf-8') def _compile(wic: Path, tools: Tools | None = None) -> CompilationArtifact: @@ -151,160 +60,133 @@ def _entry(tool: dict[str, Any]) -> Any: @pytest.mark.fast -def test_a_tool_with_an_include_and_a_relative_default_is_emitted_packed(tmp_path: Path) -> None: - """The include is its text and the default an absolute URI; the registry still holds the tool as read.""" - tool = _relcat(tmp_path / 'tools') - write_tree(tmp_path, {'w.wic': 'steps:\n- id: relcat\n'}) - registry = _registry(tool) - - written = _tool(_compile(tmp_path / 'w.wic', registry), 'relcat') - - assert _entry(written) == SCRIPT - assert written['inputs']['extra']['default'] == { - 'class': 'File', 'location': (tmp_path / 'tools/data.txt').as_uri()} +# pylint: disable-next=too-many-locals,too-many-statements +def test_a_tool_that_refers_to_files_beside_it_is_written_packed_by_every_door( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Every step running `relcat` is described packed: its include its text, its default an absolute URI; the + registry still holds the tool as read. The same inline body in two `.wic` files in two directories includes each + one's own `s.sh`. Inference reads `make` as written, so its `edam:format_2330` output feeds `use`: no new root + input. Only a tool a step runs is packed: one on the search path that cannot be costs nothing, until a step runs + it, when cwltool's own message is the error, at the line of the step. Packing never fetches a tool's `$schemas`. + The command line's tree and its one embedded document carry a Dockerfile itself, and the tree keeps the tool's own + `v1.0`; Python's `compile()`, the document `run()` writes, and a real-time analysis's tool are packed alike.""" + registry = get_tools_cwl({'search_paths_cwl': {'global': [str(TOOLS)]}}) + artifact = _compile(PROJECT / 'relcat.wic', registry) + assert [_entry(child.cwl) for child in artifact.children] == [SCRIPT] * 3 + written = artifact.children[0].cwl + assert written['inputs']['extra']['default'] == {'class': 'File', 'location': (TOOLS / 'data.txt').as_uri()} assert written['cwlVersion'] == 'v1.2' assert _entry(registry[StepId('relcat', 'global')].cwl) == {'$include': 's.sh'} - -@pytest.mark.fast -def test_every_step_running_a_tool_is_described_packed(tmp_path: Path) -> None: - """However many steps run a tool, every step's description is packed.""" - tool = _relcat(tmp_path / 'tools') - write_tree(tmp_path, {'w.wic': 'steps:\n- id: relcat\n- id: relcat\n- id: relcat\n'}) - - artifact = _compile(tmp_path / 'w.wic', _registry(tool)) - - assert [_entry(child.cwl) for child in artifact.children] == [SCRIPT] * 3 - - -@pytest.mark.fast -def test_one_inline_body_in_two_directories_reads_each_ones_files(tmp_path: Path) -> None: - """The same body, written in two `.wic` files in two directories, includes each directory's `s.sh`.""" - write_tree(tmp_path, {'a/s.sh': 'echo a\n', 'b/s.sh': 'echo b\n', 'b/inner.wic': 'steps:\n' + INLINE_SAY, - 'a/w.wic': 'steps:\n' + INLINE_SAY + '- id: inner\n run: ../b/inner.wic\n'}) - - artifact = _compile(tmp_path / 'a' / 'w.wic') - + artifact = _compile(PROJECT / 'a' / 'w.wic') inner, = (child for child in artifact.children if child.namespace == ('inner',)) - assert (_entry(_tool(artifact, 'say')), _entry(_tool(inner, 'say'))) == ('echo a\n', 'echo b\n') + included = _entry(_tool(artifact, 'say')), _entry(_tool(inner, 'say')) + assert included == ('#!/bin/sh\necho a\n', '#!/bin/sh\necho b\n') + artifact = _compile(PROJECT / 'make_use.wic') + use, = (step for step in artifact.cwl['steps'] if step['id'] == 'use') + assert use['in'] == {'file': 'make/out'} and not artifact.cwl['inputs'] + assert _tool(artifact, 'make')['inputs']['seed']['default']['location'] == (TOOLS / 'seed.txt').as_uri() + + broken = get_tools_cwl({'search_paths_cwl': {'global': [str(PROJECT / 'broken')]}}) + artifact = _compile(PROJECT / 'broken' / 'unused.wic', broken) + assert [child.namespace for child in artifact.children] == [('echo',)] + assert _tool(artifact, 'echo') == broken[StepId('echo', 'global')].cwl, \ + 'nothing to resolve, so the tool is emitted as the loader read it' + with pytest.raises(SophiosError) as raised: + _compile(PROJECT / 'broken' / 'used.wic', broken) + diagnostic, = raised.value.diagnostics + assert diagnostic.code is SophiosErrorCode.SUBWORKFLOW_INVALID + assert diagnostic.locator is not None and (diagnostic.locator.step, diagnostic.locator.index) == ('broken', 2) + assert diagnostic.span is not None and diagnostic.span.start_line == 3 + assert str(PROJECT / 'broken' / 'broken.cwl') in diagnostic.message + # The OSError as schema-salad passes it on. On Windows the error's filename, spelled with backslashes, + # differs from the URI's path, so schema-salad prefixes it with `Error reading : `. + reason = diagnostic.message.splitlines()[-1].strip() + assert "[Errno 2] No such file or directory: '" in reason and reason.endswith("missing.sh'") -def _dockerfile_project(tmp_path: Path) -> Path: - """A project whose search path holds `built.cwl` and the Dockerfile it builds its image from.""" - write_tree(tmp_path, {'tools/built.cwl': DOCKERFILE_TOOL, 'tools/Dockerfile_built': DOCKERFILE, - 'w.wic': 'steps:\n- id: built\n'}) - search_config(tmp_path / 'config.json', [tmp_path / 'tools'], [tmp_path]) - return tmp_path + fetched: list[str] = [] + fetch_text = DefaultFetcher.fetch_text + def spy(self: DefaultFetcher, url: str, content_types: list[str] | None = None) -> str: + fetched.append(url) + return fetch_text(self, url, content_types) + monkeypatch.setattr(DefaultFetcher, 'fetch_text', spy) + artifact = _compile(PROJECT / 'ontology.wic', get_tools_cwl({'search_paths_cwl': {'global': [str(TOOLS)]}})) + assert _tool(artifact, 'ontology')['$schemas'] == ['http://schemas.invalid/ontology.owl'] + assert not [url for url in fetched if 'schemas.invalid' in url] -@pytest.mark.fast -def test_a_dockerfile_include_is_packed_text(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """The written tool carries the Dockerfile itself, in the tree and embedded, and keeps its own `v1.0`.""" - monkeypatch.chdir(_dockerfile_project(tmp_path)) + monkeypatch.chdir(tmp_path) + config = search_config(tmp_path / 'config.json', [TOOLS, ADAPTERS / 'file_watchers'], [PROJECT]) for flags in ((), ('--cwl_inline_runtag',)): - assert run_cli(monkeypatch, '--yaml', 'w.wic', '--config_file', 'config.json', '--generate_cwl_workflow', - '--basepath', 'out', *flags) is None - root = yaml.safe_load(Path('out/w.cwl').read_text(encoding='utf-8')) - tool = root['steps'][0]['run'] if flags else yaml.safe_load(Path('out/w~built.cwl').read_text(encoding='utf-8')) + assert run_cli(monkeypatch, '--yaml', PROJECT / 'built.wic', '--config_file', config, + '--generate_cwl_workflow', '--basepath', 'out', *flags) is None + root = yaml.safe_load(Path('out/built.cwl').read_text(encoding='utf-8')) + tool = root['steps'][0]['run'] if flags else yaml.safe_load(Path('out/built~built.cwl').read_text( + encoding='utf-8')) docker = _requirement(tool, 'hints', 'DockerRequirement') - assert docker == {'dockerImageId': 'built_here', 'dockerFile': DOCKERFILE}, flags + assert docker == {'dockerImageId': 'built_here', 'dockerFile': 'FROM alpine:3.20\nRUN echo built\n'}, flags assert flags or tool['cwlVersion'] == 'v1.0' - -def _analysis_project(tmp_path: Path) -> Path: - """`relcat` on the search path, run by `w.wic` and declared as a real-time analysis by `live.wic`.""" - tool = _relcat(tmp_path / 'tools') - write_tree(tmp_path, {'tools/slow_log.cwl': '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: [touch, out.log] -inputs: {} -outputs: {log: {type: File, outputBinding: {glob: out.log}}} -''', 'w.wic': 'steps:\n- id: relcat\n', 'live.wic': '''steps: - - id: slow_log - - id: cwl_subinterpreter - in: - file_pattern: !ii out.log - cwl_tool: !ii relcat - max_times: !ii '1' - config: !ii {in: {}} -'''}) - search_config(tmp_path / 'config.json', [tool.parent, ADAPTERS / 'file_watchers'], [tmp_path]) - return tool - - -@pytest.mark.fast -def test_compile_run_and_an_analysis_all_carry_the_packed_text(tmp_path: Path, - monkeypatch: pytest.MonkeyPatch) -> None: - """Python `compile()`, the document `run()` writes, and a real-time analysis's tool are packed alike.""" - tool = _analysis_project(tmp_path) - monkeypatch.chdir(tmp_path) monkeypatch.setattr(run_local, 'generate_run_script', lambda _cmdline: None) no_preflight(monkeypatch) - - compiled = Workflow([Step(clt_path=tool)], 'py').compile().cwl_workflow - Workflow([Step(clt_path=tool)], 'py').run(basepath='ran', run_args_dict={'generate_run_script': 'yes'}) + relcat = TOOLS / 'relcat.cwl' + compiled = Workflow([Step(clt_path=relcat)], 'py').compile().cwl_workflow + Workflow([Step(clt_path=relcat)], 'py').run(basepath='ran', run_args_dict={'generate_run_script': 'yes'}) ran = yaml.safe_load(Path('ran/py.cwl').read_text(encoding='utf-8')) - assert run_cli(monkeypatch, '--yaml', 'live.wic', '--config_file', 'config.json', '--generate_cwl_workflow') is None + assert run_cli(monkeypatch, '--yaml', PROJECT / 'live.wic', '--config_file', config, + '--generate_cwl_workflow') is None analysis, = Path('autogenerated/realtime/live').glob('*~relcat.cwl') - for where, written in (('compile()', compiled['steps'][0]['run']), ('run()', ran['steps'][0]['run']), ('analysis', yaml.safe_load(analysis.read_text(encoding='utf-8')))): assert _entry(written) == SCRIPT, where - assert written['inputs']['extra']['default']['location'] == (tool.parent / 'data.txt').as_uri(), where - - -@pytest.mark.fast -def test_inference_wires_a_packed_tool_as_it_wires_one_as_written(tmp_path: Path) -> None: - """Inference reads `make` as written, so its `edam:format_2330` output feeds `use`'s input: no new root - input. The description written for `make` is packed.""" - write_tree(tmp_path, MAKE_USE_PROJECT) - - artifact = _compile(tmp_path / 'w.wic') - - use, = (step for step in artifact.cwl['steps'] if step['id'] == 'use') - assert use['in'] == {'file': 'make/out'} - assert not artifact.cwl['inputs'] - seed = tmp_path / 'tools' / 'seed.txt' - assert _tool(artifact, 'make')['inputs']['seed']['default']['location'] == seed.as_uri() - - -@pytest.mark.fast -def test_a_broken_tool_nobody_runs_stops_no_compile(tmp_path: Path) -> None: - """Only a tool a step runs is packed: one on the search path that cannot be packed costs nothing.""" - write_tree(tmp_path, {'broken.cwl': BROKEN, 'echo.cwl': PLAIN, 'w.wic': 'steps:\n- id: echo\n'}) - - registry = _registry(tmp_path / 'broken.cwl', tmp_path / 'echo.cwl') + assert written['inputs']['extra']['default']['location'] == (TOOLS / 'data.txt').as_uri(), where - artifact = _compile(tmp_path / 'w.wic', registry) - assert [child.namespace for child in artifact.children] == [('echo',)] - assert _tool(artifact, 'echo') == registry[StepId('echo', 'global')].cwl, \ - 'nothing to resolve, so the tool is emitted as the loader read it' +def _produced() -> list[str]: + """What the run's output files hold, in order: cwltool and Toil each write them to an outdir of their own.""" + return sorted(path.read_text(encoding='utf-8') for path in Path('autogenerated').glob('outdir_*/**/*') + if path.is_file()) -@pytest.mark.fast -def test_a_step_running_a_tool_with_a_missing_include_reports_cwltools_error_at_the_step(tmp_path: Path) -> None: - """cwltool's own message, at the line of the step that runs the tool.""" - write_tree(tmp_path, {'broken.cwl': BROKEN, 'echo.cwl': PLAIN, 'w.wic': 'steps:\n- id: echo\n- id: broken\n'}) +def _hashes(root: Path) -> dict[str, tuple[str, int]]: + return {path.relative_to(root).as_posix(): (hashlib.sha256(path.read_bytes()).hexdigest(), path.stat().st_mtime_ns) + for path in root.rglob('*') if path.is_file()} - with pytest.raises(SophiosError) as raised: - _compile(tmp_path / 'w.wic', _registry(tmp_path / 'broken.cwl', tmp_path / 'echo.cwl')) - diagnostic, = raised.value.diagnostics - assert diagnostic.code is SophiosErrorCode.SUBWORKFLOW_INVALID - assert diagnostic.locator is not None and (diagnostic.locator.step, diagnostic.locator.index) == ('broken', 2) - assert diagnostic.span is not None and diagnostic.span.start_line == 3 - assert str(tmp_path / 'broken.cwl') in diagnostic.message - # The OSError as schema-salad passes it on. On Windows the error's filename, spelled with backslashes, - # differs from the URI's path, so schema-salad prefixes it with `Error reading : `. - reason = diagnostic.message.splitlines()[-1].strip() - assert "[Errno 2] No such file or directory: '" in reason and reason.endswith("missing.sh'") +@pytest.mark.needs_cwltool +def test_a_packed_project_runs_under_cwltool_and_changes_nothing_beside_it(tmp_path: Path, + monkeypatch: pytest.MonkeyPatch) -> None: + """Compiling and running packed tools reads the tools, scripts and data where they are and writes none of them, + nor anything beside them. `--partial_failure_enable` rewrites the packed description, its output optional and + exit 1 a success, in the tree and embedded, and the tree runs. The conformance tool whose record type is + `$import`ed from a file beside it is written runnable: the description the tree holds for its step runs, given the + conformance job.""" + before = _hashes(PROJECT) | _hashes(DATA / 'cwl-v1.2') + monkeypatch.chdir(tmp_path) + run_local_process(PROJECT / 'relcat_and_config.wic', check=True) + assert _produced() == ['config of A\n', PRINTED] + run_local_process(PROJECT / 'one.wic', '--partial_failure_enable', '--basepath', 'tolerant', check=True) + tree = yaml.safe_load(Path('tolerant/one~relcat.cwl').read_text(encoding='utf-8')) + assert sorted(path.read_text(encoding='utf-8') for path in Path('tolerant').glob('outdir_*/**/*') + if path.is_file()) == [PRINTED] + run_local_process(PROJECT / 'one.wic', '--partial_failure_enable', '--cwl_inline_runtag', '--basepath', 'embedded', + check=True) + embedded = yaml.safe_load(Path('embedded/one.cwl').read_text(encoding='utf-8'))['steps'][0]['run'] + for written in (tree, embedded): + assert _entry(written) == SCRIPT + assert written['outputs']['out']['type'] == 'File?' + assert written['successCodes'] == [0, 1] -def _produced() -> list[str]: - """What the run's output files hold, in order: cwltool and Toil each write them to an outdir of their own.""" - return sorted(path.read_text(encoding='utf-8') for path in Path('autogenerated').glob('outdir_*/**/*') - if path.is_file()) + assert run_cli(monkeypatch, '--yaml', PROJECT / 'schemadef.wic', '--generate_cwl_workflow', '--basepath', + 'schemadef') is None + ran = subprocess.run([sys.executable, '-c', 'import sys, cwltool.main; sys.exit(cwltool.main.main())', + '--outdir', 'out', 'schemadef/schemadef~sd.cwl', str(PROJECT / 'schemadef.yml')], + capture_output=True, text=True, check=False) + assert ran.returncode == 0, ran.stderr + assert json.loads(ran.stdout)['out'] == '1970-01-01T00:00:00Z\n' + assert _hashes(PROJECT) | _hashes(DATA / 'cwl-v1.2') == before FORMS: Final = {'tree': (), 'embedded': ('--cwl_inline_runtag',)} @@ -317,86 +199,21 @@ def test_a_packed_tool_runs_from_the_tree_and_embedded_twice(tmp_path: Path, mon runner: str, form: str) -> None: """Two steps run `relcat`, from the tree's `w~.cwl` and from one embedded document: each prints its included script's line and its default's data.""" - _relcat(tmp_path / 'tools') - write_tree(tmp_path, {'w.wic': 'steps:\n- id: one\n run: tools/relcat.cwl\n- id: two\n run: tools/relcat.cwl\n'}) monkeypatch.chdir(tmp_path) - - run_local_process(tmp_path / 'w.wic', '--cwl_runner', runner, *FORMS[form], check=True) - + run_local_process(PROJECT / 'two.wic', '--cwl_runner', runner, *FORMS[form], check=True) assert _produced() == [PRINTED, PRINTED] -SCHEMADEF: Final = Path(__file__).resolve().parent / 'data' / 'cwl-v1.2' / 'tests' - - -@pytest.mark.needs_cwltool -def test_a_schemadef_tool_with_an_import_is_written_runnable(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """The conformance tool whose record type is `$import`ed from a file beside it: the description the tree - holds for its step runs, given the conformance job.""" - tool = SCHEMADEF / 'schemadef_types_with_import-tool.cwl' - job = json.loads((SCHEMADEF / 'schemadef_types_with_import-job.json').read_text(encoding='utf-8')) - value = job['readgroups_bam'] - value['bam'] = {'class': 'File', 'location': (SCHEMADEF / value['bam']['location']).as_uri()} - write_tree(tmp_path, {'job.yml': yaml.safe_dump({'message': value}), - 'w.wic': yaml.safe_dump({'steps': [{'id': 'sd', 'run': os.path.relpath(tool, tmp_path)}]})}) - monkeypatch.chdir(tmp_path) - assert run_cli(monkeypatch, '--yaml', 'w.wic', '--generate_cwl_workflow') is None - - ran = subprocess.run([sys.executable, '-c', 'import sys, cwltool.main; sys.exit(cwltool.main.main())', - '--outdir', 'out', 'autogenerated/w~sd.cwl', 'job.yml'], capture_output=True, text=True, - check=False) - - assert ran.returncode == 0, ran.stderr - assert json.loads(ran.stdout)['out'] == '1970-01-01T00:00:00Z\n' - - -@pytest.mark.needs_cwltool -def test_a_packed_tool_keeps_the_partial_failure_rewrite_written_and_embedded(tmp_path: Path, - monkeypatch: pytest.MonkeyPatch) -> None: - """`--partial_failure_enable` rewrites the packed description: its output optional, exit 1 a success, in the - tree and embedded; the tree runs.""" - _relcat(tmp_path / 'tools') - write_tree(tmp_path, {'w.wic': 'steps:\n- id: relcat\n run: tools/relcat.cwl\n'}) - monkeypatch.chdir(tmp_path) - - run_local_process(tmp_path / 'w.wic', '--partial_failure_enable', check=True) - tree = yaml.safe_load(Path('autogenerated/w~relcat.cwl').read_text(encoding='utf-8')) - assert _produced() == [PRINTED] - run_local_process(tmp_path / 'w.wic', '--partial_failure_enable', '--cwl_inline_runtag', check=True) - embedded = yaml.safe_load(Path('autogenerated/w.cwl').read_text(encoding='utf-8'))['steps'][0]['run'] - - for written in (tree, embedded): - assert _entry(written) == SCRIPT - assert written['outputs']['out']['type'] == 'File?' - assert written['successCodes'] == [0, 1] - - @pytest.mark.needs_cwltool @EACH_RUNNER def test_a_packed_tool_and_one_as_written_run_wired_by_inference(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, runner: str) -> None: """`make`, packed, feeds `use`, as written, through the edge inference made; `use` prints `make`'s seed.""" - write_tree(tmp_path, MAKE_USE_PROJECT) monkeypatch.chdir(tmp_path) - - run_local_process(tmp_path / 'w.wic', '--cwl_runner', runner, check=True) - + run_local_process(PROJECT / 'make_use.wic', '--cwl_runner', runner, check=True) assert _produced() == ['seed\n', 'seed\n'] -def _cat_config(directory: Path, config: str) -> Path: - """A tool that prints its `config.txt` default, beside it in `directory`.""" - return write_tree(directory, {'config.txt': config, 'echo.cwl': '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: cat -stdout: out.txt -inputs: - config: {type: File, default: {class: File, location: config.txt}, inputBinding: {position: 1}} -outputs: - out: {type: stdout} -'''}) / 'echo.cwl' - - @pytest.mark.needs_cwltool @EACH_RUNNER def test_one_basepath_runs_two_echo_cwl_and_two_config_txt_with_provenance(tmp_path: Path, @@ -404,56 +221,7 @@ def test_one_basepath_runs_two_echo_cwl_and_two_config_txt_with_provenance(tmp_p runner: str) -> None: """Two tools both called `echo.cwl`, each with its own `config.txt` default, run from one base path with provenance; each step prints its own tool's file.""" - _cat_config(tmp_path / 'dataA', 'config of A\n') - _cat_config(tmp_path / 'dataB', 'config of B\n') - write_tree(tmp_path, {'w.wic': 'steps:\n- id: a\n run: dataA/echo.cwl\n- id: b\n run: dataB/echo.cwl\n'}) monkeypatch.chdir(tmp_path) - - run_local_process(tmp_path / 'w.wic', '--cwl_runner', runner, check=True) - + run_local_process(PROJECT / 'pair.wic', '--cwl_runner', runner, check=True) assert _produced() == ['config of A\n', 'config of B\n'] - assert (Path('autogenerated') / 'provenance' / 'w').is_dir() - - -def _hashes(root: Path) -> dict[str, tuple[str, int]]: - return {path.relative_to(root).as_posix(): (hashlib.sha256(path.read_bytes()).hexdigest(), path.stat().st_mtime_ns) - for path in root.rglob('*') if path.is_file()} - - -@pytest.mark.needs_cwltool -def test_nothing_outside_the_basepath_is_written_or_changed(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """Compiling and running packed tools reads the tools, scripts and data where they are and writes none of - them, nor anything beside them.""" - project = tmp_path / 'project' - _relcat(project / 'tools') - _cat_config(project / 'dataA', 'config of A\n') - write_tree(project, {'w.wic': 'steps:\n- id: relcat\n run: tools/relcat.cwl\n- id: a\n run: dataA/echo.cwl\n'}) - before = _hashes(project) - (tmp_path / 'work').mkdir() - monkeypatch.chdir(tmp_path / 'work') - - run_local_process(project / 'w.wic', check=True) - - assert _hashes(project) == before - assert _produced() == ['config of A\n', PRINTED] - - -@pytest.mark.fast -def test_packing_does_not_fetch_a_tools_schemas(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """`$schemas` stay as written: packing a tool never goes to the network for an ontology.""" - ontology = 'http://schemas.invalid/ontology.owl' - fetched: list[str] = [] - fetch_text = DefaultFetcher.fetch_text - - def spy(self: DefaultFetcher, url: str, content_types: list[str] | None = None) -> str: - fetched.append(url) - return fetch_text(self, url, content_types) - - monkeypatch.setattr(DefaultFetcher, 'fetch_text', spy) - tool = yaml.safe_load(PLAIN) - tool['$schemas'] = [ontology] - - packed = utils_cwl.packed(yaml.safe_dump(tool), (tmp_path / 'echo.cwl').as_uri()) - - assert ontology not in fetched - assert packed['$schemas'] == [ontology] + assert (Path('autogenerated') / 'provenance' / 'pair').is_dir() diff --git a/tests/core/test_plain_cwl.py b/tests/core/test_plain_cwl.py index e45a4d4bc..dceeda0ed 100644 --- a/tests/core/test_plain_cwl.py +++ b/tests/core/test_plain_cwl.py @@ -1,12 +1,15 @@ """A plain CWL workflow (top-level `cwlVersion` and `class: Workflow`, or a `$graph` `main`, no Sophios syntax) passes -through `--allow_raw_cwl` to the runner as it is, with `--inputs_file` as its job; everything else compiles.""" +through `--allow_raw_cwl` to the runner as it is, with `--inputs_file` as its job; everything else compiles. The +documents are tests/core/data/plain_cwl, copied into a directory whose name is not a URL: a '#' or a '+' in a path is a +character of the name, as a drive letter is on Windows.""" import io import json import shlex +import shutil import sys from pathlib import Path from types import SimpleNamespace -from typing import Any, Callable +from typing import Any, Callable, Final import pytest import yaml @@ -15,96 +18,12 @@ from sophios import preflight from sophios.backends import RunRequest -from .helpers import no_preflight, write_tree +from .cases import DATA +from .helpers import no_preflight #: Twelve plain Workflows of the CWL v1.2 conformance suite; see its README.md. -CONFORMANCE = Path(__file__).resolve().parent / 'data' / 'cwl-v1.2' -CASES = yaml.safe_load((CONFORMANCE / 'cases.yaml').read_text(encoding='utf-8')) - -PLAIN = '''cwlVersion: v1.2 -class: Workflow -inputs: - message: string -outputs: - copied: - type: File - outputSource: copy/copied -steps: - say: - run: say.cwl - in: - message: message - out: [said] - copy: - run: copy.cwl - in: - text: say/said - out: [copied] -''' - -SAY = '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: echo -inputs: - message: - type: string - inputBinding: {position: 1} -stdout: said.txt -outputs: - said: stdout -''' - -COPY = '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: cat -inputs: - text: - type: File - inputBinding: {position: 1} -stdout: copied.txt -outputs: - copied: stdout -''' - -PACKED = '''cwlVersion: v1.2 -$graph: -- id: say - class: CommandLineTool - baseCommand: echo - inputs: {message: {type: string, inputBinding: {position: 1}}} - stdout: said.txt - outputs: {said: stdout} -- id: {main} - class: Workflow - inputs: {message: string} - outputs: {said: {type: File, outputSource: say/said}} - steps: - say: {run: '#say', in: {message: message}, out: [said]} -''' - -LIST_STEPS = PLAIN.replace('''steps: - say: - run: say.cwl - in: - message: message - out: [said] - copy: - run: copy.cwl -''', '''steps: -- id: say - run: say.cwl - in: - message: message - out: [said] -- id: copy - run: copy.cwl -''').replace(''' in: - text: say/said - out: [copied] -''', ''' in: - text: say/said - out: [copied] -''') +CONFORMANCE: Final = DATA / 'cwl-v1.2' +CASES: Final = yaml.safe_load((CONFORMANCE / 'cases.yaml').read_text(encoding='utf-8')) class _Compiled(BaseException): @@ -112,29 +31,18 @@ class _Compiled(BaseException): arm lets it through.""" -@pytest.fixture(name='compile_path') -def _compile_path(monkeypatch: pytest.MonkeyPatch) -> None: - """The compile path raises `_Compiled` instead of compiling.""" - def compiled(*_args: object, **_kwargs: object) -> None: - raise _Compiled - monkeypatch.setattr(cli.io, 'get_config', compiled) - - @pytest.fixture(name='sophios') def _sophios(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Callable[..., Path]: - """Run the CLI from `tmp_path/cwd` on a document written to `tmp_path/wf/`, or on a path; container engines - are recorded, not reached.""" + """Run the CLI from `tmp_path/cwd` on a document of tests/core/data/plain_cwl, copied into `tmp_path/run #1 c++`, + or on a path; container engines are recorded, not reached.""" monkeypatch.setattr(preflight, 'PLATFORM_LACKS_RUNNERS', None) # Windows has no runner; `--check` would stop there prepared = no_preflight(monkeypatch) - write_tree(tmp_path, {'wf/say.cwl': SAY, 'wf/copy.cwl': COPY, 'jobs/job.yml': 'message: hello\n'}) + shutil.copytree(DATA / 'plain_cwl', tmp_path / 'run #1 c++') (tmp_path / 'cwd').mkdir() monkeypatch.chdir(tmp_path / 'cwd') - def run(text: str | Path, *flags: str, name: str = 'plain.cwl') -> Path: - if isinstance(text, Path): - workflow = text - else: - workflow = write_tree(tmp_path / 'wf', {name: text}) / name + def run(name: str | Path, *flags: str) -> Path: + workflow = name if isinstance(name, Path) else tmp_path / 'run #1 c++' / name monkeypatch.setattr('sys.argv', ['sophios', '--yaml', str(workflow), *flags]) prepared.clear() cli.main() @@ -144,159 +52,88 @@ def run(text: str | Path, *flags: str, name: str = 'plain.cwl') -> Path: @pytest.mark.fast -@pytest.mark.parametrize('text', [PLAIN, LIST_STEPS, PACKED.replace('{main}', 'main'), - PACKED.replace('{main}', "'#main'")], - ids=['steps-map', 'steps-list', 'packed-main', 'packed-hash-main']) -def test_a_plain_cwl_workflow_is_its_own_artifact(sophios: Callable[..., Path], text: str, - capsys: pytest.CaptureFixture[str]) -> None: - """Nothing is compiled or written: the file itself is what a run would use.""" - workflow = sophios(text, '--allow_raw_cwl', '--generate_cwl_workflow') - assert workflow.read_text(encoding='utf-8') == text - assert not Path('autogenerated').exists() +@pytest.mark.parametrize('name', ['plain.cwl', 'list_steps.cwl', 'packed_main.cwl', 'packed_hash_main.cwl']) +def test_a_plain_cwl_workflow_is_what_the_runner_is_given(sophios: Callable[..., Path], tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], name: str) -> None: + """Nothing is compiled or written: the file itself is what a run uses, and run.sh gives the runner it and the job + as they are, not copies under autogenerated/; without --inputs_file there is no job, and the workflow's own + defaults apply. --check stops after the pre-flight. cwltool draws the file itself, as there is no compiled graph + for Sophios to draw. A workflow of the same name compiled earlier left its real-time analyses beside its CWL; + this one is not that workflow, so they do not run.""" + text = (DATA / 'plain_cwl' / name).read_text(encoding='utf-8') + workflow = sophios(name, '--allow_raw_cwl', '--generate_cwl_workflow') + assert workflow.read_text(encoding='utf-8') == text and not Path('autogenerated').exists() assert f'{workflow} is a CWL workflow' in capsys.readouterr().out - -@pytest.mark.fast -@pytest.mark.parametrize(('text', 'name'), [ - (PLAIN.replace('message: message', 'message: !ii hello'), 'plain.cwl'), - ('wic:\n graphviz:\n label: x\n' + PLAIN, 'plain.cwl'), - (PLAIN.replace('cwlVersion: v1.2\n', ''), 'plain.cwl'), - (SAY, 'say_root.cwl'), - (PACKED.replace('{main}', 'main').replace('class: Workflow', 'class: CommandLineTool'), 'plain.cwl'), - ('steps:\n- id: say\n', 'plain.wic'), -], ids=['sophios-tag', 'wic-sidecar', 'no-cwlVersion', 'a-tool', 'packed-tool', 'a-wic-document']) -@pytest.mark.usefixtures('compile_path') -def test_anything_else_is_compiled_as_before(sophios: Callable[..., Path], text: str, name: str) -> None: - """Sophios syntax, a tool, a packed tool or a missing `cwlVersion` keeps the compile path.""" - with pytest.raises(_Compiled): - sophios(text, '--allow_raw_cwl', '--generate_cwl_workflow', name=name) - - -@pytest.mark.fast -@pytest.mark.usefixtures('compile_path') -def test_without_allow_raw_cwl_a_plain_cwl_workflow_is_compiled_as_before(sophios: Callable[..., Path]) -> None: - """Without the flag a plain CWL workflow is not a Sophios exception: it is compiled as today.""" - with pytest.raises(_Compiled): - sophios(PLAIN, '--generate_cwl_workflow') - - -@pytest.mark.fast -@pytest.mark.usefixtures('compile_path') -def test_a_target_that_takes_no_plain_cwl_says_it_compiles_the_workflow(sophios: Callable[..., Path], - capsys: pytest.CaptureFixture[str]) -> None: - """Only the CWL target takes a plain CWL workflow as it is: under another, `--allow_raw_cwl` says the file is - compiled as a Sophios document, then compiles it.""" - with pytest.raises(_Compiled): - sophios(PLAIN, '--allow_raw_cwl', '--target', 'nextflow') - assert ('--allow_raw_cwl: --target nextflow does not take a plain CWL workflow as it is, so ' - in capsys.readouterr().err) - - -@pytest.mark.fast -def test_run_sh_gives_the_runner_the_workflow_and_the_job_as_they_are(sophios: Callable[..., Path], - tmp_path: Path) -> None: - """Both paths are the files given, not copies under autogenerated/. Without --inputs_file there is no job: - the workflow's own defaults apply.""" - job = tmp_path / 'jobs' / 'job.yml' - workflow = sophios(PLAIN, '--allow_raw_cwl', '--generate_run_script', '--inputs_file', str(job)) - command = shlex.split(Path('run.sh').read_text(encoding='utf-8')) - assert command[-2:] == [str(workflow), str(job)] - assert not list(Path('autogenerated').glob('*.cwl')) - sophios(PLAIN, '--allow_raw_cwl', '--generate_run_script') + job = tmp_path / 'run #1 c++' / 'job.yml' + sophios(name, '--allow_raw_cwl', '--check', '--inputs_file', str(job)) + assert 'Checked ' in capsys.readouterr().out and not Path('run.sh').exists() + sophios(name, '--allow_raw_cwl', '--generate_run_script', '--inputs_file', str(job)) + assert shlex.split(Path('run.sh').read_text(encoding='utf-8'))[-2:] == [str(workflow), str(job)] + sophios(name, '--allow_raw_cwl', '--generate_run_script') assert shlex.split(Path('run.sh').read_text(encoding='utf-8'))[-1] == str(workflow) + assert not list(Path('autogenerated').glob('*.cwl')) - -@pytest.mark.fast -def test_check_stops_after_the_pre_flight_of_a_plain_cwl_workflow( - sophios: Callable[..., Path], tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: - sophios(PLAIN, '--allow_raw_cwl', '--check', '--inputs_file', str(tmp_path / 'jobs' / 'job.yml')) - assert 'Checked ' in capsys.readouterr().out - assert not Path('run.sh').exists() - - -@pytest.mark.fast -@pytest.mark.parametrize('workflow', [PLAIN, PACKED.replace('{main}', 'main')], ids=['steps-in-files', 'packed']) -def test_check_reads_a_plain_cwl_workflow_in_a_directory_whose_name_is_not_a_url( - sophios: Callable[..., Path], workflow: str, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: - """A '#' or a '+' in a path is a character of the name, as a drive letter is on Windows.""" - directory = tmp_path / 'run #1 c++' - directory.mkdir() - write_tree(directory, {'plain.cwl': workflow, 'say.cwl': SAY, 'copy.cwl': COPY}) - sophios(directory / 'plain.cwl', '--allow_raw_cwl', '--check') - assert 'Checked ' in capsys.readouterr().out - - -@pytest.mark.fast -def test_check_names_a_missing_input_of_a_plain_cwl_workflow( - sophios: Callable[..., Path], tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: - job = tmp_path / 'jobs' / 'missing.yml' - job.write_text('message: hello\nfile: {class: File, location: nope.txt}\n', encoding='utf-8') - with pytest.raises(SystemExit) as caught: - sophios(PLAIN, '--allow_raw_cwl', '--check', '--inputs_file', str(job)) - assert caught.value.code == 1 - assert (f"input 'file' (from --inputs_file, whose relative paths are read from {job.parent}) names 'nope.txt'" - in capsys.readouterr().err) - - -@pytest.mark.fast -@pytest.mark.parametrize('flag', ['--cwl_inline_runtag', '--cwl_inline_subworkflows', '--partial_failure_enable', - '--docker_remove_entrypoints']) -def test_a_flag_that_rewrites_compiled_cwl_is_an_error_for_a_plain_cwl_workflow( - sophios: Callable[..., Path], flag: str, capsys: pytest.CaptureFixture[str]) -> None: - """There is no compiled CWL to rewrite, so the flag is refused rather than ignored.""" - with pytest.raises(SystemExit) as caught: - sophios(PLAIN, '--allow_raw_cwl', '--generate_run_script', flag) - assert caught.value.code == 2 - assert flag in capsys.readouterr().err - assert not Path('run.sh').exists() - - -@pytest.mark.fast -def test_graphviz_draws_the_plain_cwl_workflow_with_cwltool(sophios: Callable[..., Path], - monkeypatch: pytest.MonkeyPatch) -> None: - """cwltool draws the file itself; there is no compiled graph for Sophios to draw.""" commands: list[list[str]] = [] - monkeypatch.setattr(cli.shutil, 'which', lambda _name: '/usr/bin/dot') - def run(command: list[str], **_k: Any) -> SimpleNamespace: + def drawn(command: list[str], **_k: Any) -> SimpleNamespace: commands.append(command) return SimpleNamespace(stdout=b'') - monkeypatch.setattr(cli.sub, 'run', run) - workflow = sophios(PLAIN, '--allow_raw_cwl', '--generate_cwl_workflow', '--graphviz') + monkeypatch.setattr(cli.shutil, 'which', lambda _name: '/usr/bin/dot') + monkeypatch.setattr(cli.sub, 'run', drawn) + sophios(name, '--allow_raw_cwl', '--generate_cwl_workflow', '--graphviz') assert commands == [[sys.executable, '-m', 'cwltool', '--print-dot', str(workflow)], - ['dot', '-Tsvg', '-o', str(Path('autogenerated') / 'plain.svg')]] + ['dot', '-Tsvg', '-o', str(Path('autogenerated') / f'{workflow.stem}.svg')]] - -@pytest.mark.fast -def test_a_plain_cwl_workflow_does_not_run_the_analyses_of_a_workflow_of_the_same_name( - sophios: Callable[..., Path], monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: - """A `plain.wic` compiled earlier left its real-time analyses beside its CWL; `plain.cwl` is not that workflow.""" - Path('autogenerated').mkdir() - Path('autogenerated/plain.realtime.json').write_text(json.dumps([{ - 'name': 'plain', 'analysis': 'count', 'file_pattern': '*.txt', 'max_times': 2, 'interval': 60, - 'cwl': 'realtime/plain/count_only.cwl', 'inputs': 'realtime/plain/count_only_inputs.yml', - 'root_dir': str(Path.cwd()), 'declared_at': 'plain.wic:3:3'}]), encoding='utf-8') + Path(f'autogenerated/{workflow.stem}.realtime.json').write_text(json.dumps([{ + 'name': workflow.stem, 'analysis': 'count', 'file_pattern': '*.txt', 'max_times': 2, 'interval': 60, + 'cwl': 'realtime/x/count_only.cwl', 'inputs': 'realtime/x/count_only_inputs.yml', + 'root_dir': str(Path.cwd()), 'declared_at': f'{workflow.stem}.wic:3:3'}]), encoding='utf-8') given: list[tuple[Any, ...]] = [] def run(request: RunRequest) -> int: given.append((request.cachedir, request.realtime_plans)) return 0 monkeypatch.setattr(cli.run_local, 'run', run) - - sophios(PLAIN, '--allow_raw_cwl', '--run_local') - + capsys.readouterr() + sophios(name, '--allow_raw_cwl', '--run_local') assert given == [('', ())] assert 'eal-time analysis' not in capsys.readouterr().out -@pytest.mark.needs_cwltool -def test_a_plain_cwl_workflow_runs_as_it_is(sophios: Callable[..., Path], tmp_path: Path) -> None: - """The run is cwltool's run of the file: `say/said` reaches `copy` because nothing renamed `say`.""" - workflow = sophios(PLAIN, '--allow_raw_cwl', '--run_local', '--inputs_file', str(tmp_path / 'jobs' / 'job.yml')) - summary = json.loads(Path('autogenerated/output_plain.json').read_text(encoding='utf-8')) - assert Path(summary['copied']['path']).read_text(encoding='utf-8') == 'hello\n' - assert workflow.read_text(encoding='utf-8') == PLAIN - assert not Path('autogenerated/plain.cwl').exists() +@pytest.mark.fast +def test_anything_else_is_compiled_and_what_a_plain_workflow_cannot_take_stops_it( + sophios: Callable[..., Path], tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str]) -> None: + """Sophios syntax, a `wic:` block, a missing `cwlVersion`, a tool, a packed tool or a `.wic` keeps the compile path, + and so does a plain CWL workflow without the flag. Only the CWL target takes one as it is: under another, + `--allow_raw_cwl` says the file is compiled as a Sophios document, then compiles it. A plain workflow has no + compiled CWL to rewrite, so a flag that would is refused rather than ignored, with nothing written; and --check + names an input its job names that is missing.""" + def compiled(*_args: object, **_kwargs: object) -> None: + raise _Compiled + monkeypatch.setattr(cli.io, 'get_config', compiled) + for name, flags in [('tagged.cwl', ['--allow_raw_cwl']), ('sidecar.cwl', ['--allow_raw_cwl']), + ('no_version.cwl', ['--allow_raw_cwl']), ('say.cwl', ['--allow_raw_cwl']), + ('packed_tool.cwl', ['--allow_raw_cwl']), ('plain.wic', ['--allow_raw_cwl']), + ('plain.cwl', []), ('plain.cwl', ['--allow_raw_cwl', '--target', 'nextflow'])]: + with pytest.raises(_Compiled): + sophios(name, *flags, *([] if 'nextflow' in flags else ['--generate_cwl_workflow'])) + assert ('--allow_raw_cwl: --target nextflow does not take a plain CWL workflow as it is, so ' + in capsys.readouterr().err) + for flag in ('--cwl_inline_runtag', '--cwl_inline_subworkflows', '--partial_failure_enable', + '--docker_remove_entrypoints'): + with pytest.raises(SystemExit) as caught: + sophios('plain.cwl', '--allow_raw_cwl', '--generate_run_script', flag) + assert caught.value.code == 2 and flag in capsys.readouterr().err + assert not Path('run.sh').exists() + with pytest.raises(SystemExit) as caught: + sophios('plain.cwl', '--allow_raw_cwl', '--check', '--inputs_file', + str(tmp_path / 'run #1 c++' / 'missing.yml')) + assert caught.value.code == 1 + assert (f"input 'file' (from --inputs_file, whose relative paths are read from {tmp_path / 'run #1 c++'}) " + "names 'nope.txt'") in capsys.readouterr().err def _portable(value: Any) -> Any: @@ -309,15 +146,23 @@ def _portable(value: Any) -> Any: @pytest.mark.needs_cwltool -@pytest.mark.parametrize('case', CASES, ids=[case['id'] for case in CASES]) -def test_a_conformance_workflow_runs_through_sophios_as_cwltool_runs_it( - sophios: Callable[..., Path], case: dict[str, str], tmp_path: Path) -> None: - """The output object is cwltool's own for the same file and job.""" +def test_a_plain_cwl_workflow_runs_through_sophios_as_cwltool_runs_it(sophios: Callable[..., Path], + tmp_path: Path) -> None: + """The run is cwltool's run of the file: `say/said` reaches `copy` because nothing renamed `say`, and the file is + left as it is. For each conformance workflow the output object is cwltool's own for the same file and job.""" import cwltool.main # pylint: disable=import-outside-toplevel - workflow, job = CONFORMANCE / case['tool'], CONFORMANCE / case['job'] - direct = io.StringIO() - assert cwltool.main.main(['--quiet', '--outdir', str(tmp_path / 'direct'), str(workflow), str(job)], - stdout=direct) == 0 - sophios(workflow, '--allow_raw_cwl', '--run_local', '--inputs_file', str(job)) - summary = json.loads(Path(f'autogenerated/output_{workflow.stem}.json').read_text(encoding='utf-8')) - assert _portable(summary) == _portable(json.loads(direct.getvalue())) + shutil.copytree(DATA / 'plain_cwl', tmp_path / 'plain') # cwltool runs no file in a directory named like a URL + workflow = sophios(tmp_path / 'plain' / 'plain.cwl', '--allow_raw_cwl', '--run_local', '--inputs_file', + str(tmp_path / 'plain' / 'job.yml')) + summary = json.loads(Path('autogenerated/output_plain.json').read_text(encoding='utf-8')) + assert Path(summary['copied']['path']).read_text(encoding='utf-8') == 'hello\n' + assert workflow.read_text(encoding='utf-8') == (DATA / 'plain_cwl' / 'plain.cwl').read_text(encoding='utf-8') + assert not Path('autogenerated/plain.cwl').exists() + for case in CASES: + workflow, job = CONFORMANCE / case['tool'], CONFORMANCE / case['job'] + direct = io.StringIO() + assert cwltool.main.main(['--quiet', '--outdir', str(tmp_path / 'direct'), str(workflow), str(job)], + stdout=direct) == 0, case['id'] + sophios(workflow, '--allow_raw_cwl', '--run_local', '--inputs_file', str(job)) + summary = json.loads(Path(f'autogenerated/output_{workflow.stem}.json').read_text(encoding='utf-8')) + assert _portable(summary) == _portable(json.loads(direct.getvalue())), case['id'] diff --git a/tests/core/test_plugins.py b/tests/core/test_plugins.py index cff81192e..e2f1cbc6f 100644 --- a/tests/core/test_plugins.py +++ b/tests/core/test_plugins.py @@ -7,6 +7,7 @@ import glob import os import re +import shutil from pathlib import Path from types import SimpleNamespace from typing import Any, Final @@ -15,7 +16,6 @@ import yaml from hypothesis import example, given, strategies as st -import sophios.main import sophios.plugins import sophios.post_compile import sophios.preflight @@ -25,37 +25,35 @@ from sophios.wic_types import Yaml from .budgets import budget -from .cases import cases, match -from .helpers import ADAPTERS, run_cli, search_config, write_tree +from .cases import DATA, cases, match +from .helpers import ADAPTERS, run_cli, search_config pytestmark = pytest.mark.package -#: A case's tool, but for what it says itself: a stub, never run. -_STUB: Yaml = {'cwlVersion': CWL_VERSION, 'class': 'CommandLineTool', 'baseCommand': 'true', 'inputs': {}, - 'outputs': {}} - - @pytest.mark.fast -@pytest.mark.parametrize('case', cases('partial_failure', 'tools', 'workflows', 'flags', 'refused', 'written')) -def test_partial_failure_writes_what_each_case_expects(case: Yaml, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str]) -> None: - """Each case of data/partial_failure, compiled by the command line as its header says.""" - write_tree(tmp_path, {f'{name}.cwl': yaml.safe_dump({**_STUB, **tool}, sort_keys=False) - for name, tool in case['tools'].items()}) - write_tree(tmp_path, {f'{name}.wic': text for name, text in case['workflows'].items()}) - # file_watchers holds cwl_subinterpreter, the step a-real-time-analysis declares its analysis with. - search_config(tmp_path / 'config.json', [tmp_path, ADAPTERS / 'file_watchers'], [tmp_path]) - monkeypatch.chdir(tmp_path) - code = run_cli(monkeypatch, '--yaml', 'w.wic', '--config_file', 'config.json', '--generate_cwl_workflow', - *case.get('flags', ['--partial_failure_enable'])) - if 'refused' in case: - assert code == 2 and case['refused'] in capsys.readouterr().err - return - assert code is None - for path, expected in case['written'].items(): - written = yaml.safe_load((tmp_path / 'autogenerated' / path).read_text(encoding='utf-8')) - assert match(expected, written), (path, written) +def test_partial_failure_and_entrypoint_removal_write_what_their_example_states( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + """Each run of tests/core/data/partial_failure/expected.yaml, compiled by the command line with its flags; the + images under --docker_remove_entrypoints are built after the pre-flight pulls the originals, so the CWL the runner + reads names the built ones.""" + project = tmp_path / 'project' + shutil.copytree(DATA / 'partial_failure', project, ignore=shutil.ignore_patterns('expected.yaml')) + # file_watchers holds cwl_subinterpreter, the step a real-time analysis is declared with. + search_config(project / 'config.json', [project, ADAPTERS / 'file_watchers'], [project]) + monkeypatch.setattr(sophios.preflight, 'prepare', lambda *_a, **_k: None) + monkeypatch.setattr(sophios.post_compile.docker, 'from_env', _no_images) + monkeypatch.chdir(project) + for run in yaml.safe_load((DATA / 'partial_failure' / 'expected.yaml').read_text(encoding='utf-8')): + shutil.rmtree(project / 'autogenerated', ignore_errors=True) + code = run_cli(monkeypatch, '--yaml', 'w.wic', '--config_file', 'config.json', *run['flags']) + if 'refused' in run: + assert code == 2 and run['refused'] in capsys.readouterr().err, run['why'] + continue + assert code is None, run['why'] + for path, expected in run['written'].items(): + written = yaml.safe_load((project / 'autogenerated' / path).read_text(encoding='utf-8')) + assert match(expected, written), (run['why'], path, written) #: An output's type in each form CWL writes one: one string, with `?` or `[]` or neither, a union with or without @@ -242,41 +240,13 @@ def test_every_image_the_runner_pulls_gets_the_noentrypoint_tag(document: Yaml) assert sophios.plugins.dockerPull_append_noentrypoint(updated) == updated -def _docker_pulls(document: Any) -> list[str]: - """Every `dockerPull` in `document`, at any depth.""" - if isinstance(document, dict): - own = [document['dockerPull']] if isinstance(document.get('dockerPull'), str) else [] - return own + [pull for value in document.values() for pull in _docker_pulls(value)] - if isinstance(document, list): - return [pull for value in document for pull in _docker_pulls(value)] - return [] - - def _no_images() -> SimpleNamespace: """A docker client with no images, so `--docker_remove_entrypoints` builds nothing.""" return SimpleNamespace(images=SimpleNamespace(list=lambda: [])) -@pytest.mark.fast -def test_the_cli_runs_the_noentrypoint_tags(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """The images are built after the pre-flight pulls the originals; the CWL the runner reads - must then name the built ones.""" - monkeypatch.setattr(sophios.preflight, 'prepare', lambda *_a, **_k: None) - monkeypatch.setattr(sophios.post_compile.docker, 'from_env', _no_images) - monkeypatch.chdir(tmp_path) - workflow = tmp_path / 'touch_one.wic' - workflow.write_text('steps:\n touch:\n in:\n filename: !ii empty.txt\n', encoding='utf-8') - monkeypatch.setattr('sys.argv', ['sophios', '--yaml', str(workflow), '--generate_run_script', - '--docker_remove_entrypoints']) - sophios.main.main() - pulls = [pull for written in sorted((tmp_path / 'autogenerated').glob('*.cwl')) - for pull in _docker_pulls(yaml.safe_load(written.read_text(encoding='utf-8')))] - # touch.cwl runs in docker.io/library/debian:bookworm-slim - assert pulls == ['docker.io/library/debian:bookworm-slim-noentrypoint'] - - -#: A file every tool case writes for each of its `files`; a workflow case writes `steps: {}`. -_TOOL = 'cwlVersion: v1.2\nclass: CommandLineTool\nbaseCommand: true\ninputs: {}\noutputs: {}\n' +#: The file a case lays out under each of its `files`, by kind. +_LAID_OUT: Final = {'tool': DATA / 'discovery' / 'laid_out.cwl', 'workflow': DATA / 'discovery' / 'laid_out.wic'} #: A warning `_warn_duplicates` prints, read back as its stem, namespace, count, files and the file used. _WARNING = re.compile(r"Warning! (tool|workflow) '(.+)' in namespace '(.+)' is defined by (\d+) files:\n" @@ -319,25 +289,34 @@ def _warnings(err: str, base: Path, kind: str) -> list[list[Any]]: @pytest.mark.fast -@pytest.mark.parametrize('case', cases('discovery', 'files', 'found', 'kinds', 'roots', 'warnings', 'links')) -def test_each_stem_resolves_to_the_last_file_found(case: Yaml, tmp_path_factory: pytest.TempPathFactory, +def test_each_stem_resolves_to_the_last_file_found(tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: """Each case of data/discovery (see its README), under the filesystem's own listing and under it reversed: - discovery must not depend on it.""" - base = tmp_path_factory.mktemp('layout') # not tmp_path, which holds the case id that biobb_md and _inputs read + discovery must not depend on it. A search path that holds no tool says so on stdout.""" + for case in (param.values[0] for param in cases('discovery', 'files', 'found', 'kinds', 'roots', 'warnings', + 'links')): + with monkeypatch.context() as listing_patches: + _resolves(case, tmp_path_factory.mktemp('layout'), listing_patches, capsys) + empty = tmp_path_factory.mktemp('empty') + assert not sophios.plugins.get_tools_cwl({'search_paths_cwl': {'global': [str(empty)]}}) + assert f'No cwl files found in {empty}' in capsys.readouterr().out + + +def _resolves(case: Yaml, base: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + """One discovery case, laid out in `base`: not a test's tmp_path, which holds the case id that biobb_md and + _inputs read.""" for link, target in case.get('links', {}).items(): (base / link).symlink_to(base / target, target_is_directory=True) for kind in case.get('kinds', ['tool']): - extension = 'cwl' if kind == 'tool' else 'wic' for name in case['files']: (base / name).parent.mkdir(parents=True, exist_ok=True) - (base / f'{name}.{extension}').write_text(_TOOL if kind == 'tool' else 'steps: {}\n', encoding='utf-8') + shutil.copyfile(_LAID_OUT[kind], base / f'{name}{_LAID_OUT[kind].suffix}') roots = {ns: [str(base / root) for root in paths] for ns, paths in case.get('roots', {'global': ['']}).items()} for listing in (_LISTED, _listed_in_reverse): monkeypatch.setattr(glob, 'glob', listing) found = _found(kind, roots, base) - assert found == case['found'] + assert found == case['found'], case['id'] if kind == 'tool': assert [list(stems) for stems in found.values()] == [list(stems) for stems in case['found'].values()] out, err = capsys.readouterr() diff --git a/tests/core/test_provenance.py b/tests/core/test_provenance.py index e01713c1a..8c5b54742 100644 --- a/tests/core/test_provenance.py +++ b/tests/core/test_provenance.py @@ -1,50 +1,16 @@ -"""A run's provenance record holds every document Sophios wrote for it, and nothing Sophios added fails it.""" +"""A run's provenance record holds every document Sophios wrote for it, and nothing Sophios added fails it. The +workflows are tests/core/data/provenance_runs, run where they are from a working directory of the test's own.""" from pathlib import Path +from typing import Final import pytest +from .cases import DATA from .helpers import EACH_RUNNER, run_local_process pytestmark = pytest.mark.package -SAY = '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: echo -stdout: out.txt -inputs: {message: {type: string, inputBinding: {position: 1}}} -outputs: {out: {type: File, outputBinding: {glob: out.txt}}} -''' -PAIR = '''steps: -- id: hello - run: say.cwl - in: {message: !ii a} -- id: shout - run: say.cwl - in: {message: !ii b} -''' -OUTER = '''steps: -- id: pair - run: pair.wic -- id: b - run: say.cwl - in: {message: !ii c} -''' -GREETING = '''steps: -- id: hello - run: say.cwl - in: {message: !ii hi} -- id: pair - run: pair.wic -- id: outer - run: outer.wic -''' -OTHER = '''steps: -- id: hello - run: say.cwl - in: {message: !ii there} -- id: pair - run: pair.wic -''' +PROJECT: Final = DATA / 'provenance_runs' def _snapshot(root: str) -> set[str]: @@ -57,12 +23,9 @@ def test_every_step_file_is_in_the_provenance_snapshot(monkeypatch: pytest.Monke runner: str) -> None: """Two roots in one base path, each calling `pair.wic` directly and through `outer.wic`: each run's snapshot holds its root and every `~
.cwl`, the nested ones too.""" - for name, text in (('say.cwl', SAY), ('pair.wic', PAIR), ('outer.wic', OUTER), - ('greeting.wic', GREETING), ('other.wic', OTHER)): - (tmp_path / name).write_text(text, encoding='utf-8') monkeypatch.chdir(tmp_path) for root in ('greeting', 'other'): - run_local_process(tmp_path / f'{root}.wic', '--cwl_runner', runner, check=True) + run_local_process(PROJECT / f'{root}.wic', '--cwl_runner', runner, check=True) pair = ['pair.cwl', 'pair~hello.cwl', 'pair~shout.cwl'] expected = { 'greeting': {'greeting.cwl', 'greeting~hello.cwl', *(f'greeting~{name}' for name in pair), @@ -73,21 +36,14 @@ def test_every_step_file_is_in_the_provenance_snapshot(monkeypatch: pytest.Monke assert files <= _snapshot(root), sorted(files - _snapshot(root)) -#: The ontology from edamontology's default branch: a URL Sophios never wrote, with the basename of the one it did. -EDAM_MAIN = 'https://raw.githubusercontent.com/edamontology/edamontology/main/EDAM_dev.owl' - - @pytest.mark.needs_cwltool @EACH_RUNNER def test_a_wic_with_its_own_edam_schemas_entry_runs_with_provenance(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, runner: str) -> None: """The root's `$schemas` is the `.wic`'s, so no second `EDAM_dev.owl` meets it in the provenance record.""" - (tmp_path / 'say.cwl').write_text(SAY, encoding='utf-8') - (tmp_path / 'wf.wic').write_text(f"$schemas: ['{EDAM_MAIN}']\nsteps:\n- id: hi\n run: say.cwl\n" - ' in: {message: !ii hi}\n', encoding='utf-8') monkeypatch.chdir(tmp_path) - run_local_process(tmp_path / 'wf.wic', '--cwl_runner', runner, check=True) # exits on a failed run - assert 'wf.cwl' in _snapshot('wf') + run_local_process(PROJECT / 'edam_root.wic', '--cwl_runner', runner, check=True) # exits on a failed run + assert 'edam_root.cwl' in _snapshot('edam_root') @pytest.mark.needs_cwltool @@ -95,9 +51,6 @@ def test_a_wic_with_its_own_edam_schemas_entry_runs_with_provenance(monkeypatch: def test_an_embedded_tool_with_its_own_edam_schemas_entry_runs_with_provenance(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, runner: str) -> None: """Embedded, a tool's `$schemas` moves up to the one document, which holds no other `EDAM_dev.owl`.""" - (tmp_path / 'say.cwl').write_text(f"$namespaces: {{edam: https://edamontology.org/}}\n$schemas: ['{EDAM_MAIN}']\n" - + SAY, encoding='utf-8') - (tmp_path / 'wf.wic').write_text('steps:\n- id: hi\n run: say.cwl\n in: {message: !ii hi}\n', encoding='utf-8') monkeypatch.chdir(tmp_path) - run_local_process(tmp_path / 'wf.wic', '--cwl_runner', runner, '--cwl_inline_runtag', check=True) - assert 'wf.cwl' in _snapshot('wf') + run_local_process(PROJECT / 'edam_tool.wic', '--cwl_runner', runner, '--cwl_inline_runtag', check=True) + assert 'edam_tool.cwl' in _snapshot('edam_tool') diff --git a/tests/core/test_python_api_from_wic.py b/tests/core/test_python_api_from_wic.py index 8a246d65c..e69f7ae78 100644 --- a/tests/core/test_python_api_from_wic.py +++ b/tests/core/test_python_api_from_wic.py @@ -2,6 +2,7 @@ properties: a file the file door compiles is refused with `api006` alone or compiles to equal output, and `write_wic` round-trips.""" # pylint: disable=redefined-outer-name # `corpus_registry` is a pytest fixture +import shutil import tempfile from dataclasses import replace from functools import lru_cache @@ -26,12 +27,11 @@ from .ast_strategies import SUBWORKFLOW_BODIES, documents from .budgets import budget -from .cases import case_dirs, diagnostic, match +from .cases import DATA, case_dirs, diagnostic, match from .equivalence import Strength, equivalent from .helpers import ADAPTERS, REPO_ROOT, shipped_tools from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS, clt from .test_examples import _is_includer_fragment, yml_paths_tuples_not_large -from .test_frontdoor import PYTHON_SCRIPT # pylint: disable-next=unused-import # `corpus_registry` is a pytest fixture from .test_setup import CorpusRegistry, corpus_registry from .wic_reading import read_wic @@ -306,19 +306,13 @@ def test_a_python_script_step_is_api006(tmp_path: Path, monkeypatch: pytest.Monk """A tool generated from a script has no `Step`: the message says to build it with `tool_builder`. The script's generator imports `workflow_types` relative to the working directory, so the - fixture supplies that sibling file, as `test_frontdoor` does. + project, tests/core/data/frontdoor/script, holds that sibling file. """ - types = tmp_path / 'sophios' / 'examples' / 'scripts' - types.mkdir(parents=True) - (types / 'workflow_types.py').write_text( - "string = {'type': 'string', 'format': 'edam:format_2330'}\n", encoding='utf-8') - work = tmp_path / 'work' - work.mkdir() - (work / 'my_script.py').write_text(PYTHON_SCRIPT, encoding='utf-8') + shutil.copytree(DATA / 'frontdoor' / 'script', tmp_path / 'script') + work = tmp_path / 'script' / 'work' monkeypatch.chdir(work) with pytest.raises(SophiosError) as caught: - _from_wic(work, root='steps:\n- id: python_script\n in:\n script: !ii my_script.py\n' - ' name: !ii made.txt\n') + _from_wic(work, root=(work / 'compile.wic').read_text(encoding='utf-8')) assert [(item.code, 'tool_builder' in item.message) for item in caught.value.diagnostics] == [ (SophiosErrorCode.NO_PYTHON_SPELLING, True)] diff --git a/tests/core/test_quiet.py b/tests/core/test_quiet.py index cd80d0a38..8652747fa 100644 --- a/tests/core/test_quiet.py +++ b/tests/core/test_quiet.py @@ -1,8 +1,8 @@ """`--quiet` and `run(run_args_dict={'quiet': ...})` hide cwltool's own log and nothing else: the compiled CWL is -unchanged, each tool's messages print as the run goes, and a failed step is named with how it ended.""" -import json +unchanged, each tool's messages print as the run goes, and a failed step is named with how it ended. The project is +tests/core/data/quiet.""" import shlex -import sys +import shutil from pathlib import Path from typing import Any, Final, Iterator, cast @@ -10,75 +10,27 @@ import yaml from sophios import run_local -from sophios.api.python import _workflow_runtime as python_runtime from sophios.api.python.workflow import Step, Workflow -from .helpers import EACH_RUNNER, no_preflight, run_cli, run_local_process, search_config, write_tree +from .cases import DATA +from .helpers import EACH_RUNNER, no_preflight, run_cli, run_local_process, search_config pytestmark = pytest.mark.package -#: Prints a line on each stream, and fails when told to. -SAY: Final = '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: [sh, -c] -arguments: ['echo "$0 out"; echo "$0 err" >&2; exit $1'] -inputs: - word: {type: string, default: say, inputBinding: {position: 1}} - status: {type: int, default: 0, inputBinding: {position: 2}} -outputs: {} -''' -#: Names its own stdout. -OWN: Final = '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: echo -stdout: own.txt -inputs: {} -outputs: {out: {type: File, outputBinding: {glob: own.txt}}} -''' -PAIR: Final = '''steps: -- id: say -- id: local - run: local/local.cwl -''' -#: A search-path tool (`say`, `own`), a tool named by a `run:` path, an inline body and a call. -WORKFLOW: Final = '''steps: -- id: say -- id: local - run: local/local.cwl -- id: inline - run: - cwlVersion: v1.2 - class: CommandLineTool - baseCommand: echo - inputs: {} - outputs: {} -- id: pair - run: pair.wic -- id: own -''' ADDRESSES: Final = ('say', 'local', 'inline', 'pair~say', 'pair~local', 'own') @pytest.fixture(name='project') def _project(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: - """`w.wic` and the tools it runs, with a config that searches `tools/`. Nothing is pulled.""" + """A copy of the project, with a config that searches `tools/`. Nothing is pulled.""" root = tmp_path / 'project' - write_tree(root, {'tools/say.cwl': SAY, 'tools/own.cwl': OWN, 'local/local.cwl': SAY, - 'pair.wic': PAIR, 'w.wic': WORKFLOW}) + shutil.copytree(DATA / 'quiet', root) search_config(root / 'config.json', [root / 'tools'], [root]) no_preflight(monkeypatch) monkeypatch.chdir(root) return root -def _sophios(monkeypatch: pytest.MonkeyPatch, *flags: str) -> list[str]: - """`sophios --yaml w.wic `; the runner commands it would run.""" - commands: list[str] = [] - monkeypatch.setattr(run_local, 'generate_run_script', commands.append) - assert run_cli(monkeypatch, '--yaml', 'w.wic', '--config_file', 'config.json', *flags) is None - return commands - - def _tools(document: dict[str, Any], address: str = '') -> Iterator[tuple[str, dict[str, Any]]]: """Each embedded tool of `document`, with the address of the step that runs it.""" for step in document['steps']: @@ -93,96 +45,53 @@ def _read(path: Path) -> dict[str, Any]: return cast(dict[str, Any], yaml.safe_load(path.read_text(encoding='utf-8'))) -def _tree(basepath: Path) -> dict[str, Any]: - """Each tool Sophios wrote under `basepath`, by its step's address.""" - return {address: _read(basepath / f'w~{address}.cwl') for address in ADDRESSES} - - -def _python_workflow(project: Path) -> Workflow: - say = Step(clt_path=project / 'tools' / 'say.cwl') - own = Step(clt_path=project / 'tools' / 'own.cwl') - inline = Step.from_cwl_document(yaml.safe_load(SAY), process_name='inline') - return Workflow([say, own, inline], 'w') - - -@pytest.mark.fast -def test_quiet_does_not_change_the_compiled_cwl(project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """A search-path tool, one named by a `run:` path, an inline body and the tools of a call are written as - they are, compiled or run, quiet or not: no stream is named that the tool does not name itself.""" - _sophios(monkeypatch, '--generate_cwl_workflow', '--basepath', 'plain') - _sophios(monkeypatch, '--generate_cwl_workflow', '--quiet', '--basepath', 'compiled') - _sophios(monkeypatch, '--generate_run_script', '--quiet', '--basepath', 'run') - plain = _tree(project / 'plain') - assert _tree(project / 'compiled') == plain - assert _tree(project / 'run') == plain - assert {address: tool.get('stdout') for address, tool in plain.items()} == { - 'say': None, 'local': None, 'inline': None, 'pair~say': None, 'pair~local': None, 'own': 'own.txt'} - assert not any('stderr' in tool for tool in plain.values()) - - -@pytest.mark.fast -def test_a_quiet_python_run_writes_what_compile_returns(project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """`run()` is quiet by default, and the document it writes is the one `compile()` returns.""" - workflow = _python_workflow(project) - monkeypatch.setattr(python_runtime.run_local, 'generate_run_script', lambda cmdline: None) - workflow.run(basepath='py', run_args_dict={'generate_run_script': 'yes'}) - written = _read(project / 'py' / 'w.cwl') - assert written == workflow.compile().cwl_workflow - assert {address: tool.get('stdout') for address, tool in _tools(written)} == { - 'say': None, 'own': 'own.txt', 'inline': None} - - @pytest.mark.fast @EACH_RUNNER -@pytest.mark.parametrize('quiet', [True, False]) -def test_only_a_quiet_cwltool_run_is_given_quiet(project: Path, monkeypatch: pytest.MonkeyPatch, - runner: str, quiet: bool) -> None: - """From the command line and from `run()`: cwltool gets `--quiet` only when the run is quiet, Toil never, - and neither runner is told to keep a tool's streams anywhere.""" - flags = ['--quiet'] if quiet else [] - cli = _sophios(monkeypatch, '--generate_run_script', '--cwl_runner', runner, *flags)[0] +def test_quiet_changes_only_what_cwltool_is_told(project: Path, monkeypatch: pytest.MonkeyPatch, runner: str) -> None: + """A search-path tool, one named by a `run:` path, an inline body and the tools of a call are written as they are, + compiled or run, quiet or not: no stream is named that the tool does not name itself. `run()` is quiet by default, + and the document it writes is the one `compile()` returns. From the command line and from `run()`, cwltool gets + `--quiet` only when the run is quiet, Toil never, and neither runner is told to keep a tool's streams anywhere.""" commands: list[str] = [] - monkeypatch.setattr(python_runtime.run_local, 'generate_run_script', commands.append) - _python_workflow(project).run(basepath='py', run_args_dict={'generate_run_script': 'yes', 'cwl_runner': runner, - 'quiet': 'yes' if quiet else 'no'}) - for cmdline in (cli, commands[0]): + monkeypatch.setattr(run_local, 'generate_run_script', commands.append) + say, own = Step(clt_path=project / 'tools' / 'say.cwl'), Step(clt_path=project / 'tools' / 'own.cwl') + inline = Step.from_cwl_document(_read(project / 'local' / 'local.cwl'), process_name='inline') + for quiet in (True, False): + flags = ['--quiet'] if quiet else [] + for mode, base in (('--generate_cwl_workflow', 'compiled'), ('--generate_run_script', 'run')): + assert run_cli(monkeypatch, '--yaml', 'w.wic', '--config_file', 'config.json', mode, *flags, + '--cwl_runner', runner, '--basepath', f'{base}_{quiet}') is None + workflow = Workflow([say, own, inline], 'w') + workflow.run(basepath=f'py_{quiet}', run_args_dict={'generate_run_script': 'yes', 'cwl_runner': runner, + 'quiet': 'yes' if quiet else 'no'}) + assert _read(project / f'py_{quiet}' / 'w.cwl') == workflow.compile().cwl_workflow + assert {address: tool.get('stdout') for address, tool in _tools(_read(project / f'py_{quiet}' / 'w.cwl'))} \ + == {'say': None, 'own': 'own.txt', 'inline': None} + trees = {base: {address: _read(project / base / f'w~{address}.cwl') for address in ADDRESSES} + for base in ('compiled_True', 'compiled_False', 'run_True', 'run_False')} + assert all(tree == trees['compiled_False'] for tree in trees.values()) + assert {address: tool.get('stdout') for address, tool in trees['compiled_False'].items()} == { + 'say': None, 'local': None, 'inline': None, 'pair~say': None, 'pair~local': None, 'own': 'own.txt'} + assert not any('stderr' in tool for tool in trees['compiled_False'].values()) + assert len(commands) == 4 + for cmdline, quiet in zip(commands, (True, True, False, False)): words = shlex.split(cmdline) - assert ('--quiet' in words) is (quiet and runner == 'cwltool') - assert '--log-dir' not in words + assert ('--quiet' in words) is (quiet and runner == 'cwltool') and '--log-dir' not in words @pytest.mark.needs_cwltool -def test_a_failing_step_is_named_with_its_status_below_its_own_messages(monkeypatch: pytest.MonkeyPatch, - tmp_path: Path) -> None: - """A quiet run still prints what the step wrote, and the summary names the step and how it ended.""" - write_tree(tmp_path, {'say.cwl': SAY, - 'fail.wic': 'steps:\n- id: say\n run: say.cwl\n in: {word: !ii boom, status: !ii 3}\n'}) +def test_a_quiet_run_prints_each_steps_messages_and_keeps_the_files_it_names(monkeypatch: pytest.MonkeyPatch, + tmp_path: Path) -> None: + """A quiet run still prints what the step wrote, and the summary names a failed step and how it ended. A tool that + writes `system.pdb` itself and also names it as its empty stdout gets the file it wrote.""" monkeypatch.chdir(tmp_path) - - ran = run_local_process(tmp_path / 'fail.wic', '--quiet', capture_output=True) - + ran = run_local_process(DATA / 'quiet' / 'fail.wic', '--quiet', capture_output=True) assert ran.returncode != 0 assert 'boom err\n' in ran.stderr assert ran.stderr.endswith( "Failure! step 'say' exited with status 3. Its own messages are above, under its name.\n") - -@pytest.mark.needs_cwltool -def test_a_quiet_run_keeps_a_file_the_tool_names_as_its_stdout(monkeypatch: pytest.MonkeyPatch, - tmp_path: Path) -> None: - """A tool that writes `system.pdb` itself and also names it as its empty stdout gets the file it wrote.""" - write = "import sys; open(sys.argv[1], 'w').write('ATOM 1\\\\n')" - write_tree(tmp_path, {'probe.cwl': f'''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: [{json.dumps(sys.executable)}, -c, "{write}"] -inputs: {{output_pdb_path: {{type: string, default: system.pdb, inputBinding: {{position: 1}}}}}} -outputs: {{output_pdb_path: {{type: File, outputBinding: {{glob: $(inputs.output_pdb_path)}}}}}} -stdout: $(inputs.output_pdb_path) -''', 'probe.wic': 'steps:\n- id: probe\n run: probe.cwl\n'}) - monkeypatch.chdir(tmp_path) - - ran = run_local_process(tmp_path / 'probe.wic', '--quiet', capture_output=True) - + ran = run_local_process(DATA / 'quiet' / 'probe.wic', '--quiet', '--basepath', 'probe', capture_output=True) assert ran.returncode == 0, ran.stdout + ran.stderr - (output,) = (tmp_path / 'autogenerated').glob('outdir_*/**/system.pdb') + (output,) = Path('probe').glob('outdir_*/**/system.pdb') assert output.read_text(encoding='utf-8') == 'ATOM 1\n' diff --git a/tests/core/test_realtime.py b/tests/core/test_realtime.py index 48f5d4d58..170222211 100644 --- a/tests/core/test_realtime.py +++ b/tests/core/test_realtime.py @@ -1,6 +1,9 @@ -"""Real-time analysis: a `cwl_subinterpreter` step declares an analysis Sophios runs beside the workflow.""" +"""Real-time analysis: a `cwl_subinterpreter` step declares an analysis Sophios runs beside the workflow. The analyses +of tests/core/data/realtime compile, are written and run as stated there; the watcher is driven over a stand-in for +cwltool's cachedir and a stand-in analysis.""" import json import os +import shutil import string import sys import time @@ -16,18 +19,17 @@ from sophios import realtime, run_local from sophios.backends import RunRequest -from sophios.cli import default_compilation_settings from sophios.input_output import NoAliasDumper from sophios.ir.realtime import Declaration from sophios.lang.diagnostics import SophiosError from sophios.lang.error_codes import SophiosErrorCode -from sophios.realtime import Analysis from sophios.wic_types import StepId, Tool, Tools, Yaml from .budgets import budget +from .cases import DATA, match, printed from .fake_runner import POSIX_ONLY, install -from .helpers import ADAPTERS, live_workflow, no_preflight, run_cli, search_config, write_tree -from .hermetic import compile_hermetic, subworkflow_step +from .helpers import ADAPTERS, live_workflow, no_preflight, run_cli, search_config +from .hermetic import compile_hermetic from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS pytestmark = pytest.mark.package @@ -44,14 +46,6 @@ def _ii(value: Any) -> Yaml: return {'wic_inline_input': value} -def _declaration_step(**overrides: Any) -> Yaml: - """A well-formed declaration: count lines of `a.txt` whenever a `*.txt` changes.""" - bindings: Yaml = {'file_pattern': _ii('*.txt'), 'cwl_tool': _ii('count'), 'max_times': _ii('3'), - 'config': _ii({'in': {'file': 'a.txt'}})} - bindings.update(overrides) - return {'id': 'cwl_subinterpreter', 'in': {key: value for key, value in bindings.items() if value is not None}} - - def _declaration_lines(document: Yaml) -> list[int]: """The line each declaration step starts on in `document` as `hermetic.bundle` writes it.""" text = yaml.dump(document, Dumper=NoAliasDumper, sort_keys=False, line_break='\n', indent=2) @@ -133,100 +127,73 @@ def test_a_declaration_is_returned_instead_of_emitted_or_is_wic044_at_each_port( for line, held in zip(lines, declarations)] -@pytest.mark.fast -def test_a_declaration_in_a_subworkflow_is_taken_out_and_its_workflow_may_be_left_empty() -> None: - """A subworkflow whose only step is a declaration is emitted with no steps; the declaration names it.""" - producer = {'id': 'mk_file', 'in': {'name': _ii('a.txt')}} - analysis = subworkflow_step('watch.wic', {'steps': [_declaration_step(interval=_ii(5))]}) - result = compile_hermetic({'steps': [producer, analysis]}, tools=TOOLS) - - (child,) = [child for child in result.artifact.children if child.namespace == ('watch',)] - assert child.cwl['steps'] == [] - assert [(d.document, d.interval) for d in result.realtime] == [('watch', 5)] - - -def _analyses(document: Yaml, yml_paths: dict[str, dict[str, Path]] | None = None) -> tuple[Analysis, ...]: - """Compile `document` and then the analyses it declares, as the CLI does.""" - return realtime.compile_analyses(compile_hermetic(document, tools=TOOLS).realtime, yml_paths or {}, TOOLS, - default_compilation_settings()) - - -def _only_analysis(document: Yaml, yml_paths: dict[str, dict[str, Path]] | None = None) -> Analysis: - """The one analysis `document` declares.""" - analyses = _analyses(document, yml_paths) - assert len(analyses) == 1 - return analyses[0] - - -def _file_inputs(job: Yaml) -> list[str]: - """The location of each job input that is a File, sorted.""" - return sorted(value['location'] for value in job.values() - if isinstance(value, dict) and value.get('class') == 'File') - +REALTIME: Final = DATA / 'realtime' -@pytest.mark.fast -def test_a_tool_analysis_compiles_with_every_config_input_a_literal() -> None: - """A plain file name and a nested `!ii` in `config: in:` are both literals of the analysis step. - - The shape of the corpus `npt_amber.wic` declaration: read as written, `a.txt` in an - `in:` would be an edge reference and fail with wic011. - """ - config = _ii({'in': {'file': 'a.txt', 'name': _ii('b.txt')}}) - analysis = _only_analysis({'steps': [_declaration_step(cwl_tool=_ii('xform'), config=config)]}) - assert analysis.name == 'oracle' - assert _file_inputs(analysis.artifact.job_inputs) == ['a.txt'] - assert 'b.txt' in analysis.artifact.job_inputs.values() +def _project(tmp_path: Path) -> Path: + """A copy of tests/core/data/realtime, and a config that finds its tools, its workflows and the adapter.""" + root = tmp_path / 'project' + shutil.copytree(REALTIME, root, ignore=shutil.ignore_patterns('expected.yaml')) + search_config(root / 'config.json', [root / 'tools', ADAPTER_PATH.parent], [root]) + return root @pytest.mark.fast -def test_a_wic_analysis_compiles_with_its_config_as_the_sidecar_of_its_steps(tmp_path: Path) -> None: - """A `.wic` analysis is configured per step, as `wic: steps:`; the shape of `cwl_subinterpreter_protein.wic`.""" - (tmp_path / 'measure.wic').write_text(yaml.safe_dump({'steps': [{'id': 'count'}, {'id': 'count'}]}), - encoding='utf-8') - config = _ii({'(1, count)': {'in': {'file': 'a.txt'}}, '(2, count)': {'in': {'file': 'b.txt'}}}) - declaration = _declaration_step(cwl_tool=_ii('measure.wic'), config=config) - analysis = _only_analysis({'steps': [declaration]}, {'global': {'measure': tmp_path / 'measure.wic'}}) +# pylint: disable-next=too-many-locals +def test_declared_analyses_are_taken_out_compiled_and_written_on_their_own_from_either_door( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + """The analyses of declared.wic, as tests/core/data/realtime/expected.yaml states them: a tool's `config: in:` + values are literals of the analysis, a .wic analysis is configured per step, a subworkflow whose only step is a + declaration is emitted with no steps, and a relative `dockerFile` `$include` is the file beside the tool, wherever + the analysis is written. With no analyses, no manifest is left. In Python, a `Step` built from the adapter is a + declaration: never emitted, compiled and pulled by `run`, the analysis written as the workflow is, one document + with every process embedded, and its job; a `.wic` named by `cwl_tool` is found through `run(workflow_paths=...)`, + as `from_wic` finds a nested one, and without them is wic044 naming the wic013 it met.""" + root = _project(tmp_path) + expected = yaml.safe_load((REALTIME / 'expected.yaml').read_text(encoding='utf-8').replace('{tmp}', str(root))) + monkeypatch.chdir(root) + assert run_cli(monkeypatch, '--yaml', 'declared.wic', '--config_file', 'config.json', + '--generate_cwl_workflow') is None + written = root / 'autogenerated' + for directory, names in expected['files'].items(): + assert sorted(path.name for path in (written / directory).iterdir()) == names, directory + for name, holds in expected['written'].items(): + assert match(holds, yaml.safe_load((written / name).read_text(encoding='utf-8'))), name + assert not realtime.write((), written, 'declared', root) + assert not realtime.manifest_path(written, 'declared').exists() + capsys.readouterr() + assert run_cli(monkeypatch, '--yaml', 'refused.wic', '--config_file', 'config.json', '--generate_cwl_workflow', + '--diagnostics', 'json') == 1 + assert match(expected['refused'], printed(capsys.readouterr().err)) - assert _file_inputs(analysis.artifact.job_inputs) == ['a.txt', 'b.txt'] - - -@pytest.mark.fast -def test_two_declarations_in_one_workflow_get_distinct_names() -> None: - """Each analysis keeps its files under its own name; a repeated document name gets a suffix.""" - analyses = _analyses({'steps': [_declaration_step(), _declaration_step()]}) - assert [analysis.name for analysis in analyses] == ['oracle', 'oracle_2'] + prepared = no_preflight(monkeypatch) + (tmp_path / 'python').mkdir() + monkeypatch.chdir(tmp_path / 'python') + workflow = live_workflow('py_live') + assert [step['id'] for step in workflow.compile().cwl_workflow['steps']] == ['touch'] + workflow.run(run_args_dict={'generate_run_script': 'yes'}) + (entry,) = json.loads(realtime.manifest_path(Path('autogenerated'), 'py_live').read_text(encoding='utf-8')) + assert (entry['analysis'], entry['max_times']) == ('touch', 2) + assert list(chain.from_iterable(prepared)) == [Path('autogenerated/py_live.cwl'), + Path('autogenerated/realtime/py_live/touch_only.cwl')] + assert 'Real-time analysis runs only with --run_local' in capsys.readouterr().err + written = Path('autogenerated/realtime/py_live') + assert sorted(path.name for path in written.iterdir()) == ['touch_only.cwl', 'touch_only_inputs.yml'] + (step,) = yaml.safe_load((written / 'touch_only.cwl').read_text(encoding='utf-8'))['steps'] + assert step['run']['class'] == 'CommandLineTool' -@pytest.mark.fast -def test_an_analysis_that_does_not_compile_is_wic044_at_the_declaration() -> None: - """An unknown analysis fails the compile at the declaration, before anything runs.""" - document = {'steps': [{'id': 'mk_file', 'in': {'name': _ii('a.txt')}}, _declaration_step(cwl_tool=_ii('nope'))]} + workflow = live_workflow('py_wic', 'touched.wic', {'(1, touch)': {'in': {'filename': 'again.txt'}}}) with pytest.raises(SophiosError) as raised: - _analyses(document) - - assert {diagnostic.code for diagnostic in raised.value.diagnostics} == {SophiosErrorCode.REALTIME_DECLARATION} - assert {diagnostic.span.start_line if diagnostic.span else None - for diagnostic in raised.value.diagnostics} == set(_declaration_lines(document)) - assert "'nope'" in str(raised.value) - - -@pytest.mark.fast -def test_the_manifest_lists_each_analysis_and_goes_when_there_are_none(tmp_path: Path) -> None: - """`write` writes each analysis and a manifest naming it, and returns its plan; with none, no manifest is left.""" - analysis = _only_analysis({'steps': [_declaration_step(interval=_ii('5'))]}) - (plan,) = realtime.write((analysis,), tmp_path, 'wf', tmp_path / 'project') - - (entry,) = json.loads(realtime.manifest_path(tmp_path, 'wf').read_text(encoding='utf-8')) - assert {key: entry[key] for key in ('name', 'analysis', 'file_pattern', 'max_times', 'interval')} == { - 'name': 'oracle', 'analysis': 'count', 'file_pattern': '*.txt', 'max_times': 3, 'interval': 5} - assert (tmp_path / entry['cwl']).is_file() and (tmp_path / entry['inputs']).is_file() - assert entry['root_dir'] == str(tmp_path / 'project') - assert (plan.name, plan.max_times, plan.interval) == ('oracle', 3, 5) - assert (plan.cwl, plan.inputs) == (tmp_path / entry['cwl'], tmp_path / entry['inputs']) - - assert not realtime.write((), tmp_path, 'wf', tmp_path) - assert not realtime.manifest_path(tmp_path, 'wf').exists() + workflow.run(run_args_dict={'generate_run_script': 'yes'}) + (diagnostic,) = raised.value.diagnostics + assert diagnostic.code is SophiosErrorCode.REALTIME_DECLARATION + assert 'touched.wic' in diagnostic.message and 'wic013' in diagnostic.message + workflow.run(run_args_dict={'generate_run_script': 'yes'}, + workflow_paths={'global': {'touched': REALTIME / 'touched.wic'}}) + (entry,) = json.loads(realtime.manifest_path(Path('autogenerated'), 'py_wic').read_text(encoding='utf-8')) + assert entry['analysis'] == 'touched.wic' + assert Path('autogenerated/realtime/py_wic/touched_only.cwl').is_file() #: An analysis stand-in: copies its job file into its output directory, so a test can read what it was given. @@ -245,6 +212,7 @@ def command(_cwl: Path, job: Path, outdir: Path, _cachedir: Path) -> list[str]: def _plan(tmp_path: Path, *, max_times: int = 5, interval: float = 0.0, pattern: str = '*.log', reference: bool = True) -> realtime.Plan: """A plan whose analysis reads `out.log` and `ref.pdb`, and takes a string; `ref.pdb` is in the project.""" + tmp_path.mkdir(parents=True, exist_ok=True) inputs = tmp_path / 'analysis_inputs.yml' inputs.write_text(yaml.safe_dump({'log': {'class': 'File', 'location': 'out.log', 'format': 'edam:format_2330'}, 'ref': {'class': 'File', 'location': 'ref.pdb'}, @@ -261,7 +229,7 @@ class _Cache: def __init__(self, root: Path) -> None: self.root = root - root.mkdir(exist_ok=True) + root.mkdir(parents=True, exist_ok=True) self.count = 0 def start(self, files: dict[str, str]) -> str: @@ -316,77 +284,39 @@ def _watch(tmp_path: Path, command: realtime.Command | None = None, **plan: Any) @pytest.mark.fast -def test_a_job_that_starts_long_after_the_watcher_is_still_analysed(tmp_path: Path) -> None: - """Polling has no budget: `max_times` counts runs, not polls.""" - cache, watcher = _watch(tmp_path, max_times=2) +# pylint: disable-next=too-many-statements +def test_an_analysis_runs_while_its_job_writes_and_once_more_at_its_end_unless_it_failed( + capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None: + """Polling has no budget: `max_times` counts runs, not polls, so a job that starts long after the watcher is still + analysed. A file that keeps changing is analysed once per `interval`, and its last state at the end; the step + finishing is the moment its outputs are complete, so no `interval` delays that run. Changes while an analysis runs + make one follow-up run, not one each, and runs while the workflow runs leave room for the final one. The outputs of + a failed step are no result to analyse, so there is no final run, and a line says why; a failed analysis is a line + naming its log, counted in the summary; and Ctrl-C does not wait for an analysis to finish.""" + cache, watcher = _watch(tmp_path / 'late', max_times=2) time.sleep(0.5) # 25 polls with nothing to see key = cache.start({'sub/out.log': '1\n'}) _until(lambda: watcher.runs == 1) watcher.finish() - (job,) = _jobs(cache) assert job['log'] == {'class': 'File', 'location': str(cache.root / key / 'sub' / 'out.log'), 'format': 'edam:format_2330'} - assert job['ref']['location'] == str(tmp_path / 'project' / 'ref.pdb') - assert job['name'] == 'out.log' + assert job['ref']['location'] == str(tmp_path / 'late' / 'project' / 'ref.pdb') and job['name'] == 'out.log' - -@pytest.mark.fast -def test_a_later_workflow_run_numbers_its_analysis_runs_after_the_earlier_ones( - capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None: - """Two runs of the workflow share the cachedir; the second keeps the first's outputs and logs.""" - cache = _Cache(tmp_path / 'cachedir') - plan = _plan(tmp_path, max_times=1) - first = _started(plan, cache) - cache.end(cache.start({'out.log': 'first\n'})) - first.finish() - second = _started(plan, cache) - key = cache.start({'out.log': 'second\n'}) - cache.end(key) - second.finish() - - first_job, second_job = _jobs(cache) - assert first_job['log']['location'] == str(cache.root / f'{1:032x}' / 'out.log') - assert second_job['log']['location'] == str(cache.root / key / 'out.log') - assert sorted(path.name for path in (cache.root / 'realtime' / 'wf').glob('run-*.log')) == [ - 'run-001.log', 'run-002.log'] - assert 'run 2 (the workflow finished) finished' in capsys.readouterr().out - - -@pytest.mark.fast -def test_a_growing_file_triggers_once_per_interval_and_once_more_at_the_end(tmp_path: Path) -> None: - """A file that keeps changing is analysed once per `interval`, and its last state at the end.""" - cache, watcher = _watch(tmp_path, interval=60) + cache, watcher = _watch(tmp_path / 'growing', interval=60) key = cache.start({'out.log': '1\n'}) _until(lambda: watcher.runs == 1) for line in range(2, 6): cache.write(key, 'out.log', f'{line}\n') time.sleep(0.05) assert watcher.runs == 1 - watcher.finish() - assert watcher.runs == 2 - - -@pytest.mark.fast -def test_a_job_that_succeeds_triggers_at_once_and_its_run_is_the_last(capsys: pytest.CaptureFixture[str], - tmp_path: Path) -> None: - """The step finishing is the moment its outputs are complete: no `interval` delays that run.""" - cache, watcher = _watch(tmp_path, interval=60) - key = cache.start({'out.log': '1\n'}) - _until(lambda: watcher.runs == 1) - cache.write(key, 'out.log', '2\n') cache.end(key) _until(lambda: watcher.runs == 2) watcher.finish() - - assert watcher.runs == 2 and watcher.succeeded == 2 + assert watcher.runs == watcher.succeeded == 2 assert 'the job that wrote out.log finished' in capsys.readouterr().out - -@pytest.mark.fast -def test_changes_during_a_run_make_one_follow_up_run(tmp_path: Path) -> None: - """Three changes while an analysis runs make one more run, not three.""" - cache, watcher = _watch(tmp_path, _command(seconds=0.6)) + cache, watcher = _watch(tmp_path / 'busy', _command(seconds=0.6)) key = cache.start({'out.log': '1\n'}) _until((cache.root / 'realtime' / 'wf' / 'run-001.log').exists) for line in range(2, 5): @@ -398,11 +328,7 @@ def test_changes_during_a_run_make_one_follow_up_run(tmp_path: Path) -> None: watcher.finish() assert watcher.runs == 2 - -@pytest.mark.fast -def test_runs_while_the_workflow_runs_leave_room_for_the_final_run(tmp_path: Path) -> None: - """With `max_times` 3, two runs happen while the workflow runs, however much changes; the third is the end's.""" - cache, watcher = _watch(tmp_path, max_times=3) + cache, watcher = _watch(tmp_path / 'room', max_times=3) key = cache.start({'out.log': '1\n'}) deadline = time.monotonic() + 2.0 # changes all along, far more than three runs' worth while time.monotonic() < deadline: @@ -410,143 +336,91 @@ def test_runs_while_the_workflow_runs_leave_room_for_the_final_run(tmp_path: Pat time.sleep(0.05) assert watcher.runs == 2 watcher.finish() - assert watcher.runs == 3 - assert len(_jobs(cache)) == 3 - - -@pytest.mark.fast -def test_a_job_from_an_earlier_run_is_not_a_trigger_but_its_files_are_used(tmp_path: Path) -> None: - """A cache hit leaves its job alone, so it never triggers; this run reused it, so its files resolve.""" - cache = _Cache(tmp_path / 'cachedir') - old = cache.start({'out.log': 'old\n', 'ref.pdb': 'ref'}) - cache.end(old) - past = time.time() - 3600 - for path in (cache.root / old, cache.root / f'{old}.status'): - os.utime(path, (past, past)) - watcher = _started(_plan(tmp_path, pattern='*.txt', reference=False), cache) - time.sleep(0.3) - assert watcher.runs == 0 - new = cache.start({'out.txt': 'x', 'out.log': 'new\n'}) - _until(lambda: watcher.runs == 1) - watcher.finish() + assert watcher.runs == 3 and len(_jobs(cache)) == 3 - (job,) = _jobs(cache) - assert job['log']['location'] == str(cache.root / new / 'out.log') - assert job['ref']['location'] == str(cache.root / old / 'ref.pdb') - - -@pytest.mark.fast -def test_a_failed_job_means_no_final_run(capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None: - """The outputs of a failed step are not a result to analyse; a line says why there is no final run.""" - cache, watcher = _watch(tmp_path, interval=60) + cache, watcher = _watch(tmp_path / 'failed', interval=60) key = cache.start({'out.log': '1\n'}) _until(lambda: watcher.runs == 1) cache.write(key, 'out.log', '2\n') cache.end(key, 'permanentFail') watcher.finish() - assert watcher.runs == 1 assert 'no final run: the job that wrote out.log failed' in capsys.readouterr().out - -@pytest.mark.fast -def test_a_failed_analysis_is_a_line(capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None: - """A failed run names its log; the summary counts it.""" - cache, watcher = _watch(tmp_path, _command(exit_code=3), interval=60) + cache, watcher = _watch(tmp_path / 'failing', _command(exit_code=3), interval=60) cache.start({'out.log': '1\n'}) _until(lambda: watcher.runs == 1) watcher.finish() - out = capsys.readouterr().out - assert 'run 1 (out.log changed) failed with exit code 3; log: ' in out - assert '1 runs, 0 succeeded' in out - + assert 'run 1 (out.log changed) failed with exit code 3; log: ' in out and '1 runs, 0 succeeded' in out -@pytest.mark.fast -def test_cancel_terminates_a_running_analysis(tmp_path: Path) -> None: - """Ctrl-C does not wait for an analysis to finish.""" - cache, watcher = _watch(tmp_path, _command(seconds=60)) + cache, watcher = _watch(tmp_path / 'cancelled', _command(seconds=60)) cache.start({'out.log': '1\n'}) _until((cache.root / 'realtime' / 'wf' / 'run-001' / 'job.json').exists) began = time.monotonic() watcher.cancel() - assert time.monotonic() - began < 10 - assert watcher.succeeded == 0 + assert time.monotonic() - began < 10 and watcher.succeeded == 0 @pytest.mark.fast -def test_a_file_written_by_two_jobs_is_named_and_the_newest_used(capsys: pytest.CaptureFixture[str], - tmp_path: Path) -> None: - """Two steps of this run wrote `out.log`: the analysis gets the newer, and a line names both.""" - cache, watcher = _watch(tmp_path, pattern='*.trr', interval=60) +# pylint: disable-next=too-many-locals +def test_an_analysis_reads_the_newest_file_this_run_wrote(capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None: + """Two steps of this run wrote `out.log`: the analysis gets the newer, and a line names both. A cache hit leaves + its job alone, so it never triggers, but this run reused it, so its files resolve. A file no job of this run wrote, + as the corpus `cwl_subinterpreter_complex.wic` reads one its own analysis writes, skips the run with one line. A + later run of the workflow shares the cachedir, keeps the earlier one's outputs and logs, and numbers its own runs + after them.""" + cache, watcher = _watch(tmp_path / 'two', pattern='*.trr', interval=60) first = cache.start({'out.log': 'first\n'}) time.sleep(0.05) second = cache.start({'out.log': 'second\n', 'prod.trr': 'x'}) _until(lambda: watcher.runs == 1) watcher.finish() - (job,) = _jobs(cache) assert job['log']['location'] == str(cache.root / second / 'out.log') assert f'out.log was written by 2 jobs of this run ({first}, {second}); using the newest' in capsys.readouterr().out + cache = _Cache(tmp_path / 'hit' / 'cachedir') + old = cache.start({'out.log': 'old\n', 'ref.pdb': 'ref'}) + cache.end(old) + past = time.time() - 3600 + for path in (cache.root / old, cache.root / f'{old}.status'): + os.utime(path, (past, past)) + watcher = _started(_plan(tmp_path / 'hit', pattern='*.txt', reference=False), cache) + time.sleep(0.3) + assert watcher.runs == 0 + new = cache.start({'out.txt': 'x', 'out.log': 'new\n'}) + _until(lambda: watcher.runs == 1) + watcher.finish() + (job,) = _jobs(cache) + assert job['log']['location'] == str(cache.root / new / 'out.log') + assert job['ref']['location'] == str(cache.root / old / 'ref.pdb') -@pytest.mark.fast -def test_a_file_found_nowhere_skips_the_run_with_one_line(capsys: pytest.CaptureFixture[str], tmp_path: Path) -> None: - """The corpus `cwl_subinterpreter_complex.wic` reads, as a literal, a file its own analysis writes.""" - cache, watcher = _watch(tmp_path, reference=False) + cache, watcher = _watch(tmp_path / 'nowhere', reference=False) key = cache.start({'out.log': '1\n'}) for line in range(2, 5): time.sleep(0.05) cache.write(key, 'out.log', f'{line}\n') watcher.finish() - assert watcher.runs == 0 out = capsys.readouterr().out - assert out.count('skipped a run: no job of this run wrote ref.pdb') == 1 - assert 'declared at wf.wic:3:3' in out - - -#: Writes `out.log` one line a second for six seconds: long enough to be watched while it grows. -SLOW_LOG: Final = '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: [bash, -c, 'for i in 1 2 3 4 5 6; do echo $i >> out.log; sleep 1; done'] -inputs: {} -outputs: - log: {type: File, outputBinding: {glob: out.log}} -''' - -#: Counts the lines of a log, or, with `false` as its command, fails. -COUNT_LINES: Final = '''cwlVersion: v1.2 -class: CommandLineTool -baseCommand: [{command}] -inputs: - log: {{type: File, inputBinding: {{position: 1}}}} -stdout: count.txt -outputs: - count: {{type: stdout}} -''' - -#: A `cwl_subinterpreter` step declaring `analysis`, watching the log `slow_log` writes. -ANALYSIS: Final = ''' - id: cwl_subinterpreter - in: - file_pattern: !ii out.log - cwl_tool: !ii {analysis} - max_times: !ii '5' - interval: !ii 1 - config: !ii - in: - log: out.log -''' - - -def _live_project(tmp_path: Path, *analyses: str, count_hints: str = '') -> Path: - """Write `slow_log`, the analyses named (`count_lines`, `fail_lines`) and a `live.wic` declaring each; return - the config file that finds them.""" - tools = {'slow_log': SLOW_LOG, 'count_lines': COUNT_LINES.format(command='wc, -l') + count_hints, - 'fail_lines': COUNT_LINES.format(command="'false'")} - write_tree(tmp_path, {f'tools/{tool}.cwl': tools[tool] for tool in ('slow_log', *analyses)} | { - 'live.wic': 'steps:\n - id: slow_log\n' + ''.join(ANALYSIS.format(analysis=name) for name in analyses)}) - return search_config(tmp_path / 'config.json', [tmp_path / 'tools', ADAPTER_PATH.parent], [tmp_path]) + assert out.count('skipped a run: no job of this run wrote ref.pdb') == 1 and 'declared at wf.wic:3:3' in out + + cache = _Cache(tmp_path / 'again' / 'cachedir') + plan = _plan(tmp_path / 'again', max_times=1) + earlier = _started(plan, cache) + cache.end(cache.start({'out.log': 'first\n'})) + earlier.finish() + later = _started(plan, cache) + key = cache.start({'out.log': 'second\n'}) + cache.end(key) + later.finish() + first_job, second_job = _jobs(cache) + assert first_job['log']['location'] == str(cache.root / f'{1:032x}' / 'out.log') + assert second_job['log']['location'] == str(cache.root / key / 'out.log') + assert sorted(path.name for path in (cache.root / 'realtime' / 'wf').glob('run-*.log')) == [ + 'run-001.log', 'run-002.log'] + assert 'run 2 (the workflow finished) finished' in capsys.readouterr().out @pytest.mark.needs_cwltool @@ -560,21 +434,21 @@ def test_the_analysis_runs_beside_the_workflow_and_never_changes_its_outcome( workflow ran: the end adds at most one. Each analysis's CWL is handed to image extraction with the workflow's. """ - config = _live_project(tmp_path, 'count_lines', 'fail_lines') + root = _project(tmp_path) prepared = no_preflight(monkeypatch) - monkeypatch.chdir(tmp_path) + monkeypatch.chdir(root) - assert run_cli(monkeypatch, '--yaml', 'live.wic', '--run_local', '--config_file', config) is None # succeeded + assert run_cli(monkeypatch, '--yaml', 'live.wic', '--run_local', '--config_file', 'config.json') is None out = capfd.readouterr().out lines = out.splitlines() for name, analysis in (('live', 'count_lines'), ('live_2', 'fail_lines')): said = f'real-time analysis {name} ({analysis}): ' - runs = sorted((tmp_path / 'cachedir' / 'realtime' / name).glob('run-*.log')) + runs = sorted((root / 'cachedir' / 'realtime' / name).glob('run-*.log')) assert len(runs) >= 2, out assert Path(f'autogenerated/realtime/{name}/{analysis}_only.cwl') in chain.from_iterable(prepared) if analysis == 'count_lines': - last = sorted((tmp_path / 'cachedir' / 'realtime' / name).glob('run-*/count.txt'))[-1] + last = sorted((root / 'cachedir' / 'realtime' / name).glob('run-*/count.txt'))[-1] assert last.read_text(encoding='utf-8').split()[0] == '6' assert f'{said}{len(runs)} runs, {len(runs)} succeeded' in lines else: @@ -582,114 +456,30 @@ def test_the_analysis_runs_beside_the_workflow_and_never_changes_its_outcome( assert f'{said}{len(runs)} runs, 0 succeeded' in lines -@pytest.mark.fast -def test_an_analysis_tool_builds_its_image_from_the_dockerfile_beside_it(monkeypatch: pytest.MonkeyPatch, - tmp_path: Path) -> None: - """An analysis is a root under `realtime//`: its document, its job and `~.cwl` beside them. - A relative `dockerFile` `$include` is the file beside the tool, wherever the analysis CWL is written.""" - config = _live_project(tmp_path, 'count_lines', count_hints='''hints: - DockerRequirement: - dockerPull: count_lines - dockerFile: {$include: Dockerfile_count} -''') - (tmp_path / 'tools' / 'Dockerfile_count').write_text('FROM alpine:3.20\n', encoding='utf-8') - monkeypatch.chdir(tmp_path) - - assert run_cli(monkeypatch, '--yaml', 'live.wic', '--generate_cwl_workflow', '--config_file', config) is None - - written = Path('autogenerated/realtime/live') - assert sorted(path.name for path in written.iterdir()) == [ - 'count_lines_only.cwl', 'count_lines_only_inputs.yml', 'count_lines_only~count_lines.cwl'] - (step,) = yaml.safe_load((written / 'count_lines_only.cwl').read_text(encoding='utf-8'))['steps'] - assert step['run'] == 'count_lines_only~count_lines.cwl' - hints = yaml.safe_load((written / step['run']).read_text(encoding='utf-8'))['hints'] - assert hints == [{'class': 'DockerRequirement', 'dockerPull': 'count_lines', 'dockerFile': 'FROM alpine:3.20\n'}] - - -@POSIX_ONLY -@pytest.mark.fast -def test_a_run_with_real_time_analysis_gives_cwltool_a_cachedir(monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - tmp_path: Path) -> None: - """The watcher reads cwltool's job directories, so a run that has analyses caches, and says so.""" - monkeypatch.chdir(tmp_path) - fake = install(monkeypatch, tmp_path) - - assert run_local.run(RunRequest('wf', Path('autogenerated'), realtime_plans=(_plan(tmp_path),))) == 0 - - args = fake.record()['argv'] - assert args[args.index('--cachedir') + 1] == str(tmp_path / 'cachedir') - out = capsys.readouterr().out - assert "Real-time analysis watches the runner's cache, so cwltool caches in cachedir/" in out - assert 'real-time analysis wf (measure.wic): 0 runs, 0 succeeded' in out - - @POSIX_ONLY @pytest.mark.fast @pytest.mark.parametrize(('request_fields', 'line'), [ + ({}, "Real-time analysis watches the runner's cache, so cwltool caches in cachedir/"), ({'generate_run_script': True}, 'Real-time analysis runs only with --run_local; run.sh runs the workflow without it.'), ({'runner': 'toil-cwl-runner'}, 'Real-time analysis needs cwltool; toil-cwl-runner runs the workflow without it.'), -]) -def test_a_run_that_cannot_watch_says_so_and_runs_the_workflow(monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], tmp_path: Path, - request_fields: dict[str, Any], line: str) -> None: - """A run script or another runner cannot run the analyses: the workflow runs, and a line says so.""" +], ids=['cwltool', 'run-script', 'toil']) +def test_a_run_watches_its_analyses_only_where_cwltool_runs_and_says_so( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path, + request_fields: dict[str, Any], line: str) -> None: + """The watcher reads cwltool's job directories, so a run that has analyses caches, and says so. A run script or + another runner cannot run the analyses: the workflow runs, and a line on stderr says so.""" monkeypatch.chdir(tmp_path) - install(monkeypatch, tmp_path) + fake = install(monkeypatch, tmp_path) assert run_local.run(RunRequest('wf', Path('autogenerated'), realtime_plans=(_plan(tmp_path),), **request_fields)) == 0 captured = capsys.readouterr() - assert line in captured.err - assert line not in captured.out - assert 'real-time analysis wf' not in captured.out + captured.err - - -@pytest.mark.fast -def test_the_python_api_declares_an_analysis_and_run_prepares_it(monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - tmp_path: Path) -> None: - """A `Step` built from the adapter is a declaration: never emitted, compiled and pulled by `run`. The analysis is - written as the workflow is: one document, every process embedded, and its job.""" - workflow = live_workflow('py_live') - prepared = no_preflight(monkeypatch) - monkeypatch.chdir(tmp_path) - - assert [step['id'] for step in workflow.compile().cwl_workflow['steps']] == ['touch'] - workflow.run(run_args_dict={'generate_run_script': 'yes'}) - - (entry,) = json.loads(realtime.manifest_path(Path('autogenerated'), 'py_live').read_text(encoding='utf-8')) - assert (entry['analysis'], entry['max_times']) == ('touch', 2) - assert list(chain.from_iterable(prepared)) == [Path('autogenerated/py_live.cwl'), - Path('autogenerated/realtime/py_live/touch_only.cwl')] - assert 'Real-time analysis runs only with --run_local' in capsys.readouterr().err - written = Path('autogenerated/realtime/py_live') - assert sorted(path.name for path in written.iterdir()) == ['touch_only.cwl', 'touch_only_inputs.yml'] - (step,) = yaml.safe_load((written / 'touch_only.cwl').read_text(encoding='utf-8'))['steps'] - assert step['run']['class'] == 'CommandLineTool' - - -@pytest.mark.fast -def test_the_python_api_finds_a_wic_analysis_through_workflow_paths(monkeypatch: pytest.MonkeyPatch, - tmp_path: Path) -> None: - """A `.wic` named by `cwl_tool` is found through `run(workflow_paths=...)`, as `from_wic` finds a nested one.""" - (tmp_path / 'measure.wic').write_text(yaml.safe_dump({'steps': [{'id': 'touch'}]}), encoding='utf-8') - workflow = live_workflow('py_wic', 'measure.wic', {'(1, touch)': {'in': {'filename': 'again.txt'}}}) - no_preflight(monkeypatch) - monkeypatch.chdir(tmp_path) - - with pytest.raises(SophiosError) as raised: - workflow.run(run_args_dict={'generate_run_script': 'yes'}) - (diagnostic,) = raised.value.diagnostics - assert diagnostic.code is SophiosErrorCode.REALTIME_DECLARATION - assert 'measure.wic' in diagnostic.message and 'wic013' in diagnostic.message - - workflow.run(run_args_dict={'generate_run_script': 'yes'}, - workflow_paths={'global': {'measure': tmp_path / 'measure.wic'}}) - - (entry,) = json.loads(realtime.manifest_path(Path('autogenerated'), 'py_wic').read_text(encoding='utf-8')) - assert entry['analysis'] == 'measure.wic' - assert Path('autogenerated/realtime/py_wic/measure_only.cwl').is_file() + watched = not request_fields + assert line in captured.out if watched else line in captured.err and line not in captured.out + assert ('real-time analysis wf (measure.wic): 0 runs, 0 succeeded' in captured.out) is watched + if watched: + args = fake.record()['argv'] + assert args[args.index('--cachedir') + 1] == str(tmp_path / 'cachedir') diff --git a/tests/core/test_release.py b/tests/core/test_release.py index eead7a238..7155ffb57 100644 --- a/tests/core/test_release.py +++ b/tests/core/test_release.py @@ -28,20 +28,15 @@ def _import_copy(root: Path, built_as: str | None) -> subprocess.CompletedProces @pytest.mark.fast @pytest.mark.parametrize(('built_as', 'version'), [('1.2.3', '1.2.3'), (None, 'unknown')]) -def test_the_version_is_the_one_built_beside_the_code(tmp_path: Path, built_as: str | None, version: str) -> None: +def test_the_version_is_the_one_built_beside_the_code(tmp_path: Path, capsys: pytest.CaptureFixture[str], + built_as: str | None, version: str) -> None: """__version__ is what the _version.py next to the package says; without one the version is unknown, and says - why.""" + why. The header of compiled CWL and --version print the running version.""" run = _import_copy(tmp_path, built_as) assert run.stdout.splitlines() == [str(tmp_path / 'sophios' / '__init__.py'), version] assert ('never built' in run.stderr) is (built_as is None) assert built_as or "RuntimeWarning: this copy of sophios was never built, so __version__ is 'unknown'" in run.stderr - - -@pytest.mark.fast -def test_the_compiled_header_and_the_cli_report_the_running_version(capsys: pytest.CaptureFixture[str]) -> None: - """The header of compiled CWL and --version print the same version as __version__.""" assert f'Sophios, version {sophios.__version__}\n' in sophios.auto_gen_header - with pytest.raises(SystemExit): sophios.cli.parser.parse_args(['--version']) assert capsys.readouterr().out.strip() == sophios.__version__ diff --git a/tests/core/test_run_local.py b/tests/core/test_run_local.py index 382bb9f5a..240523606 100644 --- a/tests/core/test_run_local.py +++ b/tests/core/test_run_local.py @@ -20,15 +20,14 @@ from sophios import backends, preflight, run_local from sophios.api.python.workflow import RunResult, RunState, StepStatus, Workflow, WorkflowRunError -from sophios.backends import RunRequest from sophios.lang.diagnostics import Diagnostic, Severity, SophiosError from sophios.lang.error_codes import SophiosErrorCode from sophios.wic_types import Yaml from .cases import cases from .fake_runner import POSIX_ONLY, FakeRunner, install -from .helpers import (ADAPTERS, EACH_RUNNER, HELLOWORLD, REPO_ROOT, adapter_step, echo_workflow, live_workflow, - no_preflight, python_process, run_cli, search_config, write_tree) +from .helpers import ADAPTERS, HELLOWORLD, REPO_ROOT, echo_workflow, live_workflow, no_preflight, \ + python_process, run_cli from .nextflow.test_public_api import CUDA_NOTES, gpu_workflow from .test_backends import _Frozen @@ -37,9 +36,11 @@ @pytest.fixture(name='offline') def _offline(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """Run from `tmp_path`, with nothing pulled and no container engine asked.""" + """Run from `tmp_path`, with nothing pulled, no container engine asked, and nothing asked of Nextflow's own + program before the stand-in starts.""" monkeypatch.chdir(tmp_path) no_preflight(monkeypatch) + monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: []) @pytest.fixture(name='sophios') @@ -52,18 +53,53 @@ def run(*flags: str) -> int: return run +def _script(directory: Path) -> list[str]: + """The command run.sh in `directory` starts.""" + return shlex.split((directory / 'run.sh').read_text(encoding='utf-8').splitlines()[-1]) + + @pytest.mark.fast -def test_the_runner_gets_the_users_variables_and_this_process_keeps_its_own( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None) -> None: - """A value reaches the runner exactly as given, through its environment and no shell; `os.environ` is - not touched, so nothing else in the process sees it.""" - del offline - fake = install(monkeypatch, tmp_path) - value = "p@ss$word! a&b 'single' \"double\" ;|<>()`x`\nline two" +@pytest.mark.parametrize(('door', 'flags', 'given', 'withheld'), [ + ('command line', ['--passthrough_flags', 'yes', '--debug', '--validate'], ['--debug', '--validate'], ['--quiet']), + ('command line', ['--quiet'], ['--quiet'], []), + ('python', {'quiet': 'no', 'cachedir': 'cache', 'logLevel': 'INFO'}, ['--cachedir'], ['--quiet']), +], ids=['passthrough', 'quiet', 'python']) +# pylint: disable-next=too-many-arguments,too-many-positional-arguments +def test_a_run_starts_what_run_sh_holds_and_echoes_and_keeps_what_the_runner_prints( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, sophios: Callable[..., int], + capsys: pytest.CaptureFixture[str], door: str, flags: Any, given: list[str], withheld: list[str]) -> None: + """A run starts what run.sh holds, from either door: the runner gets a flag it is passed, and `--quiet` only when + the run is quiet, so `--debug` can be heard, and cwltool's `--validate` is not a prefix of `--validate_plugins`. + The user's variables reach it exactly as given, through its environment and no shell, and `os.environ` is not + touched. It starts in its own session from the working directory, so a terminal's Ctrl-C reaches Sophios and not + the runner; both its streams go to this process's own, so a notebook and pytest show them, and to the run log, and + the Python door prints what the command line prints.""" + fake = install(monkeypatch, tmp_path, stdout=['said on stdout'], stderr=['said on stderr']) + monkeypatch.setattr(backends, 'datetime', _Frozen) + secret = "p@ss$word! a&b 'single' \"double\" ;|<>()`x`\nline two" monkeypatch.delenv('SOPHIOS_TEST_TOKEN', raising=False) - echo_workflow().run(user_env_vars={'SOPHIOS_TEST_TOKEN': value}) - assert fake.record()['env']['SOPHIOS_TEST_TOKEN'] == value - assert 'SOPHIOS_TEST_TOKEN' not in os.environ + if door == 'command line': + assert sophios(*flags, '--generate_run_script') == 0 + assert sophios(*flags, '--run_local') == 0 + name = 'helloworld' + else: + echo_workflow().run(run_args_dict={**flags, 'generate_run_script': 'yes'}) + echo_workflow().run(run_args_dict=flags, user_env_vars={'SOPHIOS_TEST_TOKEN': secret}) + name = 'wf' + assert fake.record()['env']['SOPHIOS_TEST_TOKEN'] == secret + assert 'SOPHIOS_TEST_TOKEN' not in os.environ + script, started = _script(tmp_path), fake.record() + # The stand-in is a script, so its own argv[0] is its path: the arguments are compared. + assert script[0] == 'cwltool_filterlog' and started['argv'][1:] == script[1:] + assert all(flag in script for flag in given) and not [flag for flag in withheld if flag in script] + assert started['sid'] == started['pid'] and Path(started['cwd']) == tmp_path.resolve() + captured = capsys.readouterr() + assert 'said on stdout\n' in captured.out and 'said on stdout' not in captured.err + assert 'said on stderr\n' in captured.err and 'said on stderr' not in captured.out + assert f'Final output json metadata blob is in output_{name}.json' in captured.out + assert 'Running cwltool_filterlog ' in captured.out and 'Success! Runner outputs are under ' in captured.out + log = (tmp_path / 'autogenerated' / f'run_{name}.log').read_text(encoding='utf-8') + assert 'said on stdout\n' in log and 'said on stderr\n' in log @pytest.mark.fast @@ -73,44 +109,22 @@ def test_the_runner_gets_the_users_variables_and_this_process_keeps_its_own( (lambda workflow: workflow.run(run_args_dict={'cwl_runner': 'nope'}), "No backend runs cwl with 'nope'; the runners are cwltool", False), (lambda workflow: workflow.start(run_args_dict={'generate_run_script': 'yes'}), 'call run', True), -], ids=['variable-name', 'unknown-runner', 'run-script']) + (lambda workflow: workflow.run(target='nextflow', basepath='refused', + run_args_dict={'cachedir': 'cache', 'resume': '', 'quiet': 'no'}), + "run_args_dict keys only a CWL run reads: 'cachedir', 'quiet'$", True), +], ids=['variable-name', 'unknown-runner', 'run-script', 'cwl-only-for-nextflow']) def test_a_refused_argument_is_refused_before_the_runner_starts( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, front_door: Callable[[Workflow], object], refusal: str, writes_nothing: bool) -> None: """A key that is not an environment variable name is an error naming it, not a variable silently dropped; a - Python caller gets an exception naming the runners, not the command line's exit; and only `run()` writes run.sh, - so `start()` says so before it compiles, pulls or writes anything.""" + Python caller gets an exception naming the runners, not the command line's exit; only `run()` writes run.sh, so + `start()` says so before it compiles, pulls or writes anything; and an option only a CWL run reads stops a Nextflow + run before anything is written.""" fake = install(monkeypatch, tmp_path) with pytest.raises(ValueError, match=refusal): front_door(echo_workflow()) assert not fake.record_path.exists() - assert not (writes_nothing and (tmp_path / 'autogenerated').exists()) - - -@pytest.mark.fast -def test_what_the_runner_prints_is_echoed_and_kept_in_the_run_log( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, sophios: Callable[..., int], - capsys: pytest.CaptureFixture[str]) -> None: - """Both streams go to this process's own, so a notebook and pytest show them, and to `run_.log`. - The runner starts in its own session from the working directory, so a terminal's Ctrl-C reaches Sophios and - not the runner.""" - fake = install(monkeypatch, tmp_path, stdout=['said on stdout'], stderr=['said on stderr']) - assert sophios('--run_local') == 0 - started = fake.record() - assert started['sid'] == started['pid'] - assert Path(started['cwd']) == tmp_path.resolve() - captured = capsys.readouterr() - assert 'said on stdout\n' in captured.out and 'said on stdout' not in captured.err - assert 'said on stderr\n' in captured.err and 'said on stderr' not in captured.out - assert 'Final output json metadata blob is in output_helloworld.json' in captured.out - assert 'Success! Runner outputs are under ' in captured.out - log = (tmp_path / 'autogenerated' / 'run_helloworld.log').read_text(encoding='utf-8') - assert 'said on stdout\n' in log and 'said on stderr\n' in log - - -#: cwltool's lines for a failed job, coloured as its log colours them. -_EXITED_127 = ['\x1b[1;30mWARNING\x1b[0m \x1b[33m[job echo_2] exited with status: 127\x1b[0m', - '\x1b[1;30mWARNING\x1b[0m \x1b[33m[job echo_2] completed permanentFail\x1b[0m'] + assert not (writes_nothing and ((tmp_path / 'autogenerated').exists() or (tmp_path / 'refused').exists())) @pytest.mark.fast @@ -121,7 +135,6 @@ def test_a_run_says_what_its_runners_transcript_says(monkeypatch: pytest.MonkeyP capsys: pytest.CaptureFixture[str], case: Yaml) -> None: """Each case of data/runner-transcripts: Sophios exits with the runner's code, echoes its stdout, prints the `failures` lines, and writes `summary` to output_helloworld.json, or no such file.""" - monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: []) stdout = case.get('stdout', []) install(monkeypatch, tmp_path, stdout=stdout, stderr=case.get('stderr', []), exit_code=case['exit']) assert sophios('--run_local', *case.get('flags', [])) == case['exit'] @@ -133,23 +146,6 @@ def test_a_run_says_what_its_runners_transcript_says(monkeypatch: pytest.MonkeyP assert 'summary' not in case or 'Final output json metadata blob is in output_helloworld.json' in out -@pytest.mark.fast -@pytest.mark.usefixtures('offline') -@pytest.mark.parametrize(('front_door', 'name', 'status'), [ - (lambda workflow: workflow.run(), 'failing', 7), (lambda workflow: workflow.start().collect(), 'failing', 7), - (lambda workflow: asyncio.run(workflow.run_async()), 'wf', 4)], ids=['run', 'start-collect', 'run_async']) -def test_a_failed_run_raises_with_the_runners_exit_code(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - front_door: Callable[[Workflow], object], name: str, - status: int) -> None: - """`run()` raises what `start().collect()` raises, and so does `run_async`: a failed run cannot be missed.""" - install(monkeypatch, tmp_path, exit_code=status) - with pytest.raises(WorkflowRunError) as raised: - front_door(echo_workflow(name)) - assert raised.value.exit_code == status - assert str(raised.value) == (f"error [api005] workflow '{name}' did not complete: the runner exited with status " - f'{status}\nerror [api005] the lines printed above this error say why') - - def _interrupt_once_started(fake: FakeRunner) -> threading.Thread: """Press Ctrl-C, as a terminal would, once the stand-in runner has started.""" def press() -> None: @@ -162,17 +158,43 @@ def press() -> None: @pytest.mark.fast @pytest.mark.serial -@EACH_RUNNER -def test_ctrl_c_stops_the_runner_and_exits_130(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - sophios: Callable[..., int], capsys: pytest.CaptureFixture[str], - runner: str) -> None: - """The runner is sent SIGTERM, on which cwltool stops the containers it started, and the CLI exits 130.""" - fake = install(monkeypatch, tmp_path, sleep=60) - pressed = _interrupt_once_started(fake) - assert sophios('--run_local', '--cwl_runner', runner) == 130 - pressed.join() - assert fake.record()['signal'] == 15 - assert "Interrupted; the runner's processes were terminated." in capsys.readouterr().err +@pytest.mark.parametrize(('runner', 'behaviour', 'flags', 'code'), [ + ('cwltool', {'exit_code': 3}, [], 3), + ('cwltool', {'sleep': 60}, [], 130), + ('toil-cwl-runner', {'sleep': 60}, [], 130), + ('none', {}, [], 1), + ('none', {}, ['--cachedir', ''], 1), +], ids=['exit-code', 'ctrl-c-cwltool', 'ctrl-c-toil', 'cannot-start', 'cannot-start-no-cachedir']) +# pylint: disable-next=too-many-arguments,too-many-positional-arguments +def test_the_command_line_exits_as_its_run_ended( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, sophios: Callable[..., int], + capsys: pytest.CaptureFixture[str], runner: str, behaviour: dict[str, Any], flags: list[str], + code: int) -> None: + """With the runner's exit code; on Ctrl-C, whichever runner ran, the runner is sent SIGTERM, on which cwltool stops + the containers it started, and the exit code is 130. A runner that cannot start says why, whatever the cache, and + its traceback goes to error_.txt. Nothing in the working directory is deleted: a run used to `rmtree` every + `*` beside it, and `--cachedir ''` matched the whole directory.""" + (tmp_path / 'cachedir_results').mkdir() + (tmp_path / 'notes.txt').write_text('mine', encoding='utf-8') + fake = install(monkeypatch, tmp_path, **behaviour) + if runner == 'none': + monkeypatch.setattr(preflight, 'runner_program', lambda _name: str(tmp_path / 'no_such_runner')) + pressed = _interrupt_once_started(fake) if code == 130 else None + try: + assert sophios('--run_local', '--cwl_runner', 'cwltool' if runner == 'none' else runner, *flags) == code + except KeyboardInterrupt: + pytest.fail('the interrupt escaped the command line') + out, err = capsys.readouterr() + if pressed is not None: + pressed.join() + assert fake.record()['signal'] == 15 + assert "Interrupted; the runner's processes were terminated." in err + if runner == 'none': + assert 'no_such_runner' in out and 'See error_helloworld.txt for detailed technical information.' in out + assert 'or the error the runner itself raised' in err + kept = (tmp_path / 'error_helloworld.txt').read_text(encoding='utf-8') + assert 'Traceback (most recent call last)' in kept and 'FileNotFoundError' in kept + assert {'cachedir_results', 'notes.txt'} <= {path.name for path in tmp_path.iterdir()} #: Sophios, in a process of its own, starting a run of the stand-in and then waiting on it (`wait`), waiting @@ -205,23 +227,6 @@ def test_ctrl_c_stops_the_runner_and_exits_130(monkeypatch: pytest.MonkeyPatch, """ -def _sophios_ended(fake: FakeRunner, mode: str, signum: int, *, grace: float = 30.0, - ignore_hangup: bool = False) -> int: - """Start `_SOPHIOS`, end it with `signum` once the stand-in runs, and return the stand-in's pid.""" - env = {**os.environ, 'PYTHONPATH': os.pathsep.join([str(REPO_ROOT / 'src'), os.environ.get('PYTHONPATH', '')])} - argv = [sys.executable, '-c', _SOPHIOS, str(fake.write()), str(fake.directory / 'b'), mode, str(grace), - 'nohup' if ignore_hangup else '-'] - with subprocess.Popen(argv, cwd=fake.directory, env=env, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as sophios: - fake.wait_until_started() - os.kill(sophios.pid, signum) - if not ignore_hangup: - assert sophios.wait(10) == -signum - else: - assert sophios.wait(30) == 0 - return int(fake.record()['pid']) - - def _gone(pid: int, within: float) -> bool: """Whether process `pid` has ended within `within` seconds; it is killed if not.""" deadline = time.monotonic() + within @@ -238,78 +243,32 @@ def _gone(pid: int, within: float) -> bool: @pytest.mark.fast @pytest.mark.parametrize(('mode', 'signame', 'runner', 'ended', 'recorded'), [ ('wait', 'SIGTERM', {}, {}, signal.SIGTERM), ('wait', 'SIGHUP', {}, {}, signal.SIGTERM), - ('wait', 'SIGKILL', {}, {}, signal.SIGTERM), ('thread', 'SIGTERM', {}, {}, signal.SIGTERM), + ('fork', 'SIGKILL', {}, {}, signal.SIGTERM), ('thread', 'SIGTERM', {}, {}, signal.SIGTERM), ('hold', 'SIGTERM', {}, {}, signal.SIGTERM), ('wait', 'SIGKILL', {'ignore_sigterm': True}, {'grace': 1.0}, None), - ('wait', 'SIGHUP', {'sleep': 1}, {'ignore_hangup': True}, None), -], ids=['wait-SIGTERM', 'wait-SIGHUP', 'wait-SIGKILL', 'thread-SIGTERM', 'hold-SIGTERM', 'ignores-SIGTERM', 'nohup']) + ('wait', 'SIGHUP', {'sleep': 1}, {'nohup': True}, None), +], ids=['wait-SIGTERM', 'wait-SIGHUP', 'fork-SIGKILL', 'thread-SIGTERM', 'hold-SIGTERM', 'ignores-SIGTERM', 'nohup']) # pylint: disable-next=too-many-arguments,too-many-positional-arguments def test_the_runner_does_not_outlive_sophios(tmp_path: Path, mode: str, signame: str, runner: dict[str, Any], ended: dict[str, Any], recorded: int | None) -> None: """However Sophios ends, its runner is sent SIGTERM, on which cwltool stops its containers, or is killed if it - ignores that; `nohup` keeps a run alive after logout: Sophios ignores the hangup, and the run finishes.""" + ignores that; a child Sophios forked, which holds the watcher's pipe too, does not keep it going; and `nohup` + keeps a run alive after logout: Sophios ignores the hangup, and the run finishes.""" fake = FakeRunner(tmp_path, **{'sleep': 60, **runner}) - pid = _sophios_ended(fake, mode, getattr(signal, signame), **ended) - assert _gone(pid, within=10) - assert fake.record().get('signal') == recorded - - -@pytest.mark.fast -def test_a_child_sophios_forked_does_not_keep_the_runner_going(tmp_path: Path) -> None: - """What a forked child inherits includes the watcher's pipe; the watcher still sees that Sophios has gone.""" - fake = FakeRunner(tmp_path, sleep=60) - pid = _sophios_ended(fake, 'fork', signal.SIGKILL) - forked = int((tmp_path / 'forked.pid').read_text()) + env = {**os.environ, 'PYTHONPATH': os.pathsep.join([str(REPO_ROOT / 'src'), os.environ.get('PYTHONPATH', '')])} + argv = [sys.executable, '-c', _SOPHIOS, str(fake.write()), str(tmp_path / 'b'), mode, + str(ended.get('grace', 30.0)), 'nohup' if ended.get('nohup') else '-'] + with subprocess.Popen(argv, cwd=tmp_path, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as process: + fake.wait_until_started() + os.kill(process.pid, getattr(signal, signame)) + assert process.wait(30) == (0 if ended.get('nohup') else -getattr(signal, signame)) try: - assert _gone(pid, within=10) - os.kill(forked, 0) # still alive, still holding the pipe + assert _gone(int(fake.record()['pid']), within=10) + assert fake.record().get('signal') == recorded + if mode == 'fork': + os.kill(int((tmp_path / 'forked.pid').read_text()), 0) # still alive, still holding the pipe finally: - os.kill(forked, signal.SIGKILL) - - -@pytest.mark.fast -def test_a_run_whose_watcher_cannot_start_is_stopped_and_says_why( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """Without its watcher nothing would stop the runner should Sophios end, so the run does not go on.""" - monkeypatch.chdir(tmp_path) - install(monkeypatch, tmp_path, sleep=60) - monkeypatch.setattr(run_local.sys, 'executable', '') # as in some embedded interpreters - handle = run_local.start(RunRequest('wf', tmp_path)) - assert handle.wait().state is run_local.RunState.FAILED - assert 'the watcher that stops it if Sophios ends could not start' in (handle.status().reason or '') - assert not handle.cancel() and handle.status().state is run_local.RunState.FAILED - - -@pytest.mark.fast -@pytest.mark.serial -def test_a_runner_that_ignores_sigterm_is_killed_after_the_grace( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None) -> None: - """Nothing the run started outlives it: the runner and its session are killed when SIGTERM is not enough.""" - del offline - fake = install(monkeypatch, tmp_path, sleep=60, ignore_sigterm=True) - monkeypatch.setattr(run_local, 'STOP_GRACE_SECONDS', 0.5) - handle = echo_workflow().start() - fake.wait_until_started() - assert handle.cancel() - status = handle.status() - assert status.state is RunState.CANCELLED - assert status.exit_code == -9 - - -@pytest.mark.fast -def test_a_run_cancelled_from_another_thread_ends_cancelled( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None, capsys: pytest.CaptureFixture[str]) -> None: - """`wait` reports the cancellation, not the exit status the runner stopped with.""" - del offline - fake = install(monkeypatch, tmp_path, sleep=60) - handle = echo_workflow().start() - fake.wait_until_started() - canceller = threading.Thread(target=handle.cancel) - canceller.start() - status = handle.wait() - canceller.join() - assert status.state is RunState.CANCELLED - assert fake.record()['signal'] == 15 - assert 'Failure!' not in capsys.readouterr().err + if mode == 'fork': + os.kill(int((tmp_path / 'forked.pid').read_text()), signal.SIGKILL) _STARTS_AND_EXITS = ''' @@ -338,114 +297,36 @@ def state(): @pytest.mark.fast -def test_a_run_ends_when_the_python_process_exits(tmp_path: Path) -> None: - """A script that starts a run and exits without waiting leaves no runner behind.""" - fake = FakeRunner(tmp_path, sleep=60) - script = _STARTS_AND_EXITS.format(program=str(fake.write()), echo=str(ADAPTERS / 'echo.cwl'), - record=str(fake.record_path)) +@pytest.mark.parametrize('runner_exits_first', [False, True], ids=['runner-running', 'runner-exited']) +def test_a_run_nobody_waited_for_ends_with_the_python_process(tmp_path: Path, runner_exits_first: bool) -> None: + """A script that starts a run and exits without waiting leaves no runner behind; a runner that exited before the + script did is settled at exit: its outputs are written, its end printed.""" + outputs = {'out': 3} + fake = FakeRunner(tmp_path, **({'stdout': json.dumps(outputs).splitlines()} if runner_exits_first + else {'sleep': 60})) + script = (_STARTS_AND_EXITS + _AFTER_THE_RUNNER_EXITS * runner_exits_first).format( + program=str(fake.write()), echo=str(ADAPTERS / 'echo.cwl'), record=str(fake.record_path)) try: exited = python_process('-c', script, cwd=tmp_path, capture_output=True, timeout=120) assert exited.returncode == 0, exited.stderr - assert fake.record().get('signal') == 15 - assert 'Python is exiting before the run ended' in exited.stderr + assert ('Python is exiting before the run ended' in exited.stderr) is not runner_exits_first + if runner_exits_first: + assert 'Success! Runner outputs are under' in exited.stdout + written = tmp_path / 'autogenerated' / 'output_wf.json' + assert json.loads(written.read_text(encoding='utf-8')) == outputs + else: + assert fake.record().get('signal') == 15 finally: # a runner the script left behind stops here, not with the test session - if fake.record_path.exists(): + if fake.record_path.exists() and not runner_exits_first: try: os.kill(fake.record()['pid'], signal.SIGTERM) except ProcessLookupError: pass -@pytest.mark.fast -def test_a_run_nobody_waited_for_is_reported_on_when_the_python_process_exits(tmp_path: Path) -> None: - """A runner that exited before the script did is settled at exit: its outputs are written, its end printed.""" - outputs = {'out': 3} - fake = FakeRunner(tmp_path, stdout=json.dumps(outputs).splitlines()) - script = (_STARTS_AND_EXITS + _AFTER_THE_RUNNER_EXITS).format( - program=str(fake.write()), echo=str(ADAPTERS / 'echo.cwl'), record=str(fake.record_path)) - exited = python_process('-c', script, cwd=tmp_path, capture_output=True, timeout=120) - assert exited.returncode == 0, exited.stderr - assert 'Success! Runner outputs are under' in exited.stdout - assert 'Python is exiting before the run ended' not in exited.stderr - written = tmp_path / 'autogenerated' / 'output_wf.json' - assert json.loads(written.read_text(encoding='utf-8')) == outputs - - -@pytest.mark.fast -def test_status_answers_at_once_while_what_the_runner_started_holds_its_output( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """The runner has exited, but a process it left behind keeps its streams open: the run is still RUNNING.""" - monkeypatch.chdir(tmp_path) - fake = install(monkeypatch, tmp_path, leave_behind=10) - handle = run_local.start(RunRequest('wf', tmp_path)) - fake.wait_until_started() - until = time.monotonic() + 1.5 - while time.monotonic() < until: - asked = time.monotonic() - assert handle.status().state is run_local.RunState.RUNNING - assert time.monotonic() - asked < 0.5 - time.sleep(0.1) - handle.cancel() # ends what it left behind - - -@pytest.mark.fast -def test_start_returns_while_the_runner_runs_and_the_handle_follows_it( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None) -> None: - """The handle is RUNNING as soon as `start` returns; `wait` ends with the run's status, the same one each time - after, and `collect` with its outputs and its log.""" - del offline - outputs = {'out': 1} - fake = install(monkeypatch, tmp_path, stdout=json.dumps(outputs).splitlines(), stderr=['toil said this'], - sleep=1.0) - handle = echo_workflow().start(run_args_dict={'cwl_runner': 'toil-cwl-runner'}) - assert handle.status().state is RunState.RUNNING and handle.outputs() is None - with pytest.raises(TimeoutError): - handle.wait(timeout=0.05) - with pytest.raises(TimeoutError): - handle.collect(timeout=0.05) - fake.wait_until_started() - status = handle.wait() - assert status.state is RunState.COMPLETED and status.outputs == outputs - assert handle.wait() is status is handle.status() - assert status.started_at is not None and status.ended_at is not None and status.started_at <= status.ended_at - result = handle.collect() - assert result == RunResult(RunState.COMPLETED, outputs, result.outdir, tmp_path / 'autogenerated' / 'run_wf.log', 0) - assert result.outdir.parent == tmp_path / 'autogenerated' and result.outdir.name.startswith('outdir_toil_wf_') - assert handle.outputs() == outputs - assert handle.logs() == result.log_file.read_text(encoding='utf-8') - assert 'toil said this' in handle.logs() - - -@pytest.mark.fast -def test_a_failed_run_is_a_status_from_wait_with_its_failed_steps( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None) -> None: - """`wait` raises nothing for a failed run: its status says how it failed, and `cancel` leaves it FAILED.""" - del offline - install(monkeypatch, tmp_path, stderr=_EXITED_127, exit_code=1) - handle = echo_workflow().start() - status = handle.wait() - assert (status.state, status.outputs, status.exit_code) == (RunState.FAILED, None, 1) - assert status.steps == (StepStatus('echo_2', RunState.FAILED, exit_status=127),) - assert not handle.cancel() - assert handle.status() is status - - -@pytest.mark.fast -def test_a_cancelled_run_stays_cancelled(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None) -> None: - """`cancel` stops the runner with SIGTERM; a second `cancel`, a later `wait` and `collect` change nothing, - and `collect` raises the run as cancelled, not as failed.""" - del offline - fake = install(monkeypatch, tmp_path, sleep=60) - handle = echo_workflow().start() - fake.wait_until_started() - assert handle.cancel() - assert handle.cancel() - assert fake.record()['signal'] == 15 - assert handle.wait().state is handle.status().state is RunState.CANCELLED - with pytest.raises(WorkflowRunError, match='did not complete: cancelled: the runner was stopped') as caught: - handle.collect() - assert 'fail' not in str(caught.value) - assert handle.outputs() is None +#: cwltool's lines for a failed job, coloured as its log colours them. +_EXITED_127 = ['\x1b[1;30mWARNING\x1b[0m \x1b[33m[job echo_2] exited with status: 127\x1b[0m', + '\x1b[1;30mWARNING\x1b[0m \x1b[33m[job echo_2] completed permanentFail\x1b[0m'] def _wait_until_exited(pid: int) -> None: @@ -458,132 +339,164 @@ def _wait_until_exited(pid: int) -> None: @pytest.mark.fast -def test_cancelling_a_run_whose_runner_has_exited_reports_how_it_ended( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None, capsys: pytest.CaptureFixture[str]) -> None: - """A runner that exited 0 before `cancel` is a COMPLETED run, with its outputs written: nothing is stopped, - and `cancel` says it cancelled nothing.""" - del offline +@pytest.mark.usefixtures('offline') +@pytest.mark.parametrize('ending', ['completes', 'fails', 'exits-before-cancel', 'leaves-a-process-behind', + 'no-watcher']) +# pylint: disable-next=too-many-locals +def test_a_started_run_is_followed_by_its_handle_to_how_it_ended( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], ending: str) -> None: + """The handle is RUNNING as soon as `start` returns, and `wait` and `collect` time out while it is; `wait` raises + nothing for a run that failed, and ends with the run's status, the same one each time after; `cancel` on an ended + run cancels nothing. `status` answers at once, even while a process the runner left behind holds its streams + open, which keeps the run RUNNING. A runner that exited 0 before `cancel` is a COMPLETED run, with its outputs + written. Without the watcher that stops the runner should Sophios end, the run does not go on.""" outputs = {'out': 1} - fake = install(monkeypatch, tmp_path, stdout=json.dumps(outputs).splitlines()) - handle = echo_workflow().start(run_args_dict={'cwl_runner': 'toil-cwl-runner'}) - fake.wait_until_started() - _wait_until_exited(fake.record()['pid']) - assert not handle.cancel() - assert handle.status().state is RunState.COMPLETED and handle.outputs() == outputs - assert handle.wait().state is RunState.COMPLETED - assert not handle.cancel() - written = tmp_path / 'autogenerated' / 'output_wf.json' - assert json.loads(written.read_text(encoding='utf-8')) == outputs + printed = json.dumps(outputs).splitlines() + behaviour: dict[str, dict[str, Any]] = { + 'completes': {'stdout': printed, 'stderr': ['toil said this'], 'sleep': 1.0}, + 'fails': {'stderr': _EXITED_127, 'exit_code': 1}, 'exits-before-cancel': {'stdout': printed}, + 'leaves-a-process-behind': {'leave_behind': 10}, 'no-watcher': {'sleep': 60}} + fake = install(monkeypatch, tmp_path, **behaviour[ending]) + if ending == 'no-watcher': + monkeypatch.setattr(run_local.sys, 'executable', '') # as in some embedded interpreters + toil = ending in ('completes', 'exits-before-cancel') # Toil prints its output object + handle = echo_workflow().start(run_args_dict={'cwl_runner': 'toil-cwl-runner' if toil else 'cwltool'}) + if ending == 'completes': + assert handle.status().state is RunState.RUNNING and handle.outputs() is None + for waits in (handle.wait, handle.collect): + with pytest.raises(TimeoutError): + waits(timeout=0.05) + if ending == 'leaves-a-process-behind': # the runner has exited, but what it started holds its streams open + fake.wait_until_started() + until = time.monotonic() + 1.5 + while time.monotonic() < until: + asked = time.monotonic() + assert handle.status().state is RunState.RUNNING + assert time.monotonic() - asked < 0.5 + time.sleep(0.1) + handle.cancel() # ends what it left behind + if ending == 'exits-before-cancel': + fake.wait_until_started() + _wait_until_exited(fake.record()['pid']) + assert not handle.cancel() + status = handle.wait() + assert handle.wait() is status is handle.status() and not handle.cancel() + if ending == 'fails': + assert (status.state, status.outputs, status.exit_code) == (RunState.FAILED, None, 1) + assert status.steps == (StepStatus('echo_2', RunState.FAILED, exit_status=127),) + elif ending == 'leaves-a-process-behind': # its runner exited 0 before + assert (status.state, status.outputs, status.exit_code) == (RunState.COMPLETED, None, 0) + elif ending == 'no-watcher': + assert status.state is RunState.FAILED + assert 'the watcher that stops it if Sophios ends could not start' in (status.reason or '') + else: + assert status.state is RunState.COMPLETED and status.outputs == outputs == handle.outputs() + assert status.started_at is not None and status.ended_at is not None and status.started_at <= status.ended_at + result = handle.collect() + log = tmp_path / 'autogenerated' / 'run_wf.log' + assert result == RunResult(RunState.COMPLETED, outputs, result.outdir, log, 0) + assert result.outdir.parent == tmp_path / 'autogenerated' and result.outdir.name.startswith('outdir_toil_wf_') + assert handle.logs() == log.read_text(encoding='utf-8') + assert json.loads((tmp_path / 'autogenerated' / 'output_wf.json').read_text(encoding='utf-8')) == outputs + assert ending != 'completes' or 'toil said this' in handle.logs() assert 'Interrupted' not in capsys.readouterr().err @pytest.mark.fast -def test_run_returns_the_completed_runs_result(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - offline: None) -> None: - """`run()` returns what `start().collect()` returns: a completed run's outputs, output directory and log.""" - del offline - outputs = {'out': 'x'} - install(monkeypatch, tmp_path, stdout=json.dumps(outputs).splitlines()) - run_args = {'cwl_runner': 'toil-cwl-runner', 'outdir': str(tmp_path / 'outdir')} - result = echo_workflow().run(run_args_dict=run_args) - assert result == echo_workflow().start(run_args_dict=run_args).collect() - assert result is not None - assert (result.state, result.outputs, result.exit_code) == (RunState.COMPLETED, outputs, 0) - assert result.log_file.is_file() and result.outdir.is_absolute() +@pytest.mark.serial +@pytest.mark.usefixtures('offline') +@pytest.mark.parametrize('how', ['here', 'from-another-thread', 'ignoring-sigterm']) +def test_a_cancelled_run_stays_cancelled(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, + capsys: pytest.CaptureFixture[str], how: str) -> None: + """`cancel` stops the runner with SIGTERM, from any thread, and kills it and its session after the grace when + SIGTERM is not enough. A second `cancel`, a later `wait` and `collect` change nothing, `wait` reports the + cancellation and not the exit status the runner stopped with, and `collect` raises the run as cancelled, not as + failed.""" + fake = install(monkeypatch, tmp_path, sleep=60, ignore_sigterm=how == 'ignoring-sigterm') + monkeypatch.setattr(run_local, 'STOP_GRACE_SECONDS', 0.5) + handle = echo_workflow().start() + fake.wait_until_started() + if how == 'from-another-thread': + canceller = threading.Thread(target=handle.cancel) + canceller.start() + assert handle.wait().state is RunState.CANCELLED + canceller.join() + else: + assert handle.cancel() + assert handle.cancel() + status = handle.status() + assert handle.wait() is status and status.state is RunState.CANCELLED + assert status.exit_code == -9 if how == 'ignoring-sigterm' else fake.record()['signal'] == 15 + with pytest.raises(WorkflowRunError, match='did not complete: cancelled: the runner was stopped') as caught: + handle.collect() + assert 'fail' not in str(caught.value) and handle.outputs() is None + assert 'Failure!' not in capsys.readouterr().err @pytest.mark.fast -def test_run_async_leaves_the_event_loop_free_while_the_runner_runs( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None) -> None: - """Another coroutine keeps running while the runner does, and the run's result is awaited.""" - del offline - outputs = {'out': 2} +@pytest.mark.usefixtures('offline') +@pytest.mark.parametrize('door', ['run', 'start-collect', 'run_async']) +def test_each_python_door_returns_a_completed_runs_result_and_raises_a_failed_ones( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], door: str) -> None: + """`run()` returns what `start().collect()` returns, and so does `run_async`, which leaves the event loop free + while the runner runs: a completed run's outputs, its output directory and its log. A failed run raises with the + runner's exit code, so it cannot be missed. Cancelling the `run_async` task stops the runner: it is sent SIGTERM + and has exited before the task's cancellation is seen.""" + outputs = {'out': 'x'} fake = install(monkeypatch, tmp_path, stdout=json.dumps(outputs).splitlines(), sleep=1.0) - - async def main() -> tuple[RunResult | None, int]: - ticks_while_running = 0 - - async def tick() -> None: - nonlocal ticks_while_running - while True: - ticks_while_running += fake.record_path.exists() - await asyncio.sleep(0.01) - - ticker = asyncio.create_task(tick()) - result = await echo_workflow().run_async(run_args_dict={'cwl_runner': 'toil-cwl-runner'}) - ticker.cancel() - return result, ticks_while_running - - result, ticks = asyncio.run(main()) - assert result is not None and (result.state, result.outputs) == (RunState.COMPLETED, outputs) - assert ticks >= 10 - - -@pytest.mark.fast -def test_cancelling_the_run_async_task_stops_the_runner( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None, capsys: pytest.CaptureFixture[str]) -> None: - """The runner is sent SIGTERM and has exited before the task's cancellation is seen.""" - del offline - fake = install(monkeypatch, tmp_path, sleep=60) - - async def main() -> None: + run_args = {'cwl_runner': 'toil-cwl-runner', 'outdir': str(tmp_path / 'outdir')} + ticks = 0 + + def through(workflow: Workflow) -> RunResult | None: + if door == 'run': + return workflow.run(run_args_dict=run_args) + if door == 'start-collect': + return workflow.start(run_args_dict=run_args).collect() + + async def main() -> RunResult | None: + async def tick() -> None: + nonlocal ticks + while True: + ticks += fake.record_path.exists() + await asyncio.sleep(0.01) + ticker = asyncio.create_task(tick()) + result = await workflow.run_async(run_args_dict=run_args) + ticker.cancel() + return result + return asyncio.run(main()) + + result = through(echo_workflow()) + assert result is not None and (result.state, result.outputs, result.exit_code) == (RunState.COMPLETED, outputs, 0) + assert result.log_file.is_file() and result.outdir == tmp_path / 'outdir' + assert door != 'run_async' or ticks >= 10 + (tmp_path / 'failing').mkdir() + install(monkeypatch, tmp_path / 'failing', exit_code=7) + with pytest.raises(WorkflowRunError) as raised: + through(echo_workflow('failing')) + assert raised.value.exit_code == 7 + assert str(raised.value) == ("error [api005] workflow 'failing' did not complete: the runner exited with status 7" + '\nerror [api005] the lines printed above this error say why') + if door != 'run_async': + return + (tmp_path / 'cancelled').mkdir() + stopping = install(monkeypatch, tmp_path / 'cancelled', sleep=60) + + async def cancelled() -> None: task = asyncio.create_task(echo_workflow().run_async()) - while not fake.record_path.exists(): + while not stopping.record_path.exists(): await asyncio.sleep(0.02) task.cancel() with pytest.raises(asyncio.CancelledError): await task - asyncio.run(main()) - stopped = fake.record() + asyncio.run(cancelled()) + stopped = stopping.record() assert stopped['signal'] == 15 with pytest.raises(ProcessLookupError): os.kill(stopped['pid'], 0) assert "Interrupted; the runner's processes were terminated." in capsys.readouterr().err -@pytest.mark.fast -def test_a_run_deletes_nothing_in_the_working_directory(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """A run used to `rmtree` every `*` beside it, and `--cachedir ''` matched the whole directory.""" - work = tmp_path / 'work' - work.mkdir() - monkeypatch.chdir(work) - (work / 'cachedir_results').mkdir() - (work / 'notes.txt').write_text('mine', encoding='utf-8') - install(monkeypatch, tmp_path) - for cachedir in ('', 'cachedir'): - assert run_local.run(RunRequest('wf', tmp_path / 'base', cachedir=cachedir)) == 0 - assert sorted(path.name for path in work.iterdir()) == ['cachedir_results', 'notes.txt'] - - -@pytest.mark.fast -def test_the_python_api_runs_the_command_its_run_script_holds(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - offline: None) -> None: - """`run()` starts exactly what `run(generate_run_script=yes)` writes to run.sh.""" - del offline - fake = install(monkeypatch, tmp_path) - monkeypatch.setattr(backends, 'datetime', _Frozen) - run_args = {'quiet': 'no', 'cachedir': 'cache', 'logLevel': 'INFO'} - echo_workflow().run(run_args_dict={**run_args, 'generate_run_script': 'yes'}) - script = shlex.split((tmp_path / 'run.sh').read_text(encoding='utf-8').splitlines()[-1]) - echo_workflow().run(run_args_dict=run_args) - # The stand-in is a script, so its own argv[0] is its path: the arguments are compared. - assert script[0] == 'cwltool_filterlog' and '--cachedir' in script and '--quiet' not in script - assert fake.record()['argv'][1:] == script[1:] - - -@pytest.mark.fast -def test_python_api_runs_go_through_the_same_path(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - offline: None, capsys: pytest.CaptureFixture[str]) -> None: - """`Workflow.run()` prints what the command line prints.""" - del offline - install(monkeypatch, tmp_path, stdout=['from the runner']) - echo_workflow().run() - out = capsys.readouterr().out - assert 'Running cwltool_filterlog ' in out and 'from the runner' in out and 'Success! ' in out - assert 'python API' not in out - - @pytest.mark.fast @pytest.mark.needs_cwltool @pytest.mark.parametrize('entry_point', [run_local.cwltool_main, run_local.cwltool_main_pf]) @@ -612,13 +525,6 @@ def provenance_run(argv: list[str]) -> int: 'basename': 'stdout'}} -@pytest.fixture(name='nextflow_ready') -def _nextflow_ready(monkeypatch: pytest.MonkeyPatch, offline: None) -> None: - """`offline`, with nothing asked of Nextflow's own program before the stand-in starts.""" - del offline - monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: []) - - def _nextflow_argv(base: Path, *passthrough: str, name: str = 'wf') -> list[str]: """The arguments Nextflow is started with for the workflow `name` in `base`, after its program.""" run = base.resolve() / f'nextflow_{name}' @@ -627,208 +533,65 @@ def _nextflow_argv(base: Path, *passthrough: str, name: str = 'wf') -> list[str] @pytest.mark.fast -@pytest.mark.parametrize('front_door', [lambda workflow: workflow.run(target='nextflow'), - lambda workflow: workflow.start(target='nextflow').collect(), - lambda workflow: asyncio.run(workflow.run_async(target='nextflow'))], - ids=['run', 'start', 'run_async']) -def test_each_python_front_door_runs_the_nextflow_target_and_reports_its_recorded_outputs( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, nextflow_ready: None, - front_door: Callable[[Workflow], RunResult | None]) -> None: - """Nextflow starts from the workflow's own directory on the pipeline Sophios wrote there, and the outputs it - recorded come back under their Sophios names, also in `output_wf.json`.""" - del nextflow_ready +@pytest.mark.filterwarnings('error::UserWarning') +@pytest.mark.parametrize('door', ['run', 'start', 'run_async', 'command line']) +# pylint: disable-next=too-many-locals +def test_each_door_runs_the_nextflow_target_and_reports_its_recorded_outputs( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, sophios: Callable[..., int], + capsys: pytest.CaptureFixture[str], door: str) -> None: + """Nextflow starts from the workflow's own directory on the pipeline Sophios wrote there, with the passthrough + arguments, and the outputs it recorded come back under their Sophios names, also in `output_.json`; the + command line's run is what its run script holds. Each note the lowering made is a line on stderr, as the command + line prints it, and never a warning, and the result of the run carries the same notes.""" fake = install(monkeypatch, tmp_path, stdout=['[PROCESS ab/cdef12] wf:echo', _RECORDED]) - result = front_door(echo_workflow()) base = (tmp_path / 'autogenerated').resolve() + if door == 'command line': + flags = ('--target', 'nextflow', '--passthrough_flags', 'yes', '-resume') + assert sophios(*flags, '--generate_run_script') == 0 + assert sophios(*flags, '--run_local') == 0 + argv = _nextflow_argv(base, '-resume', name='helloworld') + assert _script(tmp_path) == ['nextflow', *argv] and fake.record()['argv'][1:] == argv + assert json.loads((base / 'output_helloworld.json').read_text(encoding='utf-8')) == _ECHO_OUTPUTS + return + through: dict[str, Callable[[Workflow], RunResult | None]] = { + 'run': lambda workflow: workflow.run(target='nextflow'), + 'start': lambda workflow: workflow.start(target='nextflow').collect(), + 'run_async': lambda workflow: asyncio.run(workflow.run_async(target='nextflow'))} + result = through[door](echo_workflow()) assert result is not None and (result.state, result.outputs) == (RunState.COMPLETED, _ECHO_OUTPUTS) assert result.outdir == base / 'nextflow_wf' / 'work' assert json.loads((base / 'output_wf.json').read_text(encoding='utf-8')) == _ECHO_OUTPUTS - started = fake.record() - assert started['argv'][1:] == _nextflow_argv(base) and Path(started['cwd']) == base / 'nextflow_wf' - - -@pytest.mark.fast -def test_python_run_args_reach_nextflow_with_one_dash_and_a_cwl_only_option_is_refused( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, nextflow_ready: None) -> None: - """A key Sophios does not read is a Nextflow option, alone when its value is empty, with this process's - environment under the user's, and the v2 script parser whatever the shell set; one only a CWL run - reads stops the run before anything is written.""" - del nextflow_ready + assert fake.record()['argv'][1:] == _nextflow_argv(base) and Path(fake.record()['cwd']) == base / 'nextflow_wf' + capsys.readouterr() + (tmp_path / 'gpu').mkdir() + install(monkeypatch, tmp_path / 'gpu') + noted = through[door](gpu_workflow()) + assert noted is not None + printed = [line for line in capsys.readouterr().err.splitlines() if '[wic046]' in line] + assert [(str(note.severity), str(note.code), note.locator and note.locator.step) for note in noted.diagnostics + if note.code is SophiosErrorCode.UNCHECKED_CUDA_FIELD] == CUDA_NOTES + assert [str(note) for note in noted.diagnostics if note.code is SophiosErrorCode.UNCHECKED_CUDA_FIELD] == printed + if door != 'run': + return monkeypatch.setenv('SOPHIOS_TEST_KEPT', 'kept') monkeypatch.setenv('NXF_SYNTAX_PARSER', 'v1') - fake = install(monkeypatch, tmp_path, stdout=[_RECORDED]) - echo_workflow().run(target='nextflow', run_args_dict={'process.executor': 'slurm', 'resume': ''}, - user_env_vars={'SOPHIOS_TEST_TOKEN': 'x'}) + (tmp_path / 'options').mkdir() + fake = install(monkeypatch, tmp_path / 'options', stdout=[_RECORDED]) + workflow = echo_workflow() + workflow.outputs.echo_stdout = workflow.steps[0].outputs.stdout + declared = workflow.run(target='nextflow', run_args_dict={'process.executor': 'slurm', 'resume': ''}, + user_env_vars={'SOPHIOS_TEST_TOKEN': 'x'}) + assert declared is not None and declared.outputs == {'echo_stdout': _ECHO_OUTPUTS['echo~stdout']} assert fake.record()['argv'][1:] == _nextflow_argv(tmp_path / 'autogenerated', '-process.executor', 'slurm', '-resume') env = fake.record()['env'] assert (env['SOPHIOS_TEST_TOKEN'], env['SOPHIOS_TEST_KEPT'], env['NXF_SYNTAX_PARSER']) == ('x', 'kept', 'v2') - fake.record_path.unlink() - with pytest.raises(ValueError, match="run_args_dict keys only a CWL run reads: 'cachedir', 'quiet'$"): - echo_workflow().run(target='nextflow', basepath='refused', - run_args_dict={'cachedir': 'cache', 'resume': '', 'quiet': 'no'}) - assert not fake.record_path.exists() and not (tmp_path / 'refused').exists() - - -@pytest.mark.fast -@pytest.mark.filterwarnings('error::UserWarning') -def test_each_python_front_door_prints_the_nextflow_notes_and_the_run_carries_them( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, nextflow_ready: None, - capsys: pytest.CaptureFixture[str]) -> None: - """Each note the lowering made is a line on stderr, as the command line prints it, and never a warning; the - result of the run carries the same notes.""" - del nextflow_ready - install(monkeypatch, tmp_path) - - async def run_async() -> None: - await gpu_workflow().run_async(target='nextflow') - result = gpu_workflow().run(target='nextflow') - gpu_workflow().start(target='nextflow').wait() - asyncio.run(run_async()) - printed = [line for line in capsys.readouterr().err.splitlines() if '[wic046]' in line] - assert result is not None - cuda = [note for note in result.diagnostics if note.code is SophiosErrorCode.UNCHECKED_CUDA_FIELD] - assert [(str(note.severity), str(note.code), note.locator and note.locator.step) for note in cuda] == CUDA_NOTES - assert [str(note) for note in cuda] * 3 == printed - - -@pytest.mark.fast -def test_a_nextflow_run_says_its_real_time_analysis_does_not_run( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, nextflow_ready: None, - capsys: pytest.CaptureFixture[str]) -> None: - del nextflow_ready - install(monkeypatch, tmp_path) + (tmp_path / 'live').mkdir() + install(monkeypatch, tmp_path / 'live') live_workflow('live').run(target='nextflow') assert 'Real-time analysis needs cwltool; nextflow runs the workflow without it.' in capsys.readouterr().err - - -@pytest.mark.fast -def test_a_python_nextflow_run_has_the_outputs_compile_returns( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, nextflow_ready: None) -> None: - """Only those the workflow declares, so a declared `echo_stdout` is not the step output `echo~stdout`, whose - Nextflow name it would share.""" - del nextflow_ready - install(monkeypatch, tmp_path, stdout=[_RECORDED]) - workflow = echo_workflow() - workflow.outputs.echo_stdout = workflow.steps[0].outputs.stdout - result = workflow.run(target='nextflow') - assert result is not None and result.outputs == {'echo_stdout': _ECHO_OUTPUTS['echo~stdout']} - - -@pytest.mark.fast -def test_the_command_line_runs_the_nextflow_target_writes_its_run_script_and_checks_for_it( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, sophios: Callable[..., int], - capsys: pytest.CaptureFixture[str]) -> None: - """`--run_local` runs what `--generate_run_script` writes, with the passthrough arguments, and `--check` - asks the backend, which asks for Nextflow.""" - monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: []) - fake = install(monkeypatch, tmp_path, stdout=['sophios-output ' + json.dumps(['echo_stdout', 'x'])]) - flags = ('--target', 'nextflow', '--passthrough_flags', 'yes', '-resume') - assert sophios(*flags, '--generate_run_script') == 0 - script = shlex.split((tmp_path / 'run.sh').read_text(encoding='utf-8').splitlines()[-1]) - assert sophios(*flags, '--run_local') == 0 - argv = _nextflow_argv(tmp_path / 'autogenerated', '-resume', name='helloworld') - assert script == ['nextflow', *argv] - assert fake.record()['argv'][1:] == argv - summary = tmp_path / 'autogenerated' / 'output_helloworld.json' - assert json.loads(summary.read_text(encoding='utf-8')) == {'echo~stdout': 'x'} missing = Diagnostic(Severity.ERROR, SophiosErrorCode.PROGRAM_MISSING, 'nextflow is not here.') monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: [missing]) - capsys.readouterr() - assert sophios('--target', 'nextflow', '--check') == 1 - assert 'error [wic029] nextflow is not here.' in capsys.readouterr().err - - -#: A tool that writes into an output-target Directory, with two CUDA fields the Nextflow target notes it does not -#: check. -_WRITE_INTO_GPU = '''cwlVersion: v1.2 -class: CommandLineTool -$namespaces: - cwltool: http://commonwl.org/cwltool# -baseCommand: touch -requirements: - InitialWorkDirRequirement: - listing: - - entry: $(inputs.outDir) - writable: true -hints: - cwltool:CUDARequirement: - cudaVersionMin: '11.4' - cudaComputeCapability: '3.0' - cudaDeviceCountMin: 1 -inputs: - outDir: - type: Directory -outputs: - outDir: - type: Directory - outputBinding: - glob: $(inputs.outDir.basename) -arguments: -- $(inputs.outDir.basename)/result.txt -''' - - -def _check_made(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> int | str | None: - """`sophios --check --target nextflow` on `made.wic`, one step writing into the output-target Directory `made`.""" - write_tree(tmp_path, {'tools/write_into.cwl': _WRITE_INTO_GPU, - 'made.wic': 'steps:\n- id: write_into\n in:\n outDir: !ii made\n'}) - config = search_config(tmp_path / 'config.json', [tmp_path / 'tools'], [tmp_path]) - return run_cli(monkeypatch, '--yaml', 'made.wic', '--config_file', config, '--target', 'nextflow', '--check') - - -@pytest.mark.fast -def test_the_command_line_check_for_the_nextflow_target_runs_and_makes_nothing( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None, capsys: pytest.CaptureFixture[str]) -> None: - """It reports the lowering's notes and stops: Nextflow is not started, nothing is written into the base path, - and the output directory a tool writes into is not made.""" - del offline - monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: []) - fake = install(monkeypatch, tmp_path) - assert _check_made(monkeypatch, tmp_path) is None - captured = capsys.readouterr() - assert ('Checked made: nothing in the way of a local run on this machine. ' - 'Nothing was written, pulled or run.') in captured.out - assert "note [wic046] cwltool:CUDARequirement cudaVersionMin '11.4' is not checked" in captured.err - assert not fake.record_path.exists() and not (tmp_path / 'made').exists() - assert not (tmp_path / 'autogenerated').exists() - - -@pytest.mark.fast -@pytest.mark.parametrize('passes', [True, False], ids=['passes', 'fails']) -def test_a_nextflow_check_leaves_an_earlier_pipeline_as_it_was( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, offline: None, passes: bool) -> None: - """Passing or failing, a Nextflow --check writes nothing into the base path, as a CWL one does.""" - del offline - missing = Diagnostic(Severity.ERROR, SophiosErrorCode.PROGRAM_MISSING, 'nextflow is not here.') - monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: [] if passes else [missing]) - install(monkeypatch, tmp_path) - basepath = tmp_path / 'autogenerated' - (basepath / 'nextflow_made').mkdir(parents=True) - for name in ('workflow.nf', 'nextflow.config', 'nextflow_params.json', 'nextflow_workflow.json'): - (basepath / 'nextflow_made' / name).write_text(f'an earlier {name}\n', encoding='utf-8') - before = {path: None if path.is_dir() else path.read_bytes() for path in basepath.rglob('*')} - assert _check_made(monkeypatch, tmp_path) == (None if passes else 1) - assert {path: None if path.is_dir() else path.read_bytes() for path in basepath.rglob('*')} == before - - -@pytest.mark.fast -@pytest.mark.parametrize('front_door', ['python', 'command line']) -def test_a_nextflow_run_without_docker_is_not_told_of_an_option_its_target_refuses( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, nextflow_ready: None, capsys: pytest.CaptureFixture[str], - front_door: str) -> None: - """`--container_engine` is a CWL run's option: each front door says the run is Nextflow's.""" - del nextflow_ready - monkeypatch.setenv('PATH', str(tmp_path / 'nothing')) - if front_door == 'python': - with pytest.raises(SophiosError) as raised: - Workflow([adapter_step('touch', filename='empty.txt')], 'wf').run(target='nextflow') - said = '\n'.join(map(str, raised.value.diagnostics)) - else: - write_tree(tmp_path, {'touch.wic': 'steps:\n- id: touch\n in:\n filename: !ii empty.txt\n'}) - config = search_config(tmp_path / 'config.json', [ADAPTERS], [tmp_path]) - assert run_cli(monkeypatch, '--yaml', 'touch.wic', '--config_file', config, '--target', 'nextflow', - '--check') == 1 - said = capsys.readouterr().err - assert ('error [wic015] docker is not installed (it is not on PATH), and this workflow runs tools in containers ' - '(docker.io/library/debian:bookworm-slim): install docker.') in said + with pytest.raises(SophiosError) as raised: + echo_workflow().run(target='nextflow') + assert list(raised.value.diagnostics) == [missing] diff --git a/tests/core/test_run_on_windows.py b/tests/core/test_run_on_windows.py index bf43e017a..91e037490 100644 --- a/tests/core/test_run_on_windows.py +++ b/tests/core/test_run_on_windows.py @@ -12,7 +12,7 @@ from sophios.api.python.workflow import Workflow from sophios.lang import SophiosError -from .helpers import EACH_RUNNER, HELLOWORLD, echo_workflow, run_cli +from .helpers import HELLOWORLD, echo_workflow, run_cli WINDOWS = 'cwltool and Toil need the pwd module, which Windows does not have' @@ -29,34 +29,28 @@ def _refused(runner: str) -> str: @pytest.mark.fast -def test_the_platform_says_why_no_runner_runs() -> None: - assert preflight.PLATFORM_LACKS_RUNNERS == WINDOWS - - -@pytest.mark.fast -@EACH_RUNNER -def test_run_local_says_to_run_in_wsl(runner: str, monkeypatch: pytest.MonkeyPatch, +@pytest.mark.parametrize('door', ['command line cwltool', 'command line toil-cwl-runner', 'run', 'start', 'run_async', + 'compute ssh', 'compute unix']) +def test_each_door_says_to_run_in_wsl(door: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: - assert run_cli(monkeypatch, '--yaml', HELLOWORLD, '--run_local', '--cwl_runner', runner) == 1 - assert _refused(runner) in capsys.readouterr().err - - -@pytest.mark.fast -@pytest.mark.parametrize('front_door', [lambda workflow, base: workflow.run(basepath=base), - lambda workflow, base: workflow.start(basepath=base), - lambda workflow, base: asyncio.run(workflow.run_async(basepath=base))], - ids=['run', 'start', 'run_async']) -def test_each_python_front_door_raises_it(tmp_path: Path, front_door: Callable[[Workflow, str], object]) -> None: - with pytest.raises(SophiosError) as caught: - front_door(echo_workflow(), str(tmp_path / 'autogenerated')) - assert any(str(diagnostic).startswith(_refused('cwltool')) for diagnostic in caught.value.diagnostics) - - -@pytest.mark.fast -@pytest.mark.parametrize('url', ['ssh://cluster', 'unix:///api.sock', 'http://cluster:7998']) -def test_a_compute_service_says_to_run_in_wsl(url: str) -> None: - with pytest.raises(compute.ServiceUnavailable) as unavailable: - compute.Service(url) - assert unavailable.value.messages == ( - 'the compute client needs macOS, Linux or WSL: it reaches the service over a Unix socket, which Python on ' - 'Windows itself cannot open; run Sophios inside WSL',) + """The platform says why no runner runs: the command line and each Python front door stop at the pre-flight with + one diagnostic, and a compute service, which needs a Unix socket, is unavailable.""" + assert preflight.PLATFORM_LACKS_RUNNERS == WINDOWS + if door.startswith('command line'): + runner = door.split()[-1] + assert run_cli(monkeypatch, '--yaml', HELLOWORLD, '--run_local', '--cwl_runner', runner) == 1 + assert _refused(runner) in capsys.readouterr().err + elif door.startswith('compute'): + with pytest.raises(compute.ServiceUnavailable) as unavailable: + compute.Service({'ssh': 'ssh://cluster', 'unix': 'unix:///api.sock'}[door.split()[-1]]) + assert unavailable.value.messages == ( + 'the compute client needs macOS, Linux or WSL: it reaches the service over a Unix socket, which Python on ' + 'Windows itself cannot open; run Sophios inside WSL',) + else: + front_door: dict[str, Callable[[Workflow, str], object]] = { + 'run': lambda workflow, base: workflow.run(basepath=base), + 'start': lambda workflow, base: workflow.start(basepath=base), + 'run_async': lambda workflow, base: asyncio.run(workflow.run_async(basepath=base))} + with pytest.raises(SophiosError) as caught: + front_door[door](echo_workflow(), str(tmp_path / 'autogenerated')) + assert any(str(diagnostic).startswith(_refused('cwltool')) for diagnostic in caught.value.diagnostics) diff --git a/tests/core/test_settings_boundary.py b/tests/core/test_settings_boundary.py index 6916b02ca..6130d6947 100644 --- a/tests/core/test_settings_boundary.py +++ b/tests/core/test_settings_boundary.py @@ -1,26 +1,25 @@ """Configuration is a value parsed once at the boundary: nothing installs a command line over sys.argv to compute it, and no argparse.Namespace travels past the CLI, so every flag reaches the compiler as given.""" import sys -from collections.abc import Callable from pathlib import Path from typing import Any, Final import pytest -import yaml - import sophios.cli import sophios.compiler import sophios.drawing import sophios.main from sophios.wic_types import CompilerOptions, GraphSettings +from .cases import DATA + pytestmark = pytest.mark.package -#: A minimal workflow: enough to reach the compiler and the drawing, cheap enough to run once -#: per setting. The compiler's options are caught before it does any work. -PROBE_WORKFLOW: Final = {'steps': [{'id': 'touch', 'in': {'filename': {'wic_inline_input': 'empty.txt'}}}]} +#: A minimal workflow: enough to reach the compiler and the drawing, cheap enough to run once per setting. The +#: compiler's options are caught before it does any work. +PROBE_WORKFLOW: Final = DATA / 'config' / 'w.wic' class _Delivered(BaseException): @@ -36,26 +35,21 @@ def __init__(self, settings: Any) -> None: _RECEIVERS: Final = ((sophios.compiler, 'compile_source', 1, ()), (sophios.drawing, 'draw', 2, ('--graphviz',))) -@pytest.fixture(name='settings_from_cli') -def _settings_from_cli(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Callable[..., Any]: +def _settings_from_cli(monkeypatch: pytest.MonkeyPatch, workflow: Path, index: int, *flags: str) -> Any: """Run the real CLI via `main._main()` and return the settings dict the compiler (index 0) or the drawing (index 1) got. Driven end to end: the bug was a caller asking for defaults, which a test of the converter alone passed.""" - def run(index: int, *flags: str) -> Any: - workflow = tmp_path / 'probe.wic' - workflow.write_text(yaml.safe_dump(PROBE_WORKFLOW), encoding='utf-8') - module, receiver, position, needs = _RECEIVERS[index] + module, receiver, position, needs = _RECEIVERS[index] - def capture(*args: Any, **_kwargs: Any) -> None: - raise _Delivered(args[position]) + def capture(*args: Any, **_kwargs: Any) -> None: + raise _Delivered(args[position]) - monkeypatch.setattr(module, receiver, capture) - monkeypatch.setattr(sys, 'argv', ['sophios', '--yaml', str(workflow), *needs, *flags]) - try: - sophios.main._main(*sophios.cli.parser.parse_known_args()) - except _Delivered as delivered: - return delivered.settings - raise AssertionError(f'{receiver} was never reached') - return run + monkeypatch.setattr(module, receiver, capture) + monkeypatch.setattr(sys, 'argv', ['sophios', '--yaml', str(workflow), *needs, *flags]) + try: + sophios.main._main(*sophios.cli.parser.parse_known_args()) + except _Delivered as delivered: + return delivered.settings + raise AssertionError(f'{receiver} was never reached') def _settings_fields() -> list[tuple[int, str, type]]: @@ -96,21 +90,18 @@ def _non_default(name: str, annotation: type) -> tuple[list[str], object]: @pytest.mark.fast -@pytest.mark.parametrize('index,name,annotation', _DELIVERABLE, - ids=[name for _index, name, _annotation in _DELIVERABLE]) -def test_every_setting_reaches_the_compiler(settings_from_cli: Callable[..., Any], - index: int, name: str, annotation: type) -> None: +def test_every_setting_reaches_the_compiler(monkeypatch: pytest.MonkeyPatch) -> None: """A setting chosen on the command line is the setting the compiler, or the drawing, gets. - One property instead of a test per flag, and derived from the settings - types instead of a list someone maintains. Every delivery bug found so far - fails this: `main` asking for defaults, and the same mistake repeated in - the end-to-end test helper, silently turned all of these into their - defaults at once. + One check over every field of the settings types, not a test per flag, and derived from the types instead of a + list someone maintains. Every delivery bug found so far fails this: `main` asking for defaults, and the same + mistake repeated in the end-to-end test helper, silently turned all of these into their defaults at once. """ - flags, expected = _non_default(name, annotation) - settings = settings_from_cli(index, *flags) - assert settings[name] == expected, ( - f'--{name} was set on the command line but {_RECEIVERS[index][1]} received ' - f'{settings[name]!r} instead of {expected!r}' - ) + for index, name, annotation in _DELIVERABLE: + flags, expected = _non_default(name, annotation) + with monkeypatch.context() as patches: + settings = _settings_from_cli(patches, PROBE_WORKFLOW, index, *flags) + assert settings[name] == expected, ( + f'--{name} was set on the command line but {_RECEIVERS[index][1]} received ' + f'{settings[name]!r} instead of {expected!r}' + ) From a0cb5f535f32e5401ca61be6d5e9b03d0e19a3be Mon Sep 17 00:00:00 2001 From: Vasu Jaganath Date: Fri, 13 Nov 2026 01:35:45 -0500 Subject: [PATCH 6/7] test(api): pairs, scripts and refusals in files Pairs, shipped scripts, the builder script, API refusals, from_wic families and REST payloads state what they compile to; the corpus is checked once per leg. --- .github/workflows/lint_and_test.yml | 25 +- .github/workflows/lint_and_test_macos.yml | 25 +- .github/workflows/run_workflows_weekly.yml | 2 +- tests/contrib/data/__init__.py | 0 tests/contrib/data/cwl/helloworld.cwl | 24 - .../contrib/rest_wfb_objects/declaration.json | 32 + tests/contrib/rest_wfb_objects/expected.yaml | 24 + tests/contrib/rest_wfb_objects/packed.json | 43 + tests/contrib/rest_wfb_objects/s.sh | 2 + tests/contrib/test_fix_payload.py | 22 - tests/contrib/test_rest_api.py | 114 +- .../from_wic/built/every_construct/child.wic | 6 + .../built/every_construct/expected.yaml | 7 + .../from_wic/built/every_construct/left.wic | 2 + .../from_wic/built/every_construct/right.wic | 2 + .../from_wic/built/every_construct/root.wic | 46 + .../built/every_construct/same.wic} | 0 .../refused/does_not_compile/expected.yaml | 2 + .../refused}/does_not_compile/root.wic | 0 .../refused/every_construct}/child.wic | 0 .../refused/every_construct/expected.yaml | 15 + .../from_wic/refused/every_construct/left.wic | 2 + .../refused/every_construct/reader.wic} | 0 .../refused/every_construct/right.wic | 2 + .../from_wic/refused/every_construct/root.wic | 31 + .../refused/every_construct/twice.wic | 1 + .../refused/held_scatter/expected.yaml | 2 + .../from_wic/refused/held_scatter/root.wic | 4 + .../refused/held_scheme/expected.yaml | 2 + .../from_wic/refused/held_scheme/root.wic | 2 + .../refused/implementations/expected.yaml | 4 + .../refused}/implementations/root.wic | 0 .../refused/python_script/expected.yaml | 4 + .../does_not_compile/expected.yaml | 2 - .../edge_from_another_document/expected.yaml | 2 - .../edge_from_another_document/root.wic | 1 - .../every_refusal_at_once/expected.yaml | 4 - .../every_refusal_at_once/root.wic | 2 - .../generated_step_name/expected.yaml | 3 - .../generated_step_name/root.wic | 2 - .../implementations/expected.yaml | 3 - .../input_default/expected.yaml | 1 - .../from_wic_refusals/input_default/root.wic | 2 - .../language_version_pin/expected.yaml | 1 - .../language_version_pin/root.wic | 2 - .../one_file_two_bodies/expected.yaml | 2 - .../one_file_two_bodies/left.wic | 2 - .../one_file_two_bodies/right.wic | 2 - .../one_file_two_bodies/root.wic | 1 - .../plugin_namespace/expected.yaml | 2 - .../plugin_namespace/root.wic | 2 - .../port_named_ref_t/expected.yaml | 2 - .../port_named_ref_t/root.wic | 2 - .../raw_cwl_source/expected.yaml | 1 - .../from_wic_refusals/raw_cwl_source/root.wic | 1 - .../repeated_step_id/expected.yaml | 2 - .../repeated_step_id/root.wic | 1 - .../run_names_a_workflow/child.wic | 1 - .../run_names_a_workflow/expected.yaml | 1 - .../run_names_a_workflow/root.wic | 1 - .../scatter_on_a_call/expected.yaml | 2 - .../scatter_on_a_call/root.wic | 1 - .../scatter_without_method/expected.yaml | 1 - .../scatter_without_method/root.wic | 1 - .../step_label/expected.yaml | 1 - .../from_wic_refusals/step_label/root.wic | 1 - .../top_level_hints/expected.yaml | 2 - .../top_level_hints/root.wic | 2 - tests/core/data/pairs/cookbook.yaml | 69 + tests/core/data/pairs/python_api_pairs.yaml | 6 + tests/core/data/pairs/record.cwl | 98 ++ tests/core/data/python_api/aligner.cwl | 82 + tests/core/data/python_api/builder.cwl | 104 ++ tests/core/data/python_api/builder.py | 42 + tests/core/data/python_api/builder_job.yml | 4 + tests/core/data/python_api/cat.cwl | 13 + tests/core/data/python_api/exits_3.cwl | 7 + tests/core/data/python_api/false.cwl | 6 + tests/core/data/python_api/hinted.cwl | 9 + tests/core/data/python_api/refused.py | 299 ++++ tests/core/data/python_api/refused.yaml | 52 + tests/core/data/python_api/say.cwl | 6 + tests/core/data/python_api/say_hello.py | 13 + tests/core/data/python_api/write_dir.cwl | 22 + tests/core/data/shipped_scripts.yaml | 101 ++ tests/core/ground_truth_multistep1.json | 188 --- tests/core/test_ci_coverage.py | 30 +- tests/core/test_cookbook.py | 295 ++-- tests/core/test_example_scripts.py | 193 +-- tests/core/test_examples.py | 482 ++---- tests/core/test_python_api_draw.py | 61 +- tests/core/test_python_api_from_wic.py | 329 ++-- tests/core/test_python_api_inference.py | 84 +- tests/core/test_python_api_tool_builder.py | 215 +-- tests/core/test_python_api_workflow.py | 1454 ++++------------- 95 files changed, 1991 insertions(+), 2779 deletions(-) delete mode 100644 tests/contrib/data/__init__.py delete mode 100644 tests/contrib/data/cwl/helloworld.cwl create mode 100644 tests/contrib/rest_wfb_objects/declaration.json create mode 100644 tests/contrib/rest_wfb_objects/expected.yaml create mode 100644 tests/contrib/rest_wfb_objects/packed.json create mode 100644 tests/contrib/rest_wfb_objects/s.sh delete mode 100644 tests/contrib/test_fix_payload.py create mode 100644 tests/core/data/from_wic/built/every_construct/child.wic create mode 100644 tests/core/data/from_wic/built/every_construct/expected.yaml create mode 100644 tests/core/data/from_wic/built/every_construct/left.wic create mode 100644 tests/core/data/from_wic/built/every_construct/right.wic create mode 100644 tests/core/data/from_wic/built/every_construct/root.wic rename tests/core/data/{from_wic_refusals/one_file_two_bodies/child.wic => from_wic/built/every_construct/same.wic} (100%) create mode 100644 tests/core/data/from_wic/refused/does_not_compile/expected.yaml rename tests/core/data/{from_wic_refusals => from_wic/refused}/does_not_compile/root.wic (100%) rename tests/core/data/{from_wic_refusals/scatter_on_a_call => from_wic/refused/every_construct}/child.wic (100%) create mode 100644 tests/core/data/from_wic/refused/every_construct/expected.yaml create mode 100644 tests/core/data/from_wic/refused/every_construct/left.wic rename tests/core/data/{from_wic_refusals/edge_from_another_document/child.wic => from_wic/refused/every_construct/reader.wic} (100%) create mode 100644 tests/core/data/from_wic/refused/every_construct/right.wic create mode 100644 tests/core/data/from_wic/refused/every_construct/root.wic create mode 100644 tests/core/data/from_wic/refused/every_construct/twice.wic create mode 100644 tests/core/data/from_wic/refused/held_scatter/expected.yaml create mode 100644 tests/core/data/from_wic/refused/held_scatter/root.wic create mode 100644 tests/core/data/from_wic/refused/held_scheme/expected.yaml create mode 100644 tests/core/data/from_wic/refused/held_scheme/root.wic create mode 100644 tests/core/data/from_wic/refused/implementations/expected.yaml rename tests/core/data/{from_wic_refusals => from_wic/refused}/implementations/root.wic (100%) create mode 100644 tests/core/data/from_wic/refused/python_script/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/does_not_compile/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/edge_from_another_document/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/edge_from_another_document/root.wic delete mode 100644 tests/core/data/from_wic_refusals/every_refusal_at_once/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/every_refusal_at_once/root.wic delete mode 100644 tests/core/data/from_wic_refusals/generated_step_name/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/generated_step_name/root.wic delete mode 100644 tests/core/data/from_wic_refusals/implementations/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/input_default/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/input_default/root.wic delete mode 100644 tests/core/data/from_wic_refusals/language_version_pin/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/language_version_pin/root.wic delete mode 100644 tests/core/data/from_wic_refusals/one_file_two_bodies/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/one_file_two_bodies/left.wic delete mode 100644 tests/core/data/from_wic_refusals/one_file_two_bodies/right.wic delete mode 100644 tests/core/data/from_wic_refusals/one_file_two_bodies/root.wic delete mode 100644 tests/core/data/from_wic_refusals/plugin_namespace/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/plugin_namespace/root.wic delete mode 100644 tests/core/data/from_wic_refusals/port_named_ref_t/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/port_named_ref_t/root.wic delete mode 100644 tests/core/data/from_wic_refusals/raw_cwl_source/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/raw_cwl_source/root.wic delete mode 100644 tests/core/data/from_wic_refusals/repeated_step_id/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/repeated_step_id/root.wic delete mode 100644 tests/core/data/from_wic_refusals/run_names_a_workflow/child.wic delete mode 100644 tests/core/data/from_wic_refusals/run_names_a_workflow/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/run_names_a_workflow/root.wic delete mode 100644 tests/core/data/from_wic_refusals/scatter_on_a_call/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/scatter_on_a_call/root.wic delete mode 100644 tests/core/data/from_wic_refusals/scatter_without_method/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/scatter_without_method/root.wic delete mode 100644 tests/core/data/from_wic_refusals/step_label/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/step_label/root.wic delete mode 100644 tests/core/data/from_wic_refusals/top_level_hints/expected.yaml delete mode 100644 tests/core/data/from_wic_refusals/top_level_hints/root.wic create mode 100644 tests/core/data/pairs/cookbook.yaml create mode 100644 tests/core/data/pairs/python_api_pairs.yaml create mode 100644 tests/core/data/pairs/record.cwl create mode 100644 tests/core/data/python_api/aligner.cwl create mode 100644 tests/core/data/python_api/builder.cwl create mode 100644 tests/core/data/python_api/builder.py create mode 100644 tests/core/data/python_api/builder_job.yml create mode 100644 tests/core/data/python_api/cat.cwl create mode 100644 tests/core/data/python_api/exits_3.cwl create mode 100644 tests/core/data/python_api/false.cwl create mode 100644 tests/core/data/python_api/hinted.cwl create mode 100644 tests/core/data/python_api/refused.py create mode 100644 tests/core/data/python_api/refused.yaml create mode 100644 tests/core/data/python_api/say.cwl create mode 100644 tests/core/data/python_api/say_hello.py create mode 100644 tests/core/data/python_api/write_dir.cwl create mode 100644 tests/core/data/shipped_scripts.yaml delete mode 100644 tests/core/ground_truth_multistep1.json diff --git a/.github/workflows/lint_and_test.yml b/.github/workflows/lint_and_test.yml index ba13e5344..c61dcf465 100644 --- a/.github/workflows/lint_and_test.yml +++ b/.github/workflows/lint_and_test.yml @@ -229,24 +229,15 @@ jobs: # NOTE: Do NOT add coverage to PYPY CI runs https://github.com/tox-dev/tox/issues/2252 - - name: PyTest CWL Embedding Independence + # Every corpus workflow compiled once and checked in every form the inline + # flags give: no Sophios key or tool-only field in what is emitted, each + # subworkflow as it compiles alone (the isomorphism check MUST run in + # serial), and the flat and embedded forms meaning what the nested form + # does; on POSIX, cwltool validates every form. cwltool would find each + # defect only in run_workflows, behind a container pull. + - name: PyTest CWL Corpus Forms if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} - run: cd sophios/ && pytest -k test_cwl_embedding_independence # --cov --cov-config=.coveragerc_serial - # NOTE: This test MUST be run in serial! See is_isomorphic_with_timeout() - timeout-minutes: 20 # backup timeout for windows - - # Two defect classes cwltool already catches -- a Sophios key written - # into `in:`, and a promoted port carrying a tool-only `inputBinding` -- - # but only in run_workflows, behind a container pull. Measured at 21s - # over the full corpus here, against the minutes that round trip costs. - - name: PyTest Emitted CWL Residue - if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} - run: cd sophios/ && pytest -k test_emitted_cwl_says_nothing_cwl_cannot_read - timeout-minutes: 20 # backup timeout for windows - - - name: PyTest Inline Flags - if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} - run: cd sophios/ && pytest tests/core/test_examples.py -k "test_embedding_keeps or test_flatten" # --cov --cov-config=.coveragerc_serial + run: cd sophios/ && pytest tests/core/test_examples.py -k "test_corpus_ and not weekly_corpus" # --cov --cov-config=.coveragerc_serial timeout-minutes: 20 # backup timeout for windows # Entry-point resolution and CI coverage. The core/contrib import boundary diff --git a/.github/workflows/lint_and_test_macos.yml b/.github/workflows/lint_and_test_macos.yml index 9d40524b9..724f358e3 100644 --- a/.github/workflows/lint_and_test_macos.yml +++ b/.github/workflows/lint_and_test_macos.yml @@ -137,22 +137,13 @@ jobs: # NOTE: Do NOT add coverage to PYPY CI runs https://github.com/tox-dev/tox/issues/2252 - - name: PyTest CWL Embedding Independence + # Every corpus workflow compiled once and checked in every form the inline + # flags give: no Sophios key or tool-only field in what is emitted, each + # subworkflow as it compiles alone (the isomorphism check MUST run in + # serial), and the flat and embedded forms meaning what the nested form + # does; on POSIX, cwltool validates every form. cwltool would find each + # defect only in run_workflows, behind a container pull. + - name: PyTest CWL Corpus Forms if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} - run: cd sophios/ && pytest -k test_cwl_embedding_independence # --cov --cov-config=.coveragerc_serial - # NOTE: This test MUST be run in serial! See is_isomorphic_with_timeout() - timeout-minutes: 20 # backup timeout for windows - - # Two defect classes cwltool already catches -- a Sophios key written - # into `in:`, and a promoted port carrying a tool-only `inputBinding` -- - # but only in run_workflows, behind a container pull. Measured at 21s - # over the full corpus here, against the minutes that round trip costs. - - name: PyTest Emitted CWL Residue - if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} - run: cd sophios/ && pytest -k test_emitted_cwl_says_nothing_cwl_cannot_read - timeout-minutes: 20 # backup timeout for windows - - - name: PyTest Inline Flags - if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} - run: cd sophios/ && pytest tests/core/test_examples.py -k "test_embedding_keeps or test_flatten" # --cov --cov-config=.coveragerc_serial + run: cd sophios/ && pytest tests/core/test_examples.py -k "test_corpus_ and not weekly_corpus" # --cov --cov-config=.coveragerc_serial timeout-minutes: 20 # backup timeout for windows diff --git a/.github/workflows/run_workflows_weekly.yml b/.github/workflows/run_workflows_weekly.yml index 1428207fe..58828f5d7 100644 --- a/.github/workflows/run_workflows_weekly.yml +++ b/.github/workflows/run_workflows_weekly.yml @@ -224,7 +224,7 @@ jobs: - name: PyTest Inline Forms Keep Meaning (Weekly) if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} - run: cd sophios/ && pytest tests/core/test_examples.py -k test_weekly_corpus + run: cd sophios/ && pytest tests/core/test_examples.py -k weekly_corpus - name: PyTest Run Inlined Workflows (Weekly) if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} diff --git a/tests/contrib/data/__init__.py b/tests/contrib/data/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/contrib/data/cwl/helloworld.cwl b/tests/contrib/data/cwl/helloworld.cwl deleted file mode 100644 index 105c042c6..000000000 --- a/tests/contrib/data/cwl/helloworld.cwl +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env cwl-runner -# This file was autogenerated using Sophios, version 0+unknown -# https://github.com/PolusAI/sophios -steps: -- id: helloworld__step__1__echo - in: - message: - source: helloworld__step__1__echo___message - run: helloworld__step__1__echo/echo.cwl - out: - - stdout -cwlVersion: v1.2 -class: Workflow -$namespaces: - edam: https://edamontology.org/ -$schemas: -- https://raw.githubusercontent.com/edamontology/edamontology/master/EDAM_dev.owl -inputs: - helloworld__step__1__echo___message: - type: string -outputs: - helloworld__step__1__echo___stdout: - type: File - outputSource: helloworld__step__1__echo/stdout diff --git a/tests/contrib/rest_wfb_objects/declaration.json b/tests/contrib/rest_wfb_objects/declaration.json new file mode 100644 index 000000000..44f1ff0e0 --- /dev/null +++ b/tests/contrib/rest_wfb_objects/declaration.json @@ -0,0 +1,32 @@ +{ + "node": { + "id": 99, + "x": 0, + "y": 0, + "z": 9, + "name": "cwl_subinterpreter", + "pluginId": "cwl_subinterpreter", + "height": 50, + "width": 250, + "internal": false, + "settings": { + "inputs": { + "file_pattern": "empty.txt", + "cwl_tool": "touch", + "max_times": 2, + "config": { + "in": { + "filename": "again.txt" + } + } + } + } + }, + "link": { + "sourceId": 7, + "outletIndex": 0, + "targetId": 99, + "inletIndex": 0, + "id": 6 + } +} diff --git a/tests/contrib/rest_wfb_objects/expected.yaml b/tests/contrib/rest_wfb_objects/expected.yaml new file mode 100644 index 000000000..4b791484e --- /dev/null +++ b/tests/contrib/rest_wfb_objects/expected.yaml @@ -0,0 +1,24 @@ +# What the REST API returns for each payload, compiled in a directory holding s.sh: the steps of the workflow, in +# order, and for some what a step's tool holds or what the compile said. multi_node_inline_cwl.json+declaration.json +# is that payload with the declaring node and link of declaration.json added. Of multi_node_wfb.json it also states +# the inputs its edges fill, by node, each with the output that feeds it. +single_node.json: {steps: {keys: [one]}} +single_node_bbbc_download.json: + why: a blank pluginId names the step for its node + steps: {keys: [bbbcdownload]} +bbbc_download_wfb.json: {steps: {keys: [vjaganat90_bbbc-download-plugin]}} +multi_node.json: {steps: {keys: [touch, append@2, append@3]}} +multi_node_inline_cwl.json: {steps: {keys: [touch, append@2, append@3]}} +multi_node_inline_cwl.json+declaration.json: + why: a declared real-time analysis is taken out of the workflow, the steps numbered as written; nothing runs it + steps: {keys: [touch, append@2, append@4]} + said: Real-time analysis runs only with --run_local; the returned workflow has no step for touch +packed.json: + why: an inline tool that includes a file is returned with the file's text, read where the request is compiled + steps: {say: {run: {requirements: [{class: InitialWorkDirRequirement, + listing: [{entryname: s.sh, entry: "#!/bin/sh\necho from-include\n"}]}]}}} +multi_node_wfb.json: + steps: {keys: [polusai_FileRenaming, polusai_OMEConverter, polusai_Montage, polusai_ImageAssembler, + polusai_PrecomputeSlideViewer]} + filled: {1: {inpDir: filerenaming_3-outDir}, 3: {inpDir: omeconverter_2-outDir}, + 4: {stitchPath: montage_4-outDir, imgPath: omeconverter_2-outDir}, 5: {inpDir: imageassembler_5-outDir}} diff --git a/tests/contrib/rest_wfb_objects/packed.json b/tests/contrib/rest_wfb_objects/packed.json new file mode 100644 index 000000000..b20cdf6a7 --- /dev/null +++ b/tests/contrib/rest_wfb_objects/packed.json @@ -0,0 +1,43 @@ +{ + "state": { + "nodes": [ + { + "id": 1, + "x": 0, + "y": 0, + "z": 1, + "name": "say", + "pluginId": "say", + "height": 50, + "width": 250, + "settings": {}, + "run": { + "cwlVersion": "v1.2", + "class": "CommandLineTool", + "baseCommand": [ + "sh", + "s.sh" + ], + "requirements": { + "InitialWorkDirRequirement": { + "listing": [ + { + "entryname": "s.sh", + "entry": { + "$include": "s.sh" + } + } + ] + } + }, + "inputs": {}, + "outputs": {} + }, + "internal": false + } + ], + "links": [], + "selection": [] + }, + "plugins": [] +} diff --git a/tests/contrib/rest_wfb_objects/s.sh b/tests/contrib/rest_wfb_objects/s.sh new file mode 100644 index 000000000..4e8b7cc37 --- /dev/null +++ b/tests/contrib/rest_wfb_objects/s.sh @@ -0,0 +1,2 @@ +#!/bin/sh +echo from-include diff --git a/tests/contrib/test_fix_payload.py b/tests/contrib/test_fix_payload.py deleted file mode 100644 index c2602911a..000000000 --- a/tests/contrib/test_fix_payload.py +++ /dev/null @@ -1,22 +0,0 @@ -import copy -import json -from pathlib import Path - -import pytest - -from sophios.contrib.converter import update_payload_missing_inputs_outputs - -# Each input an edge feeds, filled with the output that feeds it -_FILLED = {1: {'inpDir': 'filerenaming_3-outDir'}, 3: {'inpDir': 'omeconverter_2-outDir'}, - 4: {'stitchPath': 'montage_4-outDir', 'imgPath': 'omeconverter_2-outDir'}, - 5: {'inpDir': 'imageassembler_5-outDir'}} - - -@pytest.mark.fast -def test_fix_multi_node_payload() -> None: - """Missing inputs and outputs are filled in to match the recorded payload.""" - wfb = json.loads((Path(__file__).parent / "rest_wfb_objects/multi_node_wfb.json").read_text(encoding="utf-8")) - expected = copy.deepcopy(wfb) - for node, inputs in _FILLED.items(): - expected['state']['nodes'][node]['settings']['inputs'].update(inputs) - assert update_payload_missing_inputs_outputs(wfb) == expected diff --git a/tests/contrib/test_rest_api.py b/tests/contrib/test_rest_api.py index 180c13417..58b816a3b 100644 --- a/tests/contrib/test_rest_api.py +++ b/tests/contrib/test_rest_api.py @@ -2,9 +2,9 @@ import copy import json from pathlib import Path +import shutil import subprocess as sub import traceback -from typing import Any from fastapi import Request from hypothesis import example, given, strategies as st @@ -12,11 +12,12 @@ import yaml from core.budgets import budget +from core.cases import match from sophios import preflight -from sophios.contrib.converter import wfb_to_wic +from sophios.contrib.converter import update_payload_missing_inputs_outputs, wfb_to_wic from sophios.contrib.rest import api from sophios.utils_yaml import Key -from sophios.wic_types import CompilerOptions, Json +from sophios.wic_types import Json try: import cwltool.main @@ -177,84 +178,35 @@ def test_wfb_to_wic_keeps_settings_as_sent(settings: Json) -> None: assert wic['steps'][0]['in'] == {k: {Key.INLINE_INPUT: v} for k, v in settings.items()} -def test_rest_core_blank_plugin_id_uses_node_name() -> None: - """Compile inline-run REST payloads even when pluginId is blank. - - Returns: - None: The assertion verifies a step named for the node. - """ - inp_path = REST_OBJECTS / "single_node_bbbc_download.json" - res = prepare_call_rest_api(inp_path) - assert int(res["retval"]) == 0 - assert "bbbcdownload" in res["steps"] - - -def test_rest_wfb_compile_infers_with_the_configurations_renamings(monkeypatch: pytest.MonkeyPatch) -> None: - """The renamings the compiler gets are the configuration's, not the shipped ones the options start with.""" - seen: list[Json] = [] - real_compile = api.compiler.compile_source - real_config = api.input_output.get_config - custom = [["tpr_", "gro_"]] - - def config(*args: Any, **kwargs: Any) -> Json: - return {**real_config(*args, **kwargs), "renaming_conventions": custom} - - def spy(bundle: Any, options: CompilerOptions, *args: Any, **kwargs: Any) -> Any: - seen.append(dict(options)) - return real_compile(bundle, options, *args, **kwargs) - - monkeypatch.setattr(api.input_output, "get_config", config) - monkeypatch.setattr(api.compiler, "compile_source", spy) - res = prepare_call_rest_api(REST_OBJECTS / "multi_node_wfb.json") - assert int(res["retval"]) == 0 - assert [list(pair) for pair in seen[0]["renaming_conventions"]] == custom +def _payload(name: str) -> Json: + """The payload `name` names: a file of rest_wfb_objects, or `+`, the payload with the node and + link of the addition added.""" + payload, *additions = name.split('+') + loaded: Json = json.loads((REST_OBJECTS / payload).read_text(encoding='utf-8')) + for addition in additions: + added = json.loads((REST_OBJECTS / addition).read_text(encoding='utf-8')) + loaded['state']['nodes'].append(added['node']) + loaded['state']['links'].append(added['link']) + return loaded -def test_rest_compile_says_a_real_time_analysis_is_not_in_the_returned_workflow( - tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: - """A declaration is taken out of the workflow; under REST nothing runs it, and one line says so. - - The declaring node is the registered `cwl_subinterpreter` adapter, drawn after `touch`. - """ - inp = json.loads((REST_OBJECTS / "multi_node_inline_cwl.json").read_text(encoding="utf-8")) - inp["state"]["nodes"].append({ - "id": 99, "x": 0, "y": 0, "z": 9, "name": "cwl_subinterpreter", "pluginId": "cwl_subinterpreter", - "height": 50, "width": 250, "internal": False, - "settings": {"inputs": {"file_pattern": "empty.txt", "cwl_tool": "touch", "max_times": 2, - "config": {"in": {"filename": "again.txt"}}}}, - }) - inp["state"]["links"].append({"sourceId": 7, "outletIndex": 0, "targetId": 99, "inletIndex": 0, "id": 6}) - payload = tmp_path / "declaring.json" - payload.write_text(json.dumps(inp), encoding="utf-8") - - res = prepare_call_rest_api(payload) - - assert int(res["retval"]) == 0 - # Numbered as written: the declaration was step 3, so the second append is `(4, append)`. - assert list(res["steps"]) == ["touch", "append@2", "append@4"] - assert ("Real-time analysis runs only with --run_local; the returned workflow has no step for touch" - in capsys.readouterr().err) - - -def test_rest_compile_returns_an_inline_tool_packed(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """A node's inline tool that includes a file is returned with the file's text: the request is compiled in - the working directory, so that is where `s.sh` is read.""" - (tmp_path / "s.sh").write_text("echo from-include\n", encoding="utf-8") - run = {"cwlVersion": "v1.2", "class": "CommandLineTool", "baseCommand": ["sh", "s.sh"], - "requirements": {"InitialWorkDirRequirement": { - "listing": [{"entryname": "s.sh", "entry": {"$include": "s.sh"}}]}}, - "inputs": {}, "outputs": {}} - node = {"id": 1, "x": 0, "y": 0, "z": 1, "name": "say", "pluginId": "say", "height": 50, "width": 250, - "settings": {}, "run": run, "internal": False} - payload = tmp_path / "packed.json" - payload.write_text(json.dumps({"state": {"nodes": [node], "links": [], "selection": []}, "plugins": []}), - encoding="utf-8") +def test_rest_compiles_each_payload_to_what_it_states(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str]) -> None: + """Each payload of rest_wfb_objects/expected.yaml compiles, in a directory holding s.sh, to the steps it states, + and says what it states; each input a WFB payload's edge feeds is filled with the output that feeds it.""" + shutil.copyfile(REST_OBJECTS / 's.sh', tmp_path / 's.sh') monkeypatch.chdir(tmp_path) - - res = prepare_call_rest_api(payload) - - assert int(res["retval"]) == 0 - requirements = res["steps"]["say"]["run"]["requirements"] - listing = (requirements["InitialWorkDirRequirement"] if isinstance(requirements, dict) - else next(item for item in requirements if item["class"] == "InitialWorkDirRequirement"))["listing"] - assert listing == [{"entryname": "s.sh", "entry": "echo from-include\n"}] + for name, stated in yaml.safe_load((REST_OBJECTS / 'expected.yaml').read_text(encoding='utf-8')).items(): + payload = tmp_path / 'payload.json' + payload.write_text(json.dumps(_payload(name)), encoding='utf-8') + capsys.readouterr() + res = prepare_call_rest_api(payload) + assert int(res['retval']) == 0, name + assert match(stated['steps'], res['steps']), (name, res['steps']) + assert stated.get('said', '') in capsys.readouterr().err, name + if 'filled' in stated: + wfb = _payload(name) + expected = copy.deepcopy(wfb) + for node, inputs in stated['filled'].items(): + expected['state']['nodes'][node]['settings']['inputs'].update(inputs) + assert update_payload_missing_inputs_outputs(wfb) == expected diff --git a/tests/core/data/from_wic/built/every_construct/child.wic b/tests/core/data/from_wic/built/every_construct/child.wic new file mode 100644 index 000000000..ca91bc76c --- /dev/null +++ b/tests/core/data/from_wic/built/every_construct/child.wic @@ -0,0 +1,6 @@ +inputs: {names: 'string[]'} +steps: +- id: mk_file + scatter: name + scatterMethod: dotproduct + in: {name: names} diff --git a/tests/core/data/from_wic/built/every_construct/expected.yaml b/tests/core/data/from_wic/built/every_construct/expected.yaml new file mode 100644 index 000000000..b6d511b92 --- /dev/null +++ b/tests/core/data/from_wic/built/every_construct/expected.yaml @@ -0,0 +1,7 @@ +# Reading root.wic warns that its drawing settings are dropped; the bundle the objects write names each step as +# written; the compiled workflow has a step for each but the declaration, which it returns instead. +warns: ['root.wic: wic: graphviz, inlineable dropped'] +inputs: [name, names] +steps: [mk_file, xform, count, sink, shout, child, left, right, pair_src, pair_sink] +realtime: [{analysis: count, max_times: 20}] +written: {outputs: {result: {outputSource: xform/file}}} diff --git a/tests/core/data/from_wic/built/every_construct/left.wic b/tests/core/data/from_wic/built/every_construct/left.wic new file mode 100644 index 000000000..b0b584b28 --- /dev/null +++ b/tests/core/data/from_wic/built/every_construct/left.wic @@ -0,0 +1,2 @@ +wic: {steps: {'(1, same.wic)': {wic: {steps: {'(1, mk_file)': {in: {name: !ii same.txt}}}}}}} +steps: [{id: same.wic}] diff --git a/tests/core/data/from_wic/built/every_construct/right.wic b/tests/core/data/from_wic/built/every_construct/right.wic new file mode 100644 index 000000000..b0b584b28 --- /dev/null +++ b/tests/core/data/from_wic/built/every_construct/right.wic @@ -0,0 +1,2 @@ +wic: {steps: {'(1, same.wic)': {wic: {steps: {'(1, mk_file)': {in: {name: !ii same.txt}}}}}}} +steps: [{id: same.wic}] diff --git a/tests/core/data/from_wic/built/every_construct/root.wic b/tests/core/data/from_wic/built/every_construct/root.wic new file mode 100644 index 000000000..c2a25fea4 --- /dev/null +++ b/tests/core/data/from_wic/built/every_construct/root.wic @@ -0,0 +1,46 @@ +# Every construct a Python Workflow spells, read into objects that compile as this file does: a bare name is the +# workflow input, `!*` the producing step's output object and `!ii` a literal; `count` binds nothing and is inferred, as +# in the file; an inline tool's step holds that tool, its scatter, method and `when` with it; a `!cwl` record is a +# StepInput over the output objects; `child.wic` is a nested Workflow built from its own file, its input bound by the +# caller, and `left` and `right` call `same.wic` with one body; `pair_sink` reads `pair_src` through the shipped +# renamings; a position in an outputSource is read as the step it names; and the declared analysis stays a +# declaration, `max_times` a number. +wic: + graphviz: {label: drawn} + inlineable: false +inputs: + name: string + names: string[] +steps: +- id: mk_file + in: {name: name} + out: [{file: !& made}] +- id: xform + in: {file: !* made, name: !ii renamed.txt} + out: [{file: !& again}] +- id: count +- id: sink + in: {file: !* made, n: !ii 1, extras: !cwl {source: [!* made, !* again], linkMerge: merge_flattened}} +- id: shout + run: + class: CommandLineTool + baseCommand: echo + inputs: {message: {type: string, inputBinding: {position: 1}}} + outputs: {} + in: {message: !ii [a, b]} + scatter: [message] + scatterMethod: dotproduct + when: $(inputs.message != "c") +- id: child.wic + in: {names: names} +- id: left.wic +- id: right.wic +- id: pair_src + in: {name: !ii a.txt} +- id: pair_sink +- id: cwl_subinterpreter + in: {file_pattern: !ii '*.txt', cwl_tool: !ii count, max_times: !ii '20', config: !ii {in: {file: a.txt}}} +outputs: + result: + type: File + outputSource: (2, xform)/file diff --git a/tests/core/data/from_wic_refusals/one_file_two_bodies/child.wic b/tests/core/data/from_wic/built/every_construct/same.wic similarity index 100% rename from tests/core/data/from_wic_refusals/one_file_two_bodies/child.wic rename to tests/core/data/from_wic/built/every_construct/same.wic diff --git a/tests/core/data/from_wic/refused/does_not_compile/expected.yaml b/tests/core/data/from_wic/refused/does_not_compile/expected.yaml new file mode 100644 index 000000000..80a504022 --- /dev/null +++ b/tests/core/data/from_wic/refused/does_not_compile/expected.yaml @@ -0,0 +1,2 @@ +# The file's own error, the one sophios --yaml gives, and nothing built. +refused: [{code: UNDEFINED_EDGE, file: root.wic, message: {contains: [nowhere]}}] diff --git a/tests/core/data/from_wic_refusals/does_not_compile/root.wic b/tests/core/data/from_wic/refused/does_not_compile/root.wic similarity index 100% rename from tests/core/data/from_wic_refusals/does_not_compile/root.wic rename to tests/core/data/from_wic/refused/does_not_compile/root.wic diff --git a/tests/core/data/from_wic_refusals/scatter_on_a_call/child.wic b/tests/core/data/from_wic/refused/every_construct/child.wic similarity index 100% rename from tests/core/data/from_wic_refusals/scatter_on_a_call/child.wic rename to tests/core/data/from_wic/refused/every_construct/child.wic diff --git a/tests/core/data/from_wic/refused/every_construct/expected.yaml b/tests/core/data/from_wic/refused/every_construct/expected.yaml new file mode 100644 index 000000000..f424aa1fa --- /dev/null +++ b/tests/core/data/from_wic/refused/every_construct/expected.yaml @@ -0,0 +1,15 @@ +refused: +- {code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["compile(lang_version='0.0.1')"]}} +- {code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["no top-level 'hints'"]}} +- {code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["no Python port can be called 'ref-t'"]}} +- {code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ['inputs: d: carries default']}} +- {code: NO_PYTHON_SPELLING, file: root.wic, line: 11, message: {contains: ["step 'mk_file': label:"]}} +- {code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["namespace: 'gpu' has no Python spelling"]}} +- {code: NO_PYTHON_SPELLING, file: root.wic, line: 15, message: {contains: ["steps 1 and 2 are both called 'mk_file'"]}} +- {code: NO_PYTHON_SPELLING, file: root.wic, line: 15, message: {contains: ['add scatterMethod: dotproduct']}} +- {code: NO_PYTHON_SPELLING, file: root.wic, line: 19, message: {contains: ['!cwl a/b', never as CWL text]}} +- {code: NO_PYTHON_SPELLING, file: root.wic, line: 20, message: {contains: ['write the step as id: child.wic']}} +- {code: NO_PYTHON_SPELLING, file: root.wic, line: 23, message: {contains: ['calls a workflow with scatter:, scatterMethod:']}} +- {code: NO_PYTHON_SPELLING, file: reader.wic, message: {contains: ['reads !* f, which no earlier step of this document']}} +- {code: NO_PYTHON_SPELLING, file: right.wic, message: {contains: ['twice.wic is called here and at left.wic:']}} +- {code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ['root__step__3__xform/file names no step output']}} diff --git a/tests/core/data/from_wic/refused/every_construct/left.wic b/tests/core/data/from_wic/refused/every_construct/left.wic new file mode 100644 index 000000000..45fcc2b74 --- /dev/null +++ b/tests/core/data/from_wic/refused/every_construct/left.wic @@ -0,0 +1,2 @@ +wic: {steps: {'(1, twice.wic)': {wic: {steps: {'(1, mk_file)': {in: {name: !ii from_left}}}}}}} +steps: [{id: twice.wic}] diff --git a/tests/core/data/from_wic_refusals/edge_from_another_document/child.wic b/tests/core/data/from_wic/refused/every_construct/reader.wic similarity index 100% rename from tests/core/data/from_wic_refusals/edge_from_another_document/child.wic rename to tests/core/data/from_wic/refused/every_construct/reader.wic diff --git a/tests/core/data/from_wic/refused/every_construct/right.wic b/tests/core/data/from_wic/refused/every_construct/right.wic new file mode 100644 index 000000000..43782c486 --- /dev/null +++ b/tests/core/data/from_wic/refused/every_construct/right.wic @@ -0,0 +1,2 @@ +wic: {steps: {'(1, twice.wic)': {wic: {steps: {'(1, mk_file)': {in: {name: !ii from_right}}}}}}} +steps: [{id: twice.wic}] diff --git a/tests/core/data/from_wic/refused/every_construct/root.wic b/tests/core/data/from_wic/refused/every_construct/root.wic new file mode 100644 index 000000000..33dfb8fee --- /dev/null +++ b/tests/core/data/from_wic/refused/every_construct/root.wic @@ -0,0 +1,31 @@ +# Every construct a Python Workflow cannot hold, each refused, in one raise. +hints: {ResourceRequirement: {coresMin: 1}} +wic: + lang_version: '0.0.1' + steps: + (1, mk_file): {wic: {namespace: gpu}} +inputs: + ref-t: string + d: {type: string, default: a} +steps: +- id: mk_file + label: makes + in: {name: ref-t} + out: [{file: !& f}] +- id: mk_file + scatter: name + in: {name: !ii [a, b]} +- id: xform + in: {file: !* f, name: !cwl a/b} +- id: sub + run: child.wic + in: {n: d} +- id: child.wic + scatter: [n] + scatterMethod: dotproduct + in: {n: !ii [a, b]} +- id: reader.wic +- id: left.wic +- id: right.wic +outputs: + o: {type: File, outputSource: root__step__3__xform/file} diff --git a/tests/core/data/from_wic/refused/every_construct/twice.wic b/tests/core/data/from_wic/refused/every_construct/twice.wic new file mode 100644 index 000000000..d59fd9b2a --- /dev/null +++ b/tests/core/data/from_wic/refused/every_construct/twice.wic @@ -0,0 +1 @@ +steps: [{id: mk_file}] diff --git a/tests/core/data/from_wic/refused/held_scatter/expected.yaml b/tests/core/data/from_wic/refused/held_scatter/expected.yaml new file mode 100644 index 000000000..430a7710b --- /dev/null +++ b/tests/core/data/from_wic/refused/held_scatter/expected.yaml @@ -0,0 +1,2 @@ +# Held today, though the file compiles: a scatter over a port nothing binds raises a bare ValueError, not api006. +raises: ValueError diff --git a/tests/core/data/from_wic/refused/held_scatter/root.wic b/tests/core/data/from_wic/refused/held_scatter/root.wic new file mode 100644 index 000000000..cffd5ff41 --- /dev/null +++ b/tests/core/data/from_wic/refused/held_scatter/root.wic @@ -0,0 +1,4 @@ +steps: +- id: captured + scatter: [name] + scatterMethod: dotproduct diff --git a/tests/core/data/from_wic/refused/held_scheme/expected.yaml b/tests/core/data/from_wic/refused/held_scheme/expected.yaml new file mode 100644 index 000000000..e3f81daab --- /dev/null +++ b/tests/core/data/from_wic/refused/held_scheme/expected.yaml @@ -0,0 +1,2 @@ +# Held today, though the file compiles: a step of a tool with a SchemaDefRequirement is refused as api004. +refused: [{code: INVALID_TOOL}] diff --git a/tests/core/data/from_wic/refused/held_scheme/root.wic b/tests/core/data/from_wic/refused/held_scheme/root.wic new file mode 100644 index 000000000..defb33cbc --- /dev/null +++ b/tests/core/data/from_wic/refused/held_scheme/root.wic @@ -0,0 +1,2 @@ +steps: +- id: schemed diff --git a/tests/core/data/from_wic/refused/implementations/expected.yaml b/tests/core/data/from_wic/refused/implementations/expected.yaml new file mode 100644 index 000000000..a37d6aa7f --- /dev/null +++ b/tests/core/data/from_wic/refused/implementations/expected.yaml @@ -0,0 +1,4 @@ +# A Python Workflow has one body, so a document of implementations has no spelling. +refused: +- {code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["default_implementation: 'one' has no Python spelling"]}} +- {code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: [a Python Workflow has one body]}} diff --git a/tests/core/data/from_wic_refusals/implementations/root.wic b/tests/core/data/from_wic/refused/implementations/root.wic similarity index 100% rename from tests/core/data/from_wic_refusals/implementations/root.wic rename to tests/core/data/from_wic/refused/implementations/root.wic diff --git a/tests/core/data/from_wic/refused/python_script/expected.yaml b/tests/core/data/from_wic/refused/python_script/expected.yaml new file mode 100644 index 000000000..4861a543c --- /dev/null +++ b/tests/core/data/from_wic/refused/python_script/expected.yaml @@ -0,0 +1,4 @@ +# A tool generated from a Python script has no Step: build it with tool_builder. The script's generator imports +# workflow_types relative to the working directory, so the project, tests/core/data/frontdoor/script, is run in place. +project: frontdoor/script/work/compile.wic +refused: [{code: NO_PYTHON_SPELLING, message: {contains: [tool_builder]}}] diff --git a/tests/core/data/from_wic_refusals/does_not_compile/expected.yaml b/tests/core/data/from_wic_refusals/does_not_compile/expected.yaml deleted file mode 100644 index 5adaeb96d..000000000 --- a/tests/core/data/from_wic_refusals/does_not_compile/expected.yaml +++ /dev/null @@ -1,2 +0,0 @@ -{why: "the file's own error, the one sophios --yaml gives, and nothing built", - diagnostics: [{code: UNDEFINED_EDGE, file: root.wic, message: {contains: ['nowhere']}}]} diff --git a/tests/core/data/from_wic_refusals/edge_from_another_document/expected.yaml b/tests/core/data/from_wic_refusals/edge_from_another_document/expected.yaml deleted file mode 100644 index b12750293..000000000 --- a/tests/core/data/from_wic_refusals/edge_from_another_document/expected.yaml +++ /dev/null @@ -1,2 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: child.wic, message: {contains: ['reads !* f, which no earlier step of - this document defines']}}]} diff --git a/tests/core/data/from_wic_refusals/edge_from_another_document/root.wic b/tests/core/data/from_wic_refusals/edge_from_another_document/root.wic deleted file mode 100644 index 1fed4882b..000000000 --- a/tests/core/data/from_wic_refusals/edge_from_another_document/root.wic +++ /dev/null @@ -1 +0,0 @@ -steps: [{id: mk_file, in: {name: !ii a}, out: [{file: !& f}]}, {id: child.wic}] diff --git a/tests/core/data/from_wic_refusals/every_refusal_at_once/expected.yaml b/tests/core/data/from_wic_refusals/every_refusal_at_once/expected.yaml deleted file mode 100644 index f4ba5b252..000000000 --- a/tests/core/data/from_wic_refusals/every_refusal_at_once/expected.yaml +++ /dev/null @@ -1,4 +0,0 @@ -{why: 'two constructs, two diagnostics, one raise', diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, - message: {contains: ['top-level']}}, - {code: NO_PYTHON_SPELLING, file: root.wic, - message: {contains: ['both called']}}]} diff --git a/tests/core/data/from_wic_refusals/every_refusal_at_once/root.wic b/tests/core/data/from_wic_refusals/every_refusal_at_once/root.wic deleted file mode 100644 index fe9c1944c..000000000 --- a/tests/core/data/from_wic_refusals/every_refusal_at_once/root.wic +++ /dev/null @@ -1,2 +0,0 @@ -hints: {ResourceRequirement: {coresMin: 1}} -steps: [{id: mk_file, in: {name: !ii a}}, {id: mk_file, in: {name: !ii b}}] diff --git a/tests/core/data/from_wic_refusals/generated_step_name/expected.yaml b/tests/core/data/from_wic_refusals/generated_step_name/expected.yaml deleted file mode 100644 index cf52b73f0..000000000 --- a/tests/core/data/from_wic_refusals/generated_step_name/expected.yaml +++ /dev/null @@ -1,3 +0,0 @@ -{why: 'root__step__2__xform is no step id, so the output cannot be bound to an object', - diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ['outputSource: - root__step__2__xform/file names no step output and no declared input']}}]} diff --git a/tests/core/data/from_wic_refusals/generated_step_name/root.wic b/tests/core/data/from_wic_refusals/generated_step_name/root.wic deleted file mode 100644 index 6a150d673..000000000 --- a/tests/core/data/from_wic_refusals/generated_step_name/root.wic +++ /dev/null @@ -1,2 +0,0 @@ -steps: [{id: mk_file, in: {name: !ii a}, out: [{file: !& f}]}, {id: xform, in: {file: !* f, name: !ii b}}] -outputs: {o: {type: File, outputSource: root__step__2__xform/file}} diff --git a/tests/core/data/from_wic_refusals/implementations/expected.yaml b/tests/core/data/from_wic_refusals/implementations/expected.yaml deleted file mode 100644 index 80687097a..000000000 --- a/tests/core/data/from_wic_refusals/implementations/expected.yaml +++ /dev/null @@ -1,3 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["default_implementation: 'one' has no - Python spelling"]}}, - {code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ['a Python Workflow has one body']}}]} diff --git a/tests/core/data/from_wic_refusals/input_default/expected.yaml b/tests/core/data/from_wic_refusals/input_default/expected.yaml deleted file mode 100644 index 49be9ce62..000000000 --- a/tests/core/data/from_wic_refusals/input_default/expected.yaml +++ /dev/null @@ -1 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ['inputs: n: carries default']}}]} diff --git a/tests/core/data/from_wic_refusals/input_default/root.wic b/tests/core/data/from_wic_refusals/input_default/root.wic deleted file mode 100644 index 57f2aa770..000000000 --- a/tests/core/data/from_wic_refusals/input_default/root.wic +++ /dev/null @@ -1,2 +0,0 @@ -inputs: {n: {type: string, default: a}} -steps: [{id: mk_file, in: {name: n}}] diff --git a/tests/core/data/from_wic_refusals/language_version_pin/expected.yaml b/tests/core/data/from_wic_refusals/language_version_pin/expected.yaml deleted file mode 100644 index cbadc8b2e..000000000 --- a/tests/core/data/from_wic_refusals/language_version_pin/expected.yaml +++ /dev/null @@ -1 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["compile(lang_version='0.0.1')"]}}]} diff --git a/tests/core/data/from_wic_refusals/language_version_pin/root.wic b/tests/core/data/from_wic_refusals/language_version_pin/root.wic deleted file mode 100644 index b5f78e92e..000000000 --- a/tests/core/data/from_wic_refusals/language_version_pin/root.wic +++ /dev/null @@ -1,2 +0,0 @@ -wic: {lang_version: '0.0.1'} -steps: [{id: mk_file, in: {name: !ii a}}] diff --git a/tests/core/data/from_wic_refusals/one_file_two_bodies/expected.yaml b/tests/core/data/from_wic_refusals/one_file_two_bodies/expected.yaml deleted file mode 100644 index c6d5646c0..000000000 --- a/tests/core/data/from_wic_refusals/one_file_two_bodies/expected.yaml +++ /dev/null @@ -1,2 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: right.wic, message: {contains: ['child.wic is called here and at - left.wic:']}}]} diff --git a/tests/core/data/from_wic_refusals/one_file_two_bodies/left.wic b/tests/core/data/from_wic_refusals/one_file_two_bodies/left.wic deleted file mode 100644 index 9da3c8d2e..000000000 --- a/tests/core/data/from_wic_refusals/one_file_two_bodies/left.wic +++ /dev/null @@ -1,2 +0,0 @@ -wic: {steps: {'(1, child.wic)': {wic: {steps: {'(1, mk_file)': {in: {name: !ii from_left}}}}}}} -steps: [{id: child.wic}] diff --git a/tests/core/data/from_wic_refusals/one_file_two_bodies/right.wic b/tests/core/data/from_wic_refusals/one_file_two_bodies/right.wic deleted file mode 100644 index 995ec2bfb..000000000 --- a/tests/core/data/from_wic_refusals/one_file_two_bodies/right.wic +++ /dev/null @@ -1,2 +0,0 @@ -wic: {steps: {'(1, child.wic)': {wic: {steps: {'(1, mk_file)': {in: {name: !ii from_right}}}}}}} -steps: [{id: child.wic}] diff --git a/tests/core/data/from_wic_refusals/one_file_two_bodies/root.wic b/tests/core/data/from_wic_refusals/one_file_two_bodies/root.wic deleted file mode 100644 index fab0c5e93..000000000 --- a/tests/core/data/from_wic_refusals/one_file_two_bodies/root.wic +++ /dev/null @@ -1 +0,0 @@ -steps: [{id: left.wic}, {id: right.wic}] diff --git a/tests/core/data/from_wic_refusals/plugin_namespace/expected.yaml b/tests/core/data/from_wic_refusals/plugin_namespace/expected.yaml deleted file mode 100644 index 4c985fe76..000000000 --- a/tests/core/data/from_wic_refusals/plugin_namespace/expected.yaml +++ /dev/null @@ -1,2 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["namespace: 'gpu' has no Python - spelling"]}}]} diff --git a/tests/core/data/from_wic_refusals/plugin_namespace/root.wic b/tests/core/data/from_wic_refusals/plugin_namespace/root.wic deleted file mode 100644 index 1882fab8d..000000000 --- a/tests/core/data/from_wic_refusals/plugin_namespace/root.wic +++ /dev/null @@ -1,2 +0,0 @@ -wic: {steps: {'(1, mk_file)': {wic: {namespace: gpu}}}} -steps: [{id: mk_file, in: {name: !ii a}}] diff --git a/tests/core/data/from_wic_refusals/port_named_ref_t/expected.yaml b/tests/core/data/from_wic_refusals/port_named_ref_t/expected.yaml deleted file mode 100644 index eae18269c..000000000 --- a/tests/core/data/from_wic_refusals/port_named_ref_t/expected.yaml +++ /dev/null @@ -1,2 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["no Python port can be - called 'ref-t'"]}}]} diff --git a/tests/core/data/from_wic_refusals/port_named_ref_t/root.wic b/tests/core/data/from_wic_refusals/port_named_ref_t/root.wic deleted file mode 100644 index 6bd8da845..000000000 --- a/tests/core/data/from_wic_refusals/port_named_ref_t/root.wic +++ /dev/null @@ -1,2 +0,0 @@ -inputs: {ref-t: string} -steps: [{id: mk_file, in: {name: ref-t}}] diff --git a/tests/core/data/from_wic_refusals/raw_cwl_source/expected.yaml b/tests/core/data/from_wic_refusals/raw_cwl_source/expected.yaml deleted file mode 100644 index fa68dc560..000000000 --- a/tests/core/data/from_wic_refusals/raw_cwl_source/expected.yaml +++ /dev/null @@ -1 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ['never as CWL text']}}]} diff --git a/tests/core/data/from_wic_refusals/raw_cwl_source/root.wic b/tests/core/data/from_wic_refusals/raw_cwl_source/root.wic deleted file mode 100644 index d911f8005..000000000 --- a/tests/core/data/from_wic_refusals/raw_cwl_source/root.wic +++ /dev/null @@ -1 +0,0 @@ -steps: [{id: mk_file, in: {name: !cwl a/b}}] diff --git a/tests/core/data/from_wic_refusals/repeated_step_id/expected.yaml b/tests/core/data/from_wic_refusals/repeated_step_id/expected.yaml deleted file mode 100644 index f2d371371..000000000 --- a/tests/core/data/from_wic_refusals/repeated_step_id/expected.yaml +++ /dev/null @@ -1,2 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["steps 1 and 2 are both - called 'mk_file'"]}}]} diff --git a/tests/core/data/from_wic_refusals/repeated_step_id/root.wic b/tests/core/data/from_wic_refusals/repeated_step_id/root.wic deleted file mode 100644 index aa2e33bd1..000000000 --- a/tests/core/data/from_wic_refusals/repeated_step_id/root.wic +++ /dev/null @@ -1 +0,0 @@ -steps: [{id: mk_file, in: {name: !ii a}}, {id: mk_file, in: {name: !ii b}}] diff --git a/tests/core/data/from_wic_refusals/run_names_a_workflow/child.wic b/tests/core/data/from_wic_refusals/run_names_a_workflow/child.wic deleted file mode 100644 index 01bd710c7..000000000 --- a/tests/core/data/from_wic_refusals/run_names_a_workflow/child.wic +++ /dev/null @@ -1 +0,0 @@ -steps: [{id: mk_file, in: {name: !ii a}}] diff --git a/tests/core/data/from_wic_refusals/run_names_a_workflow/expected.yaml b/tests/core/data/from_wic_refusals/run_names_a_workflow/expected.yaml deleted file mode 100644 index aef3e0df7..000000000 --- a/tests/core/data/from_wic_refusals/run_names_a_workflow/expected.yaml +++ /dev/null @@ -1 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ['write the step as id: child.wic']}}]} diff --git a/tests/core/data/from_wic_refusals/run_names_a_workflow/root.wic b/tests/core/data/from_wic_refusals/run_names_a_workflow/root.wic deleted file mode 100644 index b695937e0..000000000 --- a/tests/core/data/from_wic_refusals/run_names_a_workflow/root.wic +++ /dev/null @@ -1 +0,0 @@ -steps: [{id: sub, run: child.wic}] diff --git a/tests/core/data/from_wic_refusals/scatter_on_a_call/expected.yaml b/tests/core/data/from_wic_refusals/scatter_on_a_call/expected.yaml deleted file mode 100644 index 51039a2f1..000000000 --- a/tests/core/data/from_wic_refusals/scatter_on_a_call/expected.yaml +++ /dev/null @@ -1,2 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ['calls a workflow with scatter:, - scatterMethod:']}}]} diff --git a/tests/core/data/from_wic_refusals/scatter_on_a_call/root.wic b/tests/core/data/from_wic_refusals/scatter_on_a_call/root.wic deleted file mode 100644 index 3cceebc38..000000000 --- a/tests/core/data/from_wic_refusals/scatter_on_a_call/root.wic +++ /dev/null @@ -1 +0,0 @@ -steps: [{id: child.wic, scatter: [n], scatterMethod: dotproduct, in: {n: !ii [a, b]}}] diff --git a/tests/core/data/from_wic_refusals/scatter_without_method/expected.yaml b/tests/core/data/from_wic_refusals/scatter_without_method/expected.yaml deleted file mode 100644 index 909d34f32..000000000 --- a/tests/core/data/from_wic_refusals/scatter_without_method/expected.yaml +++ /dev/null @@ -1 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ['add scatterMethod: dotproduct']}}]} diff --git a/tests/core/data/from_wic_refusals/scatter_without_method/root.wic b/tests/core/data/from_wic_refusals/scatter_without_method/root.wic deleted file mode 100644 index b04d4691f..000000000 --- a/tests/core/data/from_wic_refusals/scatter_without_method/root.wic +++ /dev/null @@ -1 +0,0 @@ -steps: [{id: mk_file, scatter: name, in: {name: !ii [a, b]}}] diff --git a/tests/core/data/from_wic_refusals/step_label/expected.yaml b/tests/core/data/from_wic_refusals/step_label/expected.yaml deleted file mode 100644 index 56a392898..000000000 --- a/tests/core/data/from_wic_refusals/step_label/expected.yaml +++ /dev/null @@ -1 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["a Python Step carries no 'label'"]}}]} diff --git a/tests/core/data/from_wic_refusals/step_label/root.wic b/tests/core/data/from_wic_refusals/step_label/root.wic deleted file mode 100644 index eecdb4a0a..000000000 --- a/tests/core/data/from_wic_refusals/step_label/root.wic +++ /dev/null @@ -1 +0,0 @@ -steps: [{id: mk_file, label: makes, in: {name: !ii a}}] diff --git a/tests/core/data/from_wic_refusals/top_level_hints/expected.yaml b/tests/core/data/from_wic_refusals/top_level_hints/expected.yaml deleted file mode 100644 index c13f4b8f0..000000000 --- a/tests/core/data/from_wic_refusals/top_level_hints/expected.yaml +++ /dev/null @@ -1,2 +0,0 @@ -{diagnostics: [{code: NO_PYTHON_SPELLING, file: root.wic, message: {contains: ["a Python Workflow carries no - top-level 'hints'"]}}]} diff --git a/tests/core/data/from_wic_refusals/top_level_hints/root.wic b/tests/core/data/from_wic_refusals/top_level_hints/root.wic deleted file mode 100644 index 977ece944..000000000 --- a/tests/core/data/from_wic_refusals/top_level_hints/root.wic +++ /dev/null @@ -1,2 +0,0 @@ -hints: {ResourceRequirement: {coresMin: 1}} -steps: [{id: mk_file, in: {name: !ii a}}] diff --git a/tests/core/data/pairs/cookbook.yaml b/tests/core/data/pairs/cookbook.yaml new file mode 100644 index 000000000..8a19cd140 --- /dev/null +++ b/tests/core/data/pairs/cookbook.yaml @@ -0,0 +1,69 @@ +# What the cookbook pairs (docs/cookbook/.py and .wic) compile to, as the default compile and `under:` other flags +# and `compile()` arguments. A pair not named here compiles with no diagnostic. +record: + document: record.cwl +greeting_graph: + reads: &graph {append: {file: touch/file}, shout: {text: append/file}, word_count: {text: append/file}, + combine: {text: shout/shouted, counts: word_count/counts}} +greeting_graph_partial: + why: two edges written, at the branch and at the join, leave inference the other three, and the graph above + reads: *graph + notes: ['note [wic043] shout.text <- append.file (1 other fits)', + 'note [wic043] combine.counts <- word_count.counts (3 others fit)'] +greeting_graph_inferred: + why: with every edge left out, combine would read the counts as its text and as its counts + refused: + - {code: INFERENCE_DUPLICATE, severity: error, step: combine, port: text, + message: {contains: [combine.text, combine.counts, word_count.counts]}} + - {code: INFERENCE_GUESS, severity: note, step: shout, port: text} + - {code: INFERENCE_GUESS, severity: note, step: word_count, port: text} +greeting_inferred: + notes: ['note [wic043] cat.file <- append.file (1 other fits)'] +inference: + notes: ['note [wic043] cat.file <- echo.stdout (1 other fits)'] +naming: + why: the conventions give report the summary; with them off it takes the first of summarize's two files + reads: {report: {input_summary: summarize/output_summary}} + notes: ['note [wic043] report.input_summary <- summarize.output_summary (1 other fits)'] + under: + - flags: [--no_inference_naming_conventions] + inference: {naming_conventions: false} + reads: {report: {input_summary: summarize/output_details}} + notes: ['note [wic043] report.input_summary <- summarize.output_details (2 others fit)'] +naming_renamed: + why: abstract is no name summarize writes, until a renaming pairs it with summary + reads: {abstract: {input_abstract: summarize/output_details}} + notes: ['note [wic043] abstract.input_abstract <- summarize.output_details (2 others fit)'] + under: + - settings: {renaming_conventions: [[abstract, summary]]} + inference: {renamings: [[abstract, summary]]} + reads: {abstract: {input_abstract: summarize/output_summary}} + notes: ['note [wic043] abstract.input_abstract <- summarize.output_summary (1 other fits)'] +two_lines: + notes: ['note [wic043] goodbye.file <- hello.file (1 other fits)', + 'note [wic043] cat.file <- goodbye.file (2 others fit)'] +when: + under: + - why: a RunPolicy is the partial-failure flags; codes and a range, lower bound included, beside 0 + flags: [--partial_failure_enable, --partial_failure_success_codes, '3', --partial_failure_success_codes_range, + '5', '7'] + policy: {partial_failure: true, success_codes: [3, 5, 6]} + compiled: + steps: + - when: $(inputs["message"] != null && inputs["enabled"] != null && (inputs.enabled)) + run: {successCodes: [0, 3, 5, 6], outputs: {stdout: {type: 'File?'}}} + requirements: {InlineJavascriptRequirement: {}} +word_count: + notes: ['note [wic043] word_count.text <- append.file (1 other fits)'] +greet_many: + under: + - why: under a RunPolicy each step with a required input runs only when none is null, and its tool forgives the codes + flags: [--partial_failure_enable] + policy: {partial_failure: true} + compiled: + steps: + - when: $(inputs["filename"] != null) + run: {successCodes: [0, 1], outputs: {file: {type: 'File?'}}} + - when: $(inputs["str"] != null && inputs["file"] != null) + - when: $(inputs["file"] != null) + run: {successCodes: [0, 1], outputs: {output: {type: 'string?'}}} diff --git a/tests/core/data/pairs/python_api_pairs.yaml b/tests/core/data/pairs/python_api_pairs.yaml new file mode 100644 index 000000000..f7782088c --- /dev/null +++ b/tests/core/data/pairs/python_api_pairs.yaml @@ -0,0 +1,6 @@ +# What the pairs of tests/core/data/python_api_pairs compile to; one not named here compiles with no diagnostic. Each +# function of pairs.py says what its pair pins. +linear_inference: + notes: ['note [wic043] cat.file <- append.file (1 other fits)'] +equal_producers: + notes: ['note [wic043] cat.file <- second.file (1 other fits)'] diff --git a/tests/core/data/pairs/record.cwl b/tests/core/data/pairs/record.cwl new file mode 100644 index 000000000..d87e8fe51 --- /dev/null +++ b/tests/core/data/pairs/record.cwl @@ -0,0 +1,98 @@ +# What docs/cookbook/record.py and record.wic compile to: two sources merged, in the order written, into one +# File[] input, each tool as the step runs it, and every step output promoted to a workflow output. +steps: +- id: touch + in: + filename: + source: touch~filename + run: + class: CommandLineTool + requirements: + DockerRequirement: + dockerPull: docker.io/library/debian:bookworm-slim + InlineJavascriptRequirement: {} + baseCommand: touch + inputs: + filename: + type: string + inputBinding: + position: 1 + outputs: + file: + type: File + outputBinding: + glob: $(inputs.filename) + hints: + LoadListingRequirement: + loadListing: deep_listing + NetworkAccess: + networkAccess: true + out: + - file +- id: echo + in: + message: + source: echo~message + run: + class: CommandLineTool + baseCommand: echo + inputs: + message: + type: string + inputBinding: + position: 1 + outputs: + stdout: + type: File + outputBinding: + glob: stdout + stdout: stdout + hints: + LoadListingRequirement: + loadListing: deep_listing + NetworkAccess: + networkAccess: true + out: + - stdout +- id: concat + in: + files: + source: + - touch/file + - echo/stdout + linkMerge: merge_flattened + run: + class: CommandLineTool + baseCommand: cat + inputs: + files: + type: File[] + inputBinding: + position: 1 + outputs: + joined: + type: File + outputBinding: + glob: joined.txt + stdout: joined.txt + out: + - joined +cwlVersion: v1.2 +class: Workflow +inputs: + touch~filename: + type: string + echo~message: + type: string +outputs: + touch~file: + type: File + outputSource: touch/file + echo~stdout: + type: File + outputSource: echo/stdout + concat~joined: + type: File + outputSource: concat/joined +requirements: + MultipleInputFeatureRequirement: {} diff --git a/tests/core/data/python_api/aligner.cwl b/tests/core/data/python_api/aligner.cwl new file mode 100644 index 000000000..d2a8e8f82 --- /dev/null +++ b/tests/core/data/python_api/aligner.cwl @@ -0,0 +1,82 @@ +# What tests/core/test_python_api_tool_builder.py's tool builds: every builder method reaches the document, a `/` in +# the tool's name is its id, and `extra` adds keys the builder does not model. Its default is the text `1e3`. +class: CommandLineTool +id: tools/aligner +label: Align reads +doc: [Toy CLT, for serialization coverage] +inputs: +- id: reads + secondaryFiles: + - {pattern: .bai, required: false} + format: edam:format_2572 + type: {type: array, items: File} + inputBinding: {prefix: --reads} +- id: mode + type: + type: enum + symbols: [fast, accurate] + name: Mode + inputBinding: {prefix: --mode} +- id: settings + loadListing: shallow_listing + type: + type: record + fields: + - {name: threads, type: int} + - name: preset + type: + type: enum + symbols: [fast, accurate] + name: Mode + - name: tags + type: {type: array, items: string} + name: Settings +- {id: message, type: string, default: '1e3'} +- id: model + type: ['null', File] + inputBinding: {prefix: --model} +outputs: +- {id: sam, type: stdout} +requirements: +- {class: ShellCommandRequirement} +- class: InlineJavascriptRequirement + expressionLib: ['function passthrough(x) { return x; }'] +- class: SchemaDefRequirement + types: + - type: enum + symbols: [fast, accurate] + name: Mode + - type: record + fields: + - {name: threads, type: int} + - name: preset + type: + type: enum + symbols: [fast, accurate] + name: Mode + - name: tags + type: {type: array, items: string} + name: Settings +- {class: DockerRequirement, dockerPull: 'alpine:3.20'} +- {class: ResourceRequirement, coresMin: 1.5, ramMin: 1024, outdirMin: 256} +- class: EnvVarRequirement + envDef: + - {envName: LC_ALL, envValue: C} +- class: InitialWorkDirRequirement + listing: + - {entryname: config.txt, entry: "threads=4\n"} +- {class: NetworkAccess, networkAccess: false} +- {class: ToolTimeLimit, timelimit: 60} +hints: +- {class: WorkReuse, enableReuse: false} +cwlVersion: v1.2 +intent: ['edam:operation_3198'] +baseCommand: [bash, -lc] +arguments: +- {position: 0, valueFrom: run-aligner} +stdout: aligned.sam +successCodes: [0, 2] +$namespaces: {edam: 'https://edamontology.org/'} +$schemas: ['https://example.org/formats.rdf'] +sbol_intent: example:custom +customExtension: {enabled: true} diff --git a/tests/core/data/python_api/builder.cwl b/tests/core/data/python_api/builder.cwl new file mode 100644 index 000000000..7d46d06d0 --- /dev/null +++ b/tests/core/data/python_api/builder.cwl @@ -0,0 +1,104 @@ +# What builder.py's workflow() compiles to: see the comments there. +steps: +- id: emit_text + in: {message: message} + run: + class: CommandLineTool + id: emit_text + inputs: + - id: message + type: string + inputBinding: {position: 1} + outputs: + - id: file + type: File + outputBinding: {glob: stdout.txt} + baseCommand: echo + stdout: stdout.txt + out: [file] +- id: child + in: + file: {source: emit_text/file} + count~scale: child~count~scale + run: + steps: + - id: count + in: + file: file + scale: {source: count~scale} + run: + class: CommandLineTool + id: count + inputs: + - id: file + type: File + inputBinding: {position: 1} + - id: scale + type: float + inputBinding: {prefix: -s} + outputs: + - {id: counts, type: stdout} + baseCommand: [wc, -c] + stdout: counts.txt + out: [counts] + class: Workflow + inputs: + file: {type: File} + count~scale: {type: float} + outputs: + counts: {type: File, outputSource: count/counts} + count~counts: {type: File, outputSource: count/counts} + out: [counts, count~counts] +- id: write_dir + in: + outDir: {source: write_dir~outDir} + run: + class: CommandLineTool + requirements: + InitialWorkDirRequirement: + listing: + - {entry: "${\n return {\"class\": \"Directory\", \"basename\": inputs['outDir'], \"listing\": []};\n}", writable: true} + InlineJavascriptRequirement: {} + baseCommand: [bash, -lc] + arguments: + - {valueFrom: touch $(inputs.outDir)/done.txt} + inputs: + outDir: + type: string + inputBinding: {prefix: --outDir} + outputs: + outDir: + type: Directory + outputBinding: {glob: $(inputs.outDir)} + out: [outDir] +- id: cat + in: + f: {source: cat~f} + go: {source: message} + run: + class: CommandLineTool + baseCommand: cat + inputs: + f: + type: File + inputBinding: {position: 1} + outputs: + out: + type: File + outputBinding: {glob: out.txt} + stdout: out.txt + out: [out] + when: $(inputs.go == "hello") +cwlVersion: v1.2 +class: Workflow +inputs: + message: {type: string} + child~count~scale: {type: float} + write_dir~outDir: {type: string} + cat~f: {type: File} +outputs: + said: {type: string, outputSource: message} + _Counted: {type: File, outputSource: child/counts} +requirements: + InlineJavascriptRequirement: {} + SubworkflowFeatureRequirement: {} diff --git a/tests/core/data/python_api/builder.py b/tests/core/data/python_api/builder.py new file mode 100644 index 000000000..75265292c --- /dev/null +++ b/tests/core/data/python_api/builder.py @@ -0,0 +1,42 @@ +"""A workflow built from objects, as a user's script builds one. builder.cwl beside it is the CWL `workflow().compile()` +returns, and builder_job.yml its job; each comment says what they show of the line below it.""" +from pathlib import Path + +from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl +from sophios.api.python.workflow import Step, StepInput, Workflow + +HERE = Path(__file__).resolve().parent + + +def workflow() -> Workflow: + """Emit a message to a file, count it in a child workflow, make a folder, and print a file on another machine.""" + emit = (CommandLineTool('emit_text', Inputs(message=Input(cwl.string, position=1)), + Outputs(file=Output(cwl.file, glob='stdout.txt'))) + .base_command('echo').stdout('stdout.txt').to_step()) + count = (CommandLineTool('count', Inputs(file=Input(cwl.file, position=1), scale=Input(cwl.float, flag='-s')), + Outputs(counts=Output.stdout())) + .base_command('wc', '-c').stdout('counts.txt').to_step()) + # A child workflow: its step reads the child's formal parameters, which the parent binds by name. + child = Workflow([count], 'child') + count.inputs.file = child.inputs.file + child.inputs.file = emit.outputs.file + child.outputs.counts = count.outputs.counts + count.inputs.scale = 0.5 + # An output directory the step creates: a string input the runner fills, which its glob reads back. + folder = Step(clt_path=HERE / 'write_dir.cwl') + folder.inputs.outDir = Path('result.outDir') + # A path is bound as written, read from no disk: it may name a file on a cluster. + remote = Step(clt_path=HERE / 'cat.cwl') + remote.inputs.f = Path('/cluster/images.ome.zarr') + flow = Workflow([emit, child, folder, remote], 'builder') + # A record on an input the tool does not declare, read only by `when:`, does not type the workflow input it reads: + # the plain binding after it does. Reading `flow.message` declares that input, and warns of the clearer spelling. + remote.inputs.go = StepInput(source=flow.message) + remote.when = '$(inputs.go == "hello")' + emit.inputs.message = flow.inputs.message + # A value bound on a workflow input is its job value, and a workflow output may pass a workflow input through. + flow.inputs.message = 'hello' + flow.outputs.said = flow.inputs.message + # A workflow output whose name starts with `_` is declared by binding it. + setattr(flow.outputs, '_Counted', child.outputs.counts) + return flow diff --git a/tests/core/data/python_api/builder_job.yml b/tests/core/data/python_api/builder_job.yml new file mode 100644 index 000000000..147c4ec6a --- /dev/null +++ b/tests/core/data/python_api/builder_job.yml @@ -0,0 +1,4 @@ +child~count~scale: 0.5 +write_dir~outDir: result.outDir +cat~f: {class: File, location: /cluster/images.ome.zarr} +message: hello diff --git a/tests/core/data/python_api/cat.cwl b/tests/core/data/python_api/cat.cwl new file mode 100644 index 000000000..703f1281c --- /dev/null +++ b/tests/core/data/python_api/cat.cwl @@ -0,0 +1,13 @@ +# Prints the file it is given; it runs in no container. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: cat +inputs: + f: + type: File + inputBinding: {position: 1} +outputs: + out: + type: File + outputBinding: {glob: out.txt} +stdout: out.txt diff --git a/tests/core/data/python_api/exits_3.cwl b/tests/core/data/python_api/exits_3.cwl new file mode 100644 index 000000000..77790635b --- /dev/null +++ b/tests/core/data/python_api/exits_3.cwl @@ -0,0 +1,7 @@ +# A tool that fails with status 3. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: [sh, -c, 'exit 3'] +inputs: + message: string +outputs: {} diff --git a/tests/core/data/python_api/false.cwl b/tests/core/data/python_api/false.cwl new file mode 100644 index 000000000..418118bf0 --- /dev/null +++ b/tests/core/data/python_api/false.cwl @@ -0,0 +1,6 @@ +# A tool that fails, named echo.cwl where a bundle would write the shipped echo. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'false' +inputs: {} +outputs: {} diff --git a/tests/core/data/python_api/hinted.cwl b/tests/core/data/python_api/hinted.cwl new file mode 100644 index 000000000..a1b270bf6 --- /dev/null +++ b/tests/core/data/python_api/hinted.cwl @@ -0,0 +1,9 @@ +# A tool whose image is a DockerRequirement hint, not a requirement. +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: {} +outputs: {} +hints: + DockerRequirement: + dockerPull: docker.io/alpine:3.20 diff --git a/tests/core/data/python_api/refused.py b/tests/core/data/python_api/refused.py new file mode 100644 index 000000000..13d5ae5cf --- /dev/null +++ b/tests/core/data/python_api/refused.py @@ -0,0 +1,299 @@ +"""Python the API can prove wrong, one mistake to a function; refused.yaml beside it states what each raises.""" +# pylint: disable=missing-function-docstring # each function's name is the mistake it makes +import asyncio +import shutil +from decimal import Decimal +from pathlib import Path + +from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Outputs, cwl +from sophios.api.python.workflow import Step, StepInput, Workflow + +HERE = Path(__file__).resolve().parent +ADAPTERS = HERE.parents[3] / 'cwl_adapters' + + +def _step(tool: str, name: str | None = None, **values: object) -> Step: + """A step running the shipped `tool`, with `values` bound.""" + step = Step(clt_path=ADAPTERS / f'{tool}.cwl', step_name=name) + for port, value in values.items(): + setattr(step.inputs, port, value) + return step + + +def _sink(declared: object) -> Step: + """A step taking `x`, declared `declared`, and making nothing, from the document of a built tool.""" + tool = CommandLineTool('sink', Inputs(x=Input(declared)), Outputs()).base_command('true') + return Step.from_cwl_document(tool.to_cwl_document(), process_name='sink') + + +def _made() -> tuple[Step, Step]: + """Steps `a` and `b`, each touching a file of its name.""" + return _step('touch', 'a', filename='a.txt'), _step('touch', 'b', filename='b.txt') + + +# Bindings, refused where they are written: a port the tool does not declare, which only a StepInput may bind; a +# source of a type the port cannot take; a port object where a literal goes, at any depth; a string as a source. + +def misspelled_port() -> None: + _step('append').misspelled = 'Hello' + + +def undeclared_port() -> None: + _step('echo').inputs.go = True + + +def undeclared_port_a_record_bound() -> None: + _step('echo', go=StepInput(default=True)).inputs.go = True + + +def output_of_another_type() -> None: + _step('append').inputs.str = _made()[0].outputs.file + + +def workflow_input_of_another_type() -> None: + append = _step('append') + flow = Workflow([append], 'w') + append.inputs.file = flow.inputs.text.as_type('string') + + +def merged_sources_of_another_type() -> None: + a, b = _made() + _sink(cwl.int).inputs.x = StepInput(source=[a.outputs.file, b.outputs.file], link_merge='merge_flattened') + + +def picked_sources_of_another_type() -> None: + a, b = _made() + _sink(cwl.int).inputs.x = StepInput(source=[a.outputs.file, b.outputs.file], pick_value='first_non_null') + + +def port_in_a_list() -> None: + _step('cat').inputs.file = [_made()[0].outputs.file] + + +def workflow_input_in_a_tuple() -> None: + cat = _step('cat') + cat.inputs.file = (Workflow([cat], 'w').inputs.f,) + + +def port_in_a_nested_list() -> None: + _step('cat').inputs.file = [[_made()[0].outputs.file]] + + +def port_in_a_mapping() -> None: + _step('cat').inputs.file = {'x': _made()[0].outputs.file} + + +def port_in_a_list_of_mappings() -> None: + _step('cat').inputs.file = [{'x': [_made()[0].outputs.file]}] + + +def step_input_in_a_list() -> None: + _step('cat').inputs.file = [StepInput(source=_made()[0].outputs.file)] + + +def string_as_a_source() -> None: + StepInput(source='go') + + +def strings_as_sources() -> None: + StepInput(source=['go']) + + +def _decimal_for(declared: object) -> None: + sink = _sink(declared) + sink.inputs.x = Decimal(3) + Workflow([sink], 'w').compile() + + +def decimal_for_an_int() -> None: + _decimal_for(cwl.int) + + +def decimal_for_a_float() -> None: + _decimal_for(cwl.float) + + +def decimal_for_a_boolean() -> None: + _decimal_for(cwl.boolean) + + +def decimal_for_a_string() -> None: + _decimal_for(cwl.string) + + +# Workflows wired wrong, refused when compiled: a step reads only an earlier step of its own workflow, never its +# workflow's own output; a merge the bind cannot judge is the compiler's. + +def step_before_its_source() -> None: + a = _made()[0] + Workflow([_step('append', file=a.outputs.file, str='Hello'), a], 'w').compile() + + +def source_outside_the_workflow() -> None: + Workflow([_step('append', file=_made()[0].outputs.file, str='Hello')], 'w').compile() + + +def record_before_its_source() -> None: + a = _made()[0] + Workflow([_step('cat', file=StepInput(source=[a.outputs.file], pick_value='first_non_null')), a], 'w').compile() + + +def reads_its_own_output() -> None: + a, cat = _made()[0], _step('cat') + flow = Workflow([a, cat], 'loop') + flow.outputs.made = a.outputs.file + cat.inputs.file = flow.outputs.made + flow.compile() + + +def merge_into_a_file() -> None: + a, b = _made() + sink = _sink(cwl.file) + sink.inputs.x = StepInput(source=[a.outputs.file, b.outputs.file], link_merge='merge_flattened') + Workflow([a, b, sink], 'w').compile() + + +def _sharing_a_stem() -> Workflow: + return Workflow([Step(clt_path=HERE / 'cat.cwl'), _step('cat', 'shipped_cat')], 'shared_stem') + + +def two_tools_one_stem() -> None: + _sharing_a_stem().compile() + + +def two_tools_one_stem_written() -> None: + _sharing_a_stem().write_wic(Path('.')) + + +def cwl_workflow_as_a_tool() -> None: + step = Step(clt_path=HERE / 'say.cwl') + step.inputs.f = 'a.txt' + Workflow([step], 'wsay').compile() + + +def absolute_output_directory() -> None: + step = Step(clt_path=HERE / 'write_dir.cwl') + step.inputs.outDir = Path('/absolute.outDir') + Workflow([step], 'w').compile() + + +# Names Sophios cannot write: a step's name is an id of the compiled CWL, a workflow's the stem of its files. + +def step_named_with_a_tilde() -> None: + _step('touch', 'a~b') + + +def step_named_hidden() -> None: + _step('touch', '.hidden') + + +def workflow_named_for_the_directory_above() -> None: + Workflow([_step('touch')], '..') + + +# Scatter needs a bound, array-valued port of the step itself. A pickValue that picks one source delivers one value, +# and a nested workflow adds no array layer of its own. + +def scatter_over_an_unbound_port() -> None: + echo = _step('echo') + echo.scatter = [echo.inputs.message] + + +def scatter_over_a_scalar() -> None: + echo = _step('echo', message='hello') + echo.scatter = [echo.inputs.message] + + +def scatter_over_a_path() -> None: + cat = Step(clt_path=HERE / 'cat.cwl') + cat.inputs.f = Path('/cluster/images.ome.zarr') + cat.scatter_on(cat.inputs.f) + + +def scatter_over_another_steps_port() -> None: + _step('echo').scatter = [_step('echo', message=['a', 'b']).inputs.message] + + +def scatter_over_a_picked_value() -> None: + a, b = _made() + sink = _sink(cwl.file) + sink.inputs.x = StepInput(source=[a.outputs.file, b.outputs.file], pick_value='the_only_non_null') + sink.scatter_on(sink.inputs.x) + + +def scatter_over_a_nested_workflows_output() -> None: + touch = _step('touch', filename='empty.txt') + inner = Workflow([touch], 'inner') + inner.outputs.made = touch.outputs.file + cat = _step('cat', file=inner.outputs.made) + cat.scatter_on(cat.inputs.file) + + +# Each door: an unknown target, before anything is compiled; what the Nextflow target cannot run; a real-time +# analysis, which run_async() never runs. + +def unknown_target_to_compile() -> None: + Workflow([_step('touch')], 'elsewhere').compile(target='wdl') # type: ignore[call-overload] + + +def unknown_target_to_check() -> None: + Workflow([_step('touch')], 'elsewhere').check(target='wdl') # type: ignore[arg-type] + + +def unknown_target_to_run() -> None: + Workflow([_step('touch')], 'elsewhere').run(target='wdl') # type: ignore[arg-type] + + +def unknown_target_to_start() -> None: + Workflow([_step('touch')], 'elsewhere').start(target='wdl') # type: ignore[arg-type] + + +def string_comparison_under_nextflow() -> None: + echo = _step('echo', message='hi') + echo.when = '$(inputs.message < "27")' + Workflow([echo], 'refused').compile(target='nextflow') + + +def real_time_analysis_under_run_async() -> None: + declaration = Step(clt_path=ADAPTERS / 'file_watchers' / 'cwl_subinterpreter.cwl') + declaration.inputs.file_pattern = 'empty.txt' + declaration.inputs.cwl_tool = 'touch' + declaration.inputs.max_times = 2 + declaration.inputs.config = {'in': {'filename': 'again.txt'}} + asyncio.run(Workflow([_step('touch', filename='empty.txt'), declaration], 'py_async').run_async()) + + +# Files: a .wic is written to a .wic file or a directory, by write_wic, which replaced the removed .wic text +# accessors, and never over another tool of the stem it names; a step inputs file belongs to a tool on disk. + +def wic_text_of_a_workflow() -> None: + _ = Workflow([], 'wf').to_wic_yaml + + +def bundle_to_a_yaml_file() -> None: + Workflow([], 'wf').write_wic(Path('workflow.yaml')) + + +def bundle_over_another_tool_of_its_stem() -> None: + shutil.copyfile(HERE / 'false.cwl', 'echo.cwl') + Workflow([_step('echo', message='hi')], 'wf').write_wic(Path('.')) + + +def step_inputs_file_for_a_built_tool() -> None: + tool = CommandLineTool('emit', Inputs(), Outputs()).base_command('true') + Step(tool, step_inputs_file='inputs.yml') # type: ignore[call-overload] + + +# The tool builder: raw CWL may not overwrite what the builder manages or how the document is loaded, and a port is +# referenced by its object, never by its name as text. + +def raw_key_the_builder_manages() -> None: + CommandLineTool('custom', Inputs(), Outputs()).extra(inputs={'bad': 'idea'}) + + +def loader_key_in_a_requirement() -> None: + CommandLineTool('custom', Inputs(), Outputs()).requirement({'class': 'EnvVarRequirement', '$import': 'bad'}) + + +def port_named_by_text() -> None: + CommandLineTool('demo', Inputs(input=Input(cwl.file)), Outputs()).stage('input') diff --git a/tests/core/data/python_api/refused.yaml b/tests/core/data/python_api/refused.yaml new file mode 100644 index 000000000..bb1ade340 --- /dev/null +++ b/tests/core/data/python_api/refused.yaml @@ -0,0 +1,52 @@ +# What each function of refused.py raises: the exception, its diagnostic's code where it carries one, and what its +# message names. A misspelled port's AttributeError is Python's own. +misspelled_port: {raises: AttributeError, names: ["'append'", "'misspelled'"]} +undeclared_port: {raises: AttributeError, names: ["'echo'", "'go'"]} +undeclared_port_a_record_bound: {raises: AttributeError, names: ["'go'", only a StepInput binds]} +output_of_another_type: {raises: InvalidLinkError, code: INVALID_LINK, names: [append.str, "'string'", "'File'"]} +workflow_input_of_another_type: {raises: InvalidLinkError, code: INVALID_LINK, names: [append.file, w.inputs.text]} +merged_sources_of_another_type: {raises: InvalidLinkError, code: INVALID_LINK, names: [sink.x, "'int'"]} +picked_sources_of_another_type: {raises: InvalidLinkError, code: INVALID_LINK, names: [sink.x, "'int'", "'File'"]} +port_in_a_list: &literal {raises: InvalidInputValueError, code: INVALID_INPUT_VALUE, names: [cat.file, StepInput]} +workflow_input_in_a_tuple: *literal +port_in_a_nested_list: *literal +port_in_a_mapping: *literal +port_in_a_list_of_mappings: *literal +step_input_in_a_list: *literal +string_as_a_source: &string {raises: InvalidInputValueError, code: INVALID_INPUT_VALUE, names: [StepInput.source, str]} +strings_as_sources: *string +decimal_for_an_int: {raises: SophiosError, code: LITERAL_TYPE_MISMATCH, names: ["'x'", decimal.Decimal, Python int]} +decimal_for_a_float: {raises: SophiosError, code: LITERAL_TYPE_MISMATCH, names: [decimal.Decimal, Python float]} +decimal_for_a_boolean: {raises: SophiosError, code: LITERAL_TYPE_MISMATCH, names: [decimal.Decimal, Python bool]} +decimal_for_a_string: {raises: SophiosError, code: LITERAL_TYPE_MISMATCH, names: [decimal.Decimal, Python str]} +step_before_its_source: {raises: InvalidStepError, code: INVALID_STEP, names: [append.file, "'a'", earlier]} +source_outside_the_workflow: {raises: InvalidStepError, code: INVALID_STEP, names: [append.file, "'a' is not a child"]} +record_before_its_source: {raises: InvalidStepError, code: INVALID_STEP, names: [cat.file, "'a'", earlier]} +reads_its_own_output: {raises: InvalidLinkError, code: INVALID_LINK, names: [cat.file, loop.outputs.made, own output]} +merge_into_a_file: {raises: SophiosError, code: INCOMPATIBLE_INPUT_REFERENCE, names: ["'sink'", "'x'"]} +two_tools_one_stem: &stem {raises: InvalidStepError, code: INVALID_STEP, names: ["'cat'", "'shipped_cat'", "stem 'cat'"]} +two_tools_one_stem_written: *stem +cwl_workflow_as_a_tool: {raises: SophiosError, code: SUBWORKFLOW_INVALID, names: [say.cwl, nested Workflow, --allow_raw_cwl]} +absolute_output_directory: {raises: ValueError, names: [write_dir~outDir, absolute location]} +step_named_with_a_tilde: {raises: ValueError, names: ["step name 'a~b'"]} +step_named_hidden: {raises: ValueError, names: ["step name '.hidden'"]} +workflow_named_for_the_directory_above: {raises: ValueError, names: ["workflow name '..'"]} +scatter_over_an_unbound_port: {raises: ValueError, names: [bound before scattering]} +scatter_over_a_scalar: &scalar {raises: ValueError, names: [array-valued data]} +scatter_over_a_path: *scalar +scatter_over_another_steps_port: {raises: ValueError, names: [same step]} +scatter_over_a_picked_value: *scalar +scatter_over_a_nested_workflows_output: *scalar +unknown_target_to_compile: &target {raises: ValueError, names: ["unknown target 'wdl'", cwl, nextflow]} +unknown_target_to_check: *target +unknown_target_to_run: *target +unknown_target_to_start: *target +string_comparison_under_nextflow: {raises: NotLowered, code: NF_WHEN_SUBSET, names: [refused.py, "'echo'", '<']} +real_time_analysis_under_run_async: {raises: SophiosError, code: REALTIME_NOT_ASYNC, names: [refused.py, "'touch'"]} +wic_text_of_a_workflow: {raises: AttributeError, names: [Workflow.write_wic]} +bundle_to_a_yaml_file: {raises: ValueError, names: [.wic file or a directory]} +bundle_over_another_tool_of_its_stem: {raises: InvalidStepError, code: INVALID_STEP, names: [echo.cwl, "'echo'"]} +step_inputs_file_for_a_built_tool: {raises: TypeError, names: [step_inputs_file]} +raw_key_the_builder_manages: {raises: ValueError, names: [builder-managed, inputs]} +loader_key_in_a_requirement: {raises: ValueError, names: [SALAD, $import]} +port_named_by_text: {raises: TypeError, names: [named Input/Output object]} diff --git a/tests/core/data/python_api/say.cwl b/tests/core/data/python_api/say.cwl new file mode 100644 index 000000000..1fe0562e9 --- /dev/null +++ b/tests/core/data/python_api/say.cwl @@ -0,0 +1,6 @@ +# A CWL Workflow, which a Python Step cannot run as its clt_path. +class: Workflow +cwlVersion: v1.2 +inputs: {f: File} +outputs: {said: {type: File, outputSource: print/out}} +steps: {print: {run: cat.cwl, in: {f: f}, out: [out]}} diff --git a/tests/core/data/python_api/say_hello.py b/tests/core/data/python_api/say_hello.py new file mode 100644 index 000000000..0c3f6414f --- /dev/null +++ b/tests/core/data/python_api/say_hello.py @@ -0,0 +1,13 @@ +"""A user's script: it runs a workflow, and prints what its one output holds from the summary the run wrote.""" +import json +from pathlib import Path + +from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl +from sophios.api.python.workflow import Workflow + +echo = (CommandLineTool('echo', Inputs(message=Input(cwl.string, position=1)), Outputs(said=Output.stdout())) + .base_command('echo').stdout('said.txt').to_step()) +echo.inputs.message = 'hello' +Workflow([echo], 'say').run() +summary = json.loads(Path('autogenerated/output_say.json').read_text(encoding='utf-8')) +print(Path(next(iter(summary.values()))['path']).read_text(encoding='utf-8'), end='') diff --git a/tests/core/data/python_api/write_dir.cwl b/tests/core/data/python_api/write_dir.cwl new file mode 100644 index 000000000..a0779da43 --- /dev/null +++ b/tests/core/data/python_api/write_dir.cwl @@ -0,0 +1,22 @@ +# A tool whose output is a directory it is given the name of, and creates. +class: CommandLineTool +cwlVersion: v1.2 +requirements: + InitialWorkDirRequirement: + listing: + - entry: $(inputs.outDir) + writable: true + InlineJavascriptRequirement: {} +baseCommand: [bash, -lc] +arguments: + - valueFrom: "touch $(inputs.outDir.basename)/done.txt" +inputs: + outDir: + type: Directory + inputBinding: + prefix: --outDir +outputs: + outDir: + type: Directory + outputBinding: + glob: $(inputs.outDir.basename) diff --git a/tests/core/data/shipped_scripts.yaml b/tests/core/data/shipped_scripts.yaml new file mode 100644 index 000000000..198eba724 --- /dev/null +++ b/tests/core/data/shipped_scripts.yaml @@ -0,0 +1,101 @@ +# What each shipped Python script makes, in part. `call` names the function the test calls, with `args`: `compiled` +# states the CWL the workflow it returns compiles to, and `printed` the compute request it prints; `tools` states the +# tool documents the functions it names build, each but for its doc. +examples/workflows/when_pyapi.py: + why: Step.when reaches the step that declared it, and that step alone + call: workflow + compiled: {steps: [{keys: [id, in, run, out]}, {id: echo, when: $(inputs.message < "27")}]} +examples/workflows/scatter_single_pyapi.py: + why: one scattered port and no method is a dotproduct over the array, not one run on the whole array + call: workflow + compiled: {steps: [{keys: [id, in, run, out]}, {id: echo, scatter: [message], scatterMethod: dotproduct}]} +examples/scripts/tool_builder_workflow.py: + why: the string a built tool reads from its stdout file is carried through to the workflow output (docs/tool-builder.md) + call: build_workflow + args: [hello from test] + compiled: + steps: + - {id: emit_text} + - id: read_text + in: {text_file: {source: emit_text/text_file}} + run: {outputs: [{id: result, type: string, + outputBinding: {glob: stdout.txt, loadContents: true, outputEval: '$(self[0].contents)'}}]} + outputs: {result: {type: string, outputSource: read_text/result}} +examples/scripts/count_words.py: + why: the README, the landing page and docs/tool-builder.md show its third step running wc -w on the greeting + call: workflow + compiled: + steps: + - {id: touch} + - {id: append} + - {id: word_count, in: {exact: {text: {source: append/file}}}, run: {baseCommand: [wc, -w], stdout: counts.txt}} +examples/scripts/ichnaea_compact.py: + why: with a basepath the compute service requires the outputs folder, relative to it; the output folder is a name + call: main + printed: + basepath: /projects/collabs/mock_common + workflowOutDir: results_compact + inputs: {autoseg~output: {class: Directory, location: segmentation_compact}} + tools: + # The image's ENTRYPOINT is its command, which the runner puts in front of the tool's command line, so the tool + # has no base command; the three ichnaea scripts build this one tool. + build_autoseg_CLT: &autoseg + exact: + class: CommandLineTool + id: ichnaea_segmentation + label: ichnaea segmentation + inputs: + - id: input + label: Input OME-Zarr + doc: 'The OME-Zarr volume: its root, which holds .zattrs' + type: Directory + inputBinding: + position: 1 + prefix: --inpDir + - id: output + label: Output segmentation OME-Zarr + doc: An empty folder; filled with a copy of the input whose level 0 holds the labels + type: Directory + inputBinding: + position: 2 + prefix: --outDir + - id: model + label: Models folder + doc: Staged as ./models, from which the plugin loads sam2.1_hiera_small.pt + type: Directory + outputs: + - id: output + label: Output segmentation OME-Zarr + type: Directory + outputBinding: + glob: $(inputs.output.basename) + requirements: + - class: DockerRequirement + dockerPull: vjaganat90/ichnaea-segmentation-plugin:devn + - class: InitialWorkDirRequirement + listing: + - entryname: $(inputs.output.basename) + entry: $(inputs.output) + writable: true + - entryname: models + entry: $(inputs.model) + writable: false + - class: ResourceRequirement + coresMin: 4 + ramMin: 64000 + - class: InlineJavascriptRequirement + hints: + - class: cwltool:CUDARequirement + cudaVersionMin: '12.6' + cudaComputeCapability: '3.0' + cudaDeviceCountMin: 1 + cwlVersion: v1.2 + $namespaces: + edam: https://edamontology.org/ + cwltool: http://commonwl.org/cwltool# + $schemas: + - https://raw.githubusercontent.com/edamontology/edamontology/master/EDAM_dev.owl +examples/scripts/ichnaea_integrated.py: + tools: {build_autoseg_CLT: *autoseg} +examples/scripts/ichnaea_tool_builder.py: + tools: {build_tool: *autoseg} diff --git a/tests/core/ground_truth_multistep1.json b/tests/core/ground_truth_multistep1.json deleted file mode 100644 index 95822f977..000000000 --- a/tests/core/ground_truth_multistep1.json +++ /dev/null @@ -1,188 +0,0 @@ -{ - "name": "multistep1_toJson_pyapi_py", - "yaml_inputs": { - "touch~filename": "empty.txt", - "append~str": "Hello" - }, - "steps": [ - { - "id": "touch", - "in": { - "filename": { - "source": "touch~filename" - } - }, - "run": { - "class": "CommandLineTool", - "requirements": { - "DockerRequirement": { - "dockerPull": "docker.io/library/debian:bookworm-slim" - }, - "InlineJavascriptRequirement": {} - }, - "baseCommand": "touch", - "inputs": { - "filename": { - "type": "string", - "inputBinding": { - "position": 1 - } - } - }, - "outputs": { - "file": { - "type": "File", - "outputBinding": { - "glob": "$(inputs.filename)" - } - } - }, - "hints": { - "LoadListingRequirement": { - "loadListing": "deep_listing" - }, - "NetworkAccess": { - "networkAccess": true - } - } - }, - "out": [ - "file" - ] - }, - { - "id": "append", - "in": { - "str": { - "source": "append~str" - }, - "file": { - "source": "touch/file" - } - }, - "run": { - "class": "CommandLineTool", - "requirements": { - "ShellCommandRequirement": {}, - "InitialWorkDirRequirement": { - "listing": [ - { - "entry": "$(inputs.file)", - "writable": true - } - ] - } - }, - "inputs": { - "str": { - "type": "string" - }, - "file": { - "type": "File" - } - }, - "arguments": [ - "printf", - "%s\\n", - "$(inputs.str)", - { - "valueFrom": ">>", - "shellQuote": false - }, - "$(inputs.file.basename)" - ], - "outputs": { - "file": { - "type": "File", - "outputBinding": { - "glob": "$(inputs.file.basename)" - } - } - }, - "hints": { - "LoadListingRequirement": { - "loadListing": "deep_listing" - }, - "NetworkAccess": { - "networkAccess": true - } - } - }, - "out": [ - "file" - ] - }, - { - "id": "cat", - "in": { - "file": { - "source": "append/file" - } - }, - "run": { - "class": "CommandLineTool", - "requirements": { - "DockerRequirement": { - "dockerPull": "docker.io/library/debian:bookworm-slim" - }, - "InlineJavascriptRequirement": {} - }, - "baseCommand": [ - "cat" - ], - "inputs": { - "file": { - "type": "File" - } - }, - "outputs": { - "output": { - "type": "string", - "outputBinding": { - "glob": "output", - "loadContents": true, - "outputEval": "$(self[0].contents)" - } - } - }, - "stdin": "$(inputs.file.path)", - "stdout": "output", - "hints": { - "LoadListingRequirement": { - "loadListing": "deep_listing" - }, - "NetworkAccess": { - "networkAccess": true - } - } - }, - "out": [ - "output" - ] - } - ], - "cwlVersion": "v1.2", - "class": "Workflow", - "inputs": { - "touch~filename": { - "type": "string" - }, - "append~str": { - "type": "string" - } - }, - "outputs": { - "touch~file": { - "type": "File", - "outputSource": "touch/file" - }, - "append~file": { - "type": "File", - "outputSource": "append/file" - }, - "cat~output": { - "type": "string", - "outputSource": "cat/output" - } - } -} \ No newline at end of file diff --git a/tests/core/test_ci_coverage.py b/tests/core/test_ci_coverage.py index ed7244998..70a6f2c38 100644 --- a/tests/core/test_ci_coverage.py +++ b/tests/core/test_ci_coverage.py @@ -155,17 +155,16 @@ def test_the_weekly_property_lane_runs_the_whole_oracle_suite() -> None: @pytest.mark.fast def test_the_corpus_lane_round_trips_every_wic_root_through_the_python_api() -> None: - """The lane whose config reaches the external corpora runs the from_wic properties. + """The lane whose config reaches the external corpora runs the from_wic property. - `test_python_api_from_wic.py` parametrizes its two properties over every + `test_python_api_from_wic.py` parametrizes its corpus property over every `.wic` root `search_paths_wic` reaches. Only `run_workflows.yml` writes a config that reaches the mm-workflows and image-workflows roots; the package job does not select the file, and checks out neither corpus, so - the properties would see the repository's own roots and nothing else. + the property would see the repository's own roots and nothing else. """ properties = { 'tests/core/test_python_api_from_wic.py::test_a_wic_file_and_its_python_objects_compile_alike', - 'tests/core/test_python_api_from_wic.py::test_write_wic_of_a_loaded_workflow_compiles_identically', } selected = set().union(*_collect_all(_invocations(WORKFLOWS / 'run_workflows.yml'))) missing = sorted(properties - selected) @@ -350,32 +349,25 @@ def _tests_importing(module: str, path: Path) -> set[str]: # is the script's, not the test's. Its compact twin builds the same hinted # tool without validating it and still runs on Windows. 'tests/core/test_example_scripts.py::test_the_integrated_ichnaea_script_compiles_its_hinted_tool', - # Loads the corpus into cwltool, to ask it what an embedded document means. Its - # platform-neutral sibling `test_embedding_keeps_meaning` runs on every leg. - 'tests/core/test_examples.py::test_embedding_keeps_runtime_defaults', - # Loads the flat and flat-embedded corpus documents into cwltool to validate - # them. Its platform-neutral sibling `test_flatten_keeps_meaning` runs on - # every leg. - 'tests/core/test_examples.py::test_flatten_validates_as_cwl', - # The same check over the weekly workflows, which only the weekly lane runs. - 'tests/core/test_examples.py::test_weekly_corpus_flatten_validates_as_cwl', + # Loads the corpus into cwltool, to validate its flat and flat-embedded forms and ask + # what an embedded document means. Its platform-neutral sibling + # `test_corpus_compiles_clean_in_every_form` runs on every leg. + 'tests/core/test_examples.py::test_corpus_validates_in_cwltool_in_every_form', # Plain CWL workflows run by cwltool through --run_local: a two-step one, # and twelve conformance workflows, each also run by cwltool directly, in # about four seconds. The file's other tests check what the runner is # given and run on Windows. 'tests/core/test_plain_cwl.py::test_a_plain_cwl_workflow_runs_through_sophios_as_cwltool_runs_it', # One `Workflow.run()` of a one-step echo, by cwltool, from a script run by a new - # interpreter, under a second. - 'tests/core/test_python_api_workflow.py::test_workflow_run_runs_a_workflow_from_a_users_script', + # interpreter, and one real cwltool run of a failing one-line tool, in a few seconds. + # The failure pins the wording of cwltool's job-failure record, which the summary + # reads; the other tests of the summary use a stand-in for cwltool and run on every leg. + 'tests/core/test_python_api_workflow.py::test_a_real_run_prints_its_output_or_names_the_step_that_failed', # A workflow run by cwltool through --run_local, with two real-time analyses # run by cwltool beside it, one of them failing, in one run of about eight # seconds. The watcher's own tests use a stand-in for cwltool and run on # every leg. 'tests/core/test_realtime.py::test_the_analysis_runs_beside_the_workflow_and_never_changes_its_outcome', - # One real cwltool run of a failing one-line tool, under a second. It pins the - # wording of cwltool's job-failure record, which the summary reads; the other - # tests of the summary use a stand-in for cwltool and run on every leg. - 'tests/core/test_python_api_workflow.py::test_a_real_failed_step_is_named_with_its_status', # Two roots of a few echo steps, nested two deep, each run through the command line by cwltool # and by Toil with provenance, in about twenty seconds. Which files are written is checked on # every leg by tests/core/data/compiler/names; only a runner shows what its snapshot holds. diff --git a/tests/core/test_cookbook.py b/tests/core/test_cookbook.py index 116f31181..cdf4a35d5 100644 --- a/tests/core/test_cookbook.py +++ b/tests/core/test_cookbook.py @@ -1,19 +1,20 @@ -"""Every cookbook pair (`docs/cookbook/.wic` and `.py`) compiles to one CWL, job inputs and note codes from both -surfaces, or a docs page tells one surface's reader something false.""" +"""Every pair, a `.py` and a `.wic` of one stem, compiles to one CWL, job and list of notes from both surfaces, and the +bundle the `.py`'s objects write compiles to it too; each `expected.yaml` beside the pairs states what some of them +compile to, under the flags and the `compile()` arguments it names. The pairs are the cookbook's +(`docs/cookbook`), which the docs show, and tests/core/data/python_api_pairs; the docs show the files as they are.""" import re import warnings -from collections.abc import Iterable +from collections.abc import Callable from pathlib import Path +from typing import Any import pytest -from hypothesis import example, given, strategies as st +import yaml import sophios.compiler from sophios import cli -from sophios.api.python.workflow import Inference, RunPolicy -from sophios.lang import SophiosErrorCode -from sophios.lang.diagnostics import Severity, SophiosError, lines, report -from sophios.cli import default_compilation_settings +from sophios.api.python.workflow import Inference, RunPolicy, Workflow +from sophios.lang.diagnostics import Diagnostic, SophiosError, lines from sophios.ir.artifacts import CompilationResult from sophios.ir.frontdoor import bundle_from_disk from sophios.post_compile import inline_artifact_runs @@ -21,7 +22,7 @@ from sophios.runtime_inputs import normalize_artifact_cwl, normalize_artifact_job_inputs from sophios.wic_types import CompilerOptions, Json -from .budgets import budget +from .cases import DATA, diagnostic, match from .helpers import REPO_ROOT, shipped_tools from .test_setup import home_with_shipped_tools, use_home from .wic_reading import read_wic @@ -29,162 +30,132 @@ pytestmark = pytest.mark.package COOKBOOK = REPO_ROOT / 'docs' / 'cookbook' -#: A pair is a `.py` beside a `.wic` of the same stem. A `.wic` without a `.py` -#: is a subworkflow a pair calls; its Python lives in the caller's script. -PAIRS = sorted(path.stem for path in COOKBOOK.glob('*.py')) -#: The pair that stops with an error, which `test_the_inferred_graph_stops_at_the_join` pins on both surfaces. -REFUSED = 'greeting_graph_inferred' - - -@pytest.fixture(scope='module', name='shipped_tools_home') -def _shipped_tools_home(tmp_path_factory: pytest.TempPathFactory) -> Path: - """A home whose `wic/cwl_adapters` holds this checkout's tools.""" - return home_with_shipped_tools(tmp_path_factory.mktemp('home'), REPO_ROOT) - - -@pytest.fixture(autouse=True) -def _with_the_shipped_tools_at_home(monkeypatch: pytest.MonkeyPatch, shipped_tools_home: Path) -> None: - """The scripts name their tools under `Path.home() / 'wic' / 'cwl_adapters'`, as the docs tell a reader after - `sophios --generate_config`; here that home holds this checkout's tools, so an empty home and CI pass alike.""" - use_home(monkeypatch, shipped_tools_home) - - -def _codes(diagnostics: Iterable[object]) -> list[str]: - """The `wic0NN` codes in rendered diagnostics, in order.""" - return [code for text in map(str, diagnostics) for code in re.findall(r'\[(wic\d{3})\]', text)] - - -def _as_compile_returns(cwl: Json, wic_path: Path) -> Json: - """`cwl` with the outputs `Workflow.compile()` returns: only the named ones, where the CLI also exposes every step - output (docs/connecting-steps.md).""" - named = read_wic(wic_path.read_text(encoding='utf-8'), wic_path.name).get('outputs') - if not named: - return cwl - return {**cwl, 'outputs': {name: cwl['outputs'][name] for name in named}} - - -def _bodies(diagnostics: Iterable[object]) -> list[str]: - """Each diagnostic as it is printed, but for the place it points at.""" - return [re.sub(r'^.+?:\d+:\d+: ', '', str(diagnostic)) for diagnostic in diagnostics] - - -def _compile_wic(root: Path, settings: CompilerOptions | None = None) -> CompilationResult: - """`root` compiled as the CLI reads it, with the shipped tools and the `.wic` files beside it, a `run:` path read - from beside the document.""" +PYTHON_PAIRS = DATA / 'python_api_pairs' + + +#: What a stated compile may say. +_STATED = {'why', 'under', 'flags', 'settings', 'inference', 'policy', 'notes', 'reads', 'refused', 'compiled', + 'document'} + + +def _pairs() -> list[tuple[str, Callable[[], Workflow], Path, list[dict[str, Any]]]]: + """Each pair: its name, what builds its objects, its `.wic`, and the compiles tests/core/data/pairs states of it: + the default compile, then each it lists `under:` other flags and `compile()` arguments. A cookbook `.py` builds + the objects with `workflow()`; tests/core/data/python_api_pairs/pairs.py holds one function per pair. A `.wic` + with no `.py` is a workflow a pair calls.""" + paired = import_python_file('python_api_pairs', PYTHON_PAIRS / 'pairs.py') + found = [] + for directory, builders in ((COOKBOOK, {path.stem: path for path in COOKBOOK.glob('*.py')}), + (PYTHON_PAIRS, {name: getattr(paired, name) for name in dir(paired) + if (PYTHON_PAIRS / f'{name}.wic').is_file()})): + stated = yaml.safe_load((DATA / 'pairs' / f'{directory.name}.yaml').read_text(encoding='utf-8')) + for stem, build in sorted(builders.items()): + if isinstance(build, Path): + build = import_python_file(f'{directory.name}_{stem}', build).workflow + default = stated.pop(stem, {}) + for each in (default, *default.get('under', [])): + assert set(each) <= _STATED, f'{directory.name}.yaml: {stem} states {sorted(set(each) - _STATED)}' + found.append((stem, build, directory / f'{stem}.wic', [default, *default.pop('under', [])])) + assert not stated, f'{directory.name}.yaml states pairs that are not there: {sorted(stated)}' + return found + + +@pytest.fixture(name='shipped_tools_home') +def _shipped_tools_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The cookbook scripts name their tools under `Path.home() / 'wic' / 'cwl_adapters'`, as the docs tell a reader + after `sophios --generate_config`; here that home holds this checkout's tools, so an empty home and CI pass + alike.""" + use_home(monkeypatch, home_with_shipped_tools(tmp_path / 'home', REPO_ROOT)) + + +def _compile_wic(root: Path, settings: CompilerOptions) -> CompilationResult: + """`root` compiled as the command line reads it, with the shipped tools and the `.wic` files beside it.""" return sophios.compiler.compile_source( bundle_from_disk(root, {'global': {path.stem: path for path in root.parent.glob('*.wic')}}, shipped_tools()), - settings or default_compilation_settings(), quiet=True) + settings, quiet=True) -def _through_the_file(root: Path, settings: CompilerOptions | None = None) -> tuple[Json, Json, list[str]]: - """CWL (outputs narrowed as `compile()` returns them), job and diagnostics of `root`, compiled by `_compile_wic`.""" - result = _compile_wic(root, settings) - artifact = inline_artifact_runs(result.artifact) - return (_as_compile_returns(normalize_artifact_cwl(artifact), root), - normalize_artifact_job_inputs(artifact, artifact.job_inputs), _bodies(result.diagnostics)) - +def _bodies(diagnostics: Any) -> list[str]: + """Each diagnostic as it is printed, but for the place it points at, which is the surface's own.""" + return [re.sub(r'^.+?:\d+:\d+: ', '', str(item)) for item in diagnostics] -@pytest.mark.fast -@pytest.mark.parametrize('stem', [stem for stem in PAIRS if stem != REFUSED]) -def test_both_surfaces_compile_to_the_same_cwl(stem: str) -> None: - """The `.py` and the `.wic` of a pair emit one workflow, one job and one set of notes.""" - module = import_python_file(f'cookbook_{stem}', COOKBOOK / f'{stem}.py') - python_side = module.workflow().compile() - cwl, job, notes = _through_the_file(COOKBOOK / f'{stem}.wic') - assert (cwl, job) == (python_side.cwl_workflow, python_side.cwl_job_inputs) - assert _codes(notes) == _codes(python_side.diagnostics) +def _refusal(error: SophiosError) -> list[dict[str, Any]]: + """The diagnostics of `error` as cases state them, but for the place each points at.""" + return [{key: value for key, value in diagnostic(item).items() if key not in ('file', 'line', 'column', + 'end_line', 'end_column')} + for item in error.diagnostics] -@pytest.mark.fast -@given(st.sampled_from([stem for stem in PAIRS if stem != REFUSED]), st.booleans(), - st.lists(st.integers(0, 255), max_size=3), st.none() | st.tuples(st.integers(0, 9), st.integers(0, 9))) -@example('when', True, [3], (2, 5)) -@example('greeting_if', True, [], None) -@budget(10) -def test_a_policy_writes_for_the_py_what_the_partial_failure_flags_write_for_the_wic( - stem: str, enabled: bool, codes: list[int], span: tuple[int, int] | None) -> None: - """`compile(policy=...)` on the `.py` of a pair writes the CWL the command line's partial-failure flags write for - its `.wic`: `RunPolicy(partial_failure=)` is `--partial_failure_enable`, and the codes it is given are those of - `--partial_failure_success_codes`, and of a `--partial_failure_success_codes_range`, lower bound included.""" - low, high = sorted(span) if span is not None else (0, 0) - flags = [*(['--partial_failure_enable'] if enabled else []), '--partial_failure_success_codes', *map(str, codes), - *(['--partial_failure_success_codes_range', str(low), str(high)] if span is not None else [])] - settings = cli.get_dicts_for_compilation(cli.get_args('', flags))[0] - module = import_python_file(f'cookbook_{stem}', COOKBOOK / f'{stem}.py') - python_side = module.workflow().compile(policy=RunPolicy(enabled, (*codes, *range(low, high)))) - cwl, job, notes = _through_the_file(COOKBOOK / f'{stem}.wic', settings) - assert (cwl, job) == (python_side.cwl_workflow, python_side.cwl_job_inputs) - assert _codes(notes) == _codes(python_side.diagnostics) - - -@pytest.mark.fast -def test_the_inferred_graph_stops_at_the_join() -> None: - """With every edge left out, `combine` would read the counts as its text and as its counts; both surfaces - stop there with `wic055`, naming the step, the inputs and the output.""" - module = import_python_file(f'cookbook_{REFUSED}', COOKBOOK / f'{REFUSED}.py') - with pytest.raises(SophiosError) as from_python: - module.workflow().compile() - with pytest.raises(SophiosError) as from_wic: - _compile_wic(COOKBOOK / f'{REFUSED}.wic') - for caught in (from_python, from_wic): - (error,) = [d for d in caught.value.diagnostics if d.severity is Severity.ERROR] - assert error.code is SophiosErrorCode.INFERENCE_DUPLICATE - assert error.message == ('combine.text and combine.counts would both read word_count.counts; ' - 'write the edge each should read') +def _through_the_file(root: Path, settings: CompilerOptions) -> Any: + """CWL, job and notes of `root`, compiled as the command line does, the CWL's outputs narrowed to the named ones + as `compile()` returns them (docs/connecting-steps.md); or how it is refused.""" + try: + result = _compile_wic(root, settings) + except SophiosError as error: + return _refusal(error) + artifact = inline_artifact_runs(result.artifact) + cwl = normalize_artifact_cwl(artifact) + if named := read_wic(root.read_text(encoding='utf-8'), root.name).get('outputs'): + cwl['outputs'] = {name: cwl['outputs'][name] for name in named} + return cwl, normalize_artifact_job_inputs(artifact, artifact.job_inputs), _bodies(result.diagnostics) -@pytest.mark.fast -def test_the_partial_graph_is_the_explicit_graph() -> None: - """Two written edges, at the branch and at the join, leave inference the other three; the compiled - workflow has every step reading what `greeting_graph.wic` writes out.""" - def reads(stem: str) -> dict[str, dict[str, str]]: - return {step['id']: {port: source['source'] if isinstance(source, dict) else source - for port, source in step['in'].items()} - for step in _through_the_file(COOKBOOK / f'{stem}.wic')[0]['steps']} - assert reads('greeting_graph_partial') == reads('greeting_graph') +def _reads(cwl: Json) -> dict[str, dict[str, Any]]: + """What each compiled step reads, by its input.""" + return {step['id']: {port: source.get('source') if isinstance(source, dict) else source + for port, source in step['in'].items()} for step in cwl['steps']} -@pytest.mark.fast -def test_both_surfaces_print_the_inference_note_alike(capsys: pytest.CaptureFixture[str]) -> None: - """The inference entry shows a note; a pair that stopped making one would show nothing. The Python compile prints - its notes on stderr, as the command line does, and returns the same objects; nothing is a warning. The two - surfaces print the same block, each row at its own file's line.""" - module = import_python_file('cookbook_inference', COOKBOOK / 'inference.py') +def _from_python(build: Callable[[], Workflow], stated: dict[str, Any], capsys: pytest.CaptureFixture[str]) -> Any: + """CWL, job and notes of the objects `build` makes, compiled with the stated `compile()` arguments, or how they + are refused; the compile prints its notes on stderr as the command line does, and warns of nothing.""" + workflow = build() capsys.readouterr() with warnings.catch_warnings(): warnings.simplefilter('error') - compiled = module.workflow().compile() - from_python = capsys.readouterr().err.splitlines() - report(_compile_wic(COOKBOOK / 'inference.wic').diagnostics) - from_wic = capsys.readouterr().err.splitlines() - - (note,) = compiled.diagnostics - (from_the_file,) = tuple(_compile_wic(COOKBOOK / 'inference.wic').diagnostics) - assert from_python == lines(compiled.diagnostics) and from_wic == lines([from_the_file]) - assert from_python[0] == from_wic[0] == ('note [wic043] 1 edge was guessed; draw the workflow to check it ' - '(--graphviz, or Workflow.draw() in Python)') - assert note.message == from_the_file.message == 'cat.file <- echo.stdout (1 other fits)' + try: + compiled = workflow.compile(inference=Inference(**stated.get('inference', {})), + policy=RunPolicy(**stated.get('policy', {}))) + except SophiosError as error: + return _refusal(error) + assert capsys.readouterr().err.splitlines() == lines(compiled.diagnostics) + return compiled.cwl_workflow, compiled.cwl_job_inputs, _bodies(compiled.diagnostics) @pytest.mark.fast -def test_the_note_the_docs_quote_is_the_one_the_compiler_prints() -> None: - """`docs/edge-inference.md` quotes the note of the greeting with its edges left out, as Python prints it; - the quote must be the compiler's text.""" - module = import_python_file('cookbook_greeting_inferred', COOKBOOK / 'greeting_inferred.py') - diagnostics = module.workflow().compile().diagnostics - (note,) = diagnostics - assert note.span is not None - header = lines(diagnostics)[0] - row = f'greeting_inferred.py:{note.span.start_line}:{note.span.start_column} {note.message}\n' - page = (REPO_ROOT / 'docs' / 'edge-inference.md').read_text(encoding='utf-8') - assert f'{header}\n /home/you/sophios-tutorial/{row}' in page +@pytest.mark.usefixtures('shipped_tools_home') +def test_every_pair_compiles_alike_from_both_surfaces_and_as_stated( + tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Each compile of a pair gives the `.wic`, compiled with the stated `flags` and `settings`, and the `.py`, with + the stated `inference` and `policy`, one CWL, job and list of diagnostics, or one refusal. Each states what it + gives: the `notes`, every diagnostic as printed but for its place (none unless stated); as it applies, what + steps `reads`, how it is `refused`, the `compiled` document in part, or the whole `document` in a file. The + bundle the objects write compiles to what they do.""" + defaults = cli.get_dicts_for_compilation(cli.get_args(''))[0] + for stem, build, wic, compiles in _pairs(): + for stated in compiles: + from_python = _from_python(build, stated, capsys) + settings = cli.get_dicts_for_compilation(cli.get_args('', stated.get('flags', [])))[0] + assert _through_the_file(wic, settings | stated.get('settings', {})) == from_python, (stem, stated) + if isinstance(from_python, list): + assert match(stated.get('refused', []), from_python), (stem, from_python) + continue + cwl, _job, notes = from_python + assert notes == stated.get('notes', []), (stem, notes) + assert match(stated.get('reads', {}), _reads(cwl)), (stem, _reads(cwl)) + assert match(stated.get('compiled', {}), cwl), (stem, cwl) + if 'document' in stated: + assert cwl == yaml.safe_load((DATA / 'pairs' / stated['document']).read_text(encoding='utf-8')), stem + if 'refused' not in compiles[0]: + assert _through_the_file(build().write_wic(tmp_path / stem), defaults) == _from_python(build, {}, capsys) @pytest.mark.fast -def test_the_readme_shows_the_files_as_they_are() -> None: - """A README block headed `# ` is that file, byte for byte, so the README cannot drift from the pair - and the example the documentation runs.""" +@pytest.mark.usefixtures('shipped_tools_home') +def test_the_docs_show_the_files_and_the_notes_as_they_are() -> None: + """A README block headed `# ` is that file, byte for byte; and `docs/edge-inference.md` quotes the note + Python prints for the greeting with its edges left out as the compiler prints it.""" sources = {'greeting.wic': COOKBOOK / 'greeting.wic', 'greeting.py': COOKBOOK / 'greeting.py', 'count_words.py': REPO_ROOT / 'examples' / 'scripts' / 'count_words.py'} readme = (REPO_ROOT / 'README.md').read_text(encoding='utf-8') @@ -192,32 +163,10 @@ def test_the_readme_shows_the_files_as_they_are() -> None: for block in re.findall(r'```(?:yaml|python)\n(# \S+\n.*?)```', readme, re.DOTALL)} assert shown == {name: path.read_text(encoding='utf-8') for name, path in sources.items()} - -@pytest.mark.fast -@pytest.mark.parametrize(('stem', 'consumer', 'port', 'renamings'), [ - ('naming', 'report', 'input_summary', None), - ('naming_renamed', 'abstract', 'input_abstract', (('abstract', 'summary'),)), -]) -def test_naming_conventions_give_the_summary_to_the_step_that_wants_it( - stem: str, consumer: str, port: str, renamings: tuple[tuple[str, str], ...] | None) -> None: - """With the naming conventions off the consumer takes `output_details`, the first of two files; by default, with the - renaming where names differ, docs/edge-inference.md says it takes `output_summary`, from the `.wic` and `.py`.""" - module = import_python_file(f'cookbook_{stem}', COOKBOOK / f'{stem}.py') - - def source(compiled: Json) -> str: - (step,) = [step for step in compiled['steps'] if step['id'] == consumer] - binding = step['in'][port] - return str(binding['source'] if isinstance(binding, dict) else binding) - - def from_the_file(settings: CompilerOptions) -> str: - if renamings is not None: - settings['renaming_conventions'] = list(renamings) - return source(normalize_artifact_cwl(inline_artifact_runs(_compile_wic(COOKBOOK / f'{stem}.wic', - settings).artifact))) - - off = default_compilation_settings() - off['inference_use_naming_conventions'] = False - assert from_the_file(off) == source(module.workflow().compile( - inference=Inference(naming_conventions=False)).cwl_workflow) == 'summarize/output_details' - assert from_the_file(default_compilation_settings()) == source(module.workflow().compile( - inference=Inference(renamings=renamings)).cwl_workflow) == 'summarize/output_summary' + module = import_python_file('cookbook_greeting_inferred', COOKBOOK / 'greeting_inferred.py') + notes = module.workflow().compile().diagnostics + (note,) = notes + assert isinstance(note, Diagnostic) and note.span is not None + row = f'greeting_inferred.py:{note.span.start_line}:{note.span.start_column} {note.message}\n' + page = (REPO_ROOT / 'docs' / 'edge-inference.md').read_text(encoding='utf-8') + assert f'{lines(notes)[0]}\n /home/you/sophios-tutorial/{row}' in page diff --git a/tests/core/test_example_scripts.py b/tests/core/test_example_scripts.py index faf11e251..9a3192454 100644 --- a/tests/core/test_example_scripts.py +++ b/tests/core/test_example_scripts.py @@ -1,136 +1,42 @@ -"""What the shipped Python API workflows compile to, not merely that they compile: the discovery lanes assert only -that no exception escaped.""" +"""What the shipped Python scripts make, not merely that they compile: the discovery lanes assert only that no exception +escaped. tests/core/data/shipped_scripts.yaml states it.""" import json -import re import shutil from pathlib import Path from typing import Any import pytest +import yaml -from sophios.api.python.workflow import Workflow from sophios.python_cwl_adapter import import_python_file -from .helpers import REPO_ROOT, adapter_step +from .cases import DATA, match +from .helpers import REPO_ROOT from .test_setup import home_with_shipped_tools, use_home -WORKFLOWS = REPO_ROOT / 'examples' / 'workflows' - - -def _discovered(stem: str) -> Any: - """Import a shipped Python workflow as discovery does, so these claims are about the file the lanes run.""" - path = WORKFLOWS / f'{stem}.py' - assert path.is_file(), f'{path} is a discovered Python workflow and must exist' - return import_python_file(stem, path.resolve()) - - -def _steps(compiled: Any) -> dict[str, dict[str, Any]]: - """The compiled steps, keyed by the trailing name of their generated id.""" - return {step['id'].rsplit('__', 1)[-1]: step for step in compiled.cwl_workflow['steps']} - @pytest.mark.fast -def test_a_conditional_step_carries_its_when_expression() -> None: - """`Step.when` reaches the emitted CWL, on that step alone. - - `when` is a CWL v1.2 conditional and was the only surface in the Python API - no test in this repository touched — a grep for `.when` across `tests/` - found nothing. An expression dropped on the way to the CWL turns a - conditional step into an unconditional one, which is a silent change of - meaning rather than an error. - """ - steps = _steps(_discovered('when_pyapi').workflow().compile()) - - assert steps['echo'].get('when') == '$(inputs.message < "27")' - assert 'when' not in steps['toString'], 'only the step that declared it may carry when' - - -@pytest.mark.fast -def test_scattering_one_input_defaults_to_dotproduct() -> None: - """The single-input `scatter_on`, which the cross-product tests do not reach. - - Existing scatter tests pass `method=` explicitly. The default picked for one - port is part of the emitted document's meaning: `dotproduct` walks the - array, and losing the key entirely would run the step once on the whole - array instead. - """ - steps = _steps(_discovered('scatter_single_pyapi').workflow().compile()) - - assert steps['echo'].get('scatter') == ['message'] - assert steps['echo'].get('scatterMethod') == 'dotproduct' - assert 'scatter' not in steps['array_indices'], 'only the scattered step may carry scatter' - - -@pytest.mark.fast -def test_a_compiled_multistep_workflow_matches_its_checked_in_ground_truth() -> None: - """The whole compiled document, against a golden file. - - The other tests here assert one key each. This compares the entire emitted - workflow, its job inputs and its name to `ground_truth_multistep1.json`, so - a change anywhere in the compiled shape has to be acknowledged by updating - the file rather than passing unnoticed. - """ - touch = adapter_step('touch', filename='empty.txt') - append = adapter_step('append', file=touch.outputs.file, str='Hello') - cat = adapter_step('cat', file=append.outputs.file) - compiled = Workflow([touch, append, cat], 'multistep1_toJson_pyapi_py').compile() - truth = json.loads(Path(__file__).with_name('ground_truth_multistep1.json').read_text(encoding='utf-8')) - assert (compiled.name, compiled.cwl_job_inputs) == (truth.pop('name'), truth.pop('yaml_inputs')) - assert compiled.cwl_workflow == truth - - -@pytest.mark.fast -def test_two_in_memory_tools_chain_and_keep_their_output_binding() -> None: - """A built tool's string output survives composition into a workflow. - - Existing tests cover the `Step(CommandLineTool)` bridge with one tool. What - this adds is the two-tool chain and the output that is a *string read from - a file* — `load_contents` with an `output_eval`, which becomes an - `outputBinding` the compiler must carry through untouched for the - downstream `outputSource` to mean anything. - - The builder is imported from the example rather than copied here: that file - has a documentation page which links it and tells a reader to run it, so - moving or duplicating it would leave the page describing something else. - - No tool is validated: `CommandLineTool.validate()` loads the CWL v1.2 schema - through cwltool, which is seconds of CI and POSIX-only, and - `test_python_api_tool_builder.py` already owns that claim. - """ - example = REPO_ROOT / 'examples' / 'scripts' / 'tool_builder_workflow.py' - assert example.is_file(), f'{example} is linked from docs/tool-builder.md' - module = import_python_file(example.stem, example.resolve()) - - compiled = module.build_workflow('hello from test').compile() - steps = _steps(compiled) - - run_outputs = {entry['id']: entry for entry in steps['read_text']['run']['outputs']} - binding = run_outputs['result'] - assert binding['type'] == 'string' - assert binding['outputBinding'] == { - 'glob': 'stdout.txt', 'loadContents': True, 'outputEval': '$(self[0].contents)', - } - - emitted = compiled.cwl_workflow['outputs']['result'] - assert emitted['type'] == 'string' - assert emitted['outputSource'] == f"{steps['read_text']['id']}/result" - - -_INPUTS = {'input_dir': '/data/in', 'output_dir': '/data/out', 'model_dir': '/data/models'} - - -@pytest.mark.fast -def test_the_compact_ichnaea_script_names_its_outputs_folder_relative_to_basepath( - capsys: pytest.CaptureFixture[str]) -> None: - """With basepath, the compute service requires the outputs folder, relative to it, so the canonical example names - one; its output folder is just a name, which lands in that folder.""" - example = REPO_ROOT / 'examples' / 'scripts' / 'ichnaea_compact.py' - module = import_python_file(example.stem, example.resolve()) - assert module.main() == 0 - printed = capsys.readouterr().out # the compiler's progress, then the request - request, _ = json.JSONDecoder().raw_decode(printed, printed.index('{')) - assert (request['basepath'], request['workflowOutDir']) == (module.BASEPATH, 'results_compact') - assert request['inputs']['autoseg~output'] == {'class': 'Directory', 'location': 'segmentation_compact'} +def test_each_shipped_script_makes_what_it_states(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, + capsys: pytest.CaptureFixture[str]) -> None: + """Each script's `compiled` workflow, `printed` request and built `tools`, as data/shipped_scripts.yaml states + them. A script names the shipped tools under `Path.home() / 'wic' / 'cwl_adapters'`, as the docs run it.""" + use_home(monkeypatch, home_with_shipped_tools(tmp_path, REPO_ROOT)) + for script, stated in yaml.safe_load((DATA / 'shipped_scripts.yaml').read_text(encoding='utf-8')).items(): + path = REPO_ROOT / script + module = import_python_file(path.stem, path.resolve()) + capsys.readouterr() + made: Any = getattr(module, stated['call'])(*stated.get('args', [])) if 'call' in stated else None + if 'compiled' in stated: + compiled = made.compile().cwl_workflow + assert match(stated['compiled'], compiled), (script, compiled) + if 'printed' in stated: + printed = capsys.readouterr().out # the compiler's progress, then the request + request, _ = json.JSONDecoder().raw_decode(printed, printed.index('{')) + assert match(stated['printed'], request), (script, request) + for build, tool in stated.get('tools', {}).items(): + document = getattr(module, build)().to_cwl_document() + document.pop('doc') + assert match(tool, document), (script, build, document) @pytest.mark.fast @@ -142,50 +48,7 @@ def test_the_integrated_ichnaea_script_compiles_its_hinted_tool(tmp_path: Path) source = tmp_path / 'ichnaea_integrated.py' shutil.copyfile(REPO_ROOT / 'examples' / 'scripts' / source.name, source) module = import_python_file(source.stem, source) - compiled = module.workflow(dict(_INPUTS), 'autoseg_workflow').compile() - run = compiled.cwl_workflow['steps'][0]['run'] + inputs = {'input_dir': '/data/in', 'output_dir': '/data/out', 'model_dir': '/data/models'} + run = module.workflow(inputs, 'autoseg_workflow').compile().cwl_workflow['steps'][0]['run'] assert any(entry.get('class') == 'DockerRequirement' for entry in run['requirements']) assert any(entry.get('class') == 'cwltool:CUDARequirement' for entry in run['hints']) - - -@pytest.mark.fast -def test_the_ichnaea_scripts_build_one_tool_with_no_base_command() -> None: - """The three scripts build the same tool, but for its doc. The image's ENTRYPOINT is its command, which the - runner puts in front of the tool's command line, so a base command would reach it as arguments.""" - tools = [] - for script, build in (('ichnaea_compact', 'build_autoseg_CLT'), ('ichnaea_integrated', 'build_autoseg_CLT'), - ('ichnaea_tool_builder', 'build_tool')): - example = REPO_ROOT / 'examples' / 'scripts' / f'{script}.py' - document = getattr(import_python_file(script, example.resolve()), build)().to_cwl_document() - document.pop('doc') - tools.append(document) - assert 'baseCommand' not in tools[0] - assert tools[1:] == [tools[0], tools[0]] - - -@pytest.mark.fast -def test_the_word_count_example_runs_wc_on_the_greeting(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """`examples/scripts/count_words.py` is the tool-builder example the README, the landing page and - docs/tool-builder.md show: its third step runs `wc -w` and keeps what it prints as `counts.txt`.""" - # It names the shipped tools under `Path.home() / 'wic' / 'cwl_adapters'`, as the docs run it. - use_home(monkeypatch, home_with_shipped_tools(tmp_path, REPO_ROOT)) - example = REPO_ROOT / 'examples' / 'scripts' / 'count_words.py' - module = import_python_file(example.stem, example) - count = module.workflow().compile().cwl_workflow['steps'][2] - assert count['run']['baseCommand'] == ['wc', '-w'] - assert count['run']['stdout'] == 'counts.txt' - assert count['in']['text'] == {'source': count['in']['text']['source']} - assert count['in']['text']['source'] == 'append/file' - - -@pytest.mark.fast -def test_the_landing_page_shows_the_whole_word_count_tool() -> None: - """docs/index.md includes the `word_count` expression of count_words.py by line numbers; they must still - frame exactly that expression.""" - index = (REPO_ROOT / 'docs' / 'index.md').read_text(encoding='utf-8') - included = re.search(r'count_words\.py\n:language: python\n:lines: (\d+)-(\d+)', index) - assert included is not None, 'docs/index.md no longer includes count_words.py by line numbers' - first, last = map(int, included.groups()) - lines = (REPO_ROOT / 'examples' / 'scripts' / 'count_words.py').read_text(encoding='utf-8').splitlines() - shown = lines[first - 1:last] - assert (shown[0], shown[-1]) == ('word_count = (', ')') diff --git a/tests/core/test_examples.py b/tests/core/test_examples.py index 52a4d6a76..b6a9e0314 100644 --- a/tests/core/test_examples.py +++ b/tests/core/test_examples.py @@ -1,7 +1,10 @@ +"""The corpus: every workflow `search_paths_wic` reaches. Each compiles clean in every form the inline flags give, +cwltool reads every form as it is written, and the run lanes run each by the name of the test that runs it. The corpus +checks run over the workflows small enough for the graph isomorphism check on a pull request, and over the large +intensive ones weekly, as the items named `weekly_corpus-`.""" import json from collections import Counter # pylint: disable=redefined-outer-name -import subprocess as sub from dataclasses import replace from pathlib import Path import signal @@ -11,7 +14,6 @@ import pytest import networkx as nx -import yaml from networkx.algorithms import isomorphism from mergedeep import merge, Strategy @@ -21,7 +23,6 @@ import sophios.utils from sophios.ir import frontdoor from sophios import backends, post_compile, preflight, realtime, run_setup, targets -from sophios import auto_gen_header from sophios.cli import get_args from sophios.utils_yaml import Key from sophios.post_compile import apply_inline_options, inline_artifact_runs @@ -30,7 +31,7 @@ from sophios.lang.error_codes import SophiosErrorCode from sophios.ir.artifacts import CompilationArtifact, CompilationResult from sophios.ir.types import WorkflowGraph -from sophios.wic_types import Json +from sophios.wic_types import CompilerOptions, Json # pylint: disable-next=unused-import # `corpus_registry` is a pytest fixture from .test_setup import CorpusRegistry, corpus_registry, workflow_paths @@ -88,28 +89,18 @@ def _is_workflow_document(yml_path: Path) -> bool: yml_paths_partial_failure = [(s, p) for (s, p) in yml_paths_tuples if s in run_partial_failures] -def is_isomorphic_with_timeout(g_m: isomorphism.GraphMatcher, yml_path_str: str) -> None: - """`g_m.is_isomorphic()` under a 10 s alarm, naming the workflow to add to large_workflows when it times out.""" - def handler(_signum, _frame): # type: ignore - line1 = 'Graph isomorphism check timed out after 10 seconds.' - line2 = f'Consider adding {yml_path_str} to the large_workflows list.' - raise Exception(f'{line1}\n{line2}') - - if sys.platform == 'win32': # No SIGALRM on Windows: a plain call; the CI job has its own timeout. - assert g_m.is_isomorphic() - else: - # SIGALRM works only in the main thread, so not under --workers. - signal.signal(signal.SIGALRM, handler) - signal.alarm(10) - assert g_m.is_isomorphic() - signal.alarm(0) - - def _artifacts(root: CompilationArtifact) -> list[CompilationArtifact]: """Return a stable depth-first view of an emitted artifact tree.""" return [root, *(item for child in root.children for item in _artifacts(child))] +#: What the corpus checks run over: on a pull request every workflow small enough for the graph isomorphism check; +#: weekly (`-k weekly_corpus`) the large intensive ones, which only full-scale runs check otherwise. +CHECKED: Final = [*(pytest.param(s, p, id=s) for s, p in yml_paths_tuples_not_large), + *(pytest.param(s, p, id=f'weekly_corpus-{s}') for s, p in yml_paths_tuples_weekly + if s in large_workflows)] + + @pytest.mark.cwl_corpus @pytest.mark.skip_pypi_ci @pytest.mark.slow @@ -158,39 +149,6 @@ def test_run_inlined_workflows_on_push(yml_path_str: str, yml_path: Path, form: basepath=f'autogenerated/inline_{form}') -@pytest.mark.cwl_corpus -@pytest.mark.serial -@pytest.mark.parametrize( - "yml_path_str, yml_path", - [(name, path) for name, path in yml_paths_tuples_on_push if not _calls_a_workflow(path)]) -@pytest.mark.package -def test_inline_flags_change_nothing_for_a_workflow_that_calls_none( - yml_path_str: str, yml_path: Path, corpus_registry: CorpusRegistry) -> None: - """`--cwl_inline_subworkflows` changes no document of a workflow that calls none, - which is why `INLINE_CASES` runs no `flat` form of it.""" - def compiled(flags: list[str]) -> list[tuple[Any, ...]]: - """Everything in the tree but the drawings, which are new objects each compile.""" - args = get_args(str(yml_path), flags) - tree = _inlined(_compiled(yml_path, args, corpus_registry).artifact, args) - return [(item.namespace, item.name, item.run_path, item.cwl, item.job_inputs, item.graph) - for item in _artifacts(tree)] - - assert compiled(['--cwl_inline_subworkflows']) == compiled([]), yml_path_str - both, tagged = ['--cwl_inline_subworkflows', '--cwl_inline_runtag'], ['--cwl_inline_runtag'] - assert compiled(both) == compiled(tagged), yml_path_str - - -# partial failure tests -@pytest.mark.package -@pytest.mark.parametrize("yml_path_str, yml_path", yml_paths_partial_failure) -def test_run_partial_failures_fail_without_flag(yml_path_str: str, yml_path: Path, cwl_runner: str, - corpus_registry: CorpusRegistry) -> None: - """Run workflows with known failures but without partial failure cli flag. It is expected to fail""" - args = get_args(str(yml_path), []) - run_workflows(yml_path_str, yml_path, cwl_runner, args, corpus_registry, - expect_success=False) - - @pytest.mark.cwl_corpus @pytest.mark.slow @pytest.mark.parametrize("yml_path_str, yml_path", yml_paths_tuples_weekly) @@ -203,8 +161,8 @@ def test_run_workflows_weekly(yml_path_str: str, yml_path: Path, cwl_runner: str #: The one inline form the weekly workflows run in. A weekly run is a full-scale #: stress run, and the flat and embedded forms are each checked at compile time -#: by `test_weekly_corpus_*` below; `flat_embedded` stacks both transforms, so -#: it is the form a run adds the most to. +#: by the corpus checks below; `flat_embedded` stacks both transforms, so it is +#: the form a run adds the most to. WEEKLY_INLINE_FORMS: Final = [form for form in INLINE_FORMS if form.id == 'flat_embedded'] @@ -253,7 +211,6 @@ def run_workflows( *, basepath: str = 'autogenerated', docker_pull_only: bool = False, - expect_success: bool = True, ) -> None: """Compile, prepare and run one corpus workflow; `basepath` keeps each lane's and inline form's artifacts apart, since an artifact is named for its workflow and the weekly job runs several steps in one directory.""" @@ -275,7 +232,7 @@ def run_workflows( # NOTE: Do not use --cachedir; we want to actually test everything. retval = sophios.run_local.run(backends.RunRequest(prepared.name, Path(basepath), runner=cwl_runner, container_engine=args.container_engine)) - assert (retval == 0) is expect_success, retval + assert retval == 0, retval def _discover(yml_paths: dict[str, dict[str, Path]], stem: str) -> Path | None: @@ -290,88 +247,53 @@ def _is_includer_fragment(error: SophiosError) -> bool: item.code is SophiosErrorCode.UNDEFINED_EDGE for item in error.diagnostics) -#: Fields a CWL `CommandLineTool` input may declare and a workflow input may -#: not. `declarations.boundary_declaration` is the one place that reduces a -#: promoted port, and this is what says so about the output rather than about -#: the call. `secondaryFiles`, `streamable`, `loadContents` and `loadListing` -#: are not here: the CWL v1.2 schema allows each on a workflow input. -_TOOL_ONLY_BOUNDARY_FIELDS: Final = ('inputBinding',) - -#: Fields belonging to a CWL document rather than to a process, which an -#: embedded process therefore may not keep. The same set `post_compile` lifts -#: or drops when inlining, written again here on purpose: a test that reads the -#: constant it is checking can only ever agree with it. -_EMBEDDED_FORBIDDEN_FIELDS: Final = ('$namespaces', '$schemas', 'cwlVersion') - - -@pytest.mark.cwl_corpus -@pytest.mark.fast -@pytest.mark.parametrize("yml_path_str, yml_path", yml_paths_tuples_not_large) -def test_emitted_cwl_says_nothing_cwl_cannot_read(yml_path_str: str, yml_path: Path, - corpus_registry: CorpusRegistry) -> None: - """No Sophios word and no tool-only field survives into an emitted document. - - Two defect classes, one scan, and both reached a runner before they reached - a test: a `wic_alias` written into `in:`, and a promoted port carrying the - `inputBinding` its tool declared, whose `position` a workflow input has no - field for. cwltool catches each of them, but only in `run_workflows`, - behind a container pull. This is the same claim for the price of a compile. - - `EmittedValue` now makes the first unrepresentable in a step's `in:`, but - `OpaqueCwl` admits an `InputValue` by design, so passthrough freight can - still carry one anywhere else in the document. - """ - bundle = frontdoor.bundle_from_disk(Path(yml_path), yml_paths, corpus_registry.tools) - compiler_options, _graph_settings = sophios.cli.get_dicts_for_compilation(get_args(str(yml_path))) +def _compile_corpus_workflow(yml_path_str: str, yml_path: Path, registry: CorpusRegistry) -> CompilationResult: + """One corpus workflow compiled as the command line compiles it, skipping a fragment that has no standalone + compile.""" try: - result = sophios.compiler.compile_source(bundle, compiler_options, quiet=True) + return _compiled(yml_path, get_args(str(yml_path)), registry) except SophiosError as error: if _is_includer_fragment(error): pytest.skip(f'{yml_path_str} consumes edges from an includer') raise - def scan(artifact: CompilationArtifact) -> None: + +#: Fields a CWL `CommandLineTool` input may declare and a workflow input may not. `secondaryFiles`, `streamable`, +#: `loadContents` and `loadListing` are not here: the CWL v1.2 schema allows each on a workflow input. +_TOOL_ONLY_BOUNDARY_FIELDS: Final = ('inputBinding',) + +#: Fields belonging to a CWL document rather than to a process, which an embedded process therefore may not keep. +#: Spelled out rather than read from `post_compile.DOCUMENT_FIELDS`, which is what the production code pops: a test +#: that reads the constant it is checking would agree with whatever it says. +_EMBEDDED_FORBIDDEN_FIELDS: Final = ('$namespaces', '$schemas', 'cwlVersion') + + +def _check_residue(nested: CompilationArtifact) -> None: + """No Sophios word and no tool-only field survives into an emitted document, and no document field into an + embedded process. Both reached a runner before a test: a `wic_alias` written into `in:`, a promoted port carrying + its tool's `inputBinding`, and a tool declaring `cwlVersion: v1.0` that made every inlined workflow invalid.""" + for artifact in _artifacts(nested): text = json.dumps(artifact.cwl, default=str) for word in Key.ALL: assert f'"{word}"' not in text, f'{artifact.name} emits the Sophios key {word}' if artifact.cwl.get('class') == 'Workflow': for port, declared in (artifact.cwl.get('inputs') or {}).items(): - if isinstance(declared, dict): - for field in _TOOL_ONLY_BOUNDARY_FIELDS: - assert field not in declared, ( - f'{artifact.name}: workflow input {port} declares {field}, ' - 'which belongs to a tool input') - for child in artifact.children: - scan(child) - - scan(result.artifact) - - # The inlined form is a different document and CWL judges it separately: a - # field that belongs to a document has to leave the `run:` it was embedded - # into. A tool declaring `cwlVersion: v1.0` made every inlined corpus - # workflow invalid, and only the weekly lane ran one. - # - # Spelled out rather than read from `post_compile.DOCUMENT_FIELDS`, which - # is what the production code pops: iterating that would make the test - # agree with whatever the constant happens to say, so dropping `cwlVersion` - # from it would delete the check for `cwlVersion` and stay green. + for field in _TOOL_ONLY_BOUNDARY_FIELDS: + assert not isinstance(declared, dict) or field not in declared, ( + f'{artifact.name}: workflow input {port} declares {field}, which belongs to a tool input') + def embedded(node: Any, depth: int = 0, path: str = 'root') -> None: if not isinstance(node, dict): return if depth: for field in _EMBEDDED_FORBIDDEN_FIELDS: - assert field not in node, ( - f'{path} is embedded and declares {field}, which belongs to ' - 'the document it was embedded into') - # Nor does it include a file: a relative `$include` resolves - # against the embedding document, which is somewhere else, so a - # tool that includes one is embedded packed. - assert '"$include"' not in json.dumps(node), ( - f'{path} is embedded and still includes a file by its path') + assert field not in node, f'{path} is embedded and declares {field}, which belongs to a document' + # A relative `$include` resolves against the embedding document, so an embedded tool is packed. + assert '"$include"' not in json.dumps(node), f'{path} is embedded and still includes a file by its path' for step in node.get('steps', []) or []: embedded(step.get('run'), depth + 1, f'{path}/{step.get("id")}') - embedded(post_compile.inline_artifact_runs(result.artifact).cwl) + embedded(inline_artifact_runs(nested).cwl) def _dependencies(graph: WorkflowGraph) -> nx.DiGraph: @@ -383,157 +305,41 @@ def _dependencies(graph: WorkflowGraph) -> nx.DiGraph: return dependencies -@pytest.mark.cwl_corpus -@pytest.mark.fast -@pytest.mark.serial -@pytest.mark.parametrize("yml_path_str, yml_path", yml_paths_tuples_not_large) -def test_cwl_embedding_independence(yml_path_str: str, yml_path: Path, - corpus_registry: CorpusRegistry) -> None: - """Tests that compiling a subworkflow is independent of how it is embedded - into a parent workflow. Specifically, this compiles the root workflow and - re-compiles every subworkflow (individually) as if it were a root workflow, - then checks that the CWL for each subworkflow remains identical and checks - that the embedded subworkflow DAGs and the re-compiled DAGs are isomorphic. - """ - tools_cwl = corpus_registry.tools - args = get_args(str(yml_path)) - - # Load the high-level yaml workflow file. - Path('autogenerated/').mkdir(parents=True, exist_ok=True) - bundle = frontdoor.bundle_from_disk(Path(yml_path), yml_paths, tools_cwl) +def is_isomorphic_with_timeout(g_m: isomorphism.GraphMatcher, yml_path_str: str) -> None: + """`g_m.is_isomorphic()` under a 10 s alarm, naming the workflow to add to large_workflows when it times out.""" + def handler(_signum, _frame): # type: ignore + raise TimeoutError('Graph isomorphism check timed out after 10 seconds.\n' + f'Consider adding {yml_path_str} to the large_workflows list.') - compiler_options, _graph_settings = sophios.cli.get_dicts_for_compilation(args) + if sys.platform == 'win32': # No SIGALRM on Windows: a plain call; the CI job has its own timeout. + assert g_m.is_isomorphic() + else: + # SIGALRM works only in the main thread, so not under --workers. + signal.signal(signal.SIGALRM, handler) + signal.alarm(10) + assert g_m.is_isomorphic() + signal.alarm(0) - try: - result = sophios.compiler.compile_source(bundle, compiler_options, quiet=True) - except SophiosError as error: - if _is_includer_fragment(error): - pytest.skip(f'{yml_path_str} consumes edges from an includer') - raise - workflow_artifacts = [artifact for artifact in _artifacts(result.artifact) - if artifact.graph is not None] - - # This test doesn't necessarily need to write to disk, but useful for debugging. - sophios.input_output.write_artifacts_to_disk( - result.artifact, Path('autogenerated/'), args.inputs_file) - - # Now, for each subworkflow of the given root workflow, compile the - # subworkflow again from scratch, as if it were the root workflow, - # and check that the generated CWL is identical. In other words, - # check that the generated CWL of a subworkflow is independent of its - # embedding into a parent workflow. - compared = 0 - for embedded_artifact in workflow_artifacts[1:]: - assert embedded_artifact.graph is not None - sub_name = embedded_artifact.graph.name - # Its own file, compiled as a root: the subworkflow embedded above came - # from this same text, so this is the comparison the test names. The - # forest that used to supply the subtrees was an artifact of splicing - # every document into one tree, which no longer happens. - sub_path = _discover(yml_paths, sub_name) - assert sub_path is not None, f'{sub_name} is embedded but has no file of its own' - - # NOTE: Do we want to also test embedding independence with args.graph_inline_depth? - # If so, we will need to patch testargs depending on len(sub_node_data.namespaces) - # (due to the various instances of `if len(namespaces) < args.graph_inline_depth`) +def _check_embedding_independence(yml_path_str: str, nested: CompilationArtifact, registry: CorpusRegistry, + options: CompilerOptions) -> None: + """Each subworkflow compiled alone, from its own file, as a root is the CWL it is embedded as (but for `run:` + paths, whose namespaces differ in length) and an isomorphic graph.""" + for embedded in [artifact for artifact in _artifacts(nested) if artifact.graph is not None][1:]: + assert embedded.graph is not None + sub_path = _discover(yml_paths, embedded.graph.name) + assert sub_path is not None, f'{embedded.graph.name} is embedded but has no file of its own' try: - fake_result = sophios.compiler.compile_source( - frontdoor.bundle_from_disk(sub_path, yml_paths, tools_cwl), compiler_options, - quiet=True) + alone = sophios.compiler.compile_source(frontdoor.bundle_from_disk(sub_path, yml_paths, registry.tools), + options, quiet=True) except SophiosError as error: - if _is_includer_fragment(error): + if _is_includer_fragment(error): # `test_rand_fail`'s only child, `fail.wic`, is not standalone continue raise - sub_cwl_fakeroot = fake_result.artifact.cwl - - # NOTE: Relative run: paths cause this test to fail, so remove them. - # Using namespaced filenames in a single flat directory also - # doesn't work because the namespaces will be of different lengths. - sub_cwl_embedded = sophios.utils.recursively_delete_dict_key( - 'run', embedded_artifact.cwl) - sub_cwl_fakeroot = sophios.utils.recursively_delete_dict_key('run', sub_cwl_fakeroot) - - if sub_cwl_embedded != sub_cwl_fakeroot: - # Before we crash and burn, write out files for debugging. The - # source itself, not a spliced forest: it is what both sides were - # compiled from, and it is the file a reader would open. - with open(f'{sub_name}_source.wic', mode='w', encoding='utf-8') as w: - w.write(sub_path.read_text(encoding='utf-8')) - # NOTE: Use _dot_cwl so we don't glob these files in get_tools_cwl() - yaml_content = yaml.dump(sub_cwl_embedded, sort_keys=False, line_break='\n', indent=2) - filename_emb = f'{sub_name}_embedded_dot_cwl' - with open(filename_emb, mode='w', encoding='utf-8') as w: - w.write('#!/usr/bin/env cwl-runner\n') - w.write(auto_gen_header) - w.write(''.join(yaml_content)) - yaml_content = yaml.dump(sub_cwl_fakeroot, sort_keys=False, line_break='\n', indent=2) - filename_fake = f'{sub_name}_fakeroot_dot_cwl' - with open(filename_fake, mode='w', encoding='utf-8') as w: - w.write('#!/usr/bin/env cwl-runner\n') - w.write(auto_gen_header) - w.write(''.join(yaml_content)) - cmd = f'diff {filename_emb} {filename_fake} > {sub_name}.diff' - sub.run(cmd, shell=True, check=False) - print(f'Error! Check {filename_emb} and {filename_fake} and {sub_name}.diff') - assert sub_cwl_embedded == sub_cwl_fakeroot - - # Check that the subgraphs are isomorphic. - assert embedded_artifact.graph is not None - g_m = isomorphism.DiGraphMatcher(_dependencies(embedded_artifact.graph), _dependencies(fake_result.graph)) - is_isomorphic_with_timeout(g_m, yml_path_str) - compared += 1 - - # A root every one of whose subworkflows classifies as a fragment reaches - # here having compared nothing, and used to be green for it. The `continue` - # above is per subworkflow; this reports the case where it fired for all of - # them, so the parametrization says what it did rather than passing - # silently. `test_rand_fail` is one: its only child is `fail.wic`, whose - # own first line says it is not a standalone workflow. - if workflow_artifacts[1:] and not compared: - pytest.skip(f'{yml_path_str}: every subworkflow is a fragment, none compiles alone') - - -def _compile_corpus_workflow(yml_path_str: str, yml_path: Path, registry: CorpusRegistry) -> CompilationArtifact: - """The artifact tree of one corpus workflow, skipping a fragment that has no standalone compile.""" - args = get_args(str(yml_path)) - bundle = frontdoor.bundle_from_disk(Path(yml_path), yml_paths, registry.tools) - compiler_options, _graph_settings = sophios.cli.get_dicts_for_compilation(args) - try: - return sophios.compiler.compile_source(bundle, compiler_options, quiet=True).artifact - except SophiosError as error: - if _is_includer_fragment(error): - pytest.skip(f'{yml_path_str} consumes edges from an includer') - raise - - -#: The corpus documents that declare a real-time analysis, and the analysis each declares. -_REALTIME_DECLARATIONS: Final = ( - ('cwl_subinterpreter_protein', 'analysis_realtime_protein.wic'), - ('cwl_subinterpreter_complex', 'analysis_realtime_complex.wic'), - ('cwl_subinterpreter_ligand', 'analysis_realtime_ligand.wic'), - ('npt_amber', 'process_mdout'), -) - - -@pytest.mark.cwl_corpus -@pytest.mark.package -@pytest.mark.fast -@pytest.mark.parametrize("stem, analysis", _REALTIME_DECLARATIONS) -def test_a_corpus_declaration_compiles_its_analysis(stem: str, analysis: str, - corpus_registry: CorpusRegistry) -> None: - """Each analysis the corpus declares compiles, the file names in its `config: in:` read as literals.""" - yml_path = _discover(corpus_registry.workflows, stem) - if yml_path is None: - pytest.skip(f'{stem}.wic is not reachable from search_paths_wic') - bundle = frontdoor.bundle_from_disk(yml_path, corpus_registry.workflows, corpus_registry.tools) - compiler_options, _graph_settings = sophios.cli.get_dicts_for_compilation(get_args(str(yml_path))) - result = sophios.compiler.compile_source(bundle, compiler_options, quiet=True) - - analyses = realtime.compile_analyses(result.realtime, corpus_registry.workflows, corpus_registry.tools, - compiler_options) - assert [compiled.declaration.analysis for compiled in analyses] == [analysis] - assert analyses[0].artifact.cwl['steps'] + assert (sophios.utils.recursively_delete_dict_key('run', embedded.cwl) + == sophios.utils.recursively_delete_dict_key('run', alone.artifact.cwl)), embedded.graph.name + is_isomorphic_with_timeout(isomorphism.DiGraphMatcher(_dependencies(embedded.graph), + _dependencies(alone.graph)), yml_path_str) #: The fields a CWL document declares its prefixes and ontologies in. @@ -552,24 +358,15 @@ def declared_beneath(artifact: CompilationArtifact) -> dict[str, Any]: return {field: value for field, value in zip(DECLARATIONS, (namespaces, schemas)) if value} -def _check_embedding_keeps_meaning(yml_path_str: str, yml_path: Path, corpus_registry: CorpusRegistry) -> None: - nested = _compile_corpus_workflow(yml_path_str, yml_path, corpus_registry) +def _check_embedding_keeps_meaning(nested: CompilationArtifact) -> None: + """Embedding linked child graphs changes placement, not workflow meaning; what UP_TO_EMBEDDING forgives in + `$namespaces` and `$schemas` is the move up.""" embedded = inline_artifact_runs(nested) divergence = equivalent(nested.cwl, embedded.cwl, Strength.UP_TO_EMBEDDING) assert divergence is None, divergence - # What UP_TO_EMBEDDING forgives in `$namespaces` and `$schemas` is the move up. assert {field: embedded.cwl[field] for field in DECLARATIONS if field in embedded.cwl} == declared_beneath(nested) -@pytest.mark.cwl_corpus -@pytest.mark.serial -@pytest.mark.parametrize("yml_path_str, yml_path", yml_paths_tuples_not_large) -def test_embedding_keeps_meaning(yml_path_str: str, yml_path: Path, - corpus_registry: CorpusRegistry) -> None: - """Embedding linked child graphs changes placement, not workflow meaning.""" - _check_embedding_keeps_meaning(yml_path_str, yml_path, corpus_registry) - - def _kept_calls(artifact: CompilationArtifact) -> list[str]: """The ids of the steps anywhere in the tree that run a workflow and carry more than `in` and `out`, or say `wic: inlineable: false`: the calls `--cwl_inline_subworkflows` should leave nested, decided from the document and @@ -580,9 +377,12 @@ def _kept_calls(artifact: CompilationArtifact) -> list[str]: and (set(step) - {'id', 'in', 'run', 'out'} or (child.graph is not None and not child.graph.inlineable))] -def _check_flatten_keeps_meaning(yml_path_str: str, yml_path: Path, corpus_registry: CorpusRegistry, +def _check_flatten_keeps_meaning(yml_path_str: str, nested: CompilationArtifact, capsys: pytest.CaptureFixture[str]) -> None: - nested = _compile_corpus_workflow(yml_path_str, yml_path, corpus_registry) + """Flattening dissolves each call it can and nothing else: the root is a model written separately + (`flatten_model`) up to renaming, its inputs, outputs and job inputs untouched, and each call left nested is one + `_kept_calls` expects, named on stderr.""" + capsys.readouterr() flat = post_compile.flatten_subworkflows(nested) remaining = [step['id'] for document in _artifacts(flat) for step, child in zip(document.cwl.get('steps', []), document.children) @@ -598,75 +398,42 @@ def _check_flatten_keeps_meaning(yml_path_str: str, yml_path: Path, corpus_regis assert flat.job_inputs == nested.job_inputs -@pytest.mark.cwl_corpus -@pytest.mark.serial -@pytest.mark.parametrize("yml_path_str, yml_path", yml_paths_tuples_not_large) -def test_flatten_keeps_meaning(yml_path_str: str, yml_path: Path, corpus_registry: CorpusRegistry, - capsys: pytest.CaptureFixture[str]) -> None: - """Flattening dissolves each subworkflow call it can and nothing else. - - The root is compared with a model written separately (`flatten_model`) up to - renaming, and its inputs, outputs and job inputs are untouched. The calls left - nested are the ones `_kept_calls` expects, and each is named on stderr. - """ - _check_flatten_keeps_meaning(yml_path_str, yml_path, corpus_registry, capsys) - - -def _check_flatten_validates_as_cwl(yml_path_str: str, yml_path: Path, tmp_path: Path, - corpus_registry: CorpusRegistry) -> None: - nested = _compile_corpus_workflow(yml_path_str, yml_path, corpus_registry) - flat = post_compile.flatten_subworkflows(nested) - for form, artifact in (('flat', flat), ('flat_embedded', inline_artifact_runs(flat))): - sophios.input_output.write_artifacts_to_disk(artifact, tmp_path / form) - assert validate_cwl(str(tmp_path / form / f'{nested.name}.cwl')) == 0 - - -@pytest.mark.cwl_corpus -@pytest.mark.needs_cwltool -@pytest.mark.serial -@pytest.mark.parametrize("yml_path_str, yml_path", yml_paths_tuples_not_large) -def test_flatten_validates_as_cwl(yml_path_str: str, yml_path: Path, tmp_path: Path, - corpus_registry: CorpusRegistry) -> None: - """The flat form, and the flat form embedded, are documents cwltool accepts.""" - _check_flatten_validates_as_cwl(yml_path_str, yml_path, tmp_path, corpus_registry) - - -# The checks above skip `large_workflows`, so the inline forms of the large intensive -# workflows were checked only by full-scale runs. The three checks take a minute over -# them: the weekly lane runs these (`-k test_weekly_corpus`) and keeps one run form -# (`WEEKLY_INLINE_FORMS`). Named so the pull-request lanes' `-k` skips them. -WEEKLY_LARGE: Final = [(s, p) for (s, p) in yml_paths_tuples_weekly if s in large_workflows] - +def _check_inline_flags_change_nothing(yml_path: Path, registry: CorpusRegistry) -> None: + """`--cwl_inline_subworkflows` changes no document of a workflow that calls none, which is why `INLINE_CASES` + runs no `flat` form of it.""" + def compiled(flags: list[str]) -> list[tuple[Any, ...]]: + """Everything in the tree but the drawings, which are new objects each compile.""" + args = get_args(str(yml_path), flags) + tree = _inlined(_compiled(yml_path, args, registry).artifact, args) + return [(item.namespace, item.name, item.run_path, item.cwl, item.job_inputs, item.graph) + for item in _artifacts(tree)] -@pytest.mark.cwl_corpus -@pytest.mark.slow -@pytest.mark.serial -@pytest.mark.parametrize("yml_path_str, yml_path", WEEKLY_LARGE) -def test_weekly_corpus_embedding_keeps_meaning(yml_path_str: str, yml_path: Path, - corpus_registry: CorpusRegistry) -> None: - """`test_embedding_keeps_meaning`, over the large intensive workflows.""" - _check_embedding_keeps_meaning(yml_path_str, yml_path, corpus_registry) + assert compiled(['--cwl_inline_subworkflows']) == compiled([]) + assert compiled(['--cwl_inline_subworkflows', '--cwl_inline_runtag']) == compiled(['--cwl_inline_runtag']) @pytest.mark.cwl_corpus -@pytest.mark.slow @pytest.mark.serial -@pytest.mark.parametrize("yml_path_str, yml_path", WEEKLY_LARGE) -def test_weekly_corpus_flatten_keeps_meaning(yml_path_str: str, yml_path: Path, corpus_registry: CorpusRegistry, +@pytest.mark.parametrize('yml_path_str, yml_path', CHECKED) +def test_corpus_compiles_clean_in_every_form(yml_path_str: str, yml_path: Path, corpus_registry: CorpusRegistry, capsys: pytest.CaptureFixture[str]) -> None: - """`test_flatten_keeps_meaning`, over the large intensive workflows.""" - _check_flatten_keeps_meaning(yml_path_str, yml_path, corpus_registry, capsys) - - -@pytest.mark.cwl_corpus -@pytest.mark.slow -@pytest.mark.needs_cwltool -@pytest.mark.serial -@pytest.mark.parametrize("yml_path_str, yml_path", WEEKLY_LARGE) -def test_weekly_corpus_flatten_validates_as_cwl(yml_path_str: str, yml_path: Path, tmp_path: Path, - corpus_registry: CorpusRegistry) -> None: - """`test_flatten_validates_as_cwl`, over the large intensive workflows.""" - _check_flatten_validates_as_cwl(yml_path_str, yml_path, tmp_path, corpus_registry) + """Each corpus workflow compiles to documents CWL can read, its subworkflows as they compile alone, and each form + the inline flags give means what the nested form means; each real-time analysis it declares compiles. cwltool + finds each defect these find, but only in a run, behind a container pull: here each costs a compile. + + Serial: the isomorphism check's alarm works only in the main thread, so not under --workers.""" + result = _compile_corpus_workflow(yml_path_str, yml_path, corpus_registry) + options = sophios.cli.get_dicts_for_compilation(get_args(str(yml_path)))[0] + _check_residue(result.artifact) + if yml_path_str not in large_workflows: + _check_embedding_independence(yml_path_str, result.artifact, corpus_registry, options) + _check_embedding_keeps_meaning(result.artifact) + _check_flatten_keeps_meaning(yml_path_str, result.artifact, capsys) + if not _calls_a_workflow(yml_path): + _check_inline_flags_change_nothing(yml_path, corpus_registry) + for analysis in realtime.compile_analyses(result.realtime, corpus_registry.workflows, corpus_registry.tools, + options): + assert analysis.artifact.cwl['steps'], analysis.declaration.analysis def _tool_defaults(path: Path) -> Counter[tuple[str, str, Any, Any]]: @@ -694,17 +461,20 @@ def walk(process: Any) -> None: @pytest.mark.cwl_corpus @pytest.mark.needs_cwltool @pytest.mark.serial -@pytest.mark.parametrize("yml_path_str, yml_path", yml_paths_tuples_not_large) -def test_embedding_keeps_runtime_defaults(yml_path_str: str, yml_path: Path, tmp_path: Path, - corpus_registry: CorpusRegistry) -> None: - """A tool cwltool reads from its own file and the same tool embedded get the same defaults. - - A tool written for CWL v1.0 is run with network access and a deep directory - listing; embedded in a v1.2 document with no `cwlVersion` of its own it - was run without either, and every download in the weekly lane failed. - """ - nested = _compile_corpus_workflow(yml_path_str, yml_path, corpus_registry) - sophios.input_output.write_artifacts_to_disk(nested, tmp_path / 'nested') - sophios.input_output.write_artifacts_to_disk(inline_artifact_runs(nested), tmp_path / 'embedded') - root = f'{nested.name}.cwl' - assert _tool_defaults(tmp_path / 'embedded' / root) == _tool_defaults(tmp_path / 'nested' / root) +@pytest.mark.parametrize('yml_path_str, yml_path', CHECKED) +def test_corpus_validates_in_cwltool_in_every_form(yml_path_str: str, yml_path: Path, tmp_path: Path, + corpus_registry: CorpusRegistry) -> None: + """cwltool accepts the flat form and the flat form embedded, and gives a tool embedded the network and + directory-listing defaults it gives the same tool read from its own file: a tool written for CWL v1.0, embedded + in a v1.2 document with no `cwlVersion` of its own, ran without network access, and every download of the weekly + lane failed. The large workflows are only validated, as the weekly lane always did.""" + nested = _compile_corpus_workflow(yml_path_str, yml_path, corpus_registry).artifact + flat = post_compile.flatten_subworkflows(nested) + for form, artifact in (('flat', flat), ('flat_embedded', inline_artifact_runs(flat))): + sophios.input_output.write_artifacts_to_disk(artifact, tmp_path / form) + assert validate_cwl(str(tmp_path / form / f'{nested.name}.cwl')) == 0, form + if yml_path_str not in large_workflows: + sophios.input_output.write_artifacts_to_disk(nested, tmp_path / 'nested') + sophios.input_output.write_artifacts_to_disk(inline_artifact_runs(nested), tmp_path / 'embedded') + root = f'{nested.name}.cwl' + assert _tool_defaults(tmp_path / 'embedded' / root) == _tool_defaults(tmp_path / 'nested' / root) diff --git a/tests/core/test_python_api_draw.py b/tests/core/test_python_api_draw.py index 9d81d5b04..db94a62df 100644 --- a/tests/core/test_python_api_draw.py +++ b/tests/core/test_python_api_draw.py @@ -13,49 +13,36 @@ def _workflow() -> Workflow: - """`touch` feeds `append` by an edge written here, and `append` feeds `cat` by an edge inference adds.""" + """`touch` feeds `append` by an edge written here, and `append` feeds `cat` by an edge inference adds; a workflow + output named `touch` makes the compiled step `touch@1`.""" touch = adapter_step("touch", filename="empty.txt") append = adapter_step("append", str="Hello", file=touch.outputs.file) - cat = adapter_step("cat") - return Workflow([touch, append, cat], "wf") - - -def _box_labels(drawing: graphviz.Digraph) -> list[str]: - """The label of each box, in the order the drawing declares the boxes.""" - return re.findall(r'\[label="?([\w@~]+)"? ', drawing.source) - - -def _edge_colours(drawing: graphviz.Digraph) -> dict[tuple[str, str], str]: - """The colour of each edge, by the labels of the steps it joins.""" - edges = re.findall(r'^\s*"?(\w+)"? -> "?(\w+)"? \[color=(\w+)\]$', - drawing.source, re.MULTILINE) - return {(source, sink): colour for source, sink, colour in edges} + flow = Workflow([touch, append, adapter_step("cat")], "wf") + flow.outputs.touch = touch.outputs.file + return flow @pytest.mark.fast -@pytest.mark.parametrize('options, page, text, edges', [ - ({}, 'white', 'black', {('touch', 'append'): 'blue', ('append', 'cat'): 'black'}), - ({'dark': True}, '"#1e1e1e"', 'white', {('touch', 'append'): 'lightskyblue', ('append', 'cat'): 'white'}), - ({'inference': Inference(enabled=False)}, 'white', 'black', {('touch', 'append'): 'blue'}), -], ids=['default', 'dark', 'no-inference']) -def test_draw_paints_an_opaque_page_and_colours_the_edges_by_who_made_them( - options: dict[str, Any], page: str, text: str, edges: dict[tuple[str, str], str]) -> None: +@pytest.mark.parametrize('options, page, text, boxes, edges', [ + ({}, 'white', 'black', ['touch', 'append', 'cat'], + {('touch@1', 'append'): ('', 'blue'), ('append', 'cat'): ('', 'black')}), + ({'dark': True}, '"#1e1e1e"', 'white', ['touch', 'append', 'cat'], + {('touch@1', 'append'): ('', 'lightskyblue'), ('append', 'cat'): ('', 'white')}), + ({'inference': Inference(enabled=False)}, 'white', 'black', ['touch', 'append', 'cat'], + {('touch@1', 'append'): ('', 'blue')}), + ({'label_edges': True, 'label_stepname': True}, 'white', 'black', ['touch@1', 'append', 'cat'], + {('touch@1', 'append'): ('file', 'blue'), ('append', 'cat'): ('file', 'black')}), +], ids=['default', 'dark', 'no-inference', 'labelled']) +def test_draw_paints_an_opaque_page_and_draws_what_the_flags_do( + options: dict[str, Any], page: str, text: str, boxes: list[str], edges: dict[Any, tuple[str, str]]) -> None: """An opaque white page in black, or with `dark=True` a near-black one in white; a written edge blue, lighter on - the dark page, and one inference added the text's colour, none with `Inference(enabled=False)`.""" + the dark page, and one inference added the text's colour, none with `Inference(enabled=False)`. `label_edges` + names each edge's port, and `label_stepname` names each box by its name in the compiled CWL, which every edge + names it by.""" drawing = _workflow().draw(**options) assert isinstance(drawing, graphviz.Digraph) and 'transparent' not in drawing.source assert f'bgcolor={page}' in drawing.source and f'fontcolor={text}' in drawing.source - assert re.findall(r'\[label=\w+ color=(\w+) fontcolor=(\w+) shape=box', drawing.source) == [(text, text)] * 3 - assert _edge_colours(drawing) == edges - - -@pytest.mark.fast -def test_draw_labels_edges_and_boxes_as_the_flags_do() -> None: - """`label_edges` names each edge's port, and `label_stepname` names each box by its name in the - compiled CWL, which differs from the step's id when a workflow output has that id: `touch` is - compiled as `touch@1`.""" - assert 'label=file' in _workflow().draw(label_edges=True).source - flow = _workflow() - flow.outputs.touch = flow.steps[0].outputs.file - assert _box_labels(flow.draw()) == ['touch', 'append', 'cat'] - assert _box_labels(flow.draw(label_stepname=True)) == ['touch@1', 'append', 'cat'] + drawn = re.findall(r'\[label="?([\w@]+)"? color=(\w+) fontcolor=(\w+) shape=box', drawing.source) + assert drawn == [(box, text, text) for box in boxes] + assert {(source, sink): (label, colour) for source, sink, label, colour in re.findall( + r'^\s*"?([\w@]+)"? -> "?([\w@]+)"? \[(?:label=(\w+) )?color=(\w+)', drawing.source, re.MULTILINE)} == edges diff --git a/tests/core/test_python_api_from_wic.py b/tests/core/test_python_api_from_wic.py index e69f7ae78..14385e1e6 100644 --- a/tests/core/test_python_api_from_wic.py +++ b/tests/core/test_python_api_from_wic.py @@ -1,17 +1,16 @@ -"""`Workflow.from_wic`: a `.wic` file as Python objects. Examples say what a document becomes or why it is refused; -properties: a file the file door compiles is refused with `api006` alone or compiles to equal output, and `write_wic` -round-trips.""" +"""`Workflow.from_wic`: a `.wic` file as Python objects. A document of every construct Python spells, and documents of +what it cannot hold, say what each becomes (tests/core/data/from_wic); over generated documents and the corpus, a file +the file door compiles is refused with `api006` alone or compiles to equal output, and `write_wic` round-trips.""" # pylint: disable=redefined-outer-name # `corpus_registry` is a pytest fixture import shutil import tempfile from dataclasses import replace -from functools import lru_cache from pathlib import Path from typing import Any, Callable, Final, cast import pytest import yaml -from hypothesis import example, given, strategies as st +from hypothesis import given import sophios.compiler from sophios.api.python import _workflow_runtime @@ -98,9 +97,13 @@ def _objects(workflow: Workflow) -> tuple[Json, Json, list[str]]: return compiled.cwl_workflow, compiled.cwl_job_inputs, list(map(str, result.diagnostics)) -#: The synthetic tools, with `mk_file` also in a `gpu` plugin namespace, and `pair_sink`, whose `energy_x` and -#: `energy_y` read `pair_src`'s `edr_x` and `edr_y` only through the shipped renamings. +#: The real-time analysis declaration's adapter. +_WATCHER: Final = ADAPTERS / 'file_watchers' / 'cwl_subinterpreter.cwl' + +#: The synthetic tools, with `mk_file` also in a `gpu` plugin namespace; `pair_sink`, whose `energy_x` and `energy_y` +#: read `pair_src`'s `edr_x` and `edr_y` only through the shipped renamings; and the declaration's adapter. TOOLS: Final[Tools] = { + StepId(_WATCHER.stem, SYNTHETIC_NS): Tool(str(_WATCHER), yaml.safe_load(_WATCHER.read_text(encoding='utf-8'))), **SYNTHETIC_TOOLS, StepId('mk_file', 'gpu'): SYNTHETIC_TOOLS[StepId('mk_file', SYNTHETIC_NS)], StepId('pair_src', SYNTHETIC_NS): Tool('/synthetic/pair_src.cwl', clt( {'name': {'type': 'string', 'inputBinding': {'position': 1}}}, @@ -112,43 +115,10 @@ def _objects(workflow: Workflow) -> tuple[Json, Json, list[str]]: {'out': {'type': 'File', 'outputBinding': {'glob': 'out.txt'}}}, canonical=True))} -def _documents(directory: Path, **documents: str) -> WorkflowPaths: - """Write each document as `.wic` in `directory`; the paths a step may call them by.""" - for name, text in documents.items(): - (directory / f'{name}.wic').write_text(text, encoding='utf-8') - return {'global': {path.stem: path for path in directory.glob('*.wic')}} - - -def _from_wic(directory: Path, **documents: str) -> Workflow: - """`Workflow.from_wic` of `root.wic`, written with `documents` into `directory`.""" - workflow_paths = _documents(directory, **documents) - return Workflow.from_wic(directory / 'root.wic', tool_registry=TOOLS, workflow_paths=workflow_paths) - - -def _assert_compiles_alike(directory: Path, workflow: Workflow) -> None: - """Property 1 for `root.wic` in `directory` and the objects read from it.""" - cwl, job_inputs, codes = _file_door(directory / 'root.wic', _documents(directory), TOOLS) - python_cwl, python_job_inputs, python_codes = _objects(workflow) - found = equivalent(_canonical_ports(cwl), _canonical_ports(python_cwl), Strength.UP_TO_ORDER) - assert found is None, str(found) - assert (python_job_inputs, python_codes) == (job_inputs, codes) - - -CHAIN: Final = ('inputs:\n name: string\n' - 'steps:\n- id: mk_file\n in:\n name: name\n out:\n - file: !& made\n' - '- id: xform\n in:\n file: !* made\n name: !ii renamed.txt\n' - 'outputs:\n result:\n type: File\n outputSource: xform/file\n') - - -def _calling_child(name: str) -> str: - """A document that calls `child.wic` and binds its `mk_file` step's `name` to `!ii {name}`.""" - return ('wic:\n steps:\n (1, child.wic):\n wic:\n steps:\n (1, mk_file):\n' - f' in:\n name: !ii {name}\nsteps:\n- id: child.wic\n') - - def _held_today(document: Document) -> bool: """Not yet, though the file compiles: a `schemed` step, loaded as `api004`, and a scatter over an unbound port, - raised as a bare ValueError rather than `api006`; each is a strict xfail example below, so this expires.""" + raised as a bare ValueError rather than `api006`; tests/core/data/from_wic/refused/held_* state each, so this + expires.""" return not any(step.id == 'schemed' or not set(cast(list[str], dict(step.interpreted).get('scatter') or [])) <= dict(step.inputs).keys() for step in document.steps) @@ -172,47 +142,12 @@ def _outcome(compile_it: Callable[[], tuple[Json, Json, list[str]]]) -> Any: @pytest.mark.fast -@given(documents().filter(_held_today).map(_files), st.just(False)) # pylint: disable=no-member -# A bare name is the workflow input, `!*` the producing step's output object and `!ii` a literal; the workflow output -# is the step output it names. -@example((CHAIN, {}), True) -# `child.wic` becomes a nested `Workflow` named `child`, built from its own file, its input bound by the caller. -@example(('steps:\n- id: child.wic\n in:\n n: !ii made.txt\n', - {'child.wic': 'inputs:\n n: string\nsteps:\n- id: mk_file\n in:\n name: n\n'}), True) -# `count` binds nothing; the objects leave its `file` unbound and the compile infers it as the file's does, naming -# the `.wic` line the objects were read from, line 8, in its note. -@example(('steps:\n- id: mk_file\n in:\n name: !ii a\n- id: xform\n in:\n name: !ii b\n- id: count\n', {}), - True) -@example(('steps:\n- id: mk_file\n in:\n name: !ii a.txt\n- id: count\n', {}), True) -# A step named apart from its inline tool holds that tool; `scatter`, its method and `when` carry over. -@example(('steps:\n- id: shout\n run:\n class: CommandLineTool\n baseCommand: echo\n' - ' inputs:\n message:\n type: string\n inputBinding:\n position: 1\n' - ' outputs: {}\n in:\n message: !ii [a, b]\n scatter: [message]\n scatterMethod: dotproduct\n' - ' when: $(inputs.message != "c")\n', {}), True) -# A `string[]` workflow input feeds the `string` port its step scatters over, as in the file. -@example(('inputs:\n names: string[]\n' - 'steps:\n- id: mk_file\n scatter: name\n scatterMethod: dotproduct\n in:\n name: names\n', {}), True) -# The file's own compile pairs `energy_x` with `edr_x` and `energy_y` with `edr_y` through the shipped renamings; -# loading it for Python must not refuse it (`wic055`) by starting from none. -@example(('steps:\n- id: pair_src\n in:\n name: !ii a.txt\n- id: pair_sink\n', {}), True) -# `left` and `right` both call `child.wic` with the same `wic: steps:` body, so both calls build it alike. -@example(('steps:\n- id: left.wic\n- id: right.wic\n', {'left.wic': _calling_child('same.txt'), - 'right.wic': _calling_child('same.txt'), 'child.wic': 'steps:\n- id: mk_file\n'}), True) -# `!cwl {source: [...], linkMerge: ...}` is a `StepInput` over the two output objects; its `linkMerge` reaches the CWL. -@example(('steps:\n- id: mk_file\n in:\n name: !ii a\n out:\n - file: !& f\n' - '- id: xform\n in:\n file: !* f\n name: !ii b\n out:\n - file: !& g\n' - '- id: sink\n in:\n file: !* f\n n: !ii 1\n' - ' extras: !cwl {source: [!* f, !* g], linkMerge: merge_flattened}\n', {}), True) -# Held today: a scatter over an unbound port raises a bare ValueError, and a `schemed` step is refused as `api004`. -@example(('steps:\n- id: captured\n scatter: [name]\n scatterMethod: dotproduct\n', {}), False).xfail( - raises=ValueError) -@example(('steps:\n- id: schemed\n', {}), False).xfail(raises=AssertionError) +@pytest.mark.filterwarnings('ignore:.*graphviz dropped:UserWarning') # every_construct states it +@given(documents().filter(_held_today).map(_files)) # pylint: disable=no-member @budget(25) -def test_a_wic_file_and_the_objects_read_from_it_compile_alike(drawn: tuple[str, dict[str, str]], - must_build: bool) -> None: - """Property 1 over generated documents, whose reading writes nothing: `api006` alone, or the file's own refusal, - or the same CWL, job inputs and diagnostics, at the `.wic` lines the objects were read from. A pinned document - must build.""" +def test_a_wic_file_and_the_objects_read_from_it_compile_alike(drawn: tuple[str, dict[str, str]]) -> None: + """Over generated documents, whose reading writes nothing: `api006` alone, or the file's own refusal, or the same + CWL, job inputs and diagnostics, at the `.wic` lines the objects were read from.""" root, called = drawn with tempfile.TemporaryDirectory() as name, pytest.MonkeyPatch.context() as monkeypatch: directory = Path(name) @@ -224,108 +159,13 @@ def test_a_wic_file_and_the_objects_read_from_it_compile_alike(drawn: tuple[str, try: workflow = Workflow.from_wic(directory / 'root.wic', tool_registry=TOOLS, workflow_paths=workflow_paths) except SophiosError as error: - assert not must_build and (isinstance(file_door, set) or {d.code for d in error.diagnostics} == { - SophiosErrorCode.NO_PYTHON_SPELLING}), str(error) + assert isinstance(file_door, set) or {d.code for d in error.diagnostics} == { + SophiosErrorCode.NO_PYTHON_SPELLING}, str(error) return assert sorted(path.name for path in directory.iterdir()) == sorted({'root.wic', *called}) assert _outcome(lambda: _objects(workflow)) == file_door -@pytest.mark.fast -def test_an_input_declared_with_an_empty_mapping_is_left_untyped(tmp_path: Path) -> None: - """`name: {}` declares no type, as a null spec does: the call builds the workflow instead of raising.""" - root = 'inputs:\n name: {}\nsteps:\n- id: mk_file\n in:\n name: name\n' - workflow = _from_wic(tmp_path, root=root) - assert [port.name for port in workflow.inputs] == ['name'] - - -def _output_source_root(output_source: str) -> str: - return ('steps:\n- id: mk_file\n in:\n name: !ii a\n out:\n - file: !& f\n' - '- id: xform\n in:\n file: !* f\n name: !ii b\n' - f'outputs:\n o:\n type: File\n outputSource: {output_source}\n') - - -@pytest.mark.fast -def test_a_positional_output_source_becomes_an_object_reference(tmp_path: Path, - capsys: pytest.CaptureFixture[str]) -> None: - """A position is read as Lower reads it; the objects say `xform/file`, - so the written bundle names the authored step and its compile warns about no spelling.""" - workflow = _from_wic(tmp_path, root=_output_source_root('(2, xform)/file')) - written = workflow.write_wic(tmp_path / 'written') - document = read_wic(written.read_text(encoding='utf-8')) - assert document['outputs']['o']['outputSource'] == 'xform/file' - capsys.readouterr() - workflow.compile() - captured = capsys.readouterr() - assert 'Warning!' not in captured.out + captured.err - - -@pytest.mark.fast -def test_a_real_time_declaration_written_back_stays_a_declaration(tmp_path: Path) -> None: - """`write_wic` names the adapter as the registry does, so the bundle declares the same analysis - the objects do, `max_times: !ii '20'` included, and emits no step for it.""" - adapter = ADAPTERS / 'file_watchers' / 'cwl_subinterpreter.cwl' - tools = {**TOOLS, StepId(adapter.stem, SYNTHETIC_NS): Tool(str(adapter), yaml.safe_load(adapter.read_text()))} - root = ("steps:\n- id: mk_file\n in:\n name: !ii a.txt\n" - "- id: cwl_subinterpreter\n in:\n file_pattern: !ii '*.txt'\n cwl_tool: !ii count\n" - " max_times: !ii '20'\n config: !ii {in: {file: a.txt}}\n") - workflow = Workflow.from_wic(tmp_path / 'root.wic', tool_registry=tools, - workflow_paths=_documents(tmp_path, root=root)) - direct = _workflow_runtime.compile_workflow_result(workflow, tool_registry=tools) - - bundle = tmp_path / 'bundle' - written_root = workflow.write_wic(bundle) - written: WorkflowPaths = {'global': {path.stem: path for path in bundle.glob('*.wic')}} - via_file = _compile_file(written_root, written, tools) - - (declared,) = direct.realtime - assert declared.max_times == 20 - assert [replace(item, span=None) for item in via_file.realtime] == [replace(declared, span=None)] - direct_cwl = _workflow_runtime.compiled_workflow_from_result(workflow, direct).cwl_workflow - via_file_cwl = _workflow_runtime.compiled_workflow_from_result(workflow, via_file).cwl_workflow - assert [step['id'] for step in direct_cwl['steps']] == ['mk_file'] - assert equivalent(direct_cwl, via_file_cwl, Strength.IDENTICAL) is None - - -ONE_STEP: Final = 'steps:\n- id: mk_file\n in:\n name: !ii a\n' - - -@pytest.mark.fast -@pytest.mark.parametrize('case, expected', case_dirs('from_wic_refusals', 'diagnostics')) -def test_a_document_python_cannot_hold_is_refused_whole(case: Path, expected: dict[str, Any]) -> None: - """A document that compiles but holds what the Python API cannot is `api006`, once per construct, each where it - is written and saying what to write, in one raise; a document that does not compile raises its own error.""" - with pytest.raises(SophiosError) as caught: - Workflow.from_wic(case / 'root.wic', tool_registry=TOOLS, - workflow_paths={'global': {path.stem: path for path in case.glob('*.wic')}}) - assert match(expected['diagnostics'], [diagnostic(found) for found in caught.value.diagnostics]), caught.value - - -@pytest.mark.fast -def test_a_python_script_step_is_api006(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """A tool generated from a script has no `Step`: the message says to build it with `tool_builder`. - - The script's generator imports `workflow_types` relative to the working directory, so the - project, tests/core/data/frontdoor/script, holds that sibling file. - """ - shutil.copytree(DATA / 'frontdoor' / 'script', tmp_path / 'script') - work = tmp_path / 'script' / 'work' - monkeypatch.chdir(work) - with pytest.raises(SophiosError) as caught: - _from_wic(work, root=(work / 'compile.wic').read_text(encoding='utf-8')) - assert [(item.code, 'tool_builder' in item.message) for item in caught.value.diagnostics] == [ - (SophiosErrorCode.NO_PYTHON_SPELLING, True)] - - -@pytest.mark.fast -def test_graphviz_and_inlineable_are_dropped_with_a_warning(tmp_path: Path) -> None: - """Neither changes what a Python workflow compiles; the warning names the file and both keys.""" - root = 'wic:\n graphviz:\n label: drawn\n inlineable: false\n' + ONE_STEP - with pytest.warns(UserWarning, match='root.wic: wic: graphviz, inlineable dropped'): - workflow = _from_wic(tmp_path, root=root) - _assert_compiles_alike(tmp_path, workflow) - - def _loaded(path: Path, workflow_paths: WorkflowPaths, tools: Tools) -> Workflow | None: """`Workflow.from_wic(path)`, or None when every construct it refused is `api006`.""" try: @@ -336,62 +176,72 @@ def _loaded(path: Path, workflow_paths: WorkflowPaths, tools: Tools) -> Workflow return None +def _compiles_alike_and_writes_back(path: Path, workflow_paths: WorkflowPaths, tools: Tools, workflow: Workflow, + directory: Path) -> Path: + """The objects read from `path` compile as the file does, up to order and CWL's shorthand, with the same job inputs + and diagnostics; the bundle `write_wic` writes for them in `directory`, through the file door, is the objects' own + compilation, byte for byte, and so is that bundle read back. Returns the bundle's root.""" + from_file, from_objects = _file_door(path, workflow_paths, tools), _objects(workflow) + found = equivalent(_canonical_ports(from_file[0]), _canonical_ports(from_objects[0]), Strength.UP_TO_ORDER) + assert found is None, f'{path.name}: the file and its Python objects compile apart\n{found}' + assert from_objects[1:] == from_file[1:] + direct = workflow.compile() + root = workflow.write_wic(directory) + written: WorkflowPaths = {'global': {each.stem: each for each in directory.glob('*.wic')}} + via_file = _workflow_runtime.compiled_workflow_from_result(workflow, _compile_file(root, written, tools)) + reloaded = Workflow.from_wic(root, tool_registry=tools, workflow_paths=written).compile() + for other in (via_file, reloaded): + assert equivalent(direct.cwl_workflow, other.cwl_workflow, Strength.IDENTICAL) is None + assert equivalent(direct.cwl_job_inputs, other.cwl_job_inputs, Strength.IDENTICAL) is None + return root + + @pytest.mark.cwl_corpus @pytest.mark.fast @pytest.mark.parametrize('yml_path_str, yml_path', yml_paths_tuples_not_large) -def test_a_wic_file_and_its_python_objects_compile_alike(yml_path_str: str, yml_path: Path, +def test_a_wic_file_and_its_python_objects_compile_alike(yml_path_str: str, yml_path: Path, tmp_path: Path, corpus_registry: CorpusRegistry) -> None: - """Property 1: refused with `api006` alone, or the same CWL, job inputs and diagnostic codes.""" + """Over the corpus: refused with `api006` alone, or the objects compile as the file does and write a bundle that + compiles to them (`_compiles_alike_and_writes_back`).""" try: - cwl, job_inputs, codes = _file_door(Path(yml_path), corpus_registry.workflows, corpus_registry.tools) + _compile_file(Path(yml_path), corpus_registry.workflows, corpus_registry.tools) except SophiosError as error: if _is_includer_fragment(error): pytest.skip(f'{yml_path_str} consumes edges from an includer') raise workflow = _loaded(Path(yml_path), corpus_registry.workflows, corpus_registry.tools) - if workflow is None: - return - python_cwl, python_job_inputs, python_codes = _objects(workflow) - found = equivalent(_canonical_ports(cwl), _canonical_ports(python_cwl), Strength.UP_TO_ORDER) - assert found is None, f'{yml_path_str}: the file and its Python objects compile apart\n{found}' - assert python_job_inputs == job_inputs - assert python_codes == codes + if workflow is not None: + _compiles_alike_and_writes_back(Path(yml_path), corpus_registry.workflows, corpus_registry.tools, workflow, + tmp_path) -@pytest.mark.cwl_corpus @pytest.mark.fast -@pytest.mark.parametrize('yml_path_str, yml_path', yml_paths_tuples_not_large) -def test_write_wic_of_a_loaded_workflow_compiles_identically(yml_path_str: str, yml_path: Path, - corpus_registry: CorpusRegistry, - tmp_path: Path) -> None: - """Property 2: the bundle `write_wic` writes for the objects, through the file door, is the - objects' own compilation, byte for byte; and reading that bundle back compiles the same.""" - try: - _compile_file(Path(yml_path), corpus_registry.workflows, corpus_registry.tools) - except SophiosError as error: - if _is_includer_fragment(error): - pytest.skip(f'{yml_path_str} consumes edges from an includer') - raise - workflow = _loaded(Path(yml_path), corpus_registry.workflows, corpus_registry.tools) - if workflow is None: - return - direct = workflow.compile() - root = workflow.write_wic(tmp_path) - written: WorkflowPaths = {'global': {path.stem: path for path in tmp_path.glob('*.wic')}} - via_file = _workflow_runtime.compiled_workflow_from_result( - workflow, _compile_file(root, written, corpus_registry.tools)) - assert equivalent(direct.cwl_workflow, via_file.cwl_workflow, Strength.IDENTICAL) is None - assert equivalent(direct.cwl_job_inputs, via_file.cwl_job_inputs, Strength.IDENTICAL) is None - - reloaded = Workflow.from_wic(root, tool_registry=corpus_registry.tools, workflow_paths=written).compile() - assert equivalent(direct.cwl_workflow, reloaded.cwl_workflow, Strength.IDENTICAL) is None - assert equivalent(direct.cwl_job_inputs, reloaded.cwl_job_inputs, Strength.IDENTICAL) is None - - -#: The in-repo workflows the Python API cannot hold, each refused with `api006`: -#: four repeat a step id, `test_rand_fail` scatters a `.wic` call and reads an -#: edge across documents, and `secrets_echo` declares `$namespaces`, `hints` and -#: an input `default`. +def test_a_document_of_every_construct_python_spells_is_read_as_stated(monkeypatch: pytest.MonkeyPatch, + tmp_path: Path) -> None: + """tests/core/data/from_wic/built/every_construct/root.wic is read into objects, warning of what is dropped, and + they compile as the file does and write back (`_compiles_alike_and_writes_back`); expected.yaml states the + inputs, the compiled steps, the declared analysis and what the bundle writes. Nothing is written beside it.""" + case = DATA / 'from_wic' / 'built' / 'every_construct' + stated = yaml.safe_load((case / 'expected.yaml').read_text(encoding='utf-8')) + workflow_paths = {'global': {path.stem: path for path in case.glob('*.wic')}} + monkeypatch.chdir(tmp_path) + with pytest.warns(UserWarning) as warned: + workflow = Workflow.from_wic(case / 'root.wic', tool_registry=TOOLS, workflow_paths=workflow_paths) + assert [str(warning.message) for warning in warned if 'dropped' in str(warning.message)] == [ + f'{text}: the Python API has no spelling for them, and it changes no CWL a Workflow compiles or runs' + for text in stated['warns']] + assert [port.name for port in workflow.inputs] == stated['inputs'] + root = _compiles_alike_and_writes_back(case / 'root.wic', workflow_paths, TOOLS, workflow, tmp_path / 'bundle') + assert match(stated['written'], read_wic(root.read_text(encoding='utf-8'))) + result = _workflow_runtime.compile_workflow_result(workflow) + assert [step['id'] for step in result.artifact.cwl['steps']] == stated['steps'] + assert [{'analysis': item.analysis, 'max_times': item.max_times} for item in result.realtime] == stated['realtime'] + assert not list(tmp_path.glob('*.wic')) + + +#: The in-repo workflows the Python API cannot hold, each refused with `api006`: four repeat a step id, +#: `test_rand_fail` scatters a `.wic` call and reads an edge across documents, and `secrets_echo` declares +#: `$namespaces`, `hints` and an input `default`. REFUSED: Final = frozenset({'append_twice', 'multistep1', 'multistep2', 'multistep3', 'test_rand_fail', 'secrets_echo'}) @@ -399,17 +249,26 @@ def test_write_wic_of_a_loaded_workflow_compiles_identically(yml_path_str: str, IN_REPO: Final = (REPO_ROOT / 'docs' / 'tutorials', REPO_ROOT / 'examples') -@lru_cache(maxsize=1) -def _in_repo_registry() -> tuple[WorkflowPaths, Tools]: - """The `.wic` files this repository ships and the tools it ships, read from nothing else.""" - workflow_paths = {'global': {path.stem: path for directory in IN_REPO for path in directory.glob('*.wic')}} - return workflow_paths, shipped_tools() - - @pytest.mark.fast -def test_the_in_repo_workflows_that_python_cannot_hold_are_these() -> None: - """Every `.wic` this repository ships compiles; those in `REFUSED` are `api006`, every other one builds.""" - workflow_paths, tools = _in_repo_registry() - refused = {stem for stem, path in workflow_paths['global'].items() - if _loaded(path, workflow_paths, tools) is None} - assert refused == REFUSED +@pytest.mark.parametrize('case, expected', case_dirs('from_wic/refused', 'project', 'refused', 'raises')) +def test_a_document_python_cannot_hold_is_refused_whole(case: Path, expected: dict[str, Any], + monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """A document that compiles but holds what the Python API cannot is `api006`, once per construct, each saying + what to write instead, in one raise; a document that does not compile raises its own error. expected.yaml states + each diagnostic, or the exception a document held today raises. The in-repo workflows refused are `REFUSED`, and + every other one builds.""" + root = case / 'root.wic' + if 'project' in expected: # run in place, from a copy + shutil.copytree(DATA / Path(expected['project']).parts[0], tmp_path / 'project') + root = tmp_path / 'project' / Path(*Path(expected['project']).parts[1:]) + monkeypatch.chdir(root.parent) + with pytest.raises(SophiosError if 'refused' in expected else ValueError) as caught: + Workflow.from_wic(root, tool_registry=TOOLS, + workflow_paths={'global': {path.stem: path for path in root.parent.glob('*.wic')}}) + if 'refused' in expected: + refused = cast(SophiosError, caught.value) + assert match(expected['refused'], [diagnostic(found) for found in refused.diagnostics]), refused + if case.name == 'every_construct': + workflow_paths = {'global': {path.stem: path for directory in IN_REPO for path in directory.glob('*.wic')}} + assert {stem for stem, path in workflow_paths['global'].items() + if _loaded(path, workflow_paths, shipped_tools()) is None} == REFUSED diff --git a/tests/core/test_python_api_inference.py b/tests/core/test_python_api_inference.py index eca5f6ebc..fb52cad00 100644 --- a/tests/core/test_python_api_inference.py +++ b/tests/core/test_python_api_inference.py @@ -17,11 +17,10 @@ from sophios.api.python.workflow import (Inference, InvalidInferenceError, RunResult, RunState, SophiosError, SophiosErrorCode, Step, Workflow) from sophios.nf_types import NfProcessConnection -from sophios.wic_types import Json, StepId, Tool +from sophios.wic_types import Json from .budgets import budget from .helpers import search_config -from .synthetic_tools import clt pytestmark = pytest.mark.package @@ -80,22 +79,17 @@ def _cli(workflow: Workflow, directory: Path, monkeypatch: pytest.MonkeyPatch, * @pytest.mark.fast -@pytest.mark.parametrize("surface, other_output, renamings, edge", [ - ("python", "output_other_path", None, "output_edr_path"), - ("python", "output_log_path", None, "output_edr_path"), - ("python", "output_other_path", (), "output_other_path"), - ("cli", "output_log_path", None, "output_edr_path"), - ("cli", "output_log_path", (), "output_log_path"), - ("cli", "output_other_path", SHIPPED_RENAMINGS, "output_edr_path"), -], ids=["python-ships", "python-ships-over-a-log", "python-empty-is-none", "cli-key-missing-ships", - "cli-empty-list-is-none", "cli-shipped-list"]) +@pytest.mark.parametrize("surface, renamings, edge", [ + ("python", None, "output_edr_path"), ("python", (), "output_log_path"), + ("cli", None, "output_edr_path"), ("cli", (), "output_log_path"), +], ids=["python-ships", "python-empty-is-none", "cli-key-missing-ships", "cli-empty-list-is-none"]) def test_input_energy_path_reads_the_output_its_renamings_pair_it_with( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, surface: str, other_output: str, + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, surface: str, renamings: tuple[tuple[str, str], ...] | None, edge: str) -> None: """Both surfaces start from the shipped renamings when none are given (`None`: no argument, no config key), so - `energy_` pairs with `edr_` and `input_energy_path` reads `output_edr_path`, not the output declared first, a log - included. A list given is the whole list, so an empty one leaves the output declared first.""" - workflow = _mdrun_workflow(other_output) + `energy_` pairs with `edr_` and `input_energy_path` reads `output_edr_path`, not the output declared first, a log. + A list given is the whole list, so an empty one leaves the output declared first.""" + workflow = _mdrun_workflow("output_log_path") compiled = workflow.compile() if renamings is None else workflow.compile(inference=Inference(renamings=renamings)) cwl = _cli(workflow, tmp_path, monkeypatch, renamings=renamings) if surface == "cli" else compiled.cwl_workflow [feed] = _feeds(cwl) @@ -224,7 +218,8 @@ def _settings(draw: st.DrawFn) -> tuple[dict[str, Any], set[str]]: def test_an_inference_is_refused_at_construction_or_keeps_what_it_was_given( drawn: tuple[dict[str, Any], set[str]]) -> None: """Settings breaking a rule are `api007`, saying what to write instead; others are kept, renamings as tuples, the - shipped ones unless given or the conventions are off, and the format rules as a copy the caller cannot change.""" + shipped ones unless given or the conventions are off, and the format rules as a copy the caller cannot change. A + copy that switches the conventions keeps the renamings nobody gave as the shipped ones.""" settings, broken = drawn if broken: with pytest.raises(InvalidInferenceError) as raised: @@ -244,55 +239,8 @@ def test_an_inference_is_refused_at_construction_or_keeps_what_it_was_given( assert dict(inference.format_rules) == given_rules with pytest.raises(TypeError): inference.format_rules["tiff"] = "continue" # type: ignore[index] - - -def _converting_workflow(directory: Path) -> tuple[Workflow, dict[StepId, Tool]]: - """`make` writes format A, `need_b` reads format B and `need_a` reads A again; `insert_steps_automatically_a_to_b` - converts A to B and is passed in a registry, not a step. Inference inserts it before `need_b`.""" - a_file, b_file = {"type": "File", "format": "edam:format_1"}, {"type": "File", "format": "edam:format_2"} - tools = {"make": ({}, {"file": a_file}), "need_b": ({"file": b_file}, {}), "need_a": ({"file": a_file}, {}), - "insert_steps_automatically_a_to_b": ({"file": a_file}, {"file": b_file})} - paths = {} - for name, (inputs, outputs) in tools.items(): - paths[name] = directory / f"{name}.cwl" - paths[name].write_text(yaml.safe_dump(clt(inputs, outputs)), encoding="utf-8") - registry = {StepId("insert_steps_automatically_a_to_b", "global"): Tool( - str(paths["insert_steps_automatically_a_to_b"]), - clt(*tools["insert_steps_automatically_a_to_b"], canonical=True))} - steps = [Step(clt_path=paths[name]) for name in ("make", "need_b", "need_a")] - return Workflow(steps, "convert"), registry - - -def _step_ids(compiled: Any) -> list[str]: - steps = compiled.cwl_workflow["steps"] - return [step["id"] if isinstance(steps, list) else step for step in steps] - - -@pytest.mark.fast -def test_insert_steps_inserts_a_converter_from_the_tool_registry(tmp_path: Path) -> None: - """With `insert_steps=True` the converter in `tool_registry=` joins the workflow; without it, or without the - registry, `need_b`'s input is left unbound, a workflow input. `break` on format B stops `need_a`'s search at the - inserted converter, so it is left a workflow input where the default connects it.""" - workflow, registry = _converting_workflow(tmp_path) - - inserted = workflow.compile(tool_registry=registry, inference=Inference(insert_steps=True)) - plain = workflow.compile(tool_registry=registry) - unregistered = workflow.compile(inference=Inference(insert_steps=True)) - stopped = workflow.compile(tool_registry=registry, inference=Inference( - insert_steps=True, format_rules={"edam:format_2": "break"})) - - assert any("insert_steps_automatically_a_to_b" in name for name in _step_ids(inserted)) - for compiled in (plain, unregistered): - assert not any("insert_steps_automatically" in name for name in _step_ids(compiled)) - assert any("need_b" in name for name in compiled.cwl_workflow["inputs"]) - assert not any("need_b" in name for name in inserted.cwl_workflow["inputs"]) - assert not any("need_a" in name for name in inserted.cwl_workflow["inputs"]) - assert any("need_a" in name for name in stopped.cwl_workflow["inputs"]) - - -@pytest.mark.fast -def test_a_copy_of_an_inference_keeps_its_default_renamings() -> None: - """Switching naming conventions on a copy neither raises for renamings nobody gave nor drops the shipped ones.""" - assert replace(Inference(), naming_conventions=False).naming_conventions is False - switched_on = replace(Inference(naming_conventions=False), naming_conventions=True) - assert python_runtime.compiler_options(switched_on)['renaming_conventions'] == list(SHIPPED_RENAMINGS) + if given_renamings is None: # a copy switching the conventions neither raises nor drops the shipped renamings + for switched in (True, False): + copy = replace(inference, naming_conventions=switched) + assert python_runtime.compiler_options(copy)["renaming_conventions"] == list( + SHIPPED_RENAMINGS if switched else ()) diff --git a/tests/core/test_python_api_tool_builder.py b/tests/core/test_python_api_tool_builder.py index 62decada6..455f80734 100644 --- a/tests/core/test_python_api_tool_builder.py +++ b/tests/core/test_python_api_tool_builder.py @@ -21,15 +21,14 @@ secondary_file, ) from sophios.api.python.workflow import Step, Workflow -from sophios.lang.cwl import CWL_VERSION from .budgets import budget +from .cases import DATA from .strategies import author_names, pinned -def _rich_tool(default: str = "hello") -> CommandLineTool: - """A tool exercising every builder method that reaches the document, so - one assertion block covers the whole serialization surface; `default` is its `message`'s.""" +def _rich_tool(default: str) -> CommandLineTool: + """A tool exercising every builder method that reaches the document; `default` is its `message`'s.""" mode_type = cwl.enum("fast", "accurate", name="Mode") settings_type = cwl.record( Fields( @@ -46,9 +45,10 @@ def _rich_tool(default: str = "hello") -> CommandLineTool: mode=Input(mode_type, flag="--mode"), settings=Input(settings_type).load_listing("shallow_listing"), message=Input(cwl.string, default=default), + model=Input(cwl.file, flag="--model", required=False), ) return ( - CommandLineTool("aligner", inputs, Outputs(sam=Output.stdout())) + CommandLineTool("tools/aligner", inputs, Outputs(sam=Output.stdout())) .label("Align reads") .doc(["Toy CLT", "for serialization coverage"]) .namespace("edam") @@ -67,6 +67,8 @@ def _rich_tool(default: str = "hello") -> CommandLineTool: .argument("run-aligner", position=0) .stdout("aligned.sam") .success_codes(0, 2) + .time_limit(60) + .extra(sbol_intent="example:custom", customExtension={"enabled": True}) ) @@ -117,202 +119,19 @@ def test_a_port_name_is_accepted_when_python_can_write_and_reach_it(case: tuple[ @pytest.mark.fast -def test_tool_name_with_slash_keeps_document_ids() -> None: - """A `/` in the tool name is an id, not a URI base for other fields.""" - tool = CommandLineTool( - "tools/align", - Inputs(message=Input(cwl.string)), - Outputs(out=Output.stdout()), - ).to_cwl_document() - assert tool["class"] == "CommandLineTool" - assert tool["cwlVersion"] == CWL_VERSION - assert tool["id"] == "tools/align" - - -@pytest.mark.fast -def test_structured_port_references_do_not_accept_raw_strings() -> None: - """A port reference is the port object, never its name as text. - - A string cannot be checked against the tool it came from, so a typo would - survive to the emitted document and fail at runtime. The type is the check. - """ - tool = CommandLineTool( - "demo", - Inputs(input=Input(cwl.file)), - Outputs(output=Output(cwl.file, glob="out.txt")), - ) - with pytest.raises(TypeError, match="named Input/Output object"): - tool.stage("input") - - -def _by_class(entries: list[dict[str, Any]]) -> dict[str, dict[str, Any]]: - """Index a cwl_utils requirements/hints list by its `class` key.""" - return {entry["class"]: {k: v for k, v in entry.items() if k != "class"} for entry in entries} - - -def _by_id(entries: list[dict[str, Any]]) -> dict[str, dict[str, Any]]: - """Index a cwl_utils inputs/outputs list by its `id` key.""" - return {entry["id"]: {k: v for k, v in entry.items() if k != "id"} for entry in entries} - - -@pytest.mark.fast -def test_tool_builder_covers_common_clt_surface() -> None: - """Every builder method reaches the emitted document. - - One tool, one assertion block: a method that silently dropped its argument - would otherwise pass every test that never inspects the document. - """ - tool = _rich_tool().to_cwl_document() - inputs = _by_id(tool["inputs"]) - outputs = _by_id(tool["outputs"]) - requirements = _by_class(tool["requirements"]) - hints = _by_class(tool["hints"]) - - assert tool["$namespaces"] == {"edam": "https://edamontology.org/"} - assert tool["$schemas"] == ["https://example.org/formats.rdf"] - assert tool["intent"] == ["edam:operation_3198"] - assert tool["baseCommand"] == ["bash", "-lc"] - assert tool["arguments"] == [{"position": 0, "valueFrom": "run-aligner"}] - assert tool["stdout"] == "aligned.sam" - assert tool["successCodes"] == [0, 2] - assert inputs["reads"]["secondaryFiles"] == [{"pattern": ".bai", "required": False}] - assert inputs["settings"]["loadListing"] == "shallow_listing" - assert outputs["sam"]["type"] == "stdout" - assert requirements["ShellCommandRequirement"] == {} - assert requirements["DockerRequirement"] == {"dockerPull": "alpine:3.20"} - assert requirements["ResourceRequirement"] == { - "coresMin": 1.5, - "ramMin": 1024, - "outdirMin": 256, - } - assert requirements["EnvVarRequirement"] == { - "envDef": [{"envName": "LC_ALL", "envValue": "C"}] - } - assert requirements["InitialWorkDirRequirement"] == { - "listing": [{"entry": "threads=4\n", "entryname": "config.txt"}] - } - assert requirements["NetworkAccess"] == {"networkAccess": False} - assert requirements["InlineJavascriptRequirement"] == { - "expressionLib": ["function passthrough(x) { return x; }"] - } - assert len(requirements["SchemaDefRequirement"]["types"]) == 2 - assert hints["WorkReuse"] == {"enableReuse": False} - - -def _custom_tool() -> CommandLineTool: - """A small tool for the raw-extension tests.""" - return CommandLineTool("custom-tool", Inputs(message=Input(cwl.string)), - Outputs(out=Output(cwl.file, glob="out.txt"))) - - -@pytest.mark.fast -def test_tool_builder_accepts_raw_extensions() -> None: - """Unmodelled CWL can be injected, and says so when it is. - - `extra` is the escape hatch for vendor keys the builder does not model. It - warns because content that bypasses the builder also bypasses its checks. - """ +@pytest.mark.parametrize("text", ["1e3", "._", "._5", "0o17"]) +def test_a_built_tool_is_the_document_stated_and_writes_what_reads_back_as_built(tmp_path: Path, text: str) -> None: + """Every builder method reaches the document tests/core/data/python_api/aligner.cwl states, for its default `1e3`; + and what `write_cwl` writes loads back as built, by PyYAML and by cwltool's YAML 1.2, which would retype each of + these texts. `extra` warns, since what it adds bypasses the builder's checks.""" with pytest.warns(UserWarning, match="raw CWL injection"): - rendered = _custom_tool().time_limit(60).extra( - sbol_intent="example:custom", customExtension={"enabled": True}).to_cwl_document() - - assert _by_class(rendered["requirements"])["ToolTimeLimit"] == {"timelimit": 60} - assert rendered["sbol_intent"] == "example:custom" - assert rendered["customExtension"] == {"enabled": True} - - -@pytest.mark.fast -def test_tool_builder_rejects_reserved_or_salad_raw_keys() -> None: - """The escape hatch may not overwrite the document or the loader. - - Raw injection of `inputs` would silently discard what the builder computed, - and a SALAD assembly key like `$import` changes how the document is loaded - rather than what it says. - """ - tool = _custom_tool() - with pytest.raises(ValueError, match="builder-managed keys"): - tool.extra(inputs={"bad": "idea"}) - - with pytest.raises(ValueError, match="SALAD document-assembly keys"): - tool.requirement({"class": "EnvVarRequirement", "$import": "bad"}) - - -@pytest.mark.fast -def test_tool_builder_high_level_helpers_hide_cwl_plumbing() -> None: - """The helpers produce the CWL a hand-written tool would. - - `edam`, `gpu`, `stage` and `resources` each stand for a block of requirement - plumbing; this pins what each expands to, including that `stage` preserves - call order and its `writable` flag per entry. - """ - inputs = Inputs( - input=Input(cwl.directory, position=1).label("Input Zarr dataset").doc("Path to input zarr dataset"), - output=Input(cwl.directory, position=2).label("Output segmentation Zarr").doc( - "Path for output segmentation zarr" - ), - model=Input(cwl.file, flag="--model", required=False).label("Model override file"), - tile_size=Input(cwl.int, flag="--tile-size", required=False).label("Tile size"), - iou_threshold=Input(cwl.float, flag="--iou-threshold", required=False).label("IoU threshold"), - ) - outputs = Outputs(output=Output(cwl.directory, glob="$(inputs.output.basename)").label("Output segmentation Zarr")) - tool = ( - CommandLineTool("sam3", inputs, outputs) - .describe("SAM3 OME Zarr autosegmentation", "Run SAM3 autosegmentation on a zarr volume.") - .edam() - .gpu(cuda_version_min="11.7", compute_capability="3.0", device_count_min=2) - .docker("polusai/ichnaea-api:latest") - .stage(inputs.output, writable=True) - .stage(inputs.input) - .resources(cores=4, ram=64000) - .base_command("/backend/.venv/bin/python", "/backend/dagster_pipelines/jobs/autosegmentation/logic.py") - .to_cwl_document() - ) - emitted_inputs = _by_id(tool["inputs"]) - emitted_outputs = _by_id(tool["outputs"]) - requirements = _by_class(tool["requirements"]) - hints = _by_class(tool["hints"]) - - assert tool["$namespaces"]["edam"] == "https://edamontology.org/" - assert tool["$namespaces"]["cwltool"] == "http://commonwl.org/cwltool#" - assert tool["$schemas"] == [ - "https://raw.githubusercontent.com/edamontology/edamontology/master/EDAM_dev.owl" - ] - assert hints["cwltool:CUDARequirement"] == { - "cudaVersionMin": "11.7", - "cudaComputeCapability": "3.0", - "cudaDeviceCountMin": 2, - } - assert requirements["ResourceRequirement"] == {"coresMin": 4, "ramMin": 64000} - assert requirements["InitialWorkDirRequirement"] == { - "listing": [ - { - "entry": "$(inputs.output)", - "entryname": "$(inputs.output.basename)", - "writable": True, - }, - { - "entry": "$(inputs.input)", - "entryname": "$(inputs.input.basename)", - "writable": False, - }, - ] - } - assert requirements["InlineJavascriptRequirement"] == {} - assert emitted_inputs["input"]["inputBinding"] == {"position": 1} - assert emitted_inputs["model"]["type"] == ["null", "File"] - assert emitted_inputs["model"]["inputBinding"] == {"prefix": "--model"} - assert emitted_inputs["tile_size"]["type"] == ["null", "int"] - assert emitted_outputs["output"]["outputBinding"] == {"glob": "$(inputs.output.basename)"} - - -@pytest.mark.fast -@pytest.mark.parametrize("text", ["._", "._5", "1e3", "0o17"]) -def test_what_write_cwl_writes_reads_back_as_built(tmp_path: Path, text: str) -> None: - """What is written loads back as built, by PyYAML and by cwltool's YAML 1.2, which would retype these strings.""" - tool = _rich_tool(text) + tool = _rich_tool(text) + stated = yaml.safe_load((DATA / "python_api" / "aligner.cwl").read_text(encoding="utf-8")) + stated["inputs"][3]["default"] = text + assert tool.to_cwl_document() == stated assert tool.write_cwl(tmp_path / "aligner.cwl") == tmp_path / "aligner.cwl" written = (tmp_path / "aligner.cwl").read_text(encoding="utf-8") - assert yaml.safe_load(written) == yaml_no_ts().load(written) == tool.to_cwl_document() + assert yaml.safe_load(written) == yaml_no_ts().load(written) == stated #: A tool's own shorthands for a File, which cwltool refuses at a workflow's boundary. diff --git a/tests/core/test_python_api_workflow.py b/tests/core/test_python_api_workflow.py index 71acd7fcd..4030fd7fc 100644 --- a/tests/core/test_python_api_workflow.py +++ b/tests/core/test_python_api_workflow.py @@ -1,26 +1,27 @@ -from contextlib import contextmanager, nullcontext +"""The Python API: a script of objects compiles to the document stated beside it, what the API can prove wrong is +refused as stated, `check()` answers what `compile()` and `run()` would, and `run()` hands the runner what `compile()` +returns; its properties judge types as the language does, name the user's line, and build one step through every +door.""" +from contextlib import contextmanager import copy -import asyncio -import decimal +import pickle import inspect import json import os -import pickle -import re from pathlib import Path import sys import tempfile import traceback import warnings from types import SimpleNamespace -from typing import Any, Callable, Final, Iterator, Literal, NoReturn, cast +from typing import Any, Callable, Final, Iterator, Literal, cast from unittest.mock import Mock, patch from hypothesis import example, given, strategies as st +import numpy import pytest import yaml -import sophios import sophios.api.python._workflow_runtime as python_runtime import sophios.plugins import sophios.post_compile @@ -32,65 +33,19 @@ from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl from sophios.api.python.workflow import (_python_api_types_match, InvalidInputValueError, InvalidLinkError, InvalidStepError, RunPolicy, RunResult, RunState, RunStatus, SophiosError, - SophiosErrorCode, Step, StepInput, Workflow, WorkflowRunError) + Step, StepInput, Workflow, WorkflowRunError) from sophios.lang.diagnostics import lines as printed_lines from sophios.python_cwl_adapter import import_python_file from sophios.wic_types import Json, Tools from .budgets import budget -from .helpers import (ADAPTERS, REPO_ROOT, adapter_step, echo_workflow, no_preflight, python_process, - write_tree) +from .cases import DATA +from .helpers import ADAPTERS, adapter_step, echo_workflow, no_preflight, python_process from .reference_model import ReferenceExpectation, reference_expectation from .strategies import cwl_types -from .test_cookbook import _bodies, _through_the_file from .wic_reading import read_wic - -def _written(workflow: Workflow, directory: Path, name: str | None = None) -> dict[str, Any]: - """The document `write_wic` writes for `workflow` (or its nested workflow `name`), as `parse` reads it.""" - root = workflow.write_wic(directory) - target = root if name is None else directory / f"{name}.wic" - return read_wic(target.read_text(encoding="utf-8")) - - -def _emit_text_tool() -> CommandLineTool: - """A minimal built tool that writes its message to a file.""" - return ( - CommandLineTool( - "emit_text", - Inputs(message=Input(cwl.string, position=1)), - Outputs(file=Output(cwl.file, glob="stdout.txt")), - ) - .base_command("echo") - .stdout("stdout.txt") - ) - - -def _output_directory_tool(path: Path) -> Path: - """A built tool whose output is a directory it names itself.""" - write_tree(path.parent, {path.name: """class: CommandLineTool -cwlVersion: v1.2 -requirements: - InitialWorkDirRequirement: - listing: - - entry: $(inputs.outDir) - writable: true - InlineJavascriptRequirement: {} -baseCommand: [bash, -lc] -arguments: - - valueFrom: "touch $(inputs.outDir.basename)/done.txt" -inputs: - outDir: - type: Directory - inputBinding: - prefix: --outDir -outputs: - outDir: - type: Directory - outputBinding: - glob: $(inputs.outDir.basename) -"""}) - return path +PYTHON_API: Final = DATA / 'python_api' def _load_global_config() -> Json: @@ -128,216 +83,131 @@ def step_factory(*args: Any, **kwargs: Any) -> Any: yield -PAIRS = Path(__file__).resolve().parent / "data" / "python_api_pairs" -_PAIRED = import_python_file("python_api_pairs", PAIRS / "pairs.py") -#: Each pair's notes, written by hand from the inference rule: the nearest step's output, the others that fit counted. -_NOTES = {"linear_inference": ["cat.file <- append.file (1 other fits)"], - "equal_producers": ["cat.file <- second.file (1 other fits)"]} - - +@pytest.mark.cwl_corpus @pytest.mark.fast -@pytest.mark.parametrize("stem", [name for name, value in vars(_PAIRED).items() - if inspect.isfunction(value) and not name.startswith("_")]) -def test_a_python_workflow_compiles_as_the_wic_beside_it_and_as_the_wic_it_writes(stem: str, tmp_path: Path) -> None: - """The objects compile to the notes written for them and to the CWL, job and notes of the hand-written `.wic` of the - same name, a note but for where it points; and the bundle `write_wic` writes compiles, through the file door, to - the objects' CWL, job and notes.""" - workflow = getattr(_PAIRED, stem)() - compiled = workflow.compile() - assert [note.message for note in compiled.diagnostics] == _NOTES.get(stem, []) - assert _through_the_file(PAIRS / f"{stem}.wic") == ( - compiled.cwl_workflow, compiled.cwl_job_inputs, _bodies(compiled.diagnostics)) - assert _through_the_file(workflow.write_wic(tmp_path)) == ( - compiled.cwl_workflow, compiled.cwl_job_inputs, _bodies(compiled.diagnostics)) - - -def _warned_on_cwl() -> Workflow: - """A guessed edge, noted on either target (`wic043`); a `when` that gives a string, noted on CWL (`wic056`); and - `cat` running on a `when` that reads an input it does not have, noted on either target (`wic056`).""" - echo = adapter_step("echo") - echo.inputs.message = "hi" - echo.when = "$(inputs.message)" - workflow = Workflow([*_PAIRED.equal_producers().steps, echo], "noted") - workflow.steps[2].when = "$(inputs.nope)" - return workflow - - -def _noted_on_nextflow() -> Workflow: - """A CUDA field the Nextflow target does not check, which its lowering notes (`wic046`).""" - gpu = (CommandLineTool("gpu_tool", Inputs(), Outputs(file=Output(cwl.file, glob="out.txt"))) - .base_command("touch", "out.txt").gpu(cuda_version_min="11.4")) - return Workflow([Step(gpu, step_name="gpu")], "noted") +def test_compile_python_workflows() -> None: + """Import and compile all auto-discovered Python workflow scripts.""" + from sophios.api.python import workflow # pylint: disable=C0415:import-outside-toplevel + global_config = _load_global_config() + tools_cwl = sophios.plugins.get_tools_cwl(global_config) + paths_tuples = _iter_python_workflow_paths(global_config) + import_errors: list[str] = [] + for path_stem, path in paths_tuples: + try: + with _step_registry_injected(tools_cwl): + module = import_python_file(path_stem, path) + retval: workflow.Workflow = module.workflow() -def _ambiguous() -> Workflow: - """Two inputs of one step that inference would both give `touch`'s file: `wic055`, an error.""" - touch = adapter_step("touch", filename="a.txt") - both = Step.from_cwl_document({"cwlVersion": "v1.2", "class": "CommandLineTool", "baseCommand": "true", - "inputs": {"left": {"type": "File"}, "right": {"type": "File"}}, "outputs": {}}, - process_name="both") - return Workflow([touch, both], "ambiguous") + retval.compile() + retval.write_wic(path.parent) + config_ci = path.parent / "config_ci.json" + json_contents = {} + if config_ci.exists(): + with open(config_ci, mode="r", encoding="utf-8") as r: + json_contents = json.load(r) + fragments: list[str] = json_contents.get("fragments", []) + subworkflows: list[workflow.Workflow] = retval._flatten_subworkflows()[ + 1:] + fragments += [wf.process_name for wf in subworkflows] + json_contents["fragments"] = fragments + with open(config_ci, mode="w", encoding="utf-8") as f: + json.dump(json_contents, f) -@pytest.fixture(name="machine_ready") -def _machine_ready(monkeypatch: pytest.MonkeyPatch) -> None: - """A machine with every program a run calls and a container engine, whatever this one has: the pre-flight's - program and engine checks pass.""" - monkeypatch.setattr(preflight, "PLATFORM_LACKS_RUNNERS", None) - monkeypatch.setattr(preflight, "runner_program", lambda name: name) - monkeypatch.setattr(preflight, "nextflow_problems", lambda _settings: []) - monkeypatch.setattr(preflight, "engine_problems", lambda _images, _settings: []) + except Exception as exc: # pylint: disable=W0718:broad-exception-caught + import_errors.append(f"{path_stem}: {type(exc).__name__}: {exc}") + traceback.print_exception(type(exc), value=exc, tb=None) + if import_errors: + pytest.fail("Python workflow imports failed:\n" + + "\n".join(import_errors)) @pytest.mark.fast -@pytest.mark.usefixtures("machine_ready") -@pytest.mark.parametrize("target, build, codes", [("cwl", _warned_on_cwl, ["wic043", "wic056", "wic056"]), - ("nextflow", _noted_on_nextflow, ["wic046"])]) -def test_check_returns_the_notes_compile_keeps_and_prints_and_writes_nothing( - target: Literal["cwl", "nextflow"], build: Callable[[], Workflow], codes: list[str], - capsys: pytest.CaptureFixture[str], tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """`check()` makes every note `compile()` keeps, the target's own among them, and prints nothing: none of them, - nothing at all, so a `check()` and then a `compile()` show each once; it writes - nothing into the working directory, where the base path is. `compile()` prints the notes.""" - workflow = build() - capsys.readouterr() - monkeypatch.chdir(tmp_path) - notes = workflow.check(target=target) - assert not list(tmp_path.iterdir()) - assert tuple(capsys.readouterr()) == ("", "") - compiled = workflow.compile(target=target) - assert notes == compiled.diagnostics - assert [str(note.code) for note in notes] == codes - printed = capsys.readouterr().err.splitlines() - assert printed == printed_lines(notes) - assert any("reads inputs.nope, which its process does not declare" in note.message for note in notes) is ( - target == "cwl") - - -def _reading_a_file(path: Path) -> Workflow: - """`cat` of a file bound on the workflow's input.""" - tool = (CommandLineTool("cat_tool", Inputs(file=Input(cwl.file, position=1)), - Outputs(out=Output(cwl.file, glob="stdout.txt"))) - .base_command("cat").stdout("stdout.txt")) - step = tool.to_step(step_name="cat") - workflow = Workflow([step], "wf") - step.inputs.file = workflow.inputs.file.as_type("File") - workflow.inputs.file = str(path) - return workflow +def test_importing_sophios_leaves_the_root_logger_alone(tmp_path: Path) -> None: + """A library that adds a handler to the root logger on import changes the logging of every program + that imports it. Each module of the Python API is an attribute of its package, imported on first use.""" + # A new interpreter: pytest puts handlers on the root logger before any test imports Sophios. + run = python_process('-c', 'import logging\nimport sophios.main\nimport sophios.api.python as api\n' + 'assert api.workflow.Workflow\nprint(logging.getLogger().handlers)\n', cwd=tmp_path, + capture_output=True) + assert run.returncode == 0, run.stderr + assert run.stdout.strip() == '[]' @pytest.mark.fast -@pytest.mark.usefixtures("machine_ready") -@pytest.mark.parametrize("target", ["cwl", "nextflow"]) -def test_check_reports_an_input_path_that_does_not_exist_as_run_does( - target: Literal["cwl", "nextflow"], tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """`--check` reports a bound File that is not there (`wic016`), every problem at once; so does `check()`, as the - `SophiosError` `run()` raises, and it leaves the working directory as it found it.""" - monkeypatch.chdir(tmp_path) - workflow = _reading_a_file(tmp_path / "absent.txt") - with pytest.raises(SophiosError) as error: - workflow.check(target=target) - problem, = error.value.diagnostics - assert str( - problem.code) == "wic016" and f"{str(tmp_path / 'absent.txt')!r}, which does not exist" in problem.message - assert not list(tmp_path.iterdir()) - (tmp_path / "absent.txt").write_text("x", encoding="utf-8") - assert workflow.check(target=target) == workflow.compile(target=target).diagnostics - +def test_a_script_of_objects_compiles_to_the_document_stated_and_writes_what_compiles_alike( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """tests/core/data/python_api/builder.py compiles to builder.cwl and builder_job.yml beside it, as its comments + say. The bundle `write_wic` writes names each step's tool file by its stem and never the script, leaves a tool file + of that stem that is the same tool as it is, and the child declares the interface its parent binds by name + (tests/core/data/pairs compiles such bundles); each writer of the compiled workflow writes the in-memory documents + and no `.wic`, `write()` to the current directory by default.""" + builder = import_python_file('builder', PYTHON_API / 'builder.py') + with pytest.warns(UserWarning, match=r'Prefer workflow\.inputs\.message, or workflow\.inputs\.message\.as_type'): + workflow = builder.workflow() + assert getattr(workflow.outputs, '_repr_html_', None) is None # as IPython's display probes, declaring nothing + compiled = workflow.compile() + assert compiled.cwl_workflow == yaml.safe_load((PYTHON_API / 'builder.cwl').read_text(encoding='utf-8')) + assert compiled.cwl_job_inputs == yaml.safe_load((PYTHON_API / 'builder_job.yml').read_text(encoding='utf-8')) + + root = workflow.write_wic(tmp_path / 'bundle') + tools = {path: path.read_text(encoding='utf-8') for path in (tmp_path / 'bundle').glob('*.cwl')} + assert workflow.write_wic(tmp_path / 'bundle') == root # each tool file of its stem is the same tool, left as is + assert tools == {path: path.read_text(encoding='utf-8') for path in (tmp_path / 'bundle').glob('*.cwl')} + written = root.read_text(encoding='utf-8') + assert [step.get('run', step['id']) for step in read_wic(written)['steps']] == [ + 'emit_text.cwl', 'child.wic', 'write_dir.cwl', 'cat.cwl'] + assert '__step__' not in written and 'builder.py' not in written + assert read_wic((tmp_path / 'bundle' / 'child.wic').read_text(encoding='utf-8'))['inputs'] == { + 'file': {'type': 'File'}} -@pytest.mark.fast -def test_check_under_nextflow_reports_a_nextflow_that_is_not_installed( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """`--check --target nextflow` reports the missing `nextflow` (`wic029`) with the install instructions; so does - `check(target="nextflow")`, while a CWL check of the same workflow, which does not call Nextflow, passes.""" monkeypatch.chdir(tmp_path) - monkeypatch.setattr(preflight, "PLATFORM_LACKS_RUNNERS", None) - monkeypatch.setattr(preflight, "runner_program", lambda name: None if name == "nextflow" else name) - workflow = _noted_on_nextflow() - with pytest.raises(SophiosError) as error: - workflow.check(target="nextflow") - problem, = error.value.diagnostics - assert str(problem.code) == "wic029" and "the run calls nextflow, which is neither" in problem.message - assert "install Nextflow" in problem.message - workflow.check() - - -@pytest.mark.fast -@pytest.mark.parametrize("target", ["cwl", "nextflow"]) -def test_check_raises_what_compile_raises(target: Literal["cwl", "nextflow"]) -> None: - """A workflow that does not compile is the same `SophiosError` from `check()` as from `compile()`, whichever the - target.""" - with pytest.raises(SophiosError) as from_check: - _ambiguous().check(target=target) - with pytest.raises(SophiosError) as from_compile: - _ambiguous().compile(target=target) - assert "[wic055]" in str(from_check.value) and str(from_check.value) == str(from_compile.value) - - -def _refused_when() -> Workflow: - """A `when` comparing strings, which the Nextflow target's subset does not do (`nf-s010`), at the step's line.""" - echo = Step(clt_path=ADAPTERS / "echo.cwl") - flow = Workflow([echo], "refused") - echo.inputs.message = "hi" - echo.when = '$(inputs.message < "27")' - return flow - - -@pytest.mark.fast -def test_a_nextflow_refusal_prints_as_a_diagnostic_at_its_line() -> None: - """A refusal reads as every other error does: where, `error`, its code, the message, and the step.""" - line = inspect.getsourcelines(_refused_when)[1] + 2 - with pytest.raises(nextflow.NotLowered) as refused: - _refused_when().compile(target="nextflow") - assert str(refused.value) == ( - f"{__file__}:{line}:1: error [nf-s010] when: '$(inputs.message < \"27\")' is outside the safe JavaScript " - "subset: < requires number operands, not string (step 'echo')") - - -@pytest.mark.fast -@pytest.mark.parametrize("build, policy, codes", [ - (_refused_when, RunPolicy(), ["nf-s010"]), - (_noted_on_nextflow, RunPolicy(partial_failure=True), ["nf-s001"])]) -def test_check_returns_what_the_nextflow_target_refuses(build: Callable[[], Workflow], policy: RunPolicy, - codes: list[str]) -> None: - """`check()` answers whether the target can run the workflow, and returns the answer: each refusal is an error - diagnostic among the notes, and partial failure, a policy of the CWL target, is the one refusal.""" - found = build().check(target="nextflow", policy=policy) - errors = [diagnostic for diagnostic in found if str(diagnostic.severity) == "error"] - assert [str(error.code) for error in errors] == codes - with pytest.raises(nextflow.NotLowered) as refused: - build().compile(target="nextflow", policy=policy) - assert errors == list(refused.value.diagnostics) - assert all(isinstance(refusal, nextflow.Refusal) for refusal in refused.value.refusals) - + assert (compiled.write_cwl(tmp_path), compiled.write_job_inputs(tmp_path)) == ( + tmp_path / 'builder.cwl', tmp_path / 'builder_inputs.yml') + assert (yaml.safe_load(compiled.to_cwl_yaml()), yaml.safe_load(compiled.to_job_inputs_yaml())) == ( + compiled.cwl_workflow, compiled.cwl_job_inputs) + for path, directory in ((None, Path('.')), (tmp_path / 'out', tmp_path / 'out')): + assert compiled.write(path) == directory + assert yaml.safe_load((directory / 'builder.cwl').read_text(encoding='utf-8')) == compiled.cwl_workflow + assert yaml.safe_load((directory / 'builder_inputs.yml').read_text(encoding='utf-8')) == compiled.cwl_job_inputs + assert not list(directory.glob('*.wic')) -@pytest.mark.fast -@pytest.mark.parametrize("call", ["compile", "check", "run", "start"]) -def test_an_unknown_target_is_one_message_from_every_entry_point(call: str, monkeypatch: pytest.MonkeyPatch) -> None: - """The table of targets says which targets there are, once, before anything is compiled.""" - def compiled_first(*_args: Any, **_kwargs: Any) -> NoReturn: - raise AssertionError("compiled before the target was looked up") - monkeypatch.setattr(python_runtime, "compile_workflow_result", compiled_first) - flow = Workflow([adapter_step("touch")], "elsewhere") - with pytest.raises(ValueError, match=r"^unknown target 'wdl'; the targets are cwl, nextflow$"): - getattr(flow, call)(target="wdl") +#: Every exception refused.yaml names, by its name. +_RAISED: Final = {error.__name__: error for error in (AttributeError, ValueError, TypeError, SophiosError, + InvalidLinkError, InvalidStepError, InvalidInputValueError, + nextflow.NotLowered)} @pytest.mark.fast -@pytest.mark.parametrize("kind, make, name", [ - *(("step", lambda name: adapter_step("touch", name), name) - for name in ["a~b", "a@2", "a#b", ".hidden", ".."]), - ("workflow", lambda name: Workflow([adapter_step("touch")], name), "..")]) -def test_a_name_sophios_cannot_write_is_refused(kind: str, make: Callable[[str], object], name: str) -> None: - """A step's name is an id of the compiled CWL and part of the names made from it, as in a `.wic`; a workflow's - is the stem of the files it is written to, and `..` would name the directory above.""" - with pytest.raises(ValueError, match="^" + re.escape(f"{kind} name {name!r} is not a name Sophios can write: use " - "letters")): - make(name) - - +def test_what_the_api_can_prove_wrong_is_refused_as_stated(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """Each function of tests/core/data/python_api/refused.py raises what refused.yaml states, and its message names + what it states. A caller writes one `except SophiosError` and reads `.diagnostics`, whatever the compile refused; + nothing is pulled or started.""" + refused = import_python_file('refused', PYTHON_API / 'refused.py') + stated = yaml.safe_load((PYTHON_API / 'refused.yaml').read_text(encoding='utf-8')) + assert set(stated) == {name for name, value in vars(refused).items() + if inspect.isfunction(value) and value.__module__ == refused.__name__ + and not name.startswith('_')} + prepared = no_preflight(monkeypatch) + monkeypatch.setattr(python_runtime.run_local, 'start', lambda *_args, **_kwargs: pytest.fail('ran')) + monkeypatch.chdir(tmp_path) + for name, expected in stated.items(): + with warnings.catch_warnings(), pytest.raises(_RAISED[expected['raises']]) as caught: + warnings.simplefilter('ignore') # raw CWL injection warns before it is refused + getattr(refused, name)() + assert type(caught.value).__name__ == expected['raises'], name + assert [item.code.name for item in getattr(caught.value, 'diagnostics', [])] == ( + [expected['code']] if 'code' in expected else []), name + assert all(text in str(caught.value) for text in expected['names']), (name, str(caught.value)) + assert not prepared + + +_FLOATS: Final = st.floats(allow_nan=False, allow_infinity=False) +#: What a port of each type may be bound, numpy's float64 among the floats. _BINDABLE: Final = {'string': st.text(max_size=5), 'int': st.integers(-2**31, 2**31 - 1), - 'float': st.floats(allow_nan=False, allow_infinity=False), 'boolean': st.booleans()} + 'float': _FLOATS | _FLOATS.map(numpy.float64), 'boolean': st.booleans()} @st.composite @@ -354,14 +224,17 @@ def _built_tools(draw: st.DrawFn) -> tuple[CommandLineTool, dict[str, Any]]: @pytest.mark.fast @given(_built_tools(), st.sampled_from([None, 'say'])) -@example((_emit_text_tool(), {'message': 'hello'}), None) # a built tool becomes a step named for it +@example((CommandLineTool('emit_text', Inputs(message=Input(cwl.string, position=1)), + Outputs(file=Output(cwl.file, glob='stdout.txt'))).base_command('echo').stdout('stdout.txt'), + {'message': 'hello'}), None) # a built tool becomes a step named for it @example((CommandLineTool('echo_tool', Inputs(message=Input(cwl.string, position=1)), Outputs(out=Output.stdout())) .base_command('echo').stdout('stdout.txt'), {'message': 'hi'}), 'say') # `step_name` renames it and its path @budget(15) def test_a_built_tool_is_one_step_through_every_door(drawn: tuple[CommandLineTool, dict[str, Any]], step_name: str | None) -> None: """Each in-memory door, binding by attribute or `step_inputs=`, writes nothing and makes the step `Step(clt_path=)` - makes of the tool's file: named `step_name` or for the tool, with a path of that name, compiling alike.""" + makes of the tool's file: named `step_name` or for the tool, with a path of that name, compiling alike; and the + job holds plain values, a numpy float a Python one.""" tool, values = drawn name = step_name or tool.name with tempfile.TemporaryDirectory() as directory, pytest.MonkeyPatch.context() as monkeypatch: @@ -376,165 +249,7 @@ def test_a_built_tool_is_one_step_through_every_door(drawn: tuple[CommandLineToo assert {(step.process_name, step.clt_path.name) for step in steps} == {(name, f'{name}.cwl')} assert all((each.cwl_workflow, each.cwl_job_inputs) == (compiled[-1].cwl_workflow, compiled[-1].cwl_job_inputs) for each in compiled) - - -def _scale_step(declared: Any) -> Step: - """A step of a built tool whose one input `factor` is declared `declared`.""" - tool = (CommandLineTool("scale_tool", Inputs(factor=Input(declared, position=1)), Outputs(out=Output.stdout())) - .base_command("echo").stdout("stdout.txt")) - return Step.from_cwl_document(tool.to_cwl_document(), process_name="scale") - - -@pytest.mark.fast -def test_a_numpy_float_reaches_the_job_as_a_plain_float() -> None: - """numpy's float64 is a float, and a job file holds plain numbers.""" - numpy = pytest.importorskip("numpy") - step = _scale_step(cwl.float) - step.inputs.factor = numpy.float64(0.5) - - (value,) = Workflow([step], "wf").compile().cwl_job_inputs.values() - - assert (value, type(value)) == (0.5, float) - - -@pytest.mark.fast -def test_a_value_bound_on_a_workflow_input_is_its_job_value() -> None: - """`workflow.inputs. = value` is that input's value in the job of either target, in the form a value - written on a step takes, as an inputs file gives one.""" - tool = (CommandLineTool("cat_tool", Inputs(name=Input(cwl.string, position=1), file=Input(cwl.file, position=2)), - Outputs(out=Output(cwl.file, glob="stdout.txt"))).base_command("cat").stdout("stdout.txt")) - step = tool.to_step(step_name="cat") - workflow = Workflow([step], "wf") - step.inputs.name, step.inputs.file = workflow.inputs.name.as_type("string"), workflow.inputs.file.as_type("File") - workflow.inputs.name, workflow.inputs.file = "n", "data.txt" - - assert workflow.compile().cwl_job_inputs == {"name": "n", "file": {"class": "File", "location": "data.txt"}} - assert workflow.compile(target="nextflow").nextflow_workflow.params == { - "name": "n", "file": {"class": "File", "path": "data.txt"}} - - -@pytest.mark.fast -def test_a_workflow_output_with_a_leading_underscore_is_declared_by_binding_alone() -> None: - """A port name may have a leading `_`, as Nextflow normalization writes one; reading an undeclared one, as - IPython's display probes private names, declares nothing.""" - tool = CommandLineTool("make", Inputs(), Outputs(out=Output(cwl.file, glob="o"))).base_command("touch", "o") - step = tool.to_step() - workflow = Workflow([step], "wf") - assert getattr(workflow.outputs, "_repr_html_", None) is None - setattr(workflow.outputs, "_Out", step.outputs.out) - - assert [output.name for output in workflow.outputs] == ["_Out"] - assert workflow.compile().cwl_workflow["outputs"] == {"_Out": {"type": "File", "outputSource": "make/out"}} - - -@pytest.mark.fast -@pytest.mark.parametrize("declared, python_type", [ - (cwl.int, "int"), (cwl.float, "float"), (cwl.boolean, "bool"), (cwl.string, "str"), -]) -def test_a_value_of_another_python_type_is_wic020_naming_the_type_the_port_holds( - declared: Any, python_type: str) -> None: - """A numpy scalar or a Decimal is not a Python number: nothing converts it, and the message says so.""" - step = _scale_step(declared) - step.inputs.factor = decimal.Decimal(3) - - with pytest.raises(SophiosError) as caught: - Workflow([step], "wf").compile() - - diagnostic = caught.value.diagnostics[0] - assert diagnostic.code is SophiosErrorCode.LITERAL_TYPE_MISMATCH - assert diagnostic.message.endswith(f"is of type decimal.Decimal, not a Python {python_type}.") - - -@pytest.mark.fast -def test_step_constructor_rejects_a_step_inputs_file_for_in_memory_tool() -> None: - """`step_inputs_file` belongs to a tool on disk; an in-memory tool has no file to configure.""" - tool = cast(Any, _emit_text_tool()) - with pytest.raises(TypeError, match="step_inputs_file is only supported"): - Step(tool, step_inputs_file="inputs.yml") - - -@pytest.mark.fast -def test_tool_builder_step_bridge_supports_multistep_workflow(capsys: pytest.CaptureFixture[str]) -> None: - """Built tools chain: two steps, ordered, with the workflow output wired through. The Python API spells - `outputSource` with generated names itself, so no line of authored spelling is printed for it.""" - emit_step = Step(_emit_text_tool(), step_name="emit_text") - read_step = adapter_step("cat") - workflow = Workflow([emit_step, read_step], "builder_and_pyapi_demo") - emit_step.inputs.message = workflow.inputs.message.as_type(cwl.string) - read_step.inputs.file = emit_step.outputs.file - workflow.outputs.result = read_step.outputs.output - - compiled = workflow.compile() - - assert compiled.cwl_workflow["class"] == "Workflow" - step_ids = [step["id"] for step in compiled.cwl_workflow["steps"]] - assert step_ids[0].endswith("emit_text") - assert step_ids[1].endswith("cat") - assert list(compiled.cwl_workflow["outputs"]) == ["result"] - assert compiled.cwl_workflow["outputs"]["result"]["outputSource"] == f"{step_ids[1]}/output" - assert "Warning!" not in capsys.readouterr().err - - -@pytest.mark.fast -def test_attribute_sugar_input_warning_points_at_the_reference_and_the_typed_declaration() -> None: - """The sugar binding warns and names the way to write it; binding an input reference to an output does not.""" - step = Step(_emit_text_tool(), step_name="emit_text") - workflow = Workflow([step], "sugar_demo") - - with pytest.warns(UserWarning, match=r"Prefer workflow\.inputs\.message, or workflow\.inputs\.message\.as_type"): - step.inputs.message = workflow.message - with warnings.catch_warnings(): - warnings.simplefilter("error") - workflow.outputs.o = workflow.inputs.x - - -@pytest.mark.fast -def test_output_target_directories_compile_as_runner_local_inputs(tmp_path: Path) -> None: - """A declared output directory becomes a string input the runner fills. - - Typed `string` rather than `Directory` because the directory does not exist - until the step runs; the `glob` refers back to the input that names it.""" - step = Step(clt_path=_output_directory_tool(tmp_path / "write_dir.cwl")) - step.inputs.outDir = Path("result.outDir") - workflow = Workflow([step], "virtual_dir_demo") - - compiled = workflow.compile() - - assert compiled.cwl_job_inputs["write_dir~outDir"] == "result.outDir" - assert compiled.cwl_workflow["inputs"]["write_dir~outDir"]["type"] == "string" - assert compiled.cwl_workflow["steps"][0]["run"]["inputs"]["outDir"]["type"] == "string" - assert compiled.cwl_workflow["steps"][0]["run"]["outputs"]["outDir"]["outputBinding"]["glob"] == "$(inputs.outDir)" - - -@pytest.mark.fast -def test_output_target_directories_reject_absolute_locations(tmp_path: Path) -> None: - """An output directory is runner-local, so an absolute path is refused.""" - step = Step(clt_path=_output_directory_tool(tmp_path / "write_dir.cwl")) - step.inputs.outDir = tmp_path / "absolute.outDir" - workflow = Workflow([step], "absolute_dir_demo") - - with pytest.raises(ValueError, match="cannot use an absolute location"): - workflow.compile() - - -@pytest.mark.fast -def test_subworkflow_inputs_use_child_workflow_name_and_formal_parameters(tmp_path: Path) -> None: - """A subworkflow step names the child and passes its formal parameters: the bundle written for the parent - compiles to what the objects do, and the child declares the interface the parent binds by name.""" - touch = adapter_step("touch", filename="empty.txt") - sub_step = adapter_step("append") - subworkflow = Workflow([sub_step], "child") - sub_step.inputs.file = subworkflow.inputs.file - sub_step.inputs.str = subworkflow.inputs.str - subworkflow.inputs.file = touch.outputs.file - subworkflow.inputs.str = "Hello" - root = Workflow([touch, subworkflow], "root") - - compiled = root.compile() - - assert _through_the_file(root.write_wic(tmp_path))[:2] == (compiled.cwl_workflow, compiled.cwl_job_inputs) - assert "subtree" not in _written(root, tmp_path)["steps"][1] - assert _written(root, tmp_path, "child")["inputs"] == {"file": {"type": "File"}, "str": {"type": "string"}} + assert all(type(value) in (str, int, float, bool) for each in compiled for value in each.cwl_job_inputs.values()) _CWL_TYPES = cwl_types( @@ -566,155 +281,144 @@ def _bind(step: Step, **values: Any) -> Step: return step -def _sink(declared: str) -> Step: - """A step that takes `x`, declared `declared`, and does nothing.""" - return Step.from_cwl_document({"cwlVersion": "v1.2", "class": "CommandLineTool", "baseCommand": "true", - "inputs": {"x": {"type": declared}}, "outputs": {}}, process_name="sink") - - -def _touched() -> tuple[Step, Step]: - """Steps `a` and `b`, each touching a file of its name.""" - return adapter_step("touch", "a", filename="a.txt"), adapter_step("touch", "b", filename="b.txt") +#: Statements of a user's script, `# here` on the line its diagnostic, or the step it makes, must name. +_SPANNED: Final = { + 'literal': ('scale = Step.from_cwl_document(SCALE, process_name="scale")', + 'scale.inputs.n = "not an int" # here', 'workflow = Workflow([scale], "wf")'), + 'bind': ('touch = Step(clt_path=TOUCH)', 'cat = Step(clt_path=CAT)', + 'cat.inputs.file = [touch.outputs.file] # here'), + 'order': ('touch = Step(clt_path=TOUCH)', 'cat = Step(clt_path=CAT) # here', + 'cat.inputs.file = touch.outputs.file', 'workflow = Workflow([cat, touch], "backwards")'), + 'made': ('step = Step(clt_path=TOUCH) # here',), +} -def _bindable() -> SimpleNamespace: - """Fresh steps in one workflow whose input `text` is a `string`, and an `echo` whose undeclared `go` a - `StepInput` bound.""" - a, b = _touched() - steps = SimpleNamespace(a=a, b=b, append=adapter_step("append"), cat=adapter_step("cat"), - echo=adapter_step("echo"), sink=_sink("int")) - steps.workflow = Workflow([a, b, steps.append, steps.cat, steps.echo, steps.sink], "w") - steps.workflow.inputs.text.as_type("string") - steps.defaulted = adapter_step("echo", go=StepInput(default=True)) - return steps +def _script(kind: str, depth: int, padding: list[str]) -> str: + lines = [*_SPANNED[kind], 'made.update(locals())'] + for _ in range(depth): + lines = ['def build():', *(f' {line}' for line in lines), 'build()'] + return '\n'.join([*padding, *lines]) + '\n' @pytest.mark.fast -@pytest.mark.parametrize("binding, error, fragment", [ - (lambda s: (s.append, "misspelled", "Hello"), AttributeError, "has no input named"), - (lambda s: (s.append.inputs, "str", s.a.outputs.file), InvalidLinkError, "incompatible types"), - (lambda s: (s.append.inputs, "file", s.workflow.inputs.text), InvalidLinkError, - "append.file has incompatible types"), - (lambda s: (s.echo.inputs, "go", True), AttributeError, "no input named 'go'"), - (lambda s: (s.defaulted.inputs, "go", True), AttributeError, "no input named 'go'"), - (lambda s: (s.cat.inputs, "file", [s.a.outputs.file]), InvalidInputValueError, "StepInput"), - (lambda s: (s.cat.inputs, "file", (s.workflow.inputs.f,)), InvalidInputValueError, "StepInput"), - (lambda s: (s.cat.inputs, "file", [[s.a.outputs.file]]), InvalidInputValueError, "StepInput"), - (lambda s: (s.cat.inputs, "file", {"x": s.a.outputs.file}), InvalidInputValueError, "StepInput"), - (lambda s: (s.cat.inputs, "file", [{"x": [s.a.outputs.file]}]), InvalidInputValueError, "StepInput"), - (lambda s: (s.cat.inputs, "file", [StepInput(source=s.a.outputs.file)]), InvalidInputValueError, - "a StepInput is never a literal"), - *((lambda s, record=record: (s.sink.inputs, "x", StepInput(source=[s.a.outputs.file, s.b.outputs.file], **record)), - InvalidLinkError, "incompatible types") - for record in ({"link_merge": "merge_flattened"}, {"pick_value": "first_non_null"})), -]) -def test_a_binding_the_api_can_prove_wrong_is_refused_where_it_is_written( - binding: Callable[[SimpleNamespace], tuple[object, str, Any]], error: type[Exception], fragment: str) -> None: - """An input the tool does not declare, which only a `StepInput` may bind, a source of a type the input cannot - take, scattered or not, or a port where a literal goes, anywhere inside a list or mapping, which names - `StepInput` instead of passing for a literal.""" - target, name, value = binding(_bindable()) - with pytest.raises(error, match=fragment) as caught: - setattr(target, name, value) - - -def _reading_its_own_output(a: Step) -> Workflow: - """A workflow of `a` and a `cat` that reads the workflow's own output, which is `a`'s.""" - cat = adapter_step("cat") - workflow = Workflow([a, cat], "loop") - workflow.outputs.made = a.outputs.file - cat.inputs.file = workflow.outputs.made - return workflow - +@given(st.sampled_from(sorted(_SPANNED)), st.integers(0, 2), + st.lists(st.sampled_from(['', '# note', 'pass']), max_size=3), + st.sampled_from(['', '', 'build.py', str(Path(__file__).with_name('built.py'))])) +@example('literal', 1, [], __file__) # a literal of the wrong type bound in a function is reported where it is bound +@example('literal', 0, ['import sophios'], 'build.py') # one bound at a script's top level, at the script's line +@example('bind', 1, [], __file__) # an error raised while binding names the bind, not a line inside Sophios +@example('order', 1, [], __file__) # a step listed before the step it reads from, where that step was made +@example('made', 0, [''], '') # code without a file keeps its pseudo-name, not a path under the cwd +@budget(20) +def test_a_diagnostic_names_the_python_line_that_made_its_object(kind: str, depth: int, padding: list[str], + file: str) -> None: + """A diagnostic names the line of the user's innermost frame that bound the port or made the step, under the + name its code was compiled with: a path resolved, a pseudo-name such as `` kept.""" + source = _script(kind, depth, padding) + line = next(number for number, text in enumerate(source.splitlines(), start=1) if text.endswith('# here')) + made: dict[str, Any] = {} + names = {'Step': Step, 'Workflow': Workflow, 'TOUCH': ADAPTERS / 'touch.cwl', 'CAT': ADAPTERS / 'cat.cwl', + 'made': made, 'SCALE': {'cwlVersion': 'v1.2', 'class': 'CommandLineTool', 'baseCommand': 'true', + 'inputs': {'n': 'int'}, 'outputs': {}}} + named = file if file.startswith('<') else str(Path(file).resolve()) + if kind == 'made': + exec(compile(source, file, 'exec'), names) # pylint: disable=exec-used + span = made['step']._span # pylint: disable=protected-access + else: + with pytest.raises({'literal': SophiosError, 'bind': InvalidInputValueError, + 'order': InvalidStepError}[kind]) as caught: + exec(compile(source, file, 'exec'), names) # pylint: disable=exec-used + made['workflow'].compile() + diagnostic = cast(SophiosError, caught.value).diagnostics[0] + span = diagnostic.span + assert kind != 'literal' or str(diagnostic).startswith(f'{named}:{line}:1: error [wic020]') + assert span is not None and (span.file, span.start_line) == (named, line) -@pytest.mark.fast -@pytest.mark.parametrize("build, error, code, fragment", [ - (lambda a, b: Workflow([adapter_step("append", file=a.outputs.file, str="Hello"), a], "w"), - InvalidStepError, SophiosErrorCode.INVALID_STEP, "must appear earlier"), - (lambda a, b: Workflow([adapter_step("append", file=a.outputs.file, str="Hello")], "w"), - InvalidStepError, SophiosErrorCode.INVALID_STEP, "not a child"), - (lambda a, b: Workflow([adapter_step("cat", file=StepInput( - source=[a.outputs.file], pick_value="first_non_null")), a], "w"), - InvalidStepError, SophiosErrorCode.INVALID_STEP, "earlier in the workflow step list"), - (lambda a, b: _reading_its_own_output(a), InvalidLinkError, SophiosErrorCode.INVALID_LINK, "own output"), - *((lambda a, b, declared=declared: Workflow([a, b, _bind(_sink(declared), x=StepInput( - source=[a.outputs.file, b.outputs.file], link_merge="merge_flattened"))], "w"), - SophiosError, SophiosErrorCode.INCOMPATIBLE_INPUT_REFERENCE, "wic023") for declared in ("File", "int[]")), -]) -def test_compile_refuses_a_workflow_wired_wrong(build: Callable[[Step, Step], Workflow], error: type[SophiosError], - code: SophiosErrorCode, fragment: str) -> None: - """Order is meaning, as inference scans backwards: a step may read only an earlier step of its own workflow, by a - link or a record, and never its workflow's own output. A merge the bind cannot judge is the compiler's to refuse. - - A caller writes one `except SophiosError` and reads `.diagnostics`, whatever failed: the API used to raise - bare `Exception` subclasses of its own beside the compiler's `SophiosError`, neither importable from where a - user of `compile()` would look (issue 111). - """ - workflow = build(*_touched()) - with pytest.raises(SophiosError) as caught: - workflow.compile() - assert isinstance(caught.value, error) and fragment in str(caught.value) - assert [diagnostic.code for diagnostic in caught.value.diagnostics] == [code] +def _noted(_directory: Path) -> Workflow: + """A guessed edge, noted on either target (`wic043`); a `when` that gives a string, noted on CWL (`wic056`); and + `cat` running on a `when` that reads an input it does not have, noted on either target (`wic056`).""" + echo = adapter_step('echo', message='hi') + echo.when = '$(inputs.message)' + cat = adapter_step('cat') + cat.when = '$(inputs.nope)' + first, second = (adapter_step('touch', name, filename=f'{name}.txt') for name in ('first', 'second')) + return Workflow([first, second, cat, echo], 'noted') -@pytest.mark.fast -def test_compiled_workflow_writes_files_that_read_back_as_its_documents(monkeypatch: pytest.MonkeyPatch, - tmp_path: Path) -> None: - """Each writer writes the in-memory document and no intermediate `.wic`; `write()` both to one directory, the - current one by default.""" - compiled = Workflow([adapter_step("echo", message="hello")], "wf").compile() - monkeypatch.chdir(tmp_path) - assert (compiled.write_cwl(tmp_path), compiled.write_job_inputs(tmp_path)) == (tmp_path / "wf.cwl", - tmp_path / "wf_inputs.yml") - assert (yaml.safe_load(compiled.to_cwl_yaml()), yaml.safe_load(compiled.to_job_inputs_yaml())) == ( - compiled.cwl_workflow, compiled.cwl_job_inputs) - for path, directory in ((None, Path(".")), (tmp_path / "out", tmp_path / "out")): - assert compiled.write(path) == directory - assert yaml.safe_load((directory / "wf.cwl").read_text(encoding="utf-8")) == compiled.cwl_workflow - assert yaml.safe_load((directory / "wf_inputs.yml").read_text(encoding="utf-8")) == compiled.cwl_job_inputs - assert not list(directory.rglob("*.wic")) +def _on_a_gpu(_directory: Path) -> Workflow: + """A CUDA field the Nextflow target does not check, which its lowering notes (`wic046`).""" + gpu = (CommandLineTool('gpu_tool', Inputs(), Outputs(file=Output(cwl.file, glob='out.txt'))) + .base_command('touch', 'out.txt').gpu(cuda_version_min='11.4')) + return Workflow([Step(gpu, step_name='gpu')], 'noted') -@pytest.mark.fast -def test_port_names_reject_namespace_collisions() -> None: - """A port may not shadow the port namespace's own API.""" - with pytest.raises(ValueError, match="reserved by port namespaces"): - Step.from_cwl_document({'cwlVersion': 'v1.2', 'class': 'CommandLineTool', 'baseCommand': 'true', - 'inputs': {'_store': 'string'}, 'outputs': {}}, process_name='bad') +def _comparing_strings(_directory: Path) -> Workflow: + """A `when` comparing strings, which the Nextflow target's subset does not do (`nf-s010`).""" + echo = adapter_step('echo', message='hi') + echo.when = '$(inputs.message < "27")' + return Workflow([echo], 'refused') -@pytest.mark.fast -@pytest.mark.parametrize("removed, error, fix", [ - (lambda: Workflow([], "wf").yaml, AttributeError, "write_wic"), - (lambda: Workflow([], "wf").to_wic_yaml, AttributeError, "write_wic"), - (lambda: _emit_text_tool().to_step(config={}), # type: ignore[call-arg] # pylint: disable=unexpected-keyword-arg - TypeError, "config"), -], ids=["yaml", "to_wic_yaml", "config"]) -def test_a_removed_api_fails_loudly(removed: Callable[[], object], error: type[Exception], fix: str) -> None: - """The removed `.wic` accessors, and `to_step`'s `config=`, fail loudly instead of meaning something else.""" - with pytest.raises(error, match=fix): - removed() +def _ambiguous(_directory: Path) -> Workflow: + """Two inputs of one step that inference would both give `touch`'s file: `wic055`, an error.""" + both = (CommandLineTool('both', Inputs(left=Input(cwl.file), right=Input(cwl.file)), Outputs()) + .base_command('true').to_step()) + return Workflow([adapter_step('touch', filename='a.txt'), both], 'ambiguous') -@pytest.mark.fast -def test_workflow_write_wic_rejects_non_wic_file_extension(tmp_path: Path) -> None: - """A destination must be a `.wic` file or a directory to put one in.""" - workflow = Workflow([], "wf") - with pytest.raises(ValueError, match=r"\.wic file or a directory"): - workflow.write_wic(tmp_path / "workflow.yaml") +def _reading_an_absent_file(directory: Path) -> Workflow: + """`cat` of a file bound on the workflow's input, which is not there (`wic016`).""" + step = Step(clt_path=PYTHON_API / 'cat.cwl') + workflow = Workflow([step], 'wf') + step.inputs.f = workflow.inputs.file.as_type('File') + workflow.inputs.file = str(directory / 'absent.txt') + return workflow @pytest.mark.fast -def test_a_step_inputs_file_binds_each_value_as_written(tmp_path: Path) -> None: - """Nothing is checked when the step is built: a path may name a file on the machine that runs it.""" - config = tmp_path / "append.yml" - config.write_text( - yaml.safe_dump({"file": {"class": "File", "location": "/cluster/project/in.txt"}, "str": "Hello"}), - encoding="utf-8") - append = Step(clt_path=ADAPTERS / "append.cwl", step_inputs_file=config) - assert Workflow([append], "wf").compile().cwl_job_inputs["append~file"] == { - "class": "File", "location": "/cluster/project/in.txt"} +@pytest.mark.parametrize('build, target, policy, codes, refused, compiled', [ + (_noted, 'cwl', RunPolicy(), ['wic043', 'wic056', 'wic056'], False, None), + (_on_a_gpu, 'nextflow', RunPolicy(), ['wic046'], False, None), + (_comparing_strings, 'nextflow', RunPolicy(), ['nf-s010'], False, nextflow.NotLowered), + (_on_a_gpu, 'nextflow', RunPolicy(partial_failure=True), ['nf-s001'], False, nextflow.NotLowered), + (_ambiguous, 'nextflow', RunPolicy(), ['wic055'], True, SophiosError), + (_reading_an_absent_file, 'cwl', RunPolicy(), ['wic016'], True, Workflow), + (_reading_an_absent_file, 'nextflow', RunPolicy(), ['wic016', 'wic029'], True, Workflow), +], ids=['cwl-notes', 'nextflow-notes', 'nextflow-refuses', 'nextflow-refuses-a-policy', 'does-not-compile', + 'absent-input', 'absent-input-and-nextflow']) +# pylint: disable-next=too-many-arguments,too-many-positional-arguments +def test_check_answers_what_compile_and_run_would_and_prints_and_writes_nothing( + build: Callable[[Path], Workflow], target: Literal['cwl', 'nextflow'], policy: RunPolicy, codes: list[str], + refused: bool, compiled: Any, capsys: pytest.CaptureFixture[str], tmp_path: Path, + monkeypatch: pytest.MonkeyPatch) -> None: + """`check()` returns every note `compile()` keeps, a target's refusals among them as errors, which `compile()` + raises; and it raises what `compile()` raises, and what the pre-flight finds, every problem at once, as `run()` + does: an input that is not there (`wic016`) and, where the run calls one and there is none, `nextflow` + (`wic029`). It prints nothing and writes nothing where the base path is; `compile()` prints the notes.""" + monkeypatch.setattr(preflight, 'PLATFORM_LACKS_RUNNERS', None) + monkeypatch.setattr(preflight, 'runner_program', lambda name: None if name == 'nextflow' and refused else name) + if not refused: # a nextflow that is there answers `-version` + monkeypatch.setattr(preflight, 'nextflow_problems', lambda _settings: []) + monkeypatch.setattr(preflight, 'engine_problems', lambda _images, _settings: []) + monkeypatch.chdir(tmp_path) + workflow = build(tmp_path) + capsys.readouterr() + try: + notes = workflow.check(target=target, policy=policy) + except SophiosError as error: + assert [str(item.code) for item in error.diagnostics] == codes and refused, error + notes = tuple(error.diagnostics) + else: + assert [str(note.code) for note in notes] == codes and not refused + assert tuple(capsys.readouterr()) == ('', '') and not list(tmp_path.iterdir()) + if compiled is None: + assert workflow.compile(target=target, policy=policy).diagnostics == notes + assert capsys.readouterr().err.splitlines() == printed_lines(notes) + elif compiled is not Workflow: # the compile refuses what the check reports, the target's refusals as errors + with pytest.raises(compiled) as from_compile: + workflow.compile(target=target, policy=policy) + assert [note for note in notes if str(note.severity) == 'error'] == list(from_compile.value.diagnostics) class _Ended: # pylint: disable=too-few-public-methods @@ -722,323 +426,76 @@ class _Ended: # pylint: disable=too-few-public-methods def collect(self) -> RunResult: """The completed run's result.""" - return RunResult(RunState.COMPLETED, None, Path("outdir"), Path("run.log"), 0) - - -def _api_run_command(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, run_args: dict[str, Any]) -> list[str]: - """The runner command `Workflow.run()` writes to run.sh for `run_args`.""" - workflow = Workflow([adapter_step("touch", filename="empty.txt")], "quiet_demo") - no_preflight(monkeypatch) - monkeypatch.chdir(tmp_path) - workflow.run(basepath=str(tmp_path), run_args_dict={"generate_run_script": "yes", **run_args}) - return (tmp_path / "run.sh").read_text(encoding="utf-8").splitlines()[-1].split() + return RunResult(RunState.COMPLETED, None, Path('outdir'), Path('run.log'), 0) @pytest.mark.fast -@pytest.mark.parametrize("run_args, expected", [({}, True), *(({"quiet": quiet}, quiet in ("yes", "true", True)) - for quiet in ("yes", "true", True, "no", "false", False))]) -def test_workflow_run_is_quiet_unless_told_otherwise(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - run_args: dict[str, Any], expected: bool) -> None: - """The Python API has always run `cwltool` with `--quiet`; `run_args_dict={'quiet': ...}` switches it, and its - value never reaches `cwltool` as a positional.""" - cmd = _api_run_command(monkeypatch, tmp_path, run_args) - assert ("--quiet" in cmd) is expected - assert not {"yes", "no", "true", "false", "True", "False"} & set(cmd) - - -@pytest.mark.fast -@pytest.mark.parametrize("value", ["yes", "true", "1", "on", True]) -def test_workflow_run_generate_run_script_run_arg( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, value: str | bool -) -> None: - """Any spelling of yes for `generate_run_script` writes `run.sh`; it does not run the workflow.""" - assert _api_run_command(monkeypatch, tmp_path, {"generate_run_script": value}) - - -@pytest.mark.fast -def test_workflow_run_prepares_the_cwl_in_its_basepath( - monkeypatch: pytest.MonkeyPatch, - tmp_path: Path, -) -> None: - """The pre-flight is given the CWL in the basepath, not one in the current directory.""" - example_path = REPO_ROOT / "examples" / "scripts" / "tool_builder_workflow.py" - module = import_python_file(example_path.stem, example_path.resolve()) - workflow = module.build_workflow("hello from test") +# pylint: disable-next=too-many-locals # one run, followed from the documents to the runner +def test_run_writes_what_compile_returns_and_hands_the_runner_its_own_flags(monkeypatch: pytest.MonkeyPatch, + tmp_path: Path) -> None: + """`run()` writes the one document `compile()` returns and its job, and nothing else: a workflow that declares + its outputs runs with those alone, and a relative path, bound in Python, in a step inputs file (which binds values + as written) or as a `StepInput` default, names the file in the working directory, absolute. It prepares that + document in its basepath with docker, the images built without entrypoints when told, every embedded tool's and a + hint's too; and hands the runner its own flags, never the Python API's: `quiet` is on unless told otherwise and + never a positional, and any spelling of yes for `generate_run_script` writes run.sh without running.""" + monkeypatch.chdir(tmp_path) + Path('inputs').mkdir() + Path('data.txt').write_text('hello\n', encoding='utf-8') + Path('inputs/cat.yml').write_text('f: {class: File, location: data.txt}\n', encoding='utf-8') + by_file = Step(clt_path=PYTHON_API / 'cat.cwl', step_inputs_file='inputs/cat.yml') + by_value, by_default = (Step(clt_path=PYTHON_API / 'cat.cwl', step_name=name) for name in ('read', 'by_default')) + by_value.inputs.f = 'data.txt' + by_default.inputs.f = StepInput(default={'class': 'File', 'location': 'data.txt'}) + workflow = Workflow([by_file, by_value, by_default, adapter_step('touch', filename='empty.txt'), + Step(clt_path=PYTHON_API / 'hinted.cwl')], 'exact') + workflow.outputs.printed = by_file.outputs.out prepared: list[tuple[list[Path], preflight.RunSettings]] = [] - - monkeypatch.setattr(python_runtime.preflight, "prepare", + monkeypatch.setattr(python_runtime.preflight, 'prepare', lambda documents, settings, jobs=(): prepared.append((documents, settings))) - monkeypatch.setattr(python_runtime.run_local, "start", lambda request: _Ended()) - - workflow.run(basepath=str(tmp_path)) - - (documents, settings), = prepared - assert documents == [tmp_path / "tool_builder_workflow_demo.cwl"] - assert settings.container_engine == "docker" - assert settings.pull_dir == str(Path.cwd()) - assert not settings.ignore_install - - -@pytest.mark.fast -def test_run_runs_exactly_what_compile_returns(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """`run()` writes the one document `compile()` returns and its job, a relative path made absolute, and nothing - else: a workflow that declares its outputs runs with those outputs only.""" - monkeypatch.chdir(tmp_path) - Path("data.txt").write_text("hello\n", encoding="utf-8") - cat = adapter_step("cat", file="data.txt") - workflow = Workflow([cat, adapter_step("touch", filename="empty.txt")], "exact") - workflow.outputs.printed = cat.outputs.output - no_preflight(monkeypatch) - - workflow.run(basepath="base", run_args_dict={"generate_run_script": "yes", "quiet": "no"}) - - compiled = workflow.compile() - base = tmp_path / "base" - assert sorted(path.name for path in base.iterdir()) == ["exact.cwl", "exact_inputs.yml"] - assert yaml.safe_load((base / "exact.cwl").read_text(encoding="utf-8")) == compiled.cwl_workflow - assert list(compiled.cwl_workflow["outputs"]) == ["printed"] - assert yaml.safe_load((base / "exact_inputs.yml").read_text(encoding="utf-8")) == { - **compiled.cwl_job_inputs, "cat~file": {"class": "File", "location": (tmp_path / "data.txt").as_uri()}} - - -@pytest.mark.fast -def test_run_with_docker_remove_entrypoints_writes_the_noentrypoint_tags( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """`run()` builds the images without entrypoints, then hands the runner a document naming them: - every embedded tool's, a `DockerRequirement` hint's as well as a requirement's.""" - monkeypatch.chdir(tmp_path) - hinted = tmp_path / "hinted.cwl" - write_tree(tmp_path, {"hinted.cwl": "cwlVersion: v1.2\nclass: CommandLineTool\nbaseCommand: 'true'\n" - "inputs: {}\noutputs: {}\n" - "hints:\n DockerRequirement:\n dockerPull: docker.io/alpine:3.20\n"}) - no_preflight(monkeypatch) - monkeypatch.setattr(sophios.post_compile.docker, "from_env", + monkeypatch.setattr(sophios.post_compile.docker, 'from_env', lambda: SimpleNamespace(images=SimpleNamespace(list=lambda: []))) + for quiet, spelled in ((None, 'yes'), ('yes', 'true'), ('true', '1'), (True, 'on'), ('no', True), (False, 'yes')): + run_args: dict[str, Any] = {'generate_run_script': spelled, 'docker_remove_entrypoints': 'yes'} + workflow.run(basepath='base', run_args_dict=run_args | ({} if quiet is None else {'quiet': quiet})) + command = (tmp_path / 'run.sh').read_text(encoding='utf-8').splitlines()[-1].split() + assert ('--quiet' in command) is (quiet in (None, 'yes', 'true', True)) + assert not {'yes', 'no', 'true', 'false', 'True', 'False'} & set(command) - Workflow([adapter_step("touch", filename="empty.txt"), Step(clt_path=hinted)], "no_entrypoints").run( - run_args_dict={"generate_run_script": "yes", "docker_remove_entrypoints": "yes"}) - - steps = yaml.safe_load((tmp_path / "autogenerated" / "no_entrypoints.cwl").read_text(encoding="utf-8"))["steps"] - assert [step["run"]["requirements" if "requirements" in step["run"] else "hints"]["DockerRequirement"] - for step in steps] == [{"dockerPull": "docker.io/library/debian:bookworm-slim-noentrypoint"}, - {"dockerPull": "docker.io/alpine:3.20-noentrypoint"}] - - -@pytest.mark.fast -def test_workflow_run_does_not_forward_python_run_flags_to_runner( - monkeypatch: pytest.MonkeyPatch, - tmp_path: Path, -) -> None: - """Flags meant for the Python API stay there; only runner flags pass through.""" - workflow = Workflow([adapter_step("touch", filename="empty.txt")], "runtime_flag_demo") + compiled = workflow.compile() + assert sorted(path.name for path in (tmp_path / 'base').iterdir()) == ['exact.cwl', 'exact_inputs.yml'] + written = yaml.safe_load((tmp_path / 'base' / 'exact.cwl').read_text(encoding='utf-8')) + assert list(written['outputs']) == ['printed'] + assert [step['run'].get('requirements', step['run'].get('hints', {})).get('DockerRequirement') + for step in written['steps']] == [None, None, None, + {'dockerPull': 'docker.io/library/debian:bookworm-slim-noentrypoint'}, + {'dockerPull': 'docker.io/alpine:3.20-noentrypoint'}] + here = {'class': 'File', 'location': (tmp_path / 'data.txt').as_uri()} + assert written['steps'][2]['in']['f']['default'] == here + assert yaml.safe_load((tmp_path / 'base' / 'exact_inputs.yml').read_text(encoding='utf-8')) == { + **compiled.cwl_job_inputs, 'cat~f': here, 'read~f': here} + assert {(tuple(path.resolve() for path in documents), settings.container_engine, settings.ignore_install) + for documents, settings in prepared} == {(((tmp_path / 'base' / 'exact.cwl').resolve(),), 'docker', False)} requests: list[RunRequest] = [] - no_preflight(monkeypatch) - def run(request: RunRequest) -> int: requests.append(request) return 0 - monkeypatch.setattr(python_runtime.run_local, "run", run) - - workflow.run( - basepath=str(tmp_path), - run_args_dict={ - "generate_run_script": "yes", - "logLevel": "INFO", - "outdir": str(tmp_path / "workflow_output"), - }, - ) - - assert len(requests) == 1 - request = requests[0] - assert request.passthrough_args == ("--logLevel", "INFO") - assert request.generate_run_script - assert request.outdir == str(tmp_path / "workflow_output") - assert request.workflow_name == "runtime_flag_demo" - assert request.basepath == tmp_path - - -@pytest.mark.fast -@pytest.mark.skipif(sys.platform == "win32" or os.geteuid() == 0, - reason="directory modes do not stop Windows or root") -def test_workflow_run_reports_an_unwritable_basepath_as_wic021(monkeypatch: pytest.MonkeyPatch, - tmp_path: Path) -> None: - """A `basepath` that cannot be created is one `wic021` before the run, not a PermissionError.""" - step = Step(clt_path=_output_directory_tool(tmp_path / "write_dir.cwl")) - step.inputs.outDir = Path("result.outDir") - workflow = Workflow([step], "locked_run_demo") - monkeypatch.setattr(python_runtime.run_local, "start", lambda *_args, **_kwargs: pytest.fail("ran")) - locked = tmp_path / "locked" - locked.mkdir(mode=0o555) - - with pytest.raises(SophiosError) as caught: - workflow.run(basepath=str(locked / "autogenerated")) - - (problem,) = caught.value.diagnostics - assert problem.code is SophiosErrorCode.DIRECTORY_NOT_WRITABLE - assert problem.message == (f"Sophios writes the workflow and its run to {locked / 'autogenerated'}, " - f"but {locked} is not writable by you: pass run() a basepath you can write to.") - - -@pytest.mark.cwl_corpus -@pytest.mark.fast -def test_compile_python_workflows() -> None: - """Import and compile all auto-discovered Python workflow scripts.""" - from sophios.api.python import workflow # pylint: disable=C0415:import-outside-toplevel - - global_config = _load_global_config() - tools_cwl = sophios.plugins.get_tools_cwl(global_config) - paths_tuples = _iter_python_workflow_paths(global_config) - import_errors: list[str] = [] - for path_stem, path in paths_tuples: - try: - with _step_registry_injected(tools_cwl): - module = import_python_file(path_stem, path) - retval: workflow.Workflow = module.workflow() - - retval.compile() - retval.write_wic(path.parent) - - config_ci = path.parent / "config_ci.json" - json_contents = {} - if config_ci.exists(): - with open(config_ci, mode="r", encoding="utf-8") as r: - json_contents = json.load(r) - fragments: list[str] = json_contents.get("fragments", []) - subworkflows: list[workflow.Workflow] = retval._flatten_subworkflows()[ - 1:] - fragments += [wf.process_name for wf in subworkflows] - json_contents["fragments"] = fragments - with open(config_ci, mode="w", encoding="utf-8") as f: - json.dump(json_contents, f) - - except Exception as exc: # pylint: disable=W0718:broad-exception-caught - import_errors.append(f"{path_stem}: {type(exc).__name__}: {exc}") - traceback.print_exception(type(exc), value=exc, tb=None) - if import_errors: - pytest.fail("Python workflow imports failed:\n" + - "\n".join(import_errors)) - - -def _detach_run_from_the_container_engine(monkeypatch: pytest.MonkeyPatch) -> None: - """Keep a `Workflow.run()` call off the container engine and the disk.""" - no_preflight(monkeypatch) - monkeypatch.setattr(python_runtime.input_output, 'write_artifacts_to_disk', lambda *_a, **_k: None) - - -def _failed_run(monkeypatch: pytest.MonkeyPatch, exit_code: int) -> SophiosError: - """The error `Workflow.run()` raises when the runner ends with `exit_code`: the handle is the real one, its runner - never started and its `wait` saying FAILED, so the raise is its `collect()`'s.""" - _detach_run_from_the_container_engine(monkeypatch) - monkeypatch.setattr(run_local.RunHandle, '_start', lambda _handle: None) - failed = RunStatus(RunState.FAILED, f'the runner exited with status {exit_code}', exit_code=exit_code) - monkeypatch.setattr(run_local.RunHandle, 'wait', lambda _handle, _timeout=None: failed) - with pytest.raises(SophiosError) as caught: - echo_workflow('failing').run() - return caught.value - - -@pytest.mark.fast -@pytest.mark.parametrize('duplicate', [ - lambda error: error, - lambda error: pickle.loads(pickle.dumps(error)), - copy.copy, - copy.deepcopy, -], ids=['as-raised', 'pickle', 'copy', 'deepcopy']) -def test_run_raises_workflow_run_error_on_a_failed_run(monkeypatch: pytest.MonkeyPatch, - duplicate: Callable[[SophiosError], SophiosError]) -> None: - """`Workflow.run()` reports a failed run, with the runner's exit code, instead of returning; the error survives - being duplicated, so it can come back from a worker process or be re-raised elsewhere with its exit code.""" - raised = _failed_run(monkeypatch, 7) - clone = duplicate(raised) - assert (str(clone), list(clone.diagnostics)) == (str(raised), list(raised.diagnostics)) - assert clone.diagnostics[0].code is SophiosErrorCode.WORKFLOW_RUN_FAILED and "'failing'" in str(clone) - assert isinstance(clone, WorkflowRunError) - assert (clone.exit_code, clone.reason) == (7, 'the runner exited with status 7') - - -@pytest.mark.fast -def test_importing_sophios_leaves_the_root_logger_alone(tmp_path: Path) -> None: - """A library that adds a handler to the root logger on import changes the logging of every program - that imports it.""" - # A new interpreter: pytest puts handlers on the root logger before any test imports Sophios. - run = python_process('-c', 'import logging\nimport sophios.main\nimport sophios.api.python.workflow\n' - 'print(logging.getLogger().handlers)\n', cwd=tmp_path, capture_output=True) - assert run.returncode == 0, run.stderr - assert run.stdout.strip() == '[]' - - -@pytest.mark.needs_cwltool -def test_workflow_run_runs_a_workflow_from_a_users_script(tmp_path: Path) -> None: - """A real run, as a user's script makes it, in a new interpreter: cwltool runs and writes the summary.""" - script = ''' -import json -from pathlib import Path -from sophios.api.python.workflow import Step, Workflow -echo = Step.from_cwl_document({"cwlVersion": "v1.2", "class": "CommandLineTool", "baseCommand": "echo", - "inputs": {"message": {"type": "string", "inputBinding": {"position": 1}}}, - "outputs": {"said": "stdout"}, "stdout": "said.txt"}, process_name="echo") -echo.inputs.message = "hello" -Workflow([echo], "say").run() -summary = json.loads(Path("autogenerated/output_say.json").read_text(encoding="utf-8")) -print(Path(next(iter(summary.values()))["path"]).read_text(encoding="utf-8"), end="") -''' - run = python_process('-c', script, cwd=tmp_path, capture_output=True) - assert run.returncode == 0, run.stdout + run.stderr - assert run.stdout.endswith('hello\n') - - -#: A tool that reads one File, and runs in no container. -_CAT_TOOL = {'cwlVersion': 'v1.2', 'class': 'CommandLineTool', 'baseCommand': 'cat', - 'inputs': {'f': {'type': 'File', 'inputBinding': {'position': 1}}}, 'outputs': {'out': 'stdout'}} - - -def _cat() -> Step: - return Step.from_cwl_document(_CAT_TOOL, process_name='cat') - - -def _cat_tool(directory: Path) -> Path: - """`_CAT_TOOL`, written to `directory`, for a step built from a file.""" - path = directory / 'cat.cwl' - path.write_text(yaml.safe_dump(_CAT_TOOL), encoding='utf-8') - return path - - -def _job_written_by_run(monkeypatch: pytest.MonkeyPatch, workflow: Workflow) -> dict[str, Any]: - """The job `workflow.run()` writes for the runner, with the machine and the runner left out.""" - no_preflight(monkeypatch) - monkeypatch.setattr(python_runtime.run_local, 'start', lambda _request: _Ended()) - workflow.run() - job = Path('autogenerated') / f'{workflow.process_name}_inputs.yml' - return cast(dict[str, Any], yaml.safe_load(job.read_text(encoding='utf-8'))) - - -@pytest.mark.fast -def test_a_step_input_default_path_is_resolved_against_the_working_directory( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """A `StepInput(default=...)` names the file a bound value of the same text would: the one here, written - absolute when the document is built, wherever the document is then written.""" - monkeypatch.chdir(tmp_path) - cat = _cat() - cat.inputs.f = StepInput(default={'class': 'File', 'location': 'data.txt'}) - (step,) = Workflow([cat], 'wf').compile().cwl_workflow['steps'] - assert step['in']['f']['default'] == {'class': 'File', 'location': (tmp_path / 'data.txt').as_uri()} + monkeypatch.setattr(python_runtime.run_local, 'run', run) + workflow.run(basepath=str(tmp_path), run_args_dict={'generate_run_script': 'yes', 'logLevel': 'INFO', + 'outdir': str(tmp_path / 'workflow_output')}) + (request,) = requests + assert (request.passthrough_args, request.generate_run_script, request.outdir, request.workflow_name, + request.basepath) == (('--logLevel', 'INFO'), True, str(tmp_path / 'workflow_output'), 'exact', tmp_path) def _missing_paths(monkeypatch: pytest.MonkeyPatch, workflow: Workflow) -> list[str]: """The `wic016` lines `workflow.run()` raises, which it must raise before the runner starts.""" - ran: list[bool] = [] - - def runner(_request: RunRequest) -> _Ended: - ran.append(True) - return _Ended() - monkeypatch.setattr(python_runtime.run_local, 'start', runner) + monkeypatch.setattr(python_runtime.run_local, 'start', lambda _request: pytest.fail('ran')) with pytest.raises(SophiosError) as caught: workflow.run() - assert not ran - return [str(diagnostic) for diagnostic in caught.value.diagnostics - if diagnostic.code is SophiosErrorCode.MISSING_INPUT_FILE] + return [str(diagnostic) for diagnostic in caught.value.diagnostics if str(diagnostic.code) == 'wic016'] @pytest.mark.fast @@ -1063,9 +520,7 @@ def test_the_pre_flight_checks_exactly_the_paths_the_runner_reads( monkeypatch.chdir(tmp_path) for name, text in files.items(): Path(name).write_text(text, encoding="utf-8") - _cat_tool(tmp_path) - _output_directory_tool(tmp_path / "write_dir.cwl") - step = _bind(Step(clt_path=tmp_path / f"{tool}.cwl", step_inputs_file=step_inputs_file), + step = _bind(Step(clt_path=PYTHON_API / f"{tool}.cwl", step_inputs_file=step_inputs_file), **{port: value.format(cwd=Path.cwd()) if isinstance(value, str) else value for port, value in bound.items()}) if fragments: @@ -1084,23 +539,32 @@ def test_the_pre_flight_checks_exactly_the_paths_the_runner_reads( @pytest.mark.fast -@pytest.mark.parametrize("bound, step_inputs_file", [({"f": "data.txt"}, None), ({}, "inputs/cat.yml")]) -def test_a_relative_path_is_read_from_the_working_directory(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - bound: dict[str, str], - step_inputs_file: str | None) -> None: - """The job names it absolute, as the runner reads the job from the basepath, not from here; one in a step inputs - file too, not from the file's directory: the file binds values as written.""" - monkeypatch.chdir(tmp_path) - write_tree(tmp_path, {"data.txt": "hello\n", "inputs/cat.yml": "f: {class: File, location: data.txt}\n"}) - cat = _bind(Step(clt_path=_cat_tool(tmp_path), step_inputs_file=step_inputs_file), **bound) - job = _job_written_by_run(monkeypatch, Workflow([cat], "wf")) - assert job["cat~f"] == {"class": "File", "location": (Path.cwd() / "data.txt").as_uri()} - +def test_run_stops_before_the_runner_or_says_how_the_run_ended(monkeypatch: pytest.MonkeyPatch, + tmp_path: Path) -> None: + """A `basepath` that cannot be created is one `wic021` before the run, not a PermissionError. A failed run raises + `WorkflowRunError` with the runner's exit code, and the error survives being duplicated, so it can come back from + a worker process or be re-raised elsewhere; a Ctrl-C is no failed run, so a loop that handles them still stops.""" + no_preflight(monkeypatch) + if sys.platform != 'win32' and os.geteuid() != 0: # directory modes stop neither Windows nor root + locked = tmp_path / 'locked' + locked.mkdir(mode=0o555) + with pytest.MonkeyPatch.context() as unstarted, pytest.raises(SophiosError) as caught: + unstarted.setattr(python_runtime.run_local, 'start', lambda *_args, **_kwargs: pytest.fail('ran')) + echo_workflow('locked').run(basepath=str(locked / 'autogenerated')) + (problem,) = caught.value.diagnostics + assert str(problem.code) == 'wic021' and f'but {locked} is not writable by you' in problem.message -@pytest.mark.fast -def test_ctrl_c_during_run_is_not_reported_as_a_failed_run(monkeypatch: pytest.MonkeyPatch) -> None: - """A loop that handles failed runs must still stop when the user presses Ctrl-C.""" - _detach_run_from_the_container_engine(monkeypatch) + monkeypatch.setattr(python_runtime.input_output, 'write_artifacts_to_disk', lambda *_a, **_k: None) + monkeypatch.setattr(run_local.RunHandle, '_start', lambda _handle: None) + failed = RunStatus(RunState.FAILED, 'the runner exited with status 7', exit_code=7) + monkeypatch.setattr(run_local.RunHandle, 'wait', lambda _handle, _timeout=None: failed) + with pytest.raises(WorkflowRunError) as raised: + echo_workflow('failing').run() + for clone in (raised.value, pickle.loads(pickle.dumps(raised.value)), copy.copy(raised.value), + copy.deepcopy(raised.value)): + assert isinstance(clone, WorkflowRunError) and str(clone) == str(raised.value) + assert (str(clone.diagnostics[0].code), clone.exit_code, clone.reason) == ( + 'api005', 7, 'the runner exited with status 7') and "'failing'" in str(clone) def interrupted(_request: RunRequest) -> _Ended: raise KeyboardInterrupt @@ -1110,268 +574,20 @@ def interrupted(_request: RunRequest) -> _Ended: @pytest.mark.needs_cwltool -def test_a_real_failed_step_is_named_with_its_status(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, - capfd: pytest.CaptureFixture[str]) -> None: - """Pins cwltool's own wording: if a cwltool upgrade changes it, this fails, not a user's summary. - - capfd, not capsys: cwltool hands the real stderr's file descriptor to the step. - """ - tool = tmp_path / "exits_3.cwl" - tool.write_text("cwlVersion: v1.2\nclass: CommandLineTool\nbaseCommand: [sh, -c, 'exit 3']\n" - "inputs:\n message: string\noutputs: {}\n", encoding="utf-8") - step = Step(clt_path=tool) - step.inputs.message = "x" +def test_a_real_run_prints_its_output_or_names_the_step_that_failed(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, + capfd: pytest.CaptureFixture[str]) -> None: + """Real runs by cwltool. A user's script, tests/core/data/python_api/say_hello.py, run by a new interpreter, runs + its workflow and reads the summary the run wrote. A failing step is named with its status, in cwltool's own + words, which the summary reads: if a cwltool upgrade changes them, this fails, not a user's summary. capfd, not + capsys: cwltool hands the real stderr's file descriptor to the step.""" + run = python_process(PYTHON_API / 'say_hello.py', cwd=tmp_path, capture_output=True) + assert run.returncode == 0, run.stdout + run.stderr + assert run.stdout.endswith('hello\n') + + step = Step(clt_path=PYTHON_API / 'exits_3.cwl') + step.inputs.message = 'x' monkeypatch.chdir(tmp_path) with pytest.raises(WorkflowRunError): - Workflow([step], "exits").run(basepath=str(tmp_path / "autogenerated")) + Workflow([step], 'exits').run(basepath=str(tmp_path / 'autogenerated')) err = capfd.readouterr().err - assert "Failure! step 'exits_3" in err - assert "exited with status 3." in err - - -_OTHER_ECHO: Final = "cwlVersion: v1.2\nclass: CommandLineTool\nbaseCommand: false\ninputs: {}\noutputs: {}\n" - - -@pytest.mark.fast -@pytest.mark.parametrize('step_name', [None, 'say_hi'], ids=['named-for-its-tool', 'renamed']) -def test_a_written_step_runs_its_tool_stem_and_the_document_names_no_python_path(step_name: str | None, - tmp_path: Path) -> None: - """Every step, a renamed one too, names its tool file, so the bundle compiles without the tool on a search path. - Spans are internal: the written document never names the script that built it.""" - root = Workflow([adapter_step('echo', step_name, message='hi')], 'wf').write_wic(tmp_path) - text = root.read_text(encoding='utf-8') - assert read_wic(text)['steps'][0]['run'] == 'echo.cwl' - assert (tmp_path / 'echo.cwl').is_file() - assert '__step__' not in text and str(Path(__file__).resolve()) not in text - - -@pytest.mark.fast -@pytest.mark.parametrize('existing, refused', [((ADAPTERS / 'echo.cwl').read_text(encoding='utf-8'), False), - (_OTHER_ECHO, True)], ids=['the-same-tool', 'a-different-tool']) -def test_write_wic_never_rewrites_the_tool_file_of_a_stem(existing: str, refused: bool, tmp_path: Path) -> None: - """A file already named `.cwl` is never rewritten: the same tool is left as it is, a different one is - neither replaced nor trusted.""" - source = write_tree(tmp_path, {'echo.cwl': existing}) / 'echo.cwl' - workflow = Workflow([adapter_step('echo', message='hi')], 'wf') - with pytest.raises(InvalidStepError, match='already exists') if refused else nullcontext(): - workflow.write_wic(tmp_path) - assert (tmp_path / 'wf.wic').exists() is not refused - assert source.read_text(encoding='utf-8') == existing - - -@pytest.mark.fast -def test_two_tools_sharing_a_file_stem_are_rejected(tmp_path: Path) -> None: - """A document names a tool by its file stem, so two different tools under one stem are ambiguous.""" - def tool(command: str) -> dict[str, Any]: - return {'cwlVersion': 'v1.2', 'class': 'CommandLineTool', 'baseCommand': command, - 'inputs': {}, 'outputs': {}} - - first = Step.from_cwl_document(tool('true'), process_name='first', run_path='tool.cwl') - second = Step.from_cwl_document(tool('false'), process_name='second', run_path='tool.cwl') - workflow = Workflow([first, second], 'shared_stem') - - with pytest.raises(InvalidStepError, match="share the file stem 'tool'"): - workflow.write_wic(tmp_path) - with pytest.raises(InvalidStepError, match="share the file stem 'tool'"): - workflow.compile() - - -def _inner_and_sibling() -> tuple[Workflow, Step]: - touch = adapter_step('touch', filename='empty.txt') - inner = Workflow([touch], 'inner') - inner.outputs.made = touch.outputs.file - return inner, adapter_step('cat', file=inner.outputs.made) - - -def _own(step: Step, port: str) -> tuple[Step, list[Any]]: - """`step` and its input `port`, to scatter over.""" - return step, [getattr(step.inputs, port)] - - -@pytest.mark.fast -@pytest.mark.parametrize("build, setter, fragment", [ - (lambda: _own(adapter_step("echo"), "message"), True, "bound before scattering"), - (lambda: _own(adapter_step("echo", message="hello"), "message"), True, "array-valued data"), - (lambda: (adapter_step("echo"), [adapter_step("echo", message=["a", "b"]).inputs.message]), - True, "belong to the same step"), - *((lambda pick=pick: _own(_bind(_sink("File"), x=StepInput(source=[step.outputs.file for step in _touched()], - pick_value=pick)), "x"), False, "array-valued data") - for pick in ("first_non_null", "the_only_non_null")), - (lambda: _own(_inner_and_sibling()[1], "file"), False, "array-valued data"), -]) -def test_a_port_that_cannot_be_scattered_is_refused(build: Callable[[], tuple[Step, list[Any]]], setter: bool, - fragment: str) -> None: - """Scatter needs a bound, array-valued port of the step itself; any other compiles and then fails at runtime. - A `pickValue` that picks one source delivers one value, and a nested workflow adds no array layer of its own: - over an unscattered step its output stays a `File`.""" - step, ports = build() - with pytest.raises(ValueError, match=fragment): - if setter: - step.scatter = ports - else: - step.scatter_on(*ports) - - -@pytest.mark.fast -def test_nested_crossproduct_lifts_one_level_per_scattered_port() -> None: - """`nested_crossproduct` nests one array per scattered port; any other method adds one.""" - echo = adapter_step('echo', message='a') - first = adapter_step('append', file=echo.outputs.stdout, str=['x', 'y']) - sink = adapter_step('cat', 'sink') - lifted = sink.inputs.file - sink.inputs.file = first.outputs.file - first.scatter_on(first.inputs.str, method='nested_crossproduct') - assert lifted.effective_source_type() == {'type': 'array', 'items': 'File'} - first.inputs.file = [{'class': 'File', 'location': 'p.txt'}, {'class': 'File', 'location': 'q.txt'}] - first.scatter_on(first.inputs.file, first.inputs.str, method='nested_crossproduct') - assert lifted.effective_source_type() == { - 'type': 'array', 'items': {'type': 'array', 'items': 'File'}} - first.scatter_on(first.inputs.file, first.inputs.str, method='flat_crossproduct') - assert lifted.effective_source_type() == {'type': 'array', 'items': 'File'} - - -@pytest.mark.fast -def test_binding_a_path_reads_nothing_from_the_disk(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """A path is bound as written; it may name a place on another machine, such as a cluster.""" - monkeypatch.chdir(tmp_path) - Path('images.ome.zarr').mkdir() - here, elsewhere = _cat(), _cat() - local, remote = here.inputs.f, elsewhere.inputs.f - here.inputs.f = Path('images.ome.zarr') - elsewhere.inputs.f = Path('/cluster/images.ome.zarr') - assert local.effective_source_type() == remote.effective_source_type() # pylint: disable=no-member - - -@pytest.mark.fast -@pytest.mark.parametrize('source', ['go', ['go']]) -def test_a_string_is_never_a_step_input_source(source: Any) -> None: - """A bare string is never a reference: sources are port objects.""" - with pytest.raises(InvalidInputValueError, match='str'): - StepInput(source=source) - - -def _guard_and_message(record_first: bool) -> dict[str, Any]: - """`wf.inputs.go` read by a record on an undeclared input and by a plain `string` input.""" - e1, e2 = adapter_step('echo', 'e1', message='hi'), adapter_step('echo', 'e2') - wf = Workflow([e1, e2], 'order') - if record_first: - e1.inputs.go = StepInput(source=wf.inputs.go) - e2.inputs.message = wf.inputs.go - else: - e2.inputs.message = wf.inputs.go - e1.inputs.go = StepInput(source=wf.inputs.go) - e1.when = '$(inputs.go)' - return cast(dict[str, Any], wf.compile().cwl_workflow['inputs']) - - -@pytest.mark.fast -def test_a_record_on_an_undeclared_input_does_not_type_the_workflow_input() -> None: - """The workflow input's type does not depend on which binding came first.""" - assert _guard_and_message(True)['go']['type'] == _guard_and_message(False)['go']['type'] == 'string' - - -#: Statements of a user's script, `# here` on the line its diagnostic, or the step it makes, must name. -_SPANNED: Final = { - 'literal': ('scale = Step.from_cwl_document(SCALE, process_name="scale")', - 'scale.inputs.n = "not an int" # here', 'workflow = Workflow([scale], "wf")'), - 'bind': ('touch = Step(clt_path=TOUCH)', 'cat = Step(clt_path=CAT)', - 'cat.inputs.file = [touch.outputs.file] # here'), - 'order': ('touch = Step(clt_path=TOUCH)', 'cat = Step(clt_path=CAT) # here', - 'cat.inputs.file = touch.outputs.file', 'workflow = Workflow([cat, touch], "backwards")'), - 'made': ('step = Step(clt_path=TOUCH) # here',), -} - - -def _script(kind: str, depth: int, padding: list[str]) -> str: - lines = [*_SPANNED[kind], 'made.update(locals())'] - for _ in range(depth): - lines = ['def build():', *(f' {line}' for line in lines), 'build()'] - return '\n'.join([*padding, *lines]) + '\n' - - -@pytest.mark.fast -@given(st.sampled_from(sorted(_SPANNED)), st.integers(0, 2), - st.lists(st.sampled_from(['', '# note', 'pass']), max_size=3), - st.sampled_from(['', '', 'build.py', str(Path(__file__).with_name('built.py'))])) -@example('literal', 1, [], __file__) # a literal of the wrong type bound in a function is reported where it is bound -@example('literal', 0, ['import sophios'], 'build.py') # one bound at a script's top level, at the script's line -@example('bind', 1, [], __file__) # an error raised while binding names the bind, not a line inside Sophios -@example('order', 1, [], __file__) # a step listed before the step it reads from, where that step was made -@example('made', 0, [''], '') # code without a file keeps its pseudo-name, not a path under the cwd -@budget(20) -def test_a_diagnostic_names_the_python_line_that_made_its_object(kind: str, depth: int, padding: list[str], - file: str) -> None: - """A diagnostic names the line of the user's innermost frame that bound the port or made the step, under the - name its code was compiled with: a path resolved, a pseudo-name such as `` kept.""" - source = _script(kind, depth, padding) - line = next(number for number, text in enumerate(source.splitlines(), start=1) if text.endswith('# here')) - made: dict[str, Any] = {} - names = {'Step': Step, 'Workflow': Workflow, 'TOUCH': ADAPTERS / 'touch.cwl', 'CAT': ADAPTERS / 'cat.cwl', - 'made': made, 'SCALE': {'cwlVersion': 'v1.2', 'class': 'CommandLineTool', 'baseCommand': 'true', - 'inputs': {'n': 'int'}, 'outputs': {}}} - named = file if file.startswith('<') else str(Path(file).resolve()) - if kind == 'made': - exec(compile(source, file, 'exec'), names) # pylint: disable=exec-used - span = made['step']._span # pylint: disable=protected-access - else: - with pytest.raises({'literal': SophiosError, 'bind': InvalidInputValueError, - 'order': InvalidStepError}[kind]) as caught: - exec(compile(source, file, 'exec'), names) # pylint: disable=exec-used - made['workflow'].compile() - diagnostic = cast(SophiosError, caught.value).diagnostics[0] - span = diagnostic.span - assert kind != 'literal' or str(diagnostic).startswith(f'{named}:{line}:1: error [wic020]') - assert span is not None and (span.file, span.start_line) == (named, line) - - -@pytest.mark.fast -def test_a_cwl_workflow_as_a_step_clt_path_is_refused_with_python_advice(tmp_path: Path) -> None: - """A CWL Workflow given as a Step's `clt_path` is refused, naming that file and the Python fix.""" - say = tmp_path / 'say.cwl' - write_tree(tmp_path, { - 'say.cwl': '{class: Workflow, cwlVersion: v1.2, inputs: {text: string}, ' - 'outputs: {said: {type: File, outputSource: echo/out}}, ' - 'steps: {echo: {run: echo.cwl, in: {text: text}, out: [out]}}}', - 'echo.cwl': '{class: CommandLineTool, cwlVersion: v1.2, baseCommand: echo, ' - 'inputs: {text: string}, outputs: {out: stdout}}'}) - step = Step(clt_path=say) - step.inputs.text = 'hi' - with pytest.raises(SophiosError) as caught: - Workflow([step], 'wsay').compile() - diagnostic, = caught.value.diagnostics - assert diagnostic.code is SophiosErrorCode.SUBWORKFLOW_INVALID - assert diagnostic.message == ( - f"step 'say' runs {say}, a CWL Workflow given in Python as its clt_path. Sophios cannot embed " - 'a CWL Workflow as a step: build it in Python as a nested Workflow of Steps, or run the CWL ' - f'Workflow on its own with sophios --yaml {say} --allow_raw_cwl') - - -def _this_line() -> int: - """The line of the caller that calls this.""" - frame = inspect.currentframe() - assert frame is not None and frame.f_back is not None - return frame.f_back.f_lineno - - -@pytest.mark.fast -def test_run_async_refuses_a_workflow_with_real_time_analysis_before_anything_runs( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - """`api008`, at the declaration step's line; nothing is written, pulled or started.""" - touch = adapter_step('touch', filename='empty.txt') - subinterpreter = ADAPTERS / 'file_watchers' / 'cwl_subinterpreter.cwl' - declaration, declaration_line = Step(clt_path=subinterpreter), _this_line() - declaration.inputs.file_pattern = 'empty.txt' - declaration.inputs.cwl_tool = 'touch' - declaration.inputs.max_times = 2 - declaration.inputs.config = {'in': {'filename': 'again.txt'}} - prepared = no_preflight(monkeypatch) - monkeypatch.chdir(tmp_path) - - with pytest.raises(SophiosError) as raised: - asyncio.run(Workflow([touch, declaration], 'py_async').run_async()) - (diagnostic,) = raised.value.diagnostics - assert diagnostic.code is SophiosErrorCode.REALTIME_NOT_ASYNC - assert "'touch'" in diagnostic.message and 'run_async() never runs real-time analyses' in diagnostic.message - assert diagnostic.span is not None and diagnostic.span.start_line == declaration_line - assert Path(diagnostic.span.file) == Path(__file__).resolve() - assert not prepared and not list(tmp_path.iterdir()) + assert "Failure! step 'exits_3" in err and 'exited with status 3.' in err From b8bb95cb692515d739a261cee83d051d06b9f230 Mon Sep 17 00:00:00 2001 From: Vasu Jaganath Date: Fri, 13 Nov 2026 01:51:06 -0500 Subject: [PATCH 7/7] ci: every fast test gates a pull request The package job selects by exclusion, so the package marker and unused hermeticity self-tests go; pytest-xdist replaces pytest-parallel, which pytest 10 breaks. Doc merges are a compiler example; the eager check a property. --- .github/workflows/build_wheel.yml | 9 +- .github/workflows/lint_and_test.yml | 8 +- .github/workflows/property_weekly.yml | 3 +- .github/workflows/run_workflows.yml | 4 +- .github/workflows/run_workflows_weekly.yml | 8 +- docs/dev/devguide.md | 2 +- docs/dev/language_spec.md | 4 +- docs/validation.md | 2 +- pyproject.toml | 9 +- src/sophios/lang/support.py | 5 +- tests/core/_poison_plugins.py | 16 -- tests/core/compile_harness.py | 26 +-- tests/core/data/compiler/boundary/docs.wic | 20 ++ .../data/compiler/boundary/documented.cwl | 8 + .../core/data/compiler/boundary/expected.yaml | 11 + tests/core/data/infer/values/expected.yaml | 2 +- .../defaulted.cwl | 2 + .../workflow.wic | 3 +- tests/core/discovery_probe.py | 8 - tests/core/hermetic.py | 14 +- tests/core/test_backends.py | 6 - tests/core/test_basepath.py | 2 - tests/core/test_ci_coverage.py | 8 +- tests/core/test_compiler.py | 37 ---- tests/core/test_compute.py | 2 - tests/core/test_config.py | 2 - tests/core/test_cookbook.py | 2 - tests/core/test_diagnostics.py | 2 - tests/core/test_examples.py | 4 +- tests/core/test_frontdoor.py | 2 - tests/core/test_graph_features.py | 2 - tests/core/test_hermeticity.py | 191 ------------------ tests/core/test_inline_flags.py | 2 - tests/core/test_lang_parser.py | 1 - tests/core/test_nesting_scaling.py | 2 - tests/core/test_packing.py | 2 - tests/core/test_plugins.py | 10 +- tests/core/test_provenance.py | 2 - tests/core/test_python_api_draw.py | 2 - tests/core/test_python_api_inference.py | 2 - tests/core/test_python_api_workflow.py | 30 +-- tests/core/test_quiet.py | 2 - tests/core/test_realtime.py | 2 - tests/core/test_reference_compatibility.py | 43 ++-- tests/core/test_release.py | 2 - tests/core/test_run_local.py | 2 +- tests/core/test_settings_boundary.py | 2 - tests/core/test_support_matrix.py | 2 - tests/core/test_targets.py | 1 - tests/core/test_wic_defaults.py | 2 - 50 files changed, 118 insertions(+), 417 deletions(-) delete mode 100644 tests/core/_poison_plugins.py create mode 100644 tests/core/data/compiler/boundary/docs.wic create mode 100644 tests/core/data/compiler/boundary/documented.cwl delete mode 100644 tests/core/discovery_probe.py delete mode 100644 tests/core/test_hermeticity.py diff --git a/.github/workflows/build_wheel.yml b/.github/workflows/build_wheel.yml index c34f74d6b..c843f962d 100644 --- a/.github/workflows/build_wheel.yml +++ b/.github/workflows/build_wheel.yml @@ -31,12 +31,11 @@ jobs: - name: Install sophios 🔧 run: | pip install .[test] - # The tests marked package and the Nextflow tests that do not run - # Nextflow: no other pull-request lane runs them. + # Every test but those marked nextflow (no Nextflow here), cwl_corpus + # (no corpus checkout) or skip_pypi_ci: Lint And Test and Run + # Workflows run those. - name: Test with pytest - run: | - python -m pytest -m "package and not nextflow and not skip_pypi_ci" -vv - python -m pytest tests/core/nextflow -m "not nextflow and not nextflow_corpus and not skip_pypi_ci" -vv + run: python -m pytest -m "not skip_pypi_ci and not nextflow and not cwl_corpus" -vv - name: Build sophios run: | diff --git a/.github/workflows/lint_and_test.yml b/.github/workflows/lint_and_test.yml index c61dcf465..c00c9890e 100644 --- a/.github/workflows/lint_and_test.yml +++ b/.github/workflows/lint_and_test.yml @@ -256,13 +256,7 @@ jobs: - name: PyTest Environment-Dependent if: ${{ !cancelled() && steps.setup.outcome == 'success' }} timeout-minutes: 20 - run: cd sophios/ && pytest tests/core/test_predicates.py tests/core/test_leak_boundary.py tests/core/test_lang_version.py tests/core/test_lang_parser.py tests/core/test_hermeticity.py -m "skip_pypi_ci" - - # The suite's own hermeticity checks. Its own step, so a red build is - # attributable to a zone without bisecting. - - name: PyTest Oracle - if: ${{ !cancelled() && steps.setup.outcome == 'success' }} - run: cd sophios/ && pytest tests/core/test_hermeticity.py -m "not skip_pypi_ci" + run: cd sophios/ && pytest tests/core/test_predicates.py tests/core/test_leak_boundary.py tests/core/test_lang_version.py tests/core/test_lang_parser.py -m "skip_pypi_ci" # Phase contracts, the laws every compile keeps, and the compiler judged on # example workflows in files: what each compiles to on every leg, and what diff --git a/.github/workflows/property_weekly.yml b/.github/workflows/property_weekly.yml index b46cb5bfd..db6b30a4e 100644 --- a/.github/workflows/property_weekly.yml +++ b/.github/workflows/property_weekly.yml @@ -79,7 +79,7 @@ jobs: id: setup run: 'true' - # The oracle suite (tests/core/test_hermeticity.py::ORACLE_FILES) and the + # The oracle suite (tests/core/hermetic.py::ORACLE_FILES) and the # phase properties beside it, slow ones included: the `--validate` # property is slow-marked, and deepening it is the point of this lane. # test_leak_boundary.py's other test compiles against a discovered @@ -114,7 +114,6 @@ jobs: run: >- pytest tests/core/test_input_output.py tests/core/test_runtime_inputs.py tests/core/test_python_api_tool_builder.py tests/core/test_python_api_inference.py::test_an_inference_is_refused_at_construction_or_keeps_what_it_was_given - tests/core/test_python_api_workflow.py::test_python_api_uses_the_conservative_language_judgment tests/core/test_python_api_workflow.py::test_a_diagnostic_names_the_python_line_that_made_its_object tests/core/test_python_api_workflow.py::test_a_built_tool_is_one_step_through_every_door tests/core/test_realtime.py::test_a_declaration_is_returned_instead_of_emitted_or_is_wic044_at_each_port diff --git a/.github/workflows/run_workflows.yml b/.github/workflows/run_workflows.yml index ae4aaefff..1704061db 100644 --- a/.github/workflows/run_workflows.yml +++ b/.github/workflows/run_workflows.yml @@ -215,7 +215,7 @@ jobs: # One compile and a round of docker pulls per corpus workflow, mostly # waiting on the registry: 2.2 min in series, so it gets the same # workers as the runs that follow it. - run: cd sophios/ && pytest tests/core/test_examples.py -k test_cwl_docker_extract --workers "${PYTEST_WORKERS}" --durations=0 + run: cd sophios/ && pytest tests/core/test_examples.py -k test_cwl_docker_extract -n "${PYTEST_WORKERS}" --durations=0 # For self-hosted runners, make sure the docker cache is up-to-date. - name: PyTest Tool Builder @@ -240,7 +240,7 @@ jobs: - name: PyTest Run Workflows if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} - run: cd sophios/ && pytest tests/core/test_examples.py -k test_run_workflows_on_push --workers "${PYTEST_WORKERS}" --cwl_runner cwltool --durations=0 # --cov + run: cd sophios/ && pytest tests/core/test_examples.py -k test_run_workflows_on_push -n "${PYTEST_WORKERS}" --cwl_runner cwltool --durations=0 # --cov # The corpus workflows the Nextflow target supports, compiled with it and # run under Nextflow with Docker: tests/core/nextflow/test_corpus.py. The diff --git a/.github/workflows/run_workflows_weekly.yml b/.github/workflows/run_workflows_weekly.yml index 58828f5d7..9f4920f50 100644 --- a/.github/workflows/run_workflows_weekly.yml +++ b/.github/workflows/run_workflows_weekly.yml @@ -183,7 +183,7 @@ jobs: - name: PyTest Run Workflows (On Push) if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} # NOTE: Do NOT add coverage to PYPY CI runs https://github.com/tox-dev/tox/issues/2252 - run: cd sophios/ && pytest -k test_run_workflows_on_push --workers 8 --cwl_runner toil-cwl-runner --durations=0 # --cov + run: cd sophios/ && pytest -k test_run_workflows_on_push -n 8 --cwl_runner toil-cwl-runner --durations=0 # --cov - name: Disk usage (after workflows (on push)) if: ${{ !cancelled() && steps.setup.outcome == 'success' }} @@ -196,7 +196,7 @@ jobs: - name: PyTest Run Inlined Workflows (On Push) if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} # NOTE: Do NOT add coverage to PYPY CI runs https://github.com/tox-dev/tox/issues/2252 - run: cd sophios/ && pytest -k test_run_inlined_workflows_on_push --workers 8 --cwl_runner toil-cwl-runner --durations=0 # --cov + run: cd sophios/ && pytest -k test_run_inlined_workflows_on_push -n 8 --cwl_runner toil-cwl-runner --durations=0 # --cov - name: Disk usage (after inlined (on push)) if: ${{ !cancelled() && steps.setup.outcome == 'success' }} @@ -209,7 +209,7 @@ jobs: - name: PyTest Run Workflows (Weekly) if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} # NOTE: Do NOT add coverage to PYPY CI runs https://github.com/tox-dev/tox/issues/2252 - run: cd sophios/ && pytest -k test_run_workflows_weekly --workers 8 --cwl_runner toil-cwl-runner --durations=0 # --cov + run: cd sophios/ && pytest -k test_run_workflows_weekly -n 8 --cwl_runner toil-cwl-runner --durations=0 # --cov # The flat and the embedded forms of the weekly workflows, checked at # compile time; the pull-request lanes skip these workflows as large. @@ -229,7 +229,7 @@ jobs: - name: PyTest Run Inlined Workflows (Weekly) if: ${{ !cancelled() && steps.setup.outcome == 'success' && steps.corpus.outcome == 'success' }} # NOTE: Do NOT add coverage to PYPY CI runs https://github.com/tox-dev/tox/issues/2252 - run: cd sophios/ && pytest -k test_run_inlined_workflows_weekly --workers 8 --cwl_runner toil-cwl-runner --durations=0 # --cov + run: cd sophios/ && pytest -k test_run_inlined_workflows_weekly -n 8 --cwl_runner toil-cwl-runner --durations=0 # --cov - name: Disk usage (after inlined (weekly)) if: ${{ !cancelled() && steps.setup.outcome == 'success' }} diff --git a/docs/dev/devguide.md b/docs/dev/devguide.md index ac06c3d6b..221f439ea 100644 --- a/docs/dev/devguide.md +++ b/docs/dev/devguide.md @@ -69,7 +69,7 @@ falls back to the in-repository directories without writing one. ```bash pytest -m fast # the quick check: unit and API tests pytest tests/core/test_cookbook.py # the cookbook pairs -pytest -m "not serial" --workers 8 # the parallel part of the suite +pytest -m "not serial" -n 8 # the parallel part of the suite pytest -m serial # the rest ``` diff --git a/docs/dev/language_spec.md b/docs/dev/language_spec.md index b28aacf0d..0c6519f3a 100644 --- a/docs/dev/language_spec.md +++ b/docs/dev/language_spec.md @@ -128,8 +128,8 @@ step's tool is passthrough wholesale: Sophios does not classify | `type` | native | read for the reference judgment | `tests/core/data/compiler/refused` | | `format` | native | read by inference | `tests/core/data/compiler/boundary` | | `default` | passthrough | a relative File or Directory `location`/`path` is written absolute against the `.wic`'s directory | `tests/core/data/compiler/boundary`, `test_a_wic_file_default_is_written_absolute_against_the_wic` (`test_wic_defaults.py`) | -| `doc` | passthrough | | `test_a_referenced_input_merges_the_documentation_of_the_argument_it_binds` (`test_compiler.py`) | -| `label` | passthrough | | `test_a_referenced_input_merges_the_documentation_of_the_argument_it_binds` (`test_compiler.py`) | +| `doc` | passthrough | | `tests/core/data/compiler/boundary` | +| `label` | passthrough | | `tests/core/data/compiler/boundary` | | `inputBinding` | passthrough | | `tests/core/data/compiler/boundary` | | `loadContents` | passthrough | | `test_emit.py` | | `loadListing` | passthrough | | `test_emit.py` | diff --git a/docs/validation.md b/docs/validation.md index 0d7bc540e..b9e330384 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -40,7 +40,7 @@ surfaces'. The markers, declared in `pyproject.toml`: - `fast`: unit and API tests; `pytest -m fast` is the quick local check; - `slow`: workflow and integration tests; -- `serial`: tests that cannot run under `pytest --workers`; +- `serial`: tests that cannot run under `pytest -n`; - `needs_cwltool`: runs cwltool; skipped off POSIX; - `skip_pypi_ci`: left out of the release lane and the package job; - `contrib`: a contrib surface rather than the core compiler. diff --git a/pyproject.toml b/pyproject.toml index 47b7367ff..6932b84a2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -71,10 +71,9 @@ Homepage = "https://github.com/PolusAI/sophios" test = [ "networkx", "pre-commit", - "py", # See https://github.com/kevlened/pytest-parallel/pull/119 "pytest", "pytest-cov", - "pytest-parallel", + "pytest-xdist", "coverage", "mypy", "numpy", @@ -140,9 +139,6 @@ namespaces = true "*" = ["*.txt"] "sophios" = ["**/*.json"] -[tool.aliases] -test = "pytest --workers 8" - [tool.setuptools_scm] # A release is the tag vX.Y.Z that release-please puts on master. tag_regex = "^v(?P[0-9]+\\.[0-9]+\\.[0-9]+(?:[.-]dev[0-9]+)?)$" @@ -237,13 +233,12 @@ ignore_missing_imports = true markers = [ "fast: (i.e. for maximum speed, use 'pytest -m fast')", "slow: (i.e. for medium speed, use 'pytest -m \"not slow\"')", - "serial: (These tests CANNOT be run in parallel with --workers n > 1)", + "serial: (These tests CANNOT be run in parallel with -n n > 1)", "nextflow: invokes the installed Nextflow executable", "docker: requires a working Docker daemon", "nextflow_corpus: runs corpus workflows under Nextflow; only .github/workflows/run_workflows.yml collects it, on a push", "cwl_corpus: runs or reads the CWL corpus, the workflows search_paths_wic reaches in mm-workflows and image-workflows; Python Matrix Weekly leaves it out", "skip_pypi_ci: tests intentionally excluded from PyPI package-build CI", - "package: only the package job of build_wheel.yml collects it; no other pull-request lane runs it", "contrib: exercises a peripheral surface (ICT, Workflow Builder, REST) rather than the core compiler; run core only with 'pytest -m \"not contrib\"'", "needs_cwltool: runs cwltool; skipped off POSIX, see conftest.py", ] diff --git a/src/sophios/lang/support.py b/src/sophios/lang/support.py index 2d9ec976c..fe4fe9489 100644 --- a/src/sophios/lang/support.py +++ b/src/sophios/lang/support.py @@ -41,7 +41,6 @@ class Row: _OUTPUT_MERGE: Final = 'test_a_document_lowers_to_the_diagnostics_its_family_states' _PROMOTED_INPUT: Final = 'test_a_promoted_port_keeps_the_fields_a_workflow_port_may_state' _PROMOTED_OUTPUT: Final = 'test_a_promoted_port_keeps_the_fields_a_workflow_port_may_state' -_DOCUMENTED: Final = 'test_a_referenced_input_merges_the_documentation_of_the_argument_it_binds' _RECORD: Final = 'test_a_cwl_record_emits_the_fields_it_carries' WORKFLOW: Final[Mapping[str, Row]] = MappingProxyType({ @@ -104,8 +103,8 @@ class Row: 'type': Row(_N, 'test_a_compiler_example_compiles_as_it_states', 'read for the reference judgment'), 'format': Row(_N, 'test_a_compiler_example_compiles_as_it_states', 'read by inference'), 'default': Row(_P, _WRITTEN), - 'doc': Row(_P, _DOCUMENTED), - 'label': Row(_P, _DOCUMENTED), + 'doc': Row(_P, _WRITTEN), + 'label': Row(_P, _WRITTEN), 'inputBinding': Row(_P, _WRITTEN), 'loadContents': Row(_P, _PROMOTED_INPUT), 'loadListing': Row(_P, _PROMOTED_INPUT), diff --git a/tests/core/_poison_plugins.py b/tests/core/_poison_plugins.py deleted file mode 100644 index f7f023d46..000000000 --- a/tests/core/_poison_plugins.py +++ /dev/null @@ -1,16 +0,0 @@ -"""A pytest plugin (`-p core._poison_plugins`) that makes plugin discovery an error: a module reaching `get_tools_cwl` -or `get_yml_paths` fails loudly instead of reading whatever the machine has.""" -from typing import Any, NoReturn - -import sophios.plugins - - -def _poisoned(*_args: Any, **_kwargs: Any) -> NoReturn: - raise AssertionError( - 'plugin discovery reached under the hermeticity run') - - -# setattr, not `sophios.plugins.get_tools_cwl = _poisoned`: pylint reads that assignment, takes every call to -# these functions in the repo for a call that never returns (NoReturn) and reports the code after it as unreachable. -for _name in ('get_tools_cwl', 'get_yml_paths'): - setattr(sophios.plugins, _name, _poisoned) diff --git a/tests/core/compile_harness.py b/tests/core/compile_harness.py index 7062bd78b..67d9d34ae 100644 --- a/tests/core/compile_harness.py +++ b/tests/core/compile_harness.py @@ -1,4 +1,4 @@ -"""One way to compile an in-memory workflow with the real registry: the typed result, or only the emitted CWL.""" +"""One way to compile an in-memory workflow with the real registry.""" import sophios.cli import sophios.compiler from sophios.ir.artifacts import CompilationResult @@ -12,26 +12,8 @@ FAST = budget(200) COMPILED = budget(100) -#: A minimal real workflow: one tool step, one inline literal input. -TOUCH: Yaml = {'steps': [{'id': 'touch', 'in': {'filename': {'wic_inline_input': 'empty.txt'}}}]} - -def compile_info(yml: Yaml, name: str = 'harness', *, - lang_version: str | None = None, - allow_raw_cwl: bool | None = None) -> CompilationResult: - """Compile one in-memory workflow; the overrides are named so a typo is a type error.""" - compiler_options = sophios.cli.default_compilation_settings() - if lang_version is not None: - compiler_options['lang_version'] = lang_version - if allow_raw_cwl is not None: - compiler_options['allow_raw_cwl'] = allow_raw_cwl +def compile_info(yml: Yaml, name: str = 'harness') -> CompilationResult: + """Compile one in-memory workflow against the discovered registry.""" return sophios.compiler.compile_source( - bundle(yml, name, load_test_registry().tools), compiler_options, - quiet=True) - - -def compile_cwl(yml: Yaml, name: str = 'harness', *, - lang_version: str | None = None, - allow_raw_cwl: bool | None = None) -> Yaml: - """Compile one in-memory workflow and return the emitted CWL.""" - return compile_info(yml, name, lang_version=lang_version, allow_raw_cwl=allow_raw_cwl).artifact.cwl + bundle(yml, name, load_test_registry().tools), sophios.cli.default_compilation_settings(), quiet=True) diff --git a/tests/core/data/compiler/boundary/docs.wic b/tests/core/data/compiler/boundary/docs.wic new file mode 100644 index 000000000..c9b6ffe30 --- /dev/null +++ b/tests/core/data/compiler/boundary/docs.wic @@ -0,0 +1,20 @@ +# A workflow input keeps what its author wrote and appends what each argument it binds documents, joined by one real +# newline: no empty text, no synthesized field, no list. An undocumented argument, or one documenting it again, adds +# nothing. +inputs: + none: {type: string} # nothing to merge + own: {type: string, doc: mine, label: keep me} # the author wrote it all + plain: {type: string} # the argument documents a bare input + both: {type: string, doc: mine, label: keep me} # both wrote it + mine: {type: string, doc: mine} # the argument's doc is a list + listed: {type: string, doc: [one, two]} # the author's doc is a list + lists: {type: string, doc: [a, b]} # both are lists +steps: +- id: documented + in: {bare: none, text: plain, listed: mine} +- id: documented + in: {bare: own, text: both, listed: lists} +- id: documented + in: {bare: plain, text: listed} +- id: documented + in: {bare: mine, text: plain} diff --git a/tests/core/data/compiler/boundary/documented.cwl b/tests/core/data/compiler/boundary/documented.cwl new file mode 100644 index 000000000..a9287277f --- /dev/null +++ b/tests/core/data/compiler/boundary/documented.cwl @@ -0,0 +1,8 @@ +cwlVersion: v1.2 +class: CommandLineTool +baseCommand: 'true' +inputs: + bare: string? + text: {type: 'string?', doc: the file name, label: File name} + listed: {type: 'string?', doc: [one, two]} +outputs: {} diff --git a/tests/core/data/compiler/boundary/expected.yaml b/tests/core/data/compiler/boundary/expected.yaml index a2d03c95f..ad54baede 100644 --- a/tests/core/data/compiler/boundary/expected.yaml +++ b/tests/core/data/compiler/boundary/expected.yaml @@ -60,3 +60,14 @@ format_expression.wic: inputs: formatted~reference: {format: $(inputs.source.format)} formatted~body: {format: '${ return inputs.source.format; }'} +docs.wic: + written: + docs.cwl: + inputs: + none: {exact: {type: string}} + own: {exact: {type: string, doc: mine, label: keep me}} + plain: {exact: {type: string, doc: the file name, label: File name}} + both: {exact: {type: string, doc: "mine\nthe file name", label: "keep me\nFile name"}} + mine: {exact: {type: string, doc: "mine\none\ntwo"}} + listed: {exact: {type: string, doc: "one\ntwo\nthe file name", label: File name}} + lists: {exact: {type: string, doc: "a\nb\none\ntwo"}} diff --git a/tests/core/data/infer/values/expected.yaml b/tests/core/data/infer/values/expected.yaml index abec90458..01093415b 100644 --- a/tests/core/data/infer/values/expected.yaml +++ b/tests/core/data/infer/values/expected.yaml @@ -13,4 +13,4 @@ iteration_exhaustion_is_exactly_wic022: - {code: FIXED_POINT_NOT_REACHED, severity: error} falsy_defaults_satisfy_inputs: edges: {exact: {}} - inputs: [] + inputs: [defaulted~nulled] diff --git a/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/defaulted.cwl b/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/defaulted.cwl index bfe3941c8..c97f97d25 100644 --- a/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/defaulted.cwl +++ b/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/defaulted.cwl @@ -6,4 +6,6 @@ inputs: flag: {type: boolean, default: false} text: {type: string, default: ''} items: {type: 'string[]', default: []} + nulled: {type: File, default: null} + maybe: {type: 'File?', default: null} outputs: {} diff --git a/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/workflow.wic b/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/workflow.wic index 13c80ca0d..e0e750675 100644 --- a/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/workflow.wic +++ b/tests/core/data/infer/values/falsy_defaults_satisfy_inputs/workflow.wic @@ -1,3 +1,4 @@ -# Presence, not truthiness, suppresses inference for a defaulted port: none is inferred or lifted. +# Presence, not truthiness, suppresses inference for a defaulted port, but a null default satisfies only a type that +# admits null: none is inferred, and `nulled` alone is lifted. steps: - id: defaulted diff --git a/tests/core/discovery_probe.py b/tests/core/discovery_probe.py deleted file mode 100644 index e17aa4b57..000000000 --- a/tests/core/discovery_probe.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Deliberately unhermetic probe proving the runtime poison fires; not a `test_*.py` name, it is invoked explicitly -under the poison plugin.""" -import sophios.plugins - - -def test_plugin_discovery_is_attempted() -> None: - """Reach the operation the hermetic oracle must never call.""" - sophios.plugins.get_tools_cwl({}) diff --git a/tests/core/hermetic.py b/tests/core/hermetic.py index 5eeae1d05..b7086e3b0 100644 --- a/tests/core/hermetic.py +++ b/tests/core/hermetic.py @@ -1,5 +1,5 @@ """Compilation with no environment: compile_harness compiles against the registry test_setup discovers, so this -sibling compiles against SYNTHETIC_TOOLS and runs with discovery poisoned under the hermeticity property.""" +sibling compiles against SYNTHETIC_TOOLS.""" import socket from collections.abc import Iterator from contextlib import contextmanager @@ -26,6 +26,18 @@ ORACLE: Final = budget(100) PARTITION: Final = budget(50) +#: The oracle suite: test files whose properties compile against SYNTHETIC_TOOLS alone, so the weekly property lane +#: deepens them on a bare hosted runner. +ORACLE_FILES: Final = ( + 'tests/core/test_predicates.py', + 'tests/core/test_reference_compatibility.py', + 'tests/core/test_canonical_path.py', + 'tests/core/test_emit.py', + 'tests/core/test_resolve.py', + 'tests/core/test_infer_phase.py', + 'tests/core/test_edge_binding.py', +) + @contextmanager def network_refused() -> Iterator[list[str]]: diff --git a/tests/core/test_backends.py b/tests/core/test_backends.py index ee5b1dbdb..eadcee405 100644 --- a/tests/core/test_backends.py +++ b/tests/core/test_backends.py @@ -26,12 +26,6 @@ from .helpers import adapter_step, write_tree from .nextflow.testkit import runtime_workflow -pytestmark = pytest.mark.package - - -def _argv(request: RunRequest) -> list[str]: - return list(targets.backend(request.target, request.runner).launch(request).argv) - class _Frozen(backends.datetime): @classmethod diff --git a/tests/core/test_basepath.py b/tests/core/test_basepath.py index 162ab9aa9..181c65056 100644 --- a/tests/core/test_basepath.py +++ b/tests/core/test_basepath.py @@ -16,8 +16,6 @@ from .cases import DATA from .helpers import EACH_RUNNER, no_preflight, run_cli, search_config -pytestmark = pytest.mark.package - @pytest.fixture(name='project') def _project(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: diff --git a/tests/core/test_ci_coverage.py b/tests/core/test_ci_coverage.py index 70a6f2c38..0b6db0012 100644 --- a/tests/core/test_ci_coverage.py +++ b/tests/core/test_ci_coverage.py @@ -146,7 +146,7 @@ def test_the_weekly_property_lane_runs_the_whole_oracle_suite() -> None: lets the weekly lane run on a bare hosted runner. A file added there and not to the lane would be deepened nowhere, and nothing else would notice. """ - from .test_hermeticity import ORACLE_FILES # pylint: disable=import-outside-toplevel + from .hermetic import ORACLE_FILES # pylint: disable=import-outside-toplevel *lanes, oracle = _collect_all([*_invocations(WORKFLOWS / 'property_weekly.yml'), list(ORACLE_FILES)]) missing = sorted(oracle - set().union(*lanes)) @@ -159,9 +159,9 @@ def test_the_corpus_lane_round_trips_every_wic_root_through_the_python_api() -> `test_python_api_from_wic.py` parametrizes its corpus property over every `.wic` root `search_paths_wic` reaches. Only `run_workflows.yml` writes a - config that reaches the mm-workflows and image-workflows roots; the - package job does not select the file, and checks out neither corpus, so - the property would see the repository's own roots and nothing else. + config that reaches the mm-workflows and image-workflows roots; every + other lane checks out neither corpus, so there the property sees the + repository's own roots and nothing else. """ properties = { 'tests/core/test_python_api_from_wic.py::test_a_wic_file_and_its_python_objects_compile_alike', diff --git a/tests/core/test_compiler.py b/tests/core/test_compiler.py index bf7a01756..5d0ced81b 100644 --- a/tests/core/test_compiler.py +++ b/tests/core/test_compiler.py @@ -2,7 +2,6 @@ expected.yaml states (every platform) and runs under cwltool to the outputs it states (POSIX); each example of tests/core/data/compiler compiles, or is refused, as its expected.yaml states.""" import contextlib -import copy import io from pathlib import Path from typing import Any, cast @@ -22,7 +21,6 @@ from .cases import DATA, diagnostic, match from .helpers import cwltool_outputs, example_workflow, examples, files_beside, observed, stated -from .hermetic import compile_hermetic_cwl from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS @@ -130,38 +128,3 @@ def test_a_compiler_example_compiles_as_it_states(folder: Path, tmp_path: Path, mine = [name for name in written if name.split('~')[0] in (f'{stem}.cwl', stem, f'{stem}_inputs.yml')] assert 'files' not in expected or mine == expected['files'], root assert match(expected.get('written', {}), written), root - - -@pytest.mark.fast -@pytest.mark.parametrize(('claim', 'user', 'argument', 'expected'), [ - ('nothing to merge', {}, {}, {}), - ('the user wrote it all', {'doc': 'mine', 'label': 'keep me'}, {}, - {'doc': 'mine', 'label': 'keep me'}), - ('the argument documents a bare input', {}, {'doc': 'the file name'}, - {'doc': 'the file name'}), - ('both, joined by one real newline', {'doc': 'mine', 'label': 'keep me'}, - {'doc': 'the file name', 'label': 'File name'}, - {'doc': 'mine\nthe file name', 'label': 'keep me\nFile name'}), - ('argument doc is a list', {'doc': 'mine'}, {'doc': ['one', 'two']}, {'doc': 'mine\none\ntwo'}), - ('user doc is a list', {'doc': ['one', 'two']}, {'doc': 'theirs'}, {'doc': 'one\ntwo\ntheirs'}), - ('both are lists', {'doc': ['a', 'b']}, {'doc': ['c', 'd']}, {'doc': 'a\nb\nc\nd'}), -]) -def test_a_referenced_input_merges_the_documentation_of_the_argument_it_binds( - claim: str, user: Yaml, argument: Yaml, expected: Yaml) -> None: - """A workflow input keeps what its author wrote and appends what the bound - argument documents: no empty text, no synthesized field, no Python repr of - a list (CWL types `doc` as `string | string[]`; `label` is string-only), - and a newline character rather than the two-character escape. - - Two steps reference the input and only `mk_text.name` is documented, so an - undocumented reference adds nothing. - """ - tools = copy.deepcopy(SYNTHETIC_TOOLS) - tools[StepId('mk_text', SYNTHETIC_NS)].cwl['inputs']['name'].update(argument) - document: Yaml = { - 'inputs': {'wf_name': {'type': 'string', **user}}, - 'steps': [{'id': 'mk_text', 'in': {'name': 'wf_name'}}, - {'id': 'mk_file', 'in': {'name': 'wf_name'}}], - } - compiled = compile_hermetic_cwl(document, 'docs', tools=tools) - assert compiled['inputs']['wf_name'] == {'type': 'string', **expected}, claim diff --git a/tests/core/test_compute.py b/tests/core/test_compute.py index 19705ef1b..aa42e924d 100644 --- a/tests/core/test_compute.py +++ b/tests/core/test_compute.py @@ -35,8 +35,6 @@ from .cases import cases, match from .helpers import REPO_ROOT, live_workflow, python_process -pytestmark = pytest.mark.package - DOCS = REPO_ROOT / 'docs' diff --git a/tests/core/test_config.py b/tests/core/test_config.py index f7ef4763e..2950539e9 100644 --- a/tests/core/test_config.py +++ b/tests/core/test_config.py @@ -10,8 +10,6 @@ from .cases import DATA from .helpers import run_cli -pytestmark = pytest.mark.package - @pytest.mark.fast def test_an_explicit_config_file_is_only_read(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, diff --git a/tests/core/test_cookbook.py b/tests/core/test_cookbook.py index cdf4a35d5..e2998e9e2 100644 --- a/tests/core/test_cookbook.py +++ b/tests/core/test_cookbook.py @@ -27,8 +27,6 @@ from .test_setup import home_with_shipped_tools, use_home from .wic_reading import read_wic -pytestmark = pytest.mark.package - COOKBOOK = REPO_ROOT / 'docs' / 'cookbook' PYTHON_PAIRS = DATA / 'python_api_pairs' diff --git a/tests/core/test_diagnostics.py b/tests/core/test_diagnostics.py index 585ab7f68..cd9843db7 100644 --- a/tests/core/test_diagnostics.py +++ b/tests/core/test_diagnostics.py @@ -32,8 +32,6 @@ from .synthetic_tools import clt, registered from .test_lang_parser import FAST -pytestmark = pytest.mark.package - _TYPES: Final = {'int': int, 'long': int, 'float': float, 'double': float, 'boolean': bool, 'string': str} _TEXTS = st.text('07.e+-:axy', max_size=4) _READ_BACK: Final[dict[type, Callable[[str], Any]]] = {str: str, int: int, float: float, diff --git a/tests/core/test_examples.py b/tests/core/test_examples.py index b6a9e0314..e77a0c117 100644 --- a/tests/core/test_examples.py +++ b/tests/core/test_examples.py @@ -314,7 +314,7 @@ def handler(_signum, _frame): # type: ignore if sys.platform == 'win32': # No SIGALRM on Windows: a plain call; the CI job has its own timeout. assert g_m.is_isomorphic() else: - # SIGALRM works only in the main thread, so not under --workers. + # SIGALRM is delivered to the main thread only. signal.signal(signal.SIGALRM, handler) signal.alarm(10) assert g_m.is_isomorphic() @@ -421,7 +421,7 @@ def test_corpus_compiles_clean_in_every_form(yml_path_str: str, yml_path: Path, the inline flags give means what the nested form means; each real-time analysis it declares compiles. cwltool finds each defect these find, but only in a run, behind a container pull: here each costs a compile. - Serial: the isomorphism check's alarm works only in the main thread, so not under --workers.""" + Serial: the isomorphism check's alarm needs the main thread.""" result = _compile_corpus_workflow(yml_path_str, yml_path, corpus_registry) options = sophios.cli.get_dicts_for_compilation(get_args(str(yml_path)))[0] _check_residue(result.artifact) diff --git a/tests/core/test_frontdoor.py b/tests/core/test_frontdoor.py index cfd59a467..be33fb9cf 100644 --- a/tests/core/test_frontdoor.py +++ b/tests/core/test_frontdoor.py @@ -36,8 +36,6 @@ from .cases import DATA, case_dirs, cases from .synthetic_tools import SYNTHETIC_TOOLS -pytestmark = pytest.mark.package - DOOR: Final = DATA / 'frontdoor' diff --git a/tests/core/test_graph_features.py b/tests/core/test_graph_features.py index aadae6bb5..34f849be1 100644 --- a/tests/core/test_graph_features.py +++ b/tests/core/test_graph_features.py @@ -14,8 +14,6 @@ from .cases import DATA, match from .helpers import no_preflight, run_cli -pytestmark = pytest.mark.package - DRAWING: Final = DATA / 'drawing' #: A node or edge name in DOT: quoted, or a bare word. _ID = r'"[^"]*"|\w+' diff --git a/tests/core/test_hermeticity.py b/tests/core/test_hermeticity.py deleted file mode 100644 index a97dde1dd..000000000 --- a/tests/core/test_hermeticity.py +++ /dev/null @@ -1,191 +0,0 @@ -"""The oracle suite is hermetic. - -These properties are statements about the compiler. A property whose inputs -come from `get_tools_cwl` is a statement about the compiler *and* about which -plugin repositories the machine has checked out, and when it fails the two -cannot be told apart. - -Checked by running the oracle suite in a subprocess with plugin discovery -poisoned. CANNOT DETECT: a module the run does not execute, and any environment -dependence that is not an import — reading a file, an environment variable, or -the network. -""" -import os -import subprocess -import sys -import tempfile -from pathlib import Path -from typing import Any, Final - -import pytest - -from .synthetic_tools import SCHEMA_TYPES, STEMS, SYNTHETIC_TOOLS, inputs_of, outputs_of, required_inputs_of - -TESTS_ROOT = Path(__file__).resolve().parents[1] -REPO_ROOT = TESTS_ROOT.parent - - -#: Declarations whose required-ness turns on a default's presence rather than -#: its truthiness, beside every synthetic input. -_DEFAULTED: Final = ( - ({'type': 'boolean', 'default': False}, False), - ({'type': 'string', 'default': ''}, False), - ({'type': 'File[]', 'default': []}, False), - ({'type': 'File', 'default': None}, True), - ({'type': ['null', 'File'], 'default': None}, False), -) - - -@pytest.mark.fast -@pytest.mark.parametrize('raw, expected', [ - *((inputs_of(stem)[name], name in required_inputs_of(stem)) - for stem in STEMS for name in inputs_of(stem)), - *_DEFAULTED, -]) -def test_required_inputs_agree_with_the_compilers_own_rule(raw: Any, expected: bool) -> None: - """`required_inputs_of`, the generator's independent model, and the - compiler's `declarations.required` agree. A present default satisfies an - input however falsy; `null` satisfies only a type that admits it.""" - from sophios.ir.declarations import port_declaration, required # pylint: disable=import-outside-toplevel - - assert required(port_declaration(raw)) is expected - - -@pytest.mark.fast -def test_the_registry_reaches_the_branches_it_claims_to() -> None: - """A registry that cannot reach a branch silently disables every property - that depends on it — the generator-adequacy argument, applied to the tools.""" - assert any(inputs_of(s).get('value', {}).get('type') == ['int', 'string'] for s in STEMS), \ - 'no union-typed input: types_match list branches unreachable' - assert any(outputs_of(s) == {} for s in STEMS), 'no terminal tool' - assert any(len(required_inputs_of(s)) < len(inputs_of(s)) for s in STEMS), \ - 'every input is required: the optional-argument path is unreachable' - formats = {o.get('format') for s in STEMS for o in outputs_of(s).values()} - assert len({f for f in formats if f}) >= 2, 'one format: inference never has to choose' - assert any(len(outputs_of(s)) > 1 for s in STEMS), 'no tool promotes several outputs' - assert any(i.get('type') == 'Directory' for s in STEMS for i in inputs_of(s).values()), \ - 'no Directory input: its job value is never coerced' - declared = [i for s in STEMS for i in inputs_of(s).values()] - structured = {i['type'].get('type') for i in declared if isinstance(i['type'], dict)} - assert 'record' in structured, 'no record input: a record type never reaches a port' - assert 'enum' in structured, 'no enum input: enum symbols never reach a port' - assert any(isinstance(i['type'], str) and i['type'] in SCHEMA_TYPES for i in declared), \ - 'no input names a SchemaDefRequirement type' - assert any('secondaryFiles' in i and 'loadContents' in i for i in declared), \ - 'no input with secondaryFiles and loadContents: a promoted boundary never carries them' - assert any(o.get('type') == 'stdout' for s in STEMS for o in outputs_of(s).values()), \ - 'no stdout output: the tool-only type never reaches a workflow' - assert any(isinstance(t.cwl.get('requirements'), list) and isinstance(t.cwl.get('hints'), list) - for t in SYNTHETIC_TOOLS.values()), \ - 'no list-form requirements and hints: only the mapping form is ever read' - - -#: Test files whose passing constitutes "the oracle suite ran with plugin -#: discovery disabled". -ORACLE_FILES: tuple[str, ...] = ( - 'tests/core/test_predicates.py', - 'tests/core/test_reference_compatibility.py', - 'tests/core/test_canonical_path.py', - 'tests/core/test_emit.py', - 'tests/core/test_resolve.py', - 'tests/core/test_infer_phase.py', - 'tests/core/test_edge_binding.py', -) - - -#: The exact wording `_poisoned` (tests/core/_poison_plugins.py) raises. -#: Asserted against verbatim below, not just a nonzero exit code: pytest -#: returns nonzero for plenty of reasons that have nothing to do with the -#: poison firing — an ImportError while loading `-p` among them, which is -#: exactly the failure `_run_poisoned`'s explicit `PYTHONPATH` now prevents. -POISON_MESSAGE = 'plugin discovery reached under the hermeticity run' - - -def _run_poisoned(targets: tuple[str, ...]) -> subprocess.CompletedProcess[str]: - """Run pytest over `targets` with discovery poisoned and no config to read. - - `PYTHONPATH` is set explicitly to `src:tests` rather than inherited from - `os.environ`. `-p core._poison_plugins` is resolved at pytest's - `consider_preparse`, before collection would otherwise put `tests/` on - `sys.path` — so without `tests/` on `PYTHONPATH` up front, the plugin - itself fails to import (`ImportError: No module named 'core'`) and every - caller of this function fails for that reason instead of the one it - claims to test. Built explicitly, not merged with an inherited value: a - `PYTHONPATH` that happens to already include `tests/` in one shell is not - evidence this works in general. - - Joined with `os.pathsep`, not `':'`. On Windows a hardcoded colon makes - `D:\\...\\src:D:\\...\\tests` one unparsable entry — `tests/` never - reaches `sys.path`, and both callers then fail on the very `ImportError` - the explicit `PYTHONPATH` exists to prevent. - """ - python_path = os.pathsep.join((str(REPO_ROOT / 'src'), str(REPO_ROOT / 'tests'))) - env = {**os.environ, 'HOME': str(Path(tempfile.mkdtemp())), 'PYTHONPATH': python_path} - return subprocess.run( - [sys.executable, '-m', 'pytest', '-p', 'core._poison_plugins', '-q', - '-m', 'not slow', *targets], - cwd=REPO_ROOT, env=env, capture_output=True, text=True, check=False) - - -@pytest.mark.slow -@pytest.mark.serial -def test_the_oracle_suite_passes_with_plugin_discovery_disabled() -> None: - """Runtime half. `HOME` is redirected too: `get_config` writes - ~/wic/global_config.json when it is missing, so a suite that reads the - config is not merely environment-dependent, it provisions the environment. - """ - result = _run_poisoned(ORACLE_FILES) - assert result.returncode == 0, result.stdout + result.stderr - - -@pytest.mark.slow -@pytest.mark.serial -def test_the_poison_fires_on_a_suite_that_needs_discovery() -> None: - """The companion probe deliberately calls plugin discovery. - - Corpus fixtures no longer discover plugins during collection, so a - purpose-built, non-default-collected probe is the stable way to prove the - poison is installed. If it passes, the run above proved nothing. - - Asserts `POISON_MESSAGE` appears in the output, not merely that the - subprocess exits nonzero: pytest exits nonzero for reasons unrelated to - the poison too (a bad `-p` import, "no tests ran"), and a bare `!= 0` - check is satisfied by any of them just as well as by the poison firing — - which is exactly how this test passed for the wrong reason before. - """ - result = _run_poisoned(('tests/core/discovery_probe.py',)) - output = result.stdout + result.stderr - assert result.returncode != 0, output - assert POISON_MESSAGE in output, output - - -def _budgets_under(scale: str | None) -> subprocess.CompletedProcess[str]: - """Import the budgets in a fresh interpreter with `scale` set, or unset.""" - env = {key: value for key, value in os.environ.items() if key != 'SOPHIOS_PROPERTY_SCALE'} - if scale is not None: - env['SOPHIOS_PROPERTY_SCALE'] = scale - env['PYTHONPATH'] = os.pathsep.join((str(REPO_ROOT / 'src'), str(REPO_ROOT / 'tests'))) - probe = ('from core import hermetic, compile_harness as c; ' - 'print("budgets:", hermetic.COVERAGE.max_examples, hermetic.ORACLE.max_examples, ' - 'hermetic.PARTITION.max_examples, c.FAST.max_examples, c.COMPILED.max_examples)') - return subprocess.run([sys.executable, '-c', probe], cwd=REPO_ROOT, env=env, - capture_output=True, text=True, check=False) - - -def _budgets(result: subprocess.CompletedProcess[str]) -> list[str]: - """The probe's own line; importing the modules may print others (on - Windows, a notice that `cwltoil` is missing).""" - lines = [line for line in result.stdout.splitlines() if line.startswith('budgets:')] - assert len(lines) == 1, result.stdout + result.stderr - return lines[0].split()[1:] - - -@pytest.mark.fast -def test_the_property_scale_multiplies_every_budget_and_is_one_by_default() -> None: - """An ordinary run draws exactly the examples it always did; the weekly - lane's knob multiplies every shared budget; a knob that is not a positive - integer stops the run rather than silently drawing nothing.""" - assert _budgets(_budgets_under(None)) == ['500', '100', '50', '200', '100'] - assert _budgets(_budgets_under('3')) == ['1500', '300', '150', '600', '300'] - refused = _budgets_under('0') - assert refused.returncode != 0 and 'SOPHIOS_PROPERTY_SCALE' in refused.stderr diff --git a/tests/core/test_inline_flags.py b/tests/core/test_inline_flags.py index 1c884260a..3285135f8 100644 --- a/tests/core/test_inline_flags.py +++ b/tests/core/test_inline_flags.py @@ -24,8 +24,6 @@ from .test_compiler import _tools from .test_setup import workflow_paths -pytestmark = pytest.mark.package - TREE = DATA / 'inline' diff --git a/tests/core/test_lang_parser.py b/tests/core/test_lang_parser.py index f68b53a72..b7de56e7d 100644 --- a/tests/core/test_lang_parser.py +++ b/tests/core/test_lang_parser.py @@ -484,7 +484,6 @@ def test_the_corpus_parses_validates_and_round_trips() -> None: assert not failed, failed -@pytest.mark.package @pytest.mark.fast def test_reading_writing_and_the_schema_share_no_state() -> None: """Parsing, rendering and the schema export keep nothing between calls. A parse leaves `yaml.safe_load` blind to diff --git a/tests/core/test_nesting_scaling.py b/tests/core/test_nesting_scaling.py index 598aca1b5..44d5d0dbc 100644 --- a/tests/core/test_nesting_scaling.py +++ b/tests/core/test_nesting_scaling.py @@ -13,8 +13,6 @@ from .hermetic import compile_hermetic, nested_workflow -pytestmark = pytest.mark.package - #: The most a cost may multiply by per nesting level. Polynomial growth in the #: depth stays under 1.2 over the depths used here; doubling per level is 2. MAX_GROWTH_PER_LEVEL: Final = 1.4 diff --git a/tests/core/test_packing.py b/tests/core/test_packing.py index 2900cceb7..8ea93fea4 100644 --- a/tests/core/test_packing.py +++ b/tests/core/test_packing.py @@ -26,8 +26,6 @@ from .cases import DATA from .helpers import ADAPTERS, EACH_RUNNER, no_preflight, run_cli, run_local_process, search_config -pytestmark = pytest.mark.package - PROJECT: Final = DATA / 'packing' TOOLS: Final = PROJECT / 'tools' #: What `relcat` includes and prints. diff --git a/tests/core/test_plugins.py b/tests/core/test_plugins.py index e2f1cbc6f..3e92028ce 100644 --- a/tests/core/test_plugins.py +++ b/tests/core/test_plugins.py @@ -1,8 +1,6 @@ -"""Behavioural coverage for `sophios.plugins` transforms that reach emitted CWL, and for discovery; the oracle cannot -import it (FORBIDDEN in test_hermeticity.py), as importing reads the config. Partial failure is covered here too: what - -`--partial_failure_enable` writes, through the command line, and the rule a tool is written by, over every form its -outputs take, the list among them, which the command line's canonical form never shows.""" +"""Behavioural coverage for `sophios.plugins` transforms that reach emitted CWL, and for discovery. Partial failure is +covered here too: what `--partial_failure_enable` writes, through the command line, and the rule a tool is written by, +over every form its outputs take, the list among them, which the command line's canonical form never shows.""" import copy import glob import os @@ -28,8 +26,6 @@ from .cases import DATA, cases, match from .helpers import ADAPTERS, run_cli, search_config -pytestmark = pytest.mark.package - @pytest.mark.fast def test_partial_failure_and_entrypoint_removal_write_what_their_example_states( diff --git a/tests/core/test_provenance.py b/tests/core/test_provenance.py index 8c5b54742..19f058209 100644 --- a/tests/core/test_provenance.py +++ b/tests/core/test_provenance.py @@ -8,8 +8,6 @@ from .cases import DATA from .helpers import EACH_RUNNER, run_local_process -pytestmark = pytest.mark.package - PROJECT: Final = DATA / 'provenance_runs' diff --git a/tests/core/test_python_api_draw.py b/tests/core/test_python_api_draw.py index db94a62df..fcf6acafb 100644 --- a/tests/core/test_python_api_draw.py +++ b/tests/core/test_python_api_draw.py @@ -9,8 +9,6 @@ from .helpers import adapter_step -pytestmark = pytest.mark.package - def _workflow() -> Workflow: """`touch` feeds `append` by an edge written here, and `append` feeds `cat` by an edge inference adds; a workflow diff --git a/tests/core/test_python_api_inference.py b/tests/core/test_python_api_inference.py index fb52cad00..908376053 100644 --- a/tests/core/test_python_api_inference.py +++ b/tests/core/test_python_api_inference.py @@ -22,8 +22,6 @@ from .budgets import budget from .helpers import search_config -pytestmark = pytest.mark.package - RENAMINGS = (("data", "file"),) diff --git a/tests/core/test_python_api_workflow.py b/tests/core/test_python_api_workflow.py index 4030fd7fc..0b845f543 100644 --- a/tests/core/test_python_api_workflow.py +++ b/tests/core/test_python_api_workflow.py @@ -31,9 +31,9 @@ from sophios.backends import RunRequest from sophios.api.python import nextflow from sophios.api.python.tool_builder import CommandLineTool, Input, Inputs, Output, Outputs, cwl -from sophios.api.python.workflow import (_python_api_types_match, InvalidInputValueError, InvalidLinkError, - InvalidStepError, RunPolicy, RunResult, RunState, RunStatus, SophiosError, - Step, StepInput, Workflow, WorkflowRunError) +from sophios.api.python.workflow import (InvalidInputValueError, InvalidLinkError, InvalidStepError, RunPolicy, + RunResult, RunState, RunStatus, SophiosError, Step, StepInput, Workflow, + WorkflowRunError) from sophios.lang.diagnostics import lines as printed_lines from sophios.python_cwl_adapter import import_python_file from sophios.wic_types import Json, Tools @@ -41,8 +41,6 @@ from .budgets import budget from .cases import DATA from .helpers import ADAPTERS, adapter_step, echo_workflow, no_preflight, python_process -from .reference_model import ReferenceExpectation, reference_expectation -from .strategies import cwl_types from .wic_reading import read_wic PYTHON_API: Final = DATA / 'python_api' @@ -252,28 +250,6 @@ def test_a_built_tool_is_one_step_through_every_door(drawn: tuple[CommandLineToo assert all(type(value) in (str, int, float, bool) for each in compiled for value in each.cwl_job_inputs.values()) -_CWL_TYPES = cwl_types( - 'null', 'boolean', 'int', 'long', 'float', 'double', 'string', 'File', 'Directory', 'Any', 'stdout', - 'example.org#Thing', {'type': 'record', 'fields': []}, {'type': 'enum', 'symbols': ['a']}, {'type': 'array'}) - - -@pytest.mark.fast -@given(_CWL_TYPES, _CWL_TYPES) -@example('string', 'File') -@example('string', 'string') -@example('string[]', 'Any') -@example({'type': 'array', 'items': 'string'}, {'type': 'array', 'items': 'Any'}) -@example('string', {'type': 'record', 'fields': []}) -@budget(200) -def test_python_api_uses_the_conservative_language_judgment(parameter_type: Any, candidate_type: Any) -> None: - """The eager API rejects proven disjointness and defers every unknown: it refuses only what the independent model - judges disjoint from the port as declared and lifted one array level, as a later `scatter_on()` would.""" - def disjoint(sink: Any) -> bool: - return reference_expectation(candidate_type, sink) is ReferenceExpectation.DISJOINT - assert _python_api_types_match(parameter_type, candidate_type) is not ( - disjoint(parameter_type) and disjoint({'type': 'array', 'items': parameter_type})) - - def _bind(step: Step, **values: Any) -> Step: """`step`, with `values` bound to its inputs.""" for name, value in values.items(): diff --git a/tests/core/test_quiet.py b/tests/core/test_quiet.py index 8652747fa..f9f844398 100644 --- a/tests/core/test_quiet.py +++ b/tests/core/test_quiet.py @@ -15,8 +15,6 @@ from .cases import DATA from .helpers import EACH_RUNNER, no_preflight, run_cli, run_local_process, search_config -pytestmark = pytest.mark.package - ADDRESSES: Final = ('say', 'local', 'inline', 'pair~say', 'pair~local', 'own') diff --git a/tests/core/test_realtime.py b/tests/core/test_realtime.py index 170222211..7ff704f0e 100644 --- a/tests/core/test_realtime.py +++ b/tests/core/test_realtime.py @@ -32,8 +32,6 @@ from .hermetic import compile_hermetic from .synthetic_tools import SYNTHETIC_NS, SYNTHETIC_TOOLS -pytestmark = pytest.mark.package - ADAPTER_PATH: Final = ADAPTERS / 'file_watchers' / 'cwl_subinterpreter.cwl' TOOLS: Final[Tools] = { **SYNTHETIC_TOOLS, diff --git a/tests/core/test_reference_compatibility.py b/tests/core/test_reference_compatibility.py index 53125a90f..3bc7338a7 100644 --- a/tests/core/test_reference_compatibility.py +++ b/tests/core/test_reference_compatibility.py @@ -106,29 +106,34 @@ def test_the_versioned_judge_matches_the_independent_model( _RECURSIVE['items'] = _RECURSIVE +#: What a Python API port or a value bound to one may declare: the declarations above but nothing, and `stdout`. +_API_TYPES: Final = cwl_types( + *_ATOMS, 'stdout', 'example.org#Thing', {'type': 'array'}, {'type': 'record', 'fields': []}, + {'type': 'enum', 'symbols': ['a']}) + + @pytest.mark.fast -@pytest.mark.parametrize(('claim', 'sink', 'source', 'accepted'), [ - # scatter_on() lifts the sink after the binding, so an array source against a - # scalar sink is not provably disjoint at assignment time. - ('Any[] source, scalar sink', 'string', {'type': 'array', 'items': 'Any'}, True), - ('typed array source, scalar sink', 'string', {'type': 'array', 'items': 'string'}, True), +@given(st.tuples(_API_TYPES, _API_TYPES, st.none())) +@pinned( + # scatter_on() lifts the sink after the binding, so an array source against a scalar sink is not provably + # disjoint at assignment time + ('string', {'type': 'array', 'items': 'Any'}, True), ('string', {'type': 'array', 'items': 'string'}, True), + ('string[]', 'Any', True), ({'type': 'array', 'items': 'string'}, {'type': 'array', 'items': 'Any'}, True), + ('string', {'type': 'record', 'fields': []}, True), ('string', 'string', True), # no scatter arrangement rescues these - ('scalar source, incompatible scalar sink', 'File', 'string', False), - ('array source, incompatible scalar sink', 'File', {'type': 'array', 'items': 'string'}, False), - ('matching scalars', 'string', 'string', True), -]) -def test_the_eager_api_check_defers_what_scatter_could_rescue( - claim: str, sink: Any, source: Any, accepted: bool) -> None: + ('File', 'string', False), ('File', {'type': 'array', 'items': 'string'}, False), ('string', 'File', False)) +@budget(200) +def test_the_eager_api_check_defers_what_scatter_could_rescue(case: tuple[Any, Any, bool | None]) -> None: """The eager check has less information than the compiler and must say so. - A `Workflow` has no resolved language version *and* no scatter yet: binding - happens before `scatter_on()`, which lifts the sink to an array. An `Any[]` - output bound to a scalar input and scattered afterwards compiles, so - rejecting it at assignment preempts the judgment this check exists not to - preempt. Disjointness is proven here only when it holds for the sink as - declared and for the sink lifted one level. - """ - assert _python_api_types_match(sink, source) is accepted, claim + A `Workflow` has no resolved language version *and* no scatter yet: binding happens before `scatter_on()`, which + lifts the sink to an array. The check refuses a value only when the independent model proves it disjoint from the + sink as declared and from the sink lifted one level, and each pinned case is accepted or refused as it states.""" + sink, source, accepted = case + found = _python_api_types_match(sink, source) + assert found is not all(reference_expectation(source, declared) is ReferenceExpectation.DISJOINT + for declared in (sink, {'type': 'array', 'items': sink})) + assert accepted is None or found is accepted #: Each sink a reference may reach, as `typed_sink` declares it: atoms, a union, and arrays one and two deep. diff --git a/tests/core/test_release.py b/tests/core/test_release.py index 7155ffb57..d7da8fd57 100644 --- a/tests/core/test_release.py +++ b/tests/core/test_release.py @@ -9,8 +9,6 @@ import sophios import sophios.cli -pytestmark = pytest.mark.package - def _import_copy(root: Path, built_as: str | None) -> subprocess.CompletedProcess[str]: """Import a copy of the package from `root`, built as `built_as` if given; it reports a version of its own only if diff --git a/tests/core/test_run_local.py b/tests/core/test_run_local.py index 240523606..ee8f0000b 100644 --- a/tests/core/test_run_local.py +++ b/tests/core/test_run_local.py @@ -31,7 +31,7 @@ from .nextflow.test_public_api import CUDA_NOTES, gpu_workflow from .test_backends import _Frozen -pytestmark = [POSIX_ONLY, pytest.mark.package] +pytestmark = POSIX_ONLY @pytest.fixture(name='offline') diff --git a/tests/core/test_settings_boundary.py b/tests/core/test_settings_boundary.py index 6130d6947..774557c17 100644 --- a/tests/core/test_settings_boundary.py +++ b/tests/core/test_settings_boundary.py @@ -14,8 +14,6 @@ from .cases import DATA -pytestmark = pytest.mark.package - #: A minimal workflow: enough to reach the compiler and the drawing, cheap enough to run once per setting. The #: compiler's options are caught before it does any work. diff --git a/tests/core/test_support_matrix.py b/tests/core/test_support_matrix.py index b90222241..a845eace4 100644 --- a/tests/core/test_support_matrix.py +++ b/tests/core/test_support_matrix.py @@ -7,8 +7,6 @@ from sophios.lang import SUPPORT_MATRIX, Support -pytestmark = pytest.mark.package - TESTS = Path(__file__).resolve().parent diff --git a/tests/core/test_targets.py b/tests/core/test_targets.py index 6f9a9b2a4..625f63ee5 100644 --- a/tests/core/test_targets.py +++ b/tests/core/test_targets.py @@ -8,7 +8,6 @@ from sophios.api.python.workflow import Workflow -@pytest.mark.package @pytest.mark.fast def test_the_table_the_command_line_and_the_python_api_name_the_same_targets() -> None: """A target the table holds is one `--target` and every `target=` accept, and nothing else is.""" diff --git a/tests/core/test_wic_defaults.py b/tests/core/test_wic_defaults.py index cb6860f9d..d9052c06f 100644 --- a/tests/core/test_wic_defaults.py +++ b/tests/core/test_wic_defaults.py @@ -13,8 +13,6 @@ from .cases import DATA from .synthetic_tools import SYNTHETIC_TOOLS -pytestmark = pytest.mark.package - def _compile_wic(wic: Path) -> CompilationArtifact: return compile_source(bundle_from_disk(wic, {}, SYNTHETIC_TOOLS), default_compilation_settings(),