diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 9ab77a04..b9d1bb8b 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,3 +1 @@ - -[Test Task](https://twtest.teamwork.com/#/tasks/20613952) diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index b5ede0fc..91979671 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -7,6 +7,6 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v1 + uses: actions/checkout@v5 - name: Run Shellcheck uses: azohra/shell-linter@latest diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4bab5c6c..0228a287 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,22 +1,15 @@ name: teamwork on: + push: + branches: [master] pull_request: - pull_request_review: - types: [submitted, dismissed] jobs: build: runs-on: ubuntu-latest name: Ensure this project runs steps: - - uses: actions/checkout@v1 - - uses: ./ - with: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - TEAMWORK_URI: "localhost" - TEAMWORK_API_TOKEN: "test_api_token" - AUTOMATIC_TAGGING: true - BOARD_COLUMN_OPENED: "PR Open" - BOARD_COLUMN_MERGED: "Ready to Test" - BOARD_COLUMN_CLOSED: "Rejected" + - uses: actions/checkout@v5 + - name: Run the tests against a mock Teamwork API + run: ./tests/run.sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e142fd0f..18c132e5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,34 +1,23 @@ # Contributing -## Getting started - ## Setup local environment * [Install Docker](https://docs.docker.com/get-docker/) -* [Install act tool](https://github.com/nektos/act) -## Usage +## Running the tests -Simulate a new pull request +The tests run the action's Docker image against a mock Teamwork API (`tests/mock-teamwork.py`) and check what it sends: ``` -act pull_request -e tests/events/pull_request_opened.json +./tests/run.sh ``` -Simulate a pull request has been approved +Each directory in `tests/cases` is a test case: -``` -act pull_request_review -e tests/events/pull_request_approved.json -``` +* `event.json`: the GitHub event the action receives +* `inputs`: the action's inputs as the `INPUT_*` environment variables GitHub creates for them, plus `GITHUB_EVENT_NAME` and any other environment variables such as `IGNORE_PROJECT_IDS` +* `expected`: the exit code, errors and requests the mock Teamwork API should end up with -Simulate a pull request has been merged +`./tests/run.sh ` only runs the cases whose name contains the filter. -``` -act pull_request -e tests/events/pull_request_merged.json -``` - -Simulate a pull request has been closed without merging - -``` -act pull_request -e tests/events/pull_request_closed.json -``` +To add a case, create its `event.json` and `inputs`, run `./tests/run.sh --update ` to record its `expected` file, and check that file is right before committing it. The mock's data (which tasks exist, their projects and the workflow stages) is at the top of `tests/mock-teamwork.py`. diff --git a/Dockerfile b/Dockerfile index 82925d22..6eaa2ae4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM alpine:3.11 +FROM alpine:3.24 RUN apk add --no-cache bash curl jq diff --git a/README.md b/README.md index 3c54c77b..e7e3553e 100644 --- a/README.md +++ b/README.md @@ -19,11 +19,9 @@ ### Prerequisites Create the next environment vars in your repository: * `TEAMWORK_URI`: The URL of your installation (e.g.: https://yourcompany.teamwork.com) -* `TEAMWORK_API_TOKEN`: The API token to authenticate the workflow. Follow [this guide](https://support.teamwork.com/projects/using-teamwork/locating-your-api-key) to find your URL and API key. +* `TEAMWORK_API_TOKEN`: The API token to authenticate the workflow. Follow [this guide](https://support.teamwork.com/projects/using-teamwork/locating-your-api-key) to find your URL and API key. A bearer token (it starts with `tkn.`) also works, follow [this guide](https://apidocs.teamwork.com/guides/teamwork/authentication) to generate one. -**Please Note:** The Teamwork account associated with this API key is the account which these comments will be created under. If this user does not have permission to access the project, this action will be ignored. - -`GITHUB_TOKEN` doesn't need to be setup in the repository, this var is always available during the workflows execution. +**Please Note:** The Teamwork account associated with this API key is the account which these comments will be created under. If this user does not have permission to access a task's project, that task will be skipped and the workflow run will be marked as failed. ### Installation Create a new file `/.github/workflows/teamwork.yml` with the following: @@ -44,22 +42,21 @@ jobs: steps: - uses: teamwork/github-sync@master with: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} TEAMWORK_URI: ${{ secrets.TEAMWORK_URI }} TEAMWORK_API_TOKEN: ${{ secrets.TEAMWORK_API_TOKEN }} AUTOMATIC_TAGGING: false - BOARD_COLUMN_OPENED: 'PR Open' - BOARD_COLUMN_MERGED: 'Ready to Test' - BOARD_COLUMN_CLOSED: 'Rejected' + WORKFLOW_STAGE_OPENED: 'PR Open' + WORKFLOW_STAGE_MERGED: 'Ready to Test' + WORKFLOW_STAGE_CLOSED: 'Rejected' env: IGNORE_PROJECT_IDS: '1 2 3' ``` ## Usage -When creating a new PR, write in the description of the PR the URL of the task. The action will automatically add a comment in the task. +When creating a new PR, write in the description of the PR the URL of the task (it must point to the same Teamwork site as `TEAMWORK_URI`, e.g. `https://yourcompany.teamwork.com/app/tasks/123`). The action will automatically add a comment in the task. Optionally, you may choose for a lightweight comment that will only include the PR title, URL and the user that performed the action, to enable this option set the `LIGHTWEIGHT_COMMENT` input to `true`. -Please note, the comment will be created in Teamwork under the account you have attached to this action. If the API key of the user you are using does not have permissions to access certain projects, the comment will not be created. +Please note, the comment will be created in Teamwork under the account you have attached to this action. If the API key of the user you are using does not have permissions to access certain projects, the comment will not be created and the workflow run will report an error. ![GitHub pr comment](./.github/assets/github_pr_comment.png) @@ -71,12 +68,12 @@ Tags are added automatically on the task if you are have the option `AUTOMATIC_T - A PR is merged: tags `PR Open` and `PR Approved` removed, tag `PR merged` added - A PR is closed: tags `PR Open` and `PR Approved` removed -You may also specify columns you'd like the task to be moved to on every stage of the PR: -- `BOARD_COLUMN_OPENED`: The case-sensitive column name of the column you'd like the task to be moved to once the PR has been opened -- `BOARD_COLUMN_MERGED`: The case-sensitive column name of the column you'd like the task to be moved to once the PR has been merged -- `BOARD_COLUMN_CLOSED`: The case-sensitive column name of the column you'd like the task to be moved to if the PR was closed without being merged +You may also specify [workflow](https://support.teamwork.com/projects/workflows/workflows-introduction) stages you'd like the task to be moved to on every stage of the PR: +- `WORKFLOW_STAGE_OPENED`: The case-sensitive name of the workflow stage you'd like the task to be moved to once the PR has been opened +- `WORKFLOW_STAGE_MERGED`: The case-sensitive name of the workflow stage you'd like the task to be moved to once the PR has been merged +- `WORKFLOW_STAGE_CLOSED`: The case-sensitive name of the workflow stage you'd like the task to be moved to if the PR was closed without being merged -The column names will be checked against all board columns in the task's project, this will be using a `contains()` method so you may specify part of the name instead of the full name, however this `contains()` check is case-sensitive. The first matching column will be used. +The stage names will be checked against the stages of every workflow in the task's project, this will be using a `contains()` method so you may specify part of the name instead of the full name, however this `contains()` check is case-sensitive. The first matching stage will be used. ## Contributing * Open a PR: https://github.com/Teamwork/github-sync/pulls diff --git a/action.yml b/action.yml index f704b08a..0c27db6c 100644 --- a/action.yml +++ b/action.yml @@ -5,37 +5,61 @@ branding: color: 'gray-dark' inputs: GITHUB_TOKEN: - description: 'GitHub token' - required: true + description: 'Deprecated, no longer used.' + required: false + default: '' TEAMWORK_URI: description: 'Teamwork URI' required: true TEAMWORK_API_TOKEN: - description: 'Teamwork API token' + description: 'Teamwork API key, or a bearer token (starts with "tkn.")' required: true AUTOMATIC_TAGGING: description: 'Do you want to enable automatic tagging: true/false' required: false + WORKFLOW_STAGE_OPENED: + description: 'The case-sensitive name of the workflow stage you would like the task to be moved to once the PR has been opened' + required: false + default: '' + WORKFLOW_STAGE_MERGED: + description: 'The case-sensitive name of the workflow stage you would like the task to be moved to once the PR has been merged' + required: false + default: '' + WORKFLOW_STAGE_CLOSED: + description: 'The case-sensitive name of the workflow stage you would like the task to be moved to if the PR was closed without being merged' + required: false + default: '' + LIGHTWEIGHT_COMMENT: + description: 'Generate tiny comments with minimal information' + required: false + default: 'false' BOARD_COLUMN_OPENED: - description: 'The case-sensitive column name of the column you would like the task to be moved to once the PR has been opened' + description: 'Deprecated.' required: false default: '' BOARD_COLUMN_MERGED: - description: 'The case-sensitive column name of the column you would like the task to be moved to once the PR has been merged' + description: 'Deprecated.' required: false default: '' BOARD_COLUMN_CLOSED: - description: 'The case-sensitive column name of the column you would like the task to be moved to if the PR was closed without being merged' + description: 'Deprecated.' required: false default: '' runs: using: 'docker' image: 'Dockerfile' + # Secrets stay out of args, which show up in the runner's process list. The + # Teamwork token is read from its INPUT_TEAMWORK_API_TOKEN env var instead, + # and the empty slots keep the other args in place. args: - - ${{ inputs.GITHUB_TOKEN }} + - '' - ${{ inputs.TEAMWORK_URI }} - - ${{ inputs.TEAMWORK_API_TOKEN }} + - '' - ${{ inputs.AUTOMATIC_TAGGING }} + - ${{ inputs.WORKFLOW_STAGE_OPENED }} + - ${{ inputs.WORKFLOW_STAGE_MERGED }} + - ${{ inputs.WORKFLOW_STAGE_CLOSED }} + - ${{ inputs.LIGHTWEIGHT_COMMENT }} - ${{ inputs.BOARD_COLUMN_OPENED }} - ${{ inputs.BOARD_COLUMN_MERGED }} - ${{ inputs.BOARD_COLUMN_CLOSED }} diff --git a/src/ensure.sh b/src/ensure.sh index 05f12470..3bec16a0 100644 --- a/src/ensure.sh +++ b/src/ensure.sh @@ -1,18 +1,8 @@ #!/usr/bin/env bash ensure::env_variable_exist() { - if [[ -z "${!1}" ]]; then - echoerr "The env variable $1 is required." - exit 1 - fi -} - -ensure::total_args() { - local -r received_args=$(( $# - 1 )) - local -r expected_args=$1 - - if ((received_args != expected_args)); then - echoerr "Illegal number of parameters, $expected_args expected but $received_args found" + if [[ -z "${!1:-}" ]]; then + log::error "The env variable $1 is required." exit 1 fi } diff --git a/src/github.sh b/src/github.sh index 726b906b..b3932a08 100644 --- a/src/github.sh +++ b/src/github.sh @@ -8,12 +8,9 @@ github::get_action() { jq --raw-output .action "$GITHUB_EVENT_PATH" } -github::get_pr_number() { - jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH" -} - github::get_pr_body() { - jq --raw-output .pull_request.body "$GITHUB_EVENT_PATH" | sed -r 's/^#{1,3}\ /#### /g' + jq --raw-output .pull_request.body "$GITHUB_EVENT_PATH" |\ + awk '/^[[:space:]]*(```|~~~)/ { fenced = !fenced } !fenced { sub(/^#{1,3} /, "#### ") } { print }' } github::get_head_ref() { @@ -24,16 +21,12 @@ github::get_base_ref() { jq --raw-output .pull_request.base.ref "$GITHUB_EVENT_PATH" } -github::get_repository_full_name() { - jq --raw-output .pull_request.head.repo.full_name "$GITHUB_EVENT_PATH" -} - github::get_pr_url() { jq --raw-output .pull_request.html_url "$GITHUB_EVENT_PATH" } github::get_pr_title() { - jq --raw-output .pull_request.title "$GITHUB_EVENT_PATH" + jq --raw-output '.pull_request.title | trim' "$GITHUB_EVENT_PATH" } github::get_pr_patch_stats() { @@ -53,9 +46,5 @@ github::get_review_state() { } github::get_review_comment() { - jq --raw-output .review.body "$GITHUB_EVENT_PATH" -} - -github::print_all_data() { - cat "$GITHUB_EVENT_PATH" + jq --raw-output '.review.body // empty' "$GITHUB_EVENT_PATH" } diff --git a/src/main.sh b/src/main.sh index cf553262..0cc5af6f 100644 --- a/src/main.sh +++ b/src/main.sh @@ -12,16 +12,28 @@ main() { # Ensure env vars and args exist ensure::env_variable_exist "GITHUB_REPOSITORY" ensure::env_variable_exist "GITHUB_EVENT_PATH" + ensure::env_variable_exist "GITHUB_EVENT_NAME" - export GITHUB_TOKEN="$1" + # $1 used to be GITHUB_TOKEN, which was never needed. The Teamwork token comes + # from the env var GitHub creates for the input, so it isn't on the command + # line; $3 is the fallback for running the image by hand. export TEAMWORK_URI="$2" - export TEAMWORK_API_TOKEN="$3" + export TEAMWORK_API_TOKEN="${INPUT_TEAMWORK_API_TOKEN:-$3}" export AUTOMATIC_TAGGING="$4" - export BOARD_COLUMN_OPENED="$5" - export BOARD_COLUMN_MERGED="$6" - export BOARD_COLUMN_CLOSED="$7" + export WORKFLOW_STAGE_OPENED="$5" + export WORKFLOW_STAGE_MERGED="$6" + export WORKFLOW_STAGE_CLOSED="$7" + export LIGHTWEIGHT_COMMENT="$8" + # BOARD_COLUMN_* are deprecated aliases kept for backwards compatibility. + export BOARD_COLUMN_OPENED="${9:-}" + export BOARD_COLUMN_MERGED="${10:-}" + export BOARD_COLUMN_CLOSED="${11:-}" - env::set_environment + # Fall back to the deprecated BOARD_COLUMN_* inputs when their WORKFLOW_STAGE_* + # replacements are not set. + : "${WORKFLOW_STAGE_OPENED:=$BOARD_COLUMN_OPENED}" + : "${WORKFLOW_STAGE_MERGED:=$BOARD_COLUMN_MERGED}" + : "${WORKFLOW_STAGE_CLOSED:=$BOARD_COLUMN_CLOSED}" # Check if there is a task link in the PR local -r pr_body=$(github::get_pr_body) @@ -37,37 +49,50 @@ main() { log::message "Event: $event - Action: $action" + # Pick the handler before touching the API, so unsupported events make no + # requests at all + local handler + if [ "$event" == "pull_request" ] && [ "$action" == "opened" ]; then + handler=teamwork::pull_request_opened + elif [ "$event" == "pull_request" ] && [ "$action" == "closed" ]; then + handler=teamwork::pull_request_closed + elif [ "$event" == "pull_request_review" ] && [ "$action" == "submitted" ]; then + handler=teamwork::pull_request_review_submitted + elif [ "$event" == "pull_request_review" ] && [ "$action" == "dismissed" ]; then + handler=teamwork::pull_request_review_dismissed + else + log::message "Operation not allowed" + exit 0 + fi + + TEAMWORK_FAILED_REQUESTS=0 + local project_id IFS=',' read -r -a task_ids <<< "$task_ids_str" for task_id in "${task_ids[@]}"; do log::message "Task found with the id: $task_id" export TEAMWORK_TASK_ID=$task_id - project_id="$(teamwork::get_project_id_from_task "$task_id")" + if ! project_id="$(teamwork::get_project_id_from_task "$task_id")" || [[ ! $project_id =~ ^[0-9]+$ ]]; then + teamwork::request_failed "Failed to get the project of task $task_id, check the task exists and the API token's user can access it" + continue + fi export TEAMWORK_PROJECT_ID=$project_id ignored_project_ids=("${IGNORE_PROJECT_IDS:-}") if utils::in_array "$project_id" "${ignored_project_ids[*]}" then log::message "ignored due to IGNORE_PROJECT_IDS" - exit 0 + continue fi - if [ "$event" == "pull_request" ] && [ "$action" == "opened" ]; then - teamwork::pull_request_opened - elif [ "$event" == "pull_request" ] && [ "$action" == "closed" ]; then - teamwork::pull_request_closed - elif [ "$event" == "pull_request_review" ] && [ "$action" == "submitted" ]; then - teamwork::pull_request_review_submitted - elif [ "$event" == "pull_request_review" ] && [ "$action" == "dismissed" ]; then - teamwork::pull_request_review_dismissed - elif [ "$ENV" == "test" ]; then # always run pull_request_opened at the very least when in test - teamwork::pull_request_opened - else - log::message "Operation not allowed" - exit 0 - fi + "$handler" done - exit $? + if ((TEAMWORK_FAILED_REQUESTS > 0)); then + log::error "$TEAMWORK_FAILED_REQUESTS Teamwork request(s) failed, see the errors above" + exit 1 + fi + + exit 0 } diff --git a/src/misc.sh b/src/misc.sh index fe935ea9..33ea2037 100644 --- a/src/misc.sh +++ b/src/misc.sh @@ -9,14 +9,6 @@ log::message() { echo "$@" } -env::set_environment() { - if [ "$TEAMWORK_URI" == "localhost" ] && [ "$TEAMWORK_API_TOKEN" == "test_api_token" ]; then - export ENV="test" - else - export ENV="prod" - fi -} - utils::in_array() { ARRAY=$2 for e in ${ARRAY[*]} diff --git a/src/teamwork.sh b/src/teamwork.sh index b3c5e687..f68a359f 100644 --- a/src/teamwork.sh +++ b/src/teamwork.sh @@ -1,12 +1,23 @@ #!/usr/bin/env bash +# Extracts the ids of the tasks linked in the PR body, without duplicates. Only +# links to the Teamwork site in TEAMWORK_URI count, e.g. +# https://acme.teamwork.com/app/tasks/123 or https://acme.teamwork.com/#/tasks/123 teamwork::get_task_id_from_body() { - local body=$1 + # Hostnames are case-insensitive, so both the body and the host are lowercased + local body=${1,,} local task_ids=() - pat='tasks\/([0-9]{1,})' + local host=${TEAMWORK_URI,,} + host=${host#*://} + host=${host%%[/?#]*} + host=${host//./[.]} + + local -r pat="(^|[^a-z0-9.-])${host}(/[^][()<>[:space:]]*)?[/#]tasks/([0-9]+)" while [[ $body =~ $pat ]]; do - task_ids+=( "${BASH_REMATCH[1]}" ) + if ! utils::in_array "${BASH_REMATCH[3]}" "${task_ids[*]}"; then + task_ids+=( "${BASH_REMATCH[3]}" ) + fi body=${body#*"${BASH_REMATCH[0]}"} done @@ -16,69 +27,87 @@ teamwork::get_task_id_from_body() { echo "$task_ids_str" } -teamwork::get_project_id_from_task() { - local -r task_id=$1 +# Calls the Teamwork API and prints the response body. Fails on network errors, +# timeouts and HTTP error statuses, printing the error body in the latter case. +teamwork::request() { + local -r method=$1 + local -r path=$2 + local -r payload=${3:-} - if [ "$ENV" == "test" ]; then - echo "$task_id" - return + local args=(-sS --fail-with-body --max-time 30 -X "$method") + if [ -n "$payload" ]; then + args+=(-H 'Content-Type: application/json; charset=utf-8' -d "$payload") fi - response=$( - curl "$TEAMWORK_URI/projects/api/v1/tasks/$task_id.json" -u "$TEAMWORK_API_TOKEN"':' |\ - jq -r '.["todo-item"]["project-id"]' - ) - echo "$response" + # A "tkn." token is a bearer token, anything else is an API key. The bearer + # header goes in on stdin to keep the token out of the process list. + if [[ $TEAMWORK_API_TOKEN == tkn.* ]]; then + curl "${args[@]}" -H @- "$TEAMWORK_URI$path" <<< "Authorization: Bearer $TEAMWORK_API_TOKEN" + else + curl "${args[@]}" -u "$TEAMWORK_API_TOKEN"':' "$TEAMWORK_URI$path" + fi } -teamwork::get_matching_board_column_id() { - local -r column_name=$1 +# Logs a failed request and records it, so the run fails once every task has +# been processed. +teamwork::request_failed() { + log::error "$1" + TEAMWORK_FAILED_REQUESTS=$((TEAMWORK_FAILED_REQUESTS + 1)) +} - if [ -z "$column_name" ]; then - return - fi +teamwork::get_project_id_from_task() { + local -r task_id=$1 - if [ "$ENV" == "test" ]; then - echo "$TEAMWORK_PROJECT_ID" - return - fi + teamwork::request GET "/projects/api/v1/tasks/$task_id.json" |\ + jq -r '.["todo-item"]["project-id"]' +} - response=$( - curl "$TEAMWORK_URI/projects/$TEAMWORK_PROJECT_ID/boards/columns.json" -u "$TEAMWORK_API_TOKEN"':' |\ - jq -r --arg column_name "$column_name" '[.columns[] | select(.name | contains($column_name))] | map(.id)[0]' - ) +# Resolves a workflow stage name to its " " pair within the +# task's project. Matching is a case-sensitive substring match against the stage +# name (mirroring the legacy board-column behaviour), and the first match wins. +# Echoes nothing when no stage name is provided or no stage matches, and fails +# when the stages can't be fetched. +teamwork::get_workflow_stage() { + local -r stage_name=$1 - if [ "$response" = "null" ]; then + if [ -z "$stage_name" ]; then return fi - echo "$response" + # A single call scoped to the project sideloads every stage across the + # project's workflow(s); each stage carries its parent workflow id, which the + # move endpoint also needs. + teamwork::request GET "/projects/api/v3/workflows.json?projectIds=$TEAMWORK_PROJECT_ID&include=stages" |\ + jq -r --arg stage_name "$stage_name" \ + '[.included.stages[]? | select(.name | contains($stage_name)) | "\(.workflow.id) \(.id)"][0] // empty' } -teamwork::move_task_to_column() { - local -r task_id=$TEAMWORK_TASK_ID - local -r column_name=$1 +teamwork::move_task_to_stage() { + local -r stage_name=$1 - if [ -z "$column_name" ]; then - log::message "No column name provided" + if [ -z "$stage_name" ]; then + log::message "No workflow stage name provided" return fi - local -r column_id=$(teamwork::get_matching_board_column_id "$column_name") - if [ -z "$column_id" ]; then - log::message "Failed to find a matching board column for '$column_name'" + local stage + if ! stage=$(teamwork::get_workflow_stage "$stage_name"); then + teamwork::request_failed "Failed to fetch the workflow stages of project $TEAMWORK_PROJECT_ID" return fi - - if [ "$ENV" == "test" ]; then - log::message "Test - Simulate request. Task ID: $TEAMWORK_TASK_ID - Project ID: $TEAMWORK_PROJECT_ID - Column ID: $column_id" + if [ -z "$stage" ]; then + log::message "Failed to find a matching workflow stage for '$stage_name'" return fi - response=$(curl -X "PUT" "$TEAMWORK_URI/tasks/$TEAMWORK_TASK_ID.json" \ - -u "$TEAMWORK_API_TOKEN"':' \ - -H 'Content-Type: application/json; charset=utf-8' \ - -d "{ \"todo-item\": { \"columnId\": $column_id } }" ) + local workflow_id stage_id + read -r workflow_id stage_id <<< "$stage" + + if ! response=$(teamwork::request PATCH "/projects/api/v3/tasks/$TEAMWORK_TASK_ID/workflows/$workflow_id.json" \ + "{ \"stageId\": $stage_id, \"positionAfterTask\": -1 }"); then + teamwork::request_failed "Failed to move task $TEAMWORK_TASK_ID to the '$stage_name' workflow stage: $response" + return + fi log::message "$response" } @@ -86,32 +115,27 @@ teamwork::move_task_to_column() { teamwork::add_comment() { local -r body=$1 - if [ "$ENV" == "test" ]; then - log::message "Test - Simulate request. Task ID: $TEAMWORK_TASK_ID - Comment: ${body//\"/}" + # jq escapes the body (quotes, backslashes, newlines...) into valid JSON + local -r payload=$(jq -n --arg body "$body" \ + '{ comment: { body: $body, notify: true, "content-type": "text", isprivate: false } }') + + if ! response=$(teamwork::request POST "/tasks/$TEAMWORK_TASK_ID/comments.json" "$payload"); then + teamwork::request_failed "Failed to add a comment to task $TEAMWORK_TASK_ID: $response" return fi - response=$(curl -X "POST" "$TEAMWORK_URI/tasks/$TEAMWORK_TASK_ID/comments.json" \ - -u "$TEAMWORK_API_TOKEN"':' \ - -H 'Content-Type: application/json; charset=utf-8' \ - -d "{ \"comment\": { \"body\": \"${body//\"/}\", \"notify\": true, \"content-type\": \"text\", \"isprivate\": false } }" ) - log::message "$response" } teamwork::add_tag() { local -r tag_name=$1 - if [ "$ENV" == "test" ]; then - log::message "Test - Simulate request. Task ID: $TEAMWORK_TASK_ID - Tag Added: ${tag_name//\"/}" - return - fi - if [ "$AUTOMATIC_TAGGING" == true ]; then - response=$(curl -X "PUT" "$TEAMWORK_URI/tasks/$TEAMWORK_TASK_ID/tags.json" \ - -u "$TEAMWORK_API_TOKEN"':' \ - -H 'Content-Type: application/json; charset=utf-8' \ - -d "{ \"tags\": { \"content\": \"${tag_name//\"/}\" } }" ) + if ! response=$(teamwork::request PUT "/tasks/$TEAMWORK_TASK_ID/tags.json" \ + "{ \"tags\": { \"content\": \"${tag_name//\"/}\" } }"); then + teamwork::request_failed "Failed to add the '$tag_name' tag to task $TEAMWORK_TASK_ID: $response" + return + fi log::message "$response" fi @@ -120,16 +144,12 @@ teamwork::add_tag() { teamwork::remove_tag() { local -r tag_name=$1 - if [ "$ENV" == "test" ]; then - log::message "Test - Simulate request. Task ID: $TEAMWORK_TASK_ID - Tag Removed: ${tag_name//\"/}" - return - fi - if [ "$AUTOMATIC_TAGGING" == true ]; then - response=$(curl -X "PUT" "$TEAMWORK_URI/tasks/$TEAMWORK_TASK_ID/tags.json" \ - -u "$TEAMWORK_API_TOKEN"':' \ - -H 'Content-Type: application/json; charset=utf-8' \ - -d "{ \"tags\": { \"content\": \"${tag_name//\"/}\" },\"removeProvidedTags\":\"true\" }" ) + if ! response=$(teamwork::request PUT "/tasks/$TEAMWORK_TASK_ID/tags.json" \ + "{ \"tags\": { \"content\": \"${tag_name//\"/}\" },\"removeProvidedTags\":\"true\" }"); then + teamwork::request_failed "Failed to remove the '$tag_name' tag from task $TEAMWORK_TASK_ID: $response" + return + fi log::message "$response" fi @@ -145,7 +165,10 @@ teamwork::pull_request_opened() { local -r pr_body=$(github::get_pr_body) IFS=" " read -r -a pr_stats_array <<< "$pr_stats" - teamwork::add_comment " + if [ "$LIGHTWEIGHT_COMMENT" == "true" ]; then + teamwork::add_comment "PR [**\"$pr_title\"**]($pr_url) opened by **$user**" + else + teamwork::add_comment " **$user** opened a PR: **$pr_title** [$pr_url]($pr_url) \`$base_ref\` ⬅️ \`$head_ref\` @@ -158,10 +181,11 @@ ${pr_body} 🔢 ${pr_stats_array[0]} commits / 📝 ${pr_stats_array[1]} files updated / ➕ ${pr_stats_array[2]} additions / ➖ ${pr_stats_array[3]} deletions - " +" + fi teamwork::add_tag "PR Open" - teamwork::move_task_to_column "$BOARD_COLUMN_OPENED" + teamwork::move_task_to_stage "$WORKFLOW_STAGE_OPENED" } teamwork::pull_request_closed() { @@ -171,22 +195,30 @@ teamwork::pull_request_closed() { local -r pr_merged=$(github::get_pr_merged) if [ "$pr_merged" == "true" ]; then - teamwork::add_comment " + if [ "$LIGHTWEIGHT_COMMENT" == "true" ]; then + teamwork::add_comment "PR [**\"$pr_title\"**]($pr_url) merged by **$user**" + else + teamwork::add_comment " **$user** merged a PR: **$pr_title** [$pr_url]($pr_url) " - teamwork::add_tag "PR Merged" - teamwork::remove_tag "PR Open" - teamwork::remove_tag "PR Approved" - teamwork::move_task_to_column "$BOARD_COLUMN_MERGED" + fi + teamwork::add_tag "PR Merged" + teamwork::remove_tag "PR Open" + teamwork::remove_tag "PR Approved" + teamwork::move_task_to_stage "$WORKFLOW_STAGE_MERGED" else - teamwork::add_comment " + if [ "$LIGHTWEIGHT_COMMENT" == "true" ]; then + teamwork::add_comment "PR [**\"$pr_title\"**]($pr_url) closed without merging by **$user**" + else + teamwork::add_comment " **$user** closed a PR without merging: **$pr_title** [$pr_url]($pr_url) " + fi teamwork::remove_tag "PR Open" teamwork::remove_tag "PR Approved" - teamwork::move_task_to_column "$BOARD_COLUMN_CLOSED" + teamwork::move_task_to_stage "$WORKFLOW_STAGE_CLOSED" fi } @@ -199,7 +231,10 @@ teamwork::pull_request_review_submitted() { # Only add a message if the PR has been approved if [ "$review_state" == "approved" ]; then - teamwork::add_comment " + if [ "$LIGHTWEIGHT_COMMENT" == "true" ]; then + teamwork::add_comment "PR [**\"$pr_title\"**]($pr_url) approved by **$user**" + else + teamwork::add_comment " **$user** submitted a review to the PR: **$pr_title** [$pr_url]($pr_url) @@ -208,6 +243,7 @@ teamwork::pull_request_review_submitted() { Review: **$review_state** $comment " + fi teamwork::add_tag "PR Approved" fi } diff --git a/tests/cases/bearer-token/event.json b/tests/cases/bearer-token/event.json new file mode 100644 index 00000000..5f80ac3b --- /dev/null +++ b/tests/cases/bearer-token/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/bearer-token/expected b/tests/cases/bearer-token/expected new file mode 100644 index 00000000..61b2b98a --- /dev/null +++ b/tests/cases/bearer-token/expected @@ -0,0 +1,10 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) opened by **octocat**" + content-type: "text" + isprivate: false + notify: true diff --git a/tests/cases/bearer-token/inputs b/tests/cases/bearer-token/inputs new file mode 100644 index 00000000..18f518c4 --- /dev/null +++ b/tests/cases/bearer-token/inputs @@ -0,0 +1,3 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_TEAMWORK_API_TOKEN=tkn.test-token +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/cases/closed-merged-lightweight/event.json b/tests/cases/closed-merged-lightweight/event.json new file mode 100644 index 00000000..97732713 --- /dev/null +++ b/tests/cases/closed-merged-lightweight/event.json @@ -0,0 +1,27 @@ +{ + "action": "closed", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": true + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/closed-merged-lightweight/expected b/tests/cases/closed-merged-lightweight/expected new file mode 100644 index 00000000..efc96a65 --- /dev/null +++ b/tests/cases/closed-merged-lightweight/expected @@ -0,0 +1,10 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) merged by **octocat**" + content-type: "text" + isprivate: false + notify: true diff --git a/tests/cases/closed-merged-lightweight/inputs b/tests/cases/closed-merged-lightweight/inputs new file mode 100644 index 00000000..76857bf4 --- /dev/null +++ b/tests/cases/closed-merged-lightweight/inputs @@ -0,0 +1,2 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/cases/closed-merged/event.json b/tests/cases/closed-merged/event.json new file mode 100644 index 00000000..97732713 --- /dev/null +++ b/tests/cases/closed-merged/event.json @@ -0,0 +1,27 @@ +{ + "action": "closed", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": true + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/closed-merged/expected b/tests/cases/closed-merged/expected new file mode 100644 index 00000000..e7ec2753 --- /dev/null +++ b/tests/cases/closed-merged/expected @@ -0,0 +1,34 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: + | + | **octocat** merged a PR: **Add OAuth login** + | [https://github.com/acme/webapp/pull/42](https://github.com/acme/webapp/pull/42) + | + content-type: "text" + isprivate: false + notify: true + +PUT /tasks/1001/tags.json -> 200 + tags: + content: "PR Merged" + +PUT /tasks/1001/tags.json -> 200 + removeProvidedTags: "true" + tags: + content: "PR Open" + +PUT /tasks/1001/tags.json -> 200 + removeProvidedTags: "true" + tags: + content: "PR Approved" + +GET /projects/api/v3/workflows.json?projectIds=100&include=stages -> 200 + +PATCH /projects/api/v3/tasks/1001/workflows/7.json -> 204 + positionAfterTask: -1 + stageId: 73 diff --git a/tests/cases/closed-merged/inputs b/tests/cases/closed-merged/inputs new file mode 100644 index 00000000..9d43a813 --- /dev/null +++ b/tests/cases/closed-merged/inputs @@ -0,0 +1,5 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected diff --git a/tests/cases/closed-unmerged-lightweight/event.json b/tests/cases/closed-unmerged-lightweight/event.json new file mode 100644 index 00000000..09ccdcd9 --- /dev/null +++ b/tests/cases/closed-unmerged-lightweight/event.json @@ -0,0 +1,27 @@ +{ + "action": "closed", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/closed-unmerged-lightweight/expected b/tests/cases/closed-unmerged-lightweight/expected new file mode 100644 index 00000000..e7628885 --- /dev/null +++ b/tests/cases/closed-unmerged-lightweight/expected @@ -0,0 +1,10 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) closed without merging by **octocat**" + content-type: "text" + isprivate: false + notify: true diff --git a/tests/cases/closed-unmerged-lightweight/inputs b/tests/cases/closed-unmerged-lightweight/inputs new file mode 100644 index 00000000..76857bf4 --- /dev/null +++ b/tests/cases/closed-unmerged-lightweight/inputs @@ -0,0 +1,2 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/cases/closed-unmerged/event.json b/tests/cases/closed-unmerged/event.json new file mode 100644 index 00000000..09ccdcd9 --- /dev/null +++ b/tests/cases/closed-unmerged/event.json @@ -0,0 +1,27 @@ +{ + "action": "closed", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/closed-unmerged/expected b/tests/cases/closed-unmerged/expected new file mode 100644 index 00000000..a6bd6e18 --- /dev/null +++ b/tests/cases/closed-unmerged/expected @@ -0,0 +1,30 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: + | + | **octocat** closed a PR without merging: **Add OAuth login** + | [https://github.com/acme/webapp/pull/42](https://github.com/acme/webapp/pull/42) + | + content-type: "text" + isprivate: false + notify: true + +PUT /tasks/1001/tags.json -> 200 + removeProvidedTags: "true" + tags: + content: "PR Open" + +PUT /tasks/1001/tags.json -> 200 + removeProvidedTags: "true" + tags: + content: "PR Approved" + +GET /projects/api/v3/workflows.json?projectIds=100&include=stages -> 200 + +PATCH /projects/api/v3/tasks/1001/workflows/7.json -> 204 + positionAfterTask: -1 + stageId: 74 diff --git a/tests/cases/closed-unmerged/inputs b/tests/cases/closed-unmerged/inputs new file mode 100644 index 00000000..9d43a813 --- /dev/null +++ b/tests/cases/closed-unmerged/inputs @@ -0,0 +1,5 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected diff --git a/tests/cases/comment-fails/event.json b/tests/cases/comment-fails/event.json new file mode 100644 index 00000000..dd7b97e2 --- /dev/null +++ b/tests/cases/comment-fails/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1003", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/comment-fails/expected b/tests/cases/comment-fails/expected new file mode 100644 index 00000000..f181ae8c --- /dev/null +++ b/tests/cases/comment-fails/expected @@ -0,0 +1,25 @@ +exit code: 1 + +stderr: + curl: (22) The requested URL returned error: 500 + Failed to add a comment to task 1003: {"MESSAGE": "Internal server error"} + 1 Teamwork request(s) failed, see the errors above + +GET /projects/api/v1/tasks/1003.json -> 200 + +POST /tasks/1003/comments.json -> 500 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) opened by **octocat**" + content-type: "text" + isprivate: false + notify: true + +PUT /tasks/1003/tags.json -> 200 + tags: + content: "PR Open" + +GET /projects/api/v3/workflows.json?projectIds=300&include=stages -> 200 + +PATCH /projects/api/v3/tasks/1003/workflows/7.json -> 204 + positionAfterTask: -1 + stageId: 72 diff --git a/tests/cases/comment-fails/inputs b/tests/cases/comment-fails/inputs new file mode 100644 index 00000000..8a3fe736 --- /dev/null +++ b/tests/cases/comment-fails/inputs @@ -0,0 +1,6 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/cases/deprecated-board-column-closed/event.json b/tests/cases/deprecated-board-column-closed/event.json new file mode 100644 index 00000000..09ccdcd9 --- /dev/null +++ b/tests/cases/deprecated-board-column-closed/event.json @@ -0,0 +1,27 @@ +{ + "action": "closed", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/deprecated-board-column-closed/expected b/tests/cases/deprecated-board-column-closed/expected new file mode 100644 index 00000000..881198eb --- /dev/null +++ b/tests/cases/deprecated-board-column-closed/expected @@ -0,0 +1,16 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) closed without merging by **octocat**" + content-type: "text" + isprivate: false + notify: true + +GET /projects/api/v3/workflows.json?projectIds=100&include=stages -> 200 + +PATCH /projects/api/v3/tasks/1001/workflows/7.json -> 204 + positionAfterTask: -1 + stageId: 74 diff --git a/tests/cases/deprecated-board-column-closed/inputs b/tests/cases/deprecated-board-column-closed/inputs new file mode 100644 index 00000000..3a803811 --- /dev/null +++ b/tests/cases/deprecated-board-column-closed/inputs @@ -0,0 +1,3 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_LIGHTWEIGHT_COMMENT=true +INPUT_BOARD_COLUMN_CLOSED=Rejected diff --git a/tests/cases/deprecated-board-column/event.json b/tests/cases/deprecated-board-column/event.json new file mode 100644 index 00000000..5f80ac3b --- /dev/null +++ b/tests/cases/deprecated-board-column/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/deprecated-board-column/expected b/tests/cases/deprecated-board-column/expected new file mode 100644 index 00000000..0e1fefba --- /dev/null +++ b/tests/cases/deprecated-board-column/expected @@ -0,0 +1,16 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) opened by **octocat**" + content-type: "text" + isprivate: false + notify: true + +GET /projects/api/v3/workflows.json?projectIds=100&include=stages -> 200 + +PATCH /projects/api/v3/tasks/1001/workflows/7.json -> 204 + positionAfterTask: -1 + stageId: 73 diff --git a/tests/cases/deprecated-board-column/inputs b/tests/cases/deprecated-board-column/inputs new file mode 100644 index 00000000..28f49173 --- /dev/null +++ b/tests/cases/deprecated-board-column/inputs @@ -0,0 +1,3 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_LIGHTWEIGHT_COMMENT=true +INPUT_BOARD_COLUMN_OPENED=Ready to Test diff --git a/tests/cases/ignored-project/event.json b/tests/cases/ignored-project/event.json new file mode 100644 index 00000000..a68d412c --- /dev/null +++ b/tests/cases/ignored-project/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Tasks: http://teamwork:8080/app/tasks/1001 and http://teamwork:8080/app/tasks/1002", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/ignored-project/expected b/tests/cases/ignored-project/expected new file mode 100644 index 00000000..cfd35fab --- /dev/null +++ b/tests/cases/ignored-project/expected @@ -0,0 +1,12 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +GET /projects/api/v1/tasks/1002.json -> 200 + +POST /tasks/1002/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) opened by **octocat**" + content-type: "text" + isprivate: false + notify: true diff --git a/tests/cases/ignored-project/inputs b/tests/cases/ignored-project/inputs new file mode 100644 index 00000000..db11e710 --- /dev/null +++ b/tests/cases/ignored-project/inputs @@ -0,0 +1,3 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_LIGHTWEIGHT_COMMENT=true +IGNORE_PROJECT_IDS=100 300 diff --git a/tests/cases/no-task-links/event.json b/tests/cases/no-task-links/event.json new file mode 100644 index 00000000..4517e6e7 --- /dev/null +++ b/tests/cases/no-task-links/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Refactors the login form.", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/no-task-links/expected b/tests/cases/no-task-links/expected new file mode 100644 index 00000000..01fe490f --- /dev/null +++ b/tests/cases/no-task-links/expected @@ -0,0 +1 @@ +exit code: 0 diff --git a/tests/cases/no-task-links/inputs b/tests/cases/no-task-links/inputs new file mode 100644 index 00000000..9d43a813 --- /dev/null +++ b/tests/cases/no-task-links/inputs @@ -0,0 +1,5 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected diff --git a/tests/cases/opened-lightweight/event.json b/tests/cases/opened-lightweight/event.json new file mode 100644 index 00000000..d524f93d --- /dev/null +++ b/tests/cases/opened-lightweight/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Handle \"null\" in C:\\temp", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/opened-lightweight/expected b/tests/cases/opened-lightweight/expected new file mode 100644 index 00000000..0d73eac7 --- /dev/null +++ b/tests/cases/opened-lightweight/expected @@ -0,0 +1,20 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Handle \"null\" in C:\\temp\"**](https://github.com/acme/webapp/pull/42) opened by **octocat**" + content-type: "text" + isprivate: false + notify: true + +PUT /tasks/1001/tags.json -> 200 + tags: + content: "PR Open" + +GET /projects/api/v3/workflows.json?projectIds=100&include=stages -> 200 + +PATCH /projects/api/v3/tasks/1001/workflows/7.json -> 204 + positionAfterTask: -1 + stageId: 72 diff --git a/tests/cases/opened-lightweight/inputs b/tests/cases/opened-lightweight/inputs new file mode 100644 index 00000000..8a3fe736 --- /dev/null +++ b/tests/cases/opened-lightweight/inputs @@ -0,0 +1,6 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/cases/opened/event.json b/tests/cases/opened/event.json new file mode 100644 index 00000000..f3579555 --- /dev/null +++ b/tests/cases/opened/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add \"OAuth\" login", + "body": "## Summary\r\nAdds OAuth login for http://teamwork:8080/app/tasks/1001\r\n\r\n```sh\r\n# configure the \"client\" secret\r\nexport CONFIG_DIR=C:\\Users\\dev\\config\r\n```", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/opened/expected b/tests/cases/opened/expected new file mode 100644 index 00000000..319ba31d --- /dev/null +++ b/tests/cases/opened/expected @@ -0,0 +1,40 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: + | + | **octocat** opened a PR: **Add "OAuth" login** + | [https://github.com/acme/webapp/pull/42](https://github.com/acme/webapp/pull/42) + | `main` ⬅️ `feature/oauth` + | + | --- + | + | #### Summary␍ + | Adds OAuth login for http://teamwork:8080/app/tasks/1001␍ + | ␍ + | ```sh␍ + | # configure the "client" secret␍ + | export CONFIG_DIR=C:\Users\dev\config␍ + | ``` + | + | --- + | + | 🔢 3 commits / 📝 5 files updated / ➕ 120 additions / ➖ 8 deletions + | + | + content-type: "text" + isprivate: false + notify: true + +PUT /tasks/1001/tags.json -> 200 + tags: + content: "PR Open" + +GET /projects/api/v3/workflows.json?projectIds=100&include=stages -> 200 + +PATCH /projects/api/v3/tasks/1001/workflows/7.json -> 204 + positionAfterTask: -1 + stageId: 72 diff --git a/tests/cases/opened/inputs b/tests/cases/opened/inputs new file mode 100644 index 00000000..9d43a813 --- /dev/null +++ b/tests/cases/opened/inputs @@ -0,0 +1,5 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected diff --git a/tests/cases/review-approved-lightweight/event.json b/tests/cases/review-approved-lightweight/event.json new file mode 100644 index 00000000..48e8f8f7 --- /dev/null +++ b/tests/cases/review-approved-lightweight/event.json @@ -0,0 +1,31 @@ +{ + "action": "submitted", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + }, + "review": { + "state": "approved", + "body": "Looks good!" + } +} diff --git a/tests/cases/review-approved-lightweight/expected b/tests/cases/review-approved-lightweight/expected new file mode 100644 index 00000000..3a097566 --- /dev/null +++ b/tests/cases/review-approved-lightweight/expected @@ -0,0 +1,14 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) approved by **octocat**" + content-type: "text" + isprivate: false + notify: true + +PUT /tasks/1001/tags.json -> 200 + tags: + content: "PR Approved" diff --git a/tests/cases/review-approved-lightweight/inputs b/tests/cases/review-approved-lightweight/inputs new file mode 100644 index 00000000..1f98d2ae --- /dev/null +++ b/tests/cases/review-approved-lightweight/inputs @@ -0,0 +1,3 @@ +GITHUB_EVENT_NAME=pull_request_review +INPUT_AUTOMATIC_TAGGING=true +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/cases/review-approved-no-body/event.json b/tests/cases/review-approved-no-body/event.json new file mode 100644 index 00000000..ef9793c8 --- /dev/null +++ b/tests/cases/review-approved-no-body/event.json @@ -0,0 +1,31 @@ +{ + "action": "submitted", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + }, + "review": { + "state": "approved", + "body": null + } +} diff --git a/tests/cases/review-approved-no-body/expected b/tests/cases/review-approved-no-body/expected new file mode 100644 index 00000000..4624ea25 --- /dev/null +++ b/tests/cases/review-approved-no-body/expected @@ -0,0 +1,23 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: + | + | **octocat** submitted a review to the PR: **Add OAuth login** + | [https://github.com/acme/webapp/pull/42](https://github.com/acme/webapp/pull/42) + | + | --- + | + | Review: **approved** + | + | + content-type: "text" + isprivate: false + notify: true + +PUT /tasks/1001/tags.json -> 200 + tags: + content: "PR Approved" diff --git a/tests/cases/review-approved-no-body/inputs b/tests/cases/review-approved-no-body/inputs new file mode 100644 index 00000000..bf4f6030 --- /dev/null +++ b/tests/cases/review-approved-no-body/inputs @@ -0,0 +1,5 @@ +GITHUB_EVENT_NAME=pull_request_review +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected diff --git a/tests/cases/review-approved/event.json b/tests/cases/review-approved/event.json new file mode 100644 index 00000000..3e77ae9d --- /dev/null +++ b/tests/cases/review-approved/event.json @@ -0,0 +1,31 @@ +{ + "action": "submitted", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + }, + "review": { + "state": "approved", + "body": "Looks good!\r\nOne nit: rename `cfg` to \"config\"." + } +} diff --git a/tests/cases/review-approved/expected b/tests/cases/review-approved/expected new file mode 100644 index 00000000..5c558047 --- /dev/null +++ b/tests/cases/review-approved/expected @@ -0,0 +1,24 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: + | + | **octocat** submitted a review to the PR: **Add OAuth login** + | [https://github.com/acme/webapp/pull/42](https://github.com/acme/webapp/pull/42) + | + | --- + | + | Review: **approved** + | Looks good!␍ + | One nit: rename `cfg` to "config". + | + content-type: "text" + isprivate: false + notify: true + +PUT /tasks/1001/tags.json -> 200 + tags: + content: "PR Approved" diff --git a/tests/cases/review-approved/inputs b/tests/cases/review-approved/inputs new file mode 100644 index 00000000..bf4f6030 --- /dev/null +++ b/tests/cases/review-approved/inputs @@ -0,0 +1,5 @@ +GITHUB_EVENT_NAME=pull_request_review +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected diff --git a/tests/cases/review-commented/event.json b/tests/cases/review-commented/event.json new file mode 100644 index 00000000..aa67d482 --- /dev/null +++ b/tests/cases/review-commented/event.json @@ -0,0 +1,31 @@ +{ + "action": "submitted", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + }, + "review": { + "state": "commented", + "body": "Why this change?" + } +} diff --git a/tests/cases/review-commented/expected b/tests/cases/review-commented/expected new file mode 100644 index 00000000..19f4cbd7 --- /dev/null +++ b/tests/cases/review-commented/expected @@ -0,0 +1,3 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 diff --git a/tests/cases/review-commented/inputs b/tests/cases/review-commented/inputs new file mode 100644 index 00000000..bf4f6030 --- /dev/null +++ b/tests/cases/review-commented/inputs @@ -0,0 +1,5 @@ +GITHUB_EVENT_NAME=pull_request_review +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected diff --git a/tests/cases/review-dismissed/event.json b/tests/cases/review-dismissed/event.json new file mode 100644 index 00000000..3ad66cf5 --- /dev/null +++ b/tests/cases/review-dismissed/event.json @@ -0,0 +1,31 @@ +{ + "action": "dismissed", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + }, + "review": { + "state": "dismissed", + "body": null + } +} diff --git a/tests/cases/review-dismissed/expected b/tests/cases/review-dismissed/expected new file mode 100644 index 00000000..73b63c87 --- /dev/null +++ b/tests/cases/review-dismissed/expected @@ -0,0 +1,10 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "Review dismissed by octocat" + content-type: "text" + isprivate: false + notify: true diff --git a/tests/cases/review-dismissed/inputs b/tests/cases/review-dismissed/inputs new file mode 100644 index 00000000..bf4f6030 --- /dev/null +++ b/tests/cases/review-dismissed/inputs @@ -0,0 +1,5 @@ +GITHUB_EVENT_NAME=pull_request_review +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected diff --git a/tests/cases/stage-not-found/event.json b/tests/cases/stage-not-found/event.json new file mode 100644 index 00000000..5f80ac3b --- /dev/null +++ b/tests/cases/stage-not-found/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/stage-not-found/expected b/tests/cases/stage-not-found/expected new file mode 100644 index 00000000..9bcdc992 --- /dev/null +++ b/tests/cases/stage-not-found/expected @@ -0,0 +1,12 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) opened by **octocat**" + content-type: "text" + isprivate: false + notify: true + +GET /projects/api/v3/workflows.json?projectIds=100&include=stages -> 200 diff --git a/tests/cases/stage-not-found/inputs b/tests/cases/stage-not-found/inputs new file mode 100644 index 00000000..c14aee62 --- /dev/null +++ b/tests/cases/stage-not-found/inputs @@ -0,0 +1,3 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_LIGHTWEIGHT_COMMENT=true +INPUT_WORKFLOW_STAGE_OPENED=Code Review diff --git a/tests/cases/tagging-disabled/event.json b/tests/cases/tagging-disabled/event.json new file mode 100644 index 00000000..97732713 --- /dev/null +++ b/tests/cases/tagging-disabled/event.json @@ -0,0 +1,27 @@ +{ + "action": "closed", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": true + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/tagging-disabled/expected b/tests/cases/tagging-disabled/expected new file mode 100644 index 00000000..121253c7 --- /dev/null +++ b/tests/cases/tagging-disabled/expected @@ -0,0 +1,16 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) merged by **octocat**" + content-type: "text" + isprivate: false + notify: true + +GET /projects/api/v3/workflows.json?projectIds=100&include=stages -> 200 + +PATCH /projects/api/v3/tasks/1001/workflows/7.json -> 204 + positionAfterTask: -1 + stageId: 73 diff --git a/tests/cases/tagging-disabled/inputs b/tests/cases/tagging-disabled/inputs new file mode 100644 index 00000000..60904cd2 --- /dev/null +++ b/tests/cases/tagging-disabled/inputs @@ -0,0 +1,4 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_AUTOMATIC_TAGGING=false +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/cases/task-links/event.json b/tests/cases/task-links/event.json new file mode 100644 index 00000000..94875ab9 --- /dev/null +++ b/tests/cases/task-links/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Linked twice: [http://teamwork:8080/app/tasks/1001](http://teamwork:8080/app/tasks/1001)\nUpper case, old route: HTTP://TEAMWORK:8080/#/tasks/1002\nAgain: http://teamwork:8080/#tasks/1001\nNot task links: subtasks/5, https://github.com/acme/webapp/blob/main/scripts/tasks/2024_cleanup.py\nAnother Teamwork site: https://acme.teamwork.com/app/tasks/1003\nLook-alike host: http://evil-teamwork:8080/app/tasks/1003", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/task-links/expected b/tests/cases/task-links/expected new file mode 100644 index 00000000..7fc65fe7 --- /dev/null +++ b/tests/cases/task-links/expected @@ -0,0 +1,19 @@ +exit code: 0 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) opened by **octocat**" + content-type: "text" + isprivate: false + notify: true + +GET /projects/api/v1/tasks/1002.json -> 200 + +POST /tasks/1002/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) opened by **octocat**" + content-type: "text" + isprivate: false + notify: true diff --git a/tests/cases/task-links/inputs b/tests/cases/task-links/inputs new file mode 100644 index 00000000..76857bf4 --- /dev/null +++ b/tests/cases/task-links/inputs @@ -0,0 +1,2 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/cases/task-not-found/event.json b/tests/cases/task-not-found/event.json new file mode 100644 index 00000000..c9ba3a23 --- /dev/null +++ b/tests/cases/task-not-found/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Tasks: http://teamwork:8080/app/tasks/9999 and http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/task-not-found/expected b/tests/cases/task-not-found/expected new file mode 100644 index 00000000..c4a6fec0 --- /dev/null +++ b/tests/cases/task-not-found/expected @@ -0,0 +1,17 @@ +exit code: 1 + +stderr: + curl: (22) The requested URL returned error: 404 + Failed to get the project of task 9999, check the task exists and the API token's user can access it + 1 Teamwork request(s) failed, see the errors above + +GET /projects/api/v1/tasks/9999.json -> 404 + +GET /projects/api/v1/tasks/1001.json -> 200 + +POST /tasks/1001/comments.json -> 201 + comment: + body: "PR [**\"Add OAuth login\"**](https://github.com/acme/webapp/pull/42) opened by **octocat**" + content-type: "text" + isprivate: false + notify: true diff --git a/tests/cases/task-not-found/inputs b/tests/cases/task-not-found/inputs new file mode 100644 index 00000000..76857bf4 --- /dev/null +++ b/tests/cases/task-not-found/inputs @@ -0,0 +1,2 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/cases/unsupported-event/event.json b/tests/cases/unsupported-event/event.json new file mode 100644 index 00000000..da136fb5 --- /dev/null +++ b/tests/cases/unsupported-event/event.json @@ -0,0 +1,27 @@ +{ + "action": "synchronize", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/unsupported-event/expected b/tests/cases/unsupported-event/expected new file mode 100644 index 00000000..01fe490f --- /dev/null +++ b/tests/cases/unsupported-event/expected @@ -0,0 +1 @@ +exit code: 0 diff --git a/tests/cases/unsupported-event/inputs b/tests/cases/unsupported-event/inputs new file mode 100644 index 00000000..9d43a813 --- /dev/null +++ b/tests/cases/unsupported-event/inputs @@ -0,0 +1,5 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_AUTOMATIC_TAGGING=true +INPUT_WORKFLOW_STAGE_OPENED=PR Open +INPUT_WORKFLOW_STAGE_MERGED=Ready to Test +INPUT_WORKFLOW_STAGE_CLOSED=Rejected diff --git a/tests/cases/wrong-bearer-token/event.json b/tests/cases/wrong-bearer-token/event.json new file mode 100644 index 00000000..5f80ac3b --- /dev/null +++ b/tests/cases/wrong-bearer-token/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/wrong-bearer-token/expected b/tests/cases/wrong-bearer-token/expected new file mode 100644 index 00000000..23f51418 --- /dev/null +++ b/tests/cases/wrong-bearer-token/expected @@ -0,0 +1,8 @@ +exit code: 1 + +stderr: + curl: (22) The requested URL returned error: 401 + Failed to get the project of task 1001, check the task exists and the API token's user can access it + 1 Teamwork request(s) failed, see the errors above + +GET /projects/api/v1/tasks/1001.json -> 401 diff --git a/tests/cases/wrong-bearer-token/inputs b/tests/cases/wrong-bearer-token/inputs new file mode 100644 index 00000000..8690570f --- /dev/null +++ b/tests/cases/wrong-bearer-token/inputs @@ -0,0 +1,3 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_TEAMWORK_API_TOKEN=tkn.wrong-token +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/cases/wrong-token/event.json b/tests/cases/wrong-token/event.json new file mode 100644 index 00000000..5f80ac3b --- /dev/null +++ b/tests/cases/wrong-token/event.json @@ -0,0 +1,27 @@ +{ + "action": "opened", + "number": 42, + "pull_request": { + "number": 42, + "title": "Add OAuth login", + "body": "Task: http://teamwork:8080/app/tasks/1001", + "html_url": "https://github.com/acme/webapp/pull/42", + "head": { + "ref": "feature/oauth", + "repo": { + "full_name": "acme/webapp" + } + }, + "base": { + "ref": "main" + }, + "commits": 3, + "changed_files": 5, + "additions": 120, + "deletions": 8, + "merged": false + }, + "sender": { + "login": "octocat" + } +} diff --git a/tests/cases/wrong-token/expected b/tests/cases/wrong-token/expected new file mode 100644 index 00000000..23f51418 --- /dev/null +++ b/tests/cases/wrong-token/expected @@ -0,0 +1,8 @@ +exit code: 1 + +stderr: + curl: (22) The requested URL returned error: 401 + Failed to get the project of task 1001, check the task exists and the API token's user can access it + 1 Teamwork request(s) failed, see the errors above + +GET /projects/api/v1/tasks/1001.json -> 401 diff --git a/tests/cases/wrong-token/inputs b/tests/cases/wrong-token/inputs new file mode 100644 index 00000000..1e001d12 --- /dev/null +++ b/tests/cases/wrong-token/inputs @@ -0,0 +1,3 @@ +GITHUB_EVENT_NAME=pull_request +INPUT_TEAMWORK_API_TOKEN=wrong-token +INPUT_LIGHTWEIGHT_COMMENT=true diff --git a/tests/events/pull_request_approved.json b/tests/events/pull_request_approved.json deleted file mode 100644 index 2ea240ce..00000000 --- a/tests/events/pull_request_approved.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "action": "submitted", - "number": 1, - "pull_request": { - "body": "This is the body of the PR. https://xxxx.teamwork.com/#/tasks/123 https://xxx.teamwork.com/#/tasks/456", - "head": { - "repo": { - "full_name": "teamwork/github-sync" - } - }, - "html_url": "https://github.com/teamwork/github-sync/pull/2", - "title": "This is an example of a title for the PR." - }, - "review": { - "state": "approved", - "body": "This is the comment of the review." - }, - "sender": { - "login": "username" - } -} \ No newline at end of file diff --git a/tests/events/pull_request_closed.json b/tests/events/pull_request_closed.json deleted file mode 100644 index 4e6ee486..00000000 --- a/tests/events/pull_request_closed.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "action": "closed", - "number": 1, - "pull_request": { - "body": "This is the body of the PR. https://xxxx.teamwork.com/#/tasks/123 https://xxx.teamwork.com/#/tasks/456", - "head": { - "repo": { - "full_name": "teamwork/github-sync" - } - }, - "html_url": "https://github.com/teamwork/github-sync/pull/1", - "title": "This is an example of a title for the PR.", - "merged": false - }, - "sender": { - "login": "username" - } -} \ No newline at end of file diff --git a/tests/events/pull_request_merged.json b/tests/events/pull_request_merged.json deleted file mode 100644 index d3b3998b..00000000 --- a/tests/events/pull_request_merged.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "action": "closed", - "number": 1, - "pull_request": { - "body": "This is the body of the PR. https://xxxx.teamwork.com/#/tasks/123 https://xxx.teamwork.com/#/tasks/456", - "head": { - "repo": { - "full_name": "teamwork/github-sync" - } - }, - "html_url": "https://github.com/teamwork/github-sync/pull/1", - "title": "This is an example of a title for the PR.", - "merged": true - }, - "sender": { - "login": "username" - } -} \ No newline at end of file diff --git a/tests/events/pull_request_opened.json b/tests/events/pull_request_opened.json deleted file mode 100644 index 88e64a11..00000000 --- a/tests/events/pull_request_opened.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "action": "opened", - "number": 1, - "pull_request": { - "body": "# Test heading \n This is the body of the PR. https://xxxx.teamwork.com/#/tasks/123 https://xxx.teamwork.com/#/tasks/456", - "head": { - "ref": "pr-branch", - "repo": { - "full_name": "teamwork/github-sync" - } - }, - "base": { - "ref": "main" - }, - "html_url": "https://github.com/teamwork/github-sync/pull/1", - "title": "This is an example of a title for the PR.", - "commits": 1, - "additions": 2, - "deletions": 3, - "changed_files": 4 - }, - "sender": { - "login": "username" - } -} diff --git a/tests/mock-teamwork.py b/tests/mock-teamwork.py new file mode 100644 index 00000000..35829887 --- /dev/null +++ b/tests/mock-teamwork.py @@ -0,0 +1,105 @@ +"""Mock Teamwork API for tests/run.sh. + +Answers from the fixed data below and records every request it receives, in a +readable form, to the file given as its only argument. +""" +import base64 +import json +import re +import sys +from http.server import BaseHTTPRequestHandler, HTTPServer + +LOG_PATH = sys.argv[1] +AUTHORIZATIONS = {"Basic " + base64.b64encode(b"test-token:").decode(), "Bearer tkn.test-token"} + +# Task id -> project id. Requests about any other task fail with a 404. +TASKS = {"1001": 100, "1002": 200, "1003": 300} +# Adding a comment to these tasks fails with a server error. +FAILING_COMMENTS = {"1003"} +# Every project uses the same workflow (id 7), with these stages. +STAGES = { + str(stage_id): {"id": stage_id, "name": name, "workflow": {"id": 7, "type": "workflows"}} + for stage_id, name in [(71, "To Do"), (72, "PR Open"), (73, "Ready to Test"), (74, "Rejected")] +} + + +def render(value, indent=1): + """Renders a JSON body as indented "key: value" lines. Multi-line strings are + shown line by line after a "|" gutter, with control characters such as \\r + shown as their Unicode pictures (␍).""" + pad = " " * indent + if not isinstance(value, dict): + return [pad + json.dumps(value, ensure_ascii=False)] + lines = [] + for key in sorted(value): + item = value[key] + if isinstance(item, dict): + lines += [f"{pad}{key}:", *render(item, indent + 1)] + elif isinstance(item, str) and "\n" in item: + lines.append(f"{pad}{key}:") + for line in item.split("\n"): + line = "".join(chr(0x2400 + ord(c)) if ord(c) < 0x20 else c for c in line) + lines.append(f"{pad} | {line}".rstrip()) + else: + lines.append(f"{pad}{key}: {json.dumps(item, ensure_ascii=False)}") + return lines + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def handle_request(self): + raw = self.rfile.read(int(self.headers.get("Content-Length") or 0)).decode() + status, response, details = self.respond(raw) + # Record before replying, so the log is complete once the action exits + with open(LOG_PATH, "a") as log: + log.write("\n" + "\n".join([f"{self.command} {self.path} -> {status}", *details]) + "\n") + + body = json.dumps(response).encode() if response is not None else b"" + self.send_response(status) + if body: + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + do_GET = do_POST = do_PUT = do_PATCH = handle_request + + def respond(self, raw): + """Returns the status, response body and recorded details of a request.""" + details = [] + if raw: + if not self.headers.get("Content-Type", "").startswith("application/json"): + return 415, {"MESSAGE": "Expected a JSON body"}, [" " + json.dumps(raw)] + try: + details = render(json.loads(raw)) + except ValueError as error: + return 400, {"MESSAGE": "Invalid JSON"}, [f" invalid JSON: {error}", " " + json.dumps(raw)] + + if self.headers.get("Authorization") not in AUTHORIZATIONS: + return 401, {"MESSAGE": "Unauthorized"}, details + + task = re.search(r"/tasks/(\d+)", self.path) + if task and task[1] not in TASKS: + return 404, {"MESSAGE": "Not found"}, details + + request = f"{self.command} {self.path}" + if task := re.fullmatch(r"GET /projects/api/v1/tasks/(\d+)\.json", request): + return 200, {"todo-item": {"id": int(task[1]), "project-id": TASKS[task[1]]}}, details + if re.fullmatch(r"GET /projects/api/v3/workflows\.json\?projectIds=\d+&include=stages", request): + return 200, {"workflows": [{"id": 7, "name": "Development"}], "included": {"stages": STAGES}}, details + if task := re.fullmatch(r"POST /tasks/(\d+)/comments\.json", request): + if task[1] in FAILING_COMMENTS: + return 500, {"MESSAGE": "Internal server error"}, details + return 201, {"STATUS": "OK", "commentId": "1"}, details + if re.fullmatch(r"PUT /tasks/\d+/tags\.json", request): + return 200, {"STATUS": "OK"}, details + if re.fullmatch(r"PATCH /projects/api/v3/tasks/\d+/workflows/7\.json", request): + return 204, None, details + return 404, {"MESSAGE": "Unknown route"}, details + + +server = HTTPServer(("", 8080), Handler) +print("listening", flush=True) +server.serve_forever() diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 00000000..f2cd198c --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# Runs the action's Docker image against a mock Teamwork API +# (tests/mock-teamwork.py) for every case in tests/cases, and compares the exit +# code, stderr and requests the mock received with the case's expected file. +# +# A case is a directory with: +# event.json the GitHub event payload +# inputs KEY=VALUE lines: GITHUB_EVENT_NAME, the INPUT_* env vars GitHub +# creates for the action's inputs, and any other env such as +# IGNORE_PROJECT_IDS. Inputs that aren't set are empty. +# expected what the run should produce +# +# Usage: tests/run.sh [--update] [filter] +# --update rewrites the expected files from the current output +# filter only runs the cases whose name contains it +set -euo pipefail + +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +IMAGE=github-sync:test +NETWORK=github-sync-test +MOCK=github-sync-teamwork + +update=false +filter= +for arg in "$@"; do + if [ "$arg" == "--update" ]; then + update=true + else + filter=$arg + fi +done + +stop_mock() { + docker rm --force "$MOCK" >/dev/null 2>&1 || true + docker network rm "$NETWORK" >/dev/null 2>&1 || true +} + +work=$(mktemp -d) +trap 'stop_mock; rm -rf "$work"' EXIT + +# The action's args, in action.yml order, as the input each one comes from +# (empty for the '' placeholders). The GitHub runner builds them the same way. +arg_inputs=() +while IFS= read -r item || [ -n "$item" ]; do + case $item in + "''") arg_inputs+=("") ;; + "\${{ inputs."*" }}") + item=${item#"\${{ inputs."} + arg_inputs+=("${item%" }}"}") ;; + *) + echo "Unsupported item in action.yml's runs.args: $item" >&2 + exit 1 ;; + esac +done < <(sed -n '/^ args:/,/^[^ #]/ s/^ - //p' "$ROOT/action.yml") + +# Runs the action for the case in $1 the way GitHub does: inputs as INPUT_* env +# vars, passed by name only, and as positional args built from action.yml. +run_case() ( + local -r dir=$1 + + export INPUT_TEAMWORK_URI=http://teamwork:8080 + export INPUT_TEAMWORK_API_TOKEN=test-token + local env_names=(INPUT_TEAMWORK_URI INPUT_TEAMWORK_API_TOKEN) + local line + while IFS= read -r line || [ -n "$line" ]; do + case $line in ''|'#'*) continue ;; esac + export "${line%%=*}=${line#*=}" + env_names+=("${line%%=*}") + done < "$dir/inputs" + + local docker_args=(--rm --network "$NETWORK" --volume "$dir/event.json:/github/workflow/event.json:ro" + --env GITHUB_REPOSITORY=acme/webapp --env GITHUB_EVENT_PATH=/github/workflow/event.json) + local env_name + for env_name in "${env_names[@]}"; do + docker_args+=(--env "$env_name") + done + + local action_args=() input value + for input in "${arg_inputs[@]}"; do + value= + if [ -n "$input" ]; then + env_name="INPUT_$input" + value=${!env_name:-} + fi + action_args+=("$value") + done + + docker run "${docker_args[@]}" "$IMAGE" "${action_args[@]}" +) + +docker build --quiet --tag "$IMAGE" "$ROOT" >/dev/null + +stop_mock +docker network create "$NETWORK" >/dev/null +docker run --detach --name "$MOCK" --network "$NETWORK" --network-alias teamwork \ + --volume "$ROOT/tests/mock-teamwork.py:/mock-teamwork.py:ro" --volume "$work:/out" \ + python:3.13-alpine python /mock-teamwork.py /out/requests >/dev/null +for _ in $(seq 50); do + if docker logs "$MOCK" 2>&1 | grep -q listening; then + break + fi + sleep 0.1 +done +if ! docker logs "$MOCK" 2>&1 | grep -q listening; then + echo "The mock Teamwork API didn't start:" >&2 + docker logs "$MOCK" >&2 + exit 1 +fi + +ran=0 +failed=0 +for dir in "$ROOT"/tests/cases/*/; do + dir=${dir%/} + name=$(basename "$dir") + case $name in *"$filter"*) ;; *) continue ;; esac + ran=$((ran + 1)) + + : > "$work/requests" + code=0 + run_case "$dir" > "$work/stdout" 2> "$work/stderr" || code=$? + { + echo "exit code: $code" + if [ -s "$work/stderr" ]; then + echo + echo "stderr:" + sed 's/^/ /' "$work/stderr" + fi + cat "$work/requests" + } > "$work/actual" + + if $update; then + cp "$work/actual" "$dir/expected" + echo "updated $name" + elif diff -u "$dir/expected" "$work/actual" > "$work/diff" 2>&1; then + echo "ok $name" + else + failed=$((failed + 1)) + echo "FAIL $name" + sed 's/^/ /' "$work/diff" + echo " action stdout:" + sed 's/^/ /' "$work/stdout" + fi +done + +echo +if ((ran == 0)); then + echo "No cases match '$filter'" + exit 1 +fi +if $update; then + echo "Updated $ran expected file(s), review them before committing" +elif ((failed > 0)); then + echo "$failed of $ran case(s) failed" + exit 1 +else + echo "All $ran case(s) passed" +fi