James A. Fellows Yates
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: Adding unit tests to nf-core pipelines with nf-test authors: James A. Fellows Yates & Nicolas Vannieuwkerke tags: nf-test,nf-core,ci-testing,nextflow,tutorial --- # Adding unit tests to nf-core pipelines with nf-test ## Introduction We should really add unit tests, and pytest is nice but a lot of overhead. Instead we will try with [nf-test](https://code.askimed.com/nf-test/). This tutorial is based on experiences from the nf-test documentation and @nvnieuwk's testing. ## Install nf-test I've installed this with conda into my personal nf-core conda environment (containing `nf-core` tools, and `nextflow`). > TODO update with proper instructions ```bash conda activate nf-core conda install nf-test -c bioconda ``` ## Pipeline repository update Before we run any nf-test commands, we need to tweak the github repository slightly, by adding the default nf-test 'work' directory to our `.gitignore` ``` echo '.nf-test/' >> .gitignore ``` ## Configure nf-test for your pipeline First we need to generate a couple config files (`nf-test.config`, and `tests/nextflow.config`). ```bash nf-test init ``` For nf-core pipelines we need to add `tests/nextflow.config` a couple of parameters as we do in any other nextflow config file. ``` params { outdir = '${params.outputDir}' } ``` 🛈 The purpose of using `params.outputDir` is to isolate all test files into a directory generated by nf-test`.nf-test/`. This also prevents test results files being uploaded to the git repostiory as specified in the [.gitignore](#pipeline-repository-update) ## Generate basic test template Then we can make a template test file (ending in `.test`), by specifying we want to make a test for a nf-core workflow with a nf-test 'pipeline' template. ```bash nf-test generate pipeline main.nf ``` > 🛈 workflows vs pipelines appear to have slightly different definitions of a workflow. A nf-test `workflow` corresponds to a nf-core `subworkflow`. You can also rename the resulting `tests/main.nf.test` file to make it more specific, such as corresponding to a specific test profile. ## Writing a minimal test Now you can edit the `tests/test.test.file`. You should also remove the `when` block inside the generated test template file (for nf-core purposes, we will instead use our existing test `-profile`s to specify parameters). You can also change the `then` block to `expect` to make it more clear (`nf-test` version 0.6.2 or higher). For a very minimal example, you can just `expect` that the workflow should complete successfully, with `assert workflow.success`. Therefore the test should look like as follows: ```groovy nextflow_pipeline { name "Test Workflow main.nf" script "main.nf" test("Should run without failures") { expect { assert workflow.success } } } ``` ## Running the minimal test locally To run the test, you can then execute the `nf-test test` subcommand, pointing to your given test file, and then the particular profile you want to test against > ⚠️ for `nf-test` we MUST specify a _double_ dash to profile (`--profile`)! ``` nf-test test tests/test_nothing.test --profile singularity,test_nothing ``` > 🛈 In this case, we are using the same profile name to that of the test, you could conceptually provide another `--profile`, assuming the output files are expected to be the same. > 🛈 All tests are run by default in a ## Integrating the tests into nf-core GitHub Actions To get this minimal test working in github actions, we need to make three changes to the nf-core `.github/workflows/ci.yml` - Add a install nf-test step - Update any parameter matrices you may have - Update the test command ### Installing nf-test To install the nf-test, add the following after the `nf-core/setup-nextflow` step. ```yaml - name: Install Nextflow uses: nf-core/setup-nextflow@v1 with: version: "${{ matrix.NXF_VER }}" - name: Install nf-test run: | sudo bash; mkdir /opt/nf-test; cd /opt/nf-test; wget https://github.com/askimed/nf-test/releases/download/v0.6.2/nf-test-0.6.2.tar.gz; tar xvfz nf-test-0.6.2.tar.gz; chmod +x nf-test; echo "/opt/nf-test" >> $GITHUB_PATH; ``` ### Update parameter matrices For updating the parameter matrices, you may have something like ```yaml NXF_VER: - "21.10.3" - "latest-everything" parameters: - "--perform_longread_qc false" - "--perform_shortread_qc false" - "--shortread_qc_tool fastp" ``` You should move these into new test profiles, and replace the `parameters` matrix with one called `profiles`, and put the name of each test profile as entries, e.g. looking something like this: ```yaml NXF_VER: - "21.10.3" - "latest-everything" profiles: - "test_longreadqcfalse" - "test_shortreadqcfalse" - "test_shortreadqctoolfastp" ``` ### Update commands Finally we can update the command itself, but replacing the `nextflow run` command with `nf-test test` and inserting our new profiles to the nf-test test file name and supply the profile itself. So: ```yaml - name: Run pipeline with test data with: command: nextflow run ${GITHUB_WORKSPACE} -profile test,docker --outdir ./results ${{ matrix.parameters }} ``` becomes: ```yaml - name: Run pipeline with test data with: command: nf-test test ${GITHUB_WORKSPACE}/tests/${{ matrix.profiles }}.test --profile ${{ matrix.profiles }},docker ``` ### Checking for output files To convert the tests to _actual_ unit tests (i.e. checking output files), we can then update the `expect` block of each test file to specify things such as expected files, md5sums, string contents etc. > 💡 One of the benefits of nf-test is you can write your own customs assertions in Groovy to check for anything you want. #### Snapshot nf-test provides a semi automated way of checking for file differences between CI tests using `snapshots`. This is somewhat equivalent to the `nf-core/tools` repeat test functionality that generates md5sum for you, but built directly into the testing tool. You can supply any nextflow object (file/path, channel name, trace etc.) to the `snapshot()` function. The first time you run `nf-test test`, it will pick up any snapshot functions, and generate a new file with the same name as the test file but with `.snap` appended to it, that contains md5sums of each file. Every subsequent test run will then compare the md5sum in the run against those listed in the `.snap` file. ```groovy expect { assert workflow.success assert snapshot(path("${outputDir}/pipeline_info/database_sheet.valid.csv")).match() } ``` > ⚠️ Make sure to check the contents of each file looks correct before adding it the list of files for `snapshot`! > ⚠️ Make sure to re-generate the 'snapshot' file if you expect contents of files to change! You can do this including `--update-snapshot` in your test command or by deleting the `.snap` file. However in some cases, you will not be able to use snapshots due to variabilty of file contents. In this case we can 'manually' specify other types of files. #### Manual Specifications As with `pytestWorkflows`, we generally prefer `md5sum` checks to ensure there is no variability in the output (for reproducibility) via `.md5`, however in cases where a tool produces inheriently different output (e.g. rows in a different order in a table), you can check for strings with `.contains()` ```groovy expect { assert workflow.success // File has a md5sum matching - preferred assert path("${outputDir}/fastqc/raw/2612_ERR5766176_B_raw_1_fastqc.html").md5 == "09d0dd1ef6219b5726b11d691fd22a37" // File contains the following string - backup e.g., when timestamp or variable row order assert path("${outputDir}/fastqc/raw/2612_ERR5766176_B_raw_2_fastqc.html").readLines().join('').matches(".*FastQC Report.*") // File exists - last resort assert path("${outputDir}/multiqc/multiqc_report.html").exists() } ``` > 🛈 `outputDir` here corresponds to whatever is specified to `--outdir` ([default](https://code.askimed.com/nf-test/testcases/global_variables/#outputdir) being a directory named 'output') ### Automating the generation of the entire file <!-- Not really automated, but run your test profile, then use XYZ command to generate a list of files found within the directory, saving them into a file then use `sed` to replace with the necessary function -->

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully