Upload NUnit Result File to GitHub Actions - nunit

I'm in the process of setting up GitHub Actions for my C# project, and as part of that I want to have the test results displayed in GitHub.
Using this action, the relevant portion of my YML looks like this:
steps:
- name: 🎉 Test
run: dotnet test --no-restore --verbosity normal --logger:"nunit"
- name: ⏫ Publish Unit Test Results
uses: EnricoMi/publish-unit-test-result-action#v1
if: always()
with:
files: ${{ github.workspace }}/*/TestResults/*.xml
The tests run correctly, the TestResults.xml is present and gets uploaded, but GitHub Actions prints:
Error processing result file
Invalid format.
Now the documentations are a bit sparse at this point, but from what I could gather both GitHub Actions and NUnit should use the JUnit test result format, and the file looks a lot like this, too:
<test-run id="2" duration="0.028704999999999998" testcasecount="18" total="18" passed="18" failed="0" inconclusive="0" skipped="0" result="Passed" start-time="2022-02-19T 11:32:34Z" end-time="2022-02-19T 11:32:36Z">
<test-suite type="Assembly" name="HelloCSharp.Api.Tests.dll" fullname="/home/runner/work/hello-c-sharp/hello-c-sharp/HelloCSharp.Api.Tests/bin/Debug/net6.0/HelloCSharp.Api.Tests.dll" total="18" passed="18" failed="0" inconclusive="0" skipped="0" result="Passed" start-time="2022-02-19T 11:32:36Z" end-time="2022-02-19T 11:32:36Z" duration="0.028705">
<test-case name="DisplayNameForAll" fullname="HelloCSharp.Api.Tests.Models.RelationshipTypeTest.DisplayNameForAll" methodname="DisplayNameForAll" classname="RelationshipTypeTest" result="Passed" start-time="2022-02-19T 11:32:36Z" end-time="2022-02-19T 11:32:36Z" duration="0.006137" asserts="0" seed="1714534364" />
<!-- snip -->
<errors />
</test-suite>
</test-run>
So what could be the problem here?

Okay, NUnit format is definitively not JUnit format. I tried uploading a fix JUnit file and it worked, then I compared the XMLs. JUnit files have "testsuite" and "testcase" tags instead of "test-suite" and "test-case".
So my quick and dirty solution is too add this step between the ones in the question:
- name: ☢ Reformat Test Files (NUnit != JUnit)
run: |
sed -i 's/test-case/testcase/' ${{ github.workspace }}/*/TestResults/*.xml
sed -i 's/test-suite/testsuite/' ${{ github.workspace }}/*/TestResults/*.xml
sed -i 's/test-run/testsuite/' ${{ github.workspace }}/*/TestResults/*.xml

Related

GitHub Actions: Setting Working Directory with Context Fails to Find File

I am trying to set my working directory with an environment variable so that I can handle 2 different situations, however, if I use context with the working-directory it does not find files in the directory, but if I hardcode the path, it does. I have tried many different syntax iterations but will paste one iteration below so it is easier to see what I am trying to accomplish.
- uses: actions/checkout#v2
. . .
- name: Monorepo - Set working Directory
if: env.WASMCLOUD_REPO_STYLE == 'MONO' # Run if monorepo
run: |
echo "WORKING_DIR = ${GITHUB_WORKSPACE}/actors/${{ env.ACTOR_NAME }}" >> $GITHUB_ENV
- name: Multirepo - Set working Directory
if: env.WASMCLOUD_REPO_STYLE == 'MULTI' # Run if multirepo
run: |
echo "WORKING_DIR = ${GITHUB_WORKSPACE}" >> $GITHUB_ENV
- name: Build wasmcloud actor
run: make
working-directory: ${{ env.WORKING_DIR }} # If I Hardcode path here it works
The environment variable is showing the correct path during debugging which is formatted as: /home/runner/work/REPO_NAME/REPO_NAME/actors/ACTOR_NAME
For step 3 if I type working-directory: actors/ACTOR_NAME it works (until a later issue :P where it again does not find a directory)
This is my first few days with GitHub Actions so help would be really appreciated. I am not sure why context is not being accepted but a static path is. Examples often show working-directory using context.
See #Benjamin W.'s comments above for the answer.

How to use working-directory in GitHub actions?

I'm trying to set-up and run a GitHub action in a nested folder of the repo.
I thought I could use working-directory, but if I write this:
jobs:
test-working-directory:
runs-on: ubuntu-latest
name: Test
defaults:
run:
working-directory: my_folder
steps:
- run: echo test
I get an error:
Run echo test
echo test
shell: /usr/bin/bash -e {0}
Error: An error occurred trying to start process '/usr/bin/bash' with working directory '/home/runner/work/my_repo/my_repo/my_folder'. No such file or directory
I notice my_repo appears twice in the path of the error.
Here is the run on my repo, where:
my_repo = novade_flutter_packages
my_folder = packages
What am I missing?
You didn't check out the repository on the second job.
Each job runs on a different instance, so you have to checkout it separately for each one of them.

Is there a way to log error responses from Github Actions?

I am trying to create a bug tracker that allows me to record the error messages of the python script I run. Here is my YAML file at the moment:
name: Bug Tracker
#Controls when the workflow will run
on:
# Triggers the workflow on push request events
push:
branches: [ main ]
# Allows you to run this workflow manually from the Actions tab (for testing)
workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
build:
# Self Hosted Runner
runs-on: windows-latest
# Steps for tracker to get activated
steps:
# Checks-out your repository under BugTracker so the job can find it
- uses: actions/checkout#v2
- name: setup python
uses: actions/setup-python#v2
with:
python-version: 3.8
# Runs main script to look for
- name: Run File and collect bug
id: response
run: |
echo Running File...
python script.py
echo "${{steps.response.outputs.result}}"
Every time I run the workflow I can't save the error code. By save the error code, I mean for example... if the python script produces "Process completed with exit code 1." then I can save that to a txt file. I've seen cases where I could save if it runs successfully. I've thought about getting the error in the python script but I don't want to have to add the same code to every file if I don't have to. Any thoughts? Greatly appreciate any help or suggestions.
Update: I have been able to successfully use code in python to save to the txt file. However, I'm still looking to do this in Github if anyone has any suggestions.
You could :
redirect the output to a log file while capturing the exit code
set an output with the exit code value like:
echo ::set-output name=status::$status
in another step, commit the log file
in a final step, check that the exit code is success (0) otherwise exit the script with this exit code
Using ubuntu-latest, it would be like this:
name: Bug Tracker
on: [push,workflow_dispatch]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
- name: setup python
uses: actions/setup-python#v2
with:
python-version: 3.8
- name: Run File and collect logs
id: run
run: |
echo Running File...
status=$(python script.py > log.txt 2>&1; echo $?)
cat log.txt
echo ::set-output name=status::$status
- name: Commit log
run: |
git config --global user.name 'GitHub Action'
git config --global user.email 'action#github.com'
git add -A
git checkout master
git diff-index --quiet HEAD || git commit -am "deploy workflow logs"
git push
- name: Check run status
if: steps.run.outputs.status != '0'
run: exit "${{ steps.run.outputs.status }}"
On windows, I think you would need to update this part:
status=$(python script.py > log.txt 2>&1; echo $?)
cat log.txt

(GitHub Actions) Split step into two consecutive ones

I'd like to use GitHub Actions to publish an npm package. So far I am using quite a trivial script to do that. Now I'd like to split one step of the script into two consecutive ones.
here's an excerpt from my workflows/...yaml file:
steps:
# ...
- name: Build
run: |
cd src
npm install
tsc
# TODO split here
npm set registry https://npm.pkg.github.com
npm set //npm.pkg.github.com/:_authToken ${{ secrets.GITHUB_TOKEN }}
npm publish
env:
CI: true
Now, when I tried to have these as separate Steps, they ran in parallel which is not the behavior I hope for, since the first step yields results (creates a src/lib directory) that I depend on in step #2. (The one where I log into npm and publish this).
Can someone please help me to unravel this?
As #smac89 explains above, steps can't be executed in parallel, only jobs and workflows can.
The official Github Documentation shares this illustration about the Github Actions structure:
What probably happened in your case was that you created 2 jobs instead of 2 steps.
The syntax to split your steps should be something like this:
jobs:
my-job:
runs-on: ubuntu-latest #for example
steps:
# ...
- name: Build
run: |
cd src
npm install
tsc
env:
CI: true
- name: Publish
run: |
npm set registry https://npm.pkg.github.com
npm set //npm.pkg.github.com/:_authToken ${{ secrets.GITHUB_TOKEN }}
npm publish
env:
CI: true

Using output from a previous job in a new one in a GitHub Action

For (mainly) pedagogical reasons, I'm trying to run this workflow in GitHub actions:
name: "We 🎔 Perl"
on:
issues:
types: [opened, edited, milestoned]
jobs:
seasonal_greetings:
runs-on: windows-latest
steps:
- name: Maybe greet
id: maybe-greet
env:
HEY: "Hey you!"
GREETING: "Merry Xmas to you too!"
BODY: ${{ github.event.issue.body }}
run: |
$output=(perl -e 'print ($ENV{BODY} =~ /Merry/)?$ENV{GREETING}:$ENV{HEY};')
Write-Output "::set-output name=GREET::$output"
produce_comment:
name: Respond to issue
runs-on: ubuntu-latest
steps:
- name: Dump job context
env:
JOB_CONTEXT: ${{ jobs.maybe-greet.steps.id }}
run: echo "$JOB_CONTEXT"
I need two different jobs, since they use different context (operating systems), but I need to get the output of a step in the first job to the second job. I am trying with several combinations of the jobs context as found here but there does not seem to be any way to do that. Apparently, jobs is just the name of a YAML variable that does not really have a context, and the context job contains just the success or failure. Any idea?
Check the "GitHub Actions: New workflow features" from April 2020, which could help in your case (to reference step outputs from previous jobs)
Job outputs
You can specify a set of outputs that you want to pass to subsequent jobs and then access those values from your needs context.
See documentation:
jobs.<jobs_id>.outputs
A map of outputs for a job.
Job outputs are available to all downstream jobs that depend on this job.
For more information on defining job dependencies, see jobs.<job_id>.needs.
Job outputs are strings, and job outputs containing expressions are evaluated on the runner at the end of each job. Outputs containing secrets are redacted on the runner and not sent to GitHub Actions.
To use job outputs in a dependent job, you can use the needs context.
For more information, see "Context and expression syntax for GitHub Actions."
To use job outputs in a dependent job, you can use the needs context.
Example
jobs:
job1:
runs-on: ubuntu-latest
# Map a step output to a job output
outputs:
output1: ${{ steps.step1.outputs.test }}
output2: ${{ steps.step2.outputs.test }}
steps:
- id: step1
run: echo "test=hello" >> $GITHUB_OUTPUT
- id: step2
run: echo "test=world" >> $GITHUB_OUTPUT
job2:
runs-on: ubuntu-latest
needs: job1
steps:
- run: echo ${{needs.job1.outputs.output1}} ${{needs.job1.outputs.output2}}
Note the use of $GITHUB_OUTPUT, instead of the older ::set-output now (Oct. 2022) deprecated.
To avoid untrusted logged data to use set-state and set-output workflow commands without the intention of the workflow author we have introduced a new set of environment files to manage state and output.
Jesse Adelman adds in the comments:
This seems to not work well for anything beyond a static string.
How, for example, would I take a multiline text output of step (say, I'm running a pytest or similar) and use that output in another job?
either write the multi-line text to a file (jschmitter's comment)
or base64-encode the output and then decode it in the next job (Nate Karasch's comment)
Update: It's now possible to set job outputs that can be used to transfer string values to downstream jobs. See this answer.
What follows is the original answer. These techniques might still be useful for some use cases.
Write the data to file and use actions/upload-artifact and actions/download-artifact. A bit awkward, but it works.
Create a repository dispatch event and send the data to a second workflow. I prefer this method personally, but the downside is that it needs a repo scoped PAT.
Here is an example of how the second way could work. It uses repository-dispatch action.
name: "We 🎔 Perl"
on:
issues:
types: [opened, edited, milestoned]
jobs:
seasonal_greetings:
runs-on: windows-latest
steps:
- name: Maybe greet
id: maybe-greet
env:
HEY: "Hey you!"
GREETING: "Merry Xmas to you too!"
BODY: ${{ github.event.issue.body }}
run: |
$output=(perl -e 'print ($ENV{BODY} =~ /Merry/)?$ENV{GREETING}:$ENV{HEY};')
Write-Output "::set-output name=GREET::$output"
- name: Repository Dispatch
uses: peter-evans/repository-dispatch#v1
with:
token: ${{ secrets.REPO_ACCESS_TOKEN }}
event-type: my-event
client-payload: '{"greet": "${{ steps.maybe-greet.outputs.GREET }}"}'
This triggers a repository dispatch workflow in the same repository.
name: Repository Dispatch
on:
repository_dispatch:
types: [my-event]
jobs:
myEvent:
runs-on: ubuntu-latest
steps:
- run: echo ${{ github.event.client_payload.greet }}
In my case I wanted to pass an entire build/artifact, not just a string:
name: Build something on Ubuntu then use it on MacOS
on:
workflow_dispatch:
# Allows for manual build trigger
jobs:
buildUbuntuProject:
name: Builds the project on Ubuntu (Put your stuff here)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
- uses: some/compile-action#v99
- uses: actions/upload-artifact#v2
# Upload the artifact so the MacOS runner do something with it
with:
name: CompiledProject
path: pathToCompiledProject
doSomethingOnMacOS:
name: Runs the program on MacOS or something
runs-on: macos-latest
needs: buildUbuntuProject # Needed so the job waits for the Ubuntu job to finish
steps:
- uses: actions/download-artifact#master
with:
name: CompiledProject
path: somewhereToPutItOnMacOSRunner
- run: ls somewhereToPutItOnMacOSRunner # See the artifact on the MacOS runner
It is possible to capture the entire output (and return code) of a command within a run step, which I've written up here to hopefully save someone else the headache. Fair warning, it requires a lot of shell trickery and a multiline run to ensure everything happens within a single shell instance.
In my case, I needed to invoke a script and capture the entirety of its stdout for use in a later step, as well as preserve its outcome for error checking:
# capture stdout from script
SCRIPT_OUTPUT=$(./do-something.sh)
# capture exit code as well
SCRIPT_RC=$?
# FYI, this would get stdout AND stderr
SCRIPT_ALL_OUTPUT=$(./do-something.sh 2>&1)
Since Github's job outputs only seem to be able to capture a single line of text, I also had to escape any newlines for the output:
echo "::set-output name=stdout::${SCRIPT_OUTPUT//$'\n'/\\n}"
Additionally, I needed to ultimately return the script's exit code to correctly indicate whether it failed. The whole shebang ends up looking like this:
- name: A run step with stdout as a captured output
id: myscript
run: |
# run in subshell, capturiing stdout to var
SCRIPT_OUTPUT=$(./do-something.sh)
# capture exit code too
SCRIPT_RC=$?
# print a single line output for github
echo "::set-output name=stdout::${SCRIPT_OUTPUT//$'\n'/\\n}"
# exit with the script status
exit $SCRIPT_RC
continue-on-error: true
- name: Add above outcome and output as an issue comment
uses: actions/github-script#v5
env:
STEP_OUTPUT: ${{ steps.myscript.outputs.stdout }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
// indicates whather script succeeded or not
let comment = `Script finished with \`${{ steps.myscript.outcome }}\`\n`;
// adds stdout, unescaping newlines again to make it readable
comment += `<details><summary>Show Output</summary>
\`\`\`
${process.env.STEP_OUTPUT.replace(/\\n/g, '\n')}
\`\`\`
</details>`;
// add the whole damn thing as an issue comment
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
})
Edit: there is also an action to accomplish this with much less bootstrapping, which I only just found.
2022 October update: GitHub is deprecating set-output and recommends to use GITHUB_OUTPUT instead. The syntax for defining the outputs and referencing them in other steps, jobs.
An example from the docs:
- name: Set color
id: random-color-generator
run: echo "SELECTED_COLOR=green" >> $GITHUB_OUTPUT
- name: Get color
run: echo "The selected color is ${{ steps.random-color-generator.outputs.SELECTED_COLOR }}"