Skip to main content

Эта версия GitHub Enterprise Server была прекращена 2024-07-09. Исправления выпускаться не будут даже при критических проблемах безопасности. Для повышения производительности, повышения безопасности и новых функций выполните обновление до последней версии GitHub Enterprise Server. Чтобы получить справку по обновлению, обратитесь в службу поддержки GitHub Enterprise.

Использование скриптов для тестирования кода в средстве выполнения тестов

Использование основных функций GitHub Actions для непрерывной интеграции (CI).

Примечание. В GitHub Enterprise Server в настоящее время не поддерживаются средства выполнения тестов, размещенные в GitHub. Дополнительные сведения о планируемой поддержке в будущем см. в GitHub public roadmap.

Обзор примера

В этой статье на примере рабочего процесса демонстрируется применение некоторых функций GitHub Actions для непрерывной интеграции. При активации этого рабочего процесса он автоматически запускает скрипт, который проверяет, есть ли на сайте Документов GitHub неработающие ссылки.

На следующей схеме показано общее представление этапов рабочего процесса и их выполнение в задании:

Схема события, запускающего рабочий процесс, использующий скрипты для тестирования кода.

Функции, используемые в этом примере

В примере рабочего процесса показаны следующие возможности GitHub Actions.

КомпонентРеализация
Активация рабочего процесса для автоматического запускаpush
Активация рабочего процесса для автоматического запускаpull_request
Запуск рабочего процесса вручную из пользовательского интерфейсаworkflow_dispatch
Настройка разрешений для маркераpermissions
Управление числом запусков или заданий рабочего процесса в одно и то же времяconcurrency
Выполнение задания в разных запусках в зависимости от репозиторияruns-on
Использование стороннего действияtrilom/file-changes-action

Пример рабочего процесса

Следующий рабочий процесс был создан командой разработчиков документации для GitHub. Чтобы получить последнюю версию этого файла из репозитория github/docs, перейдите по адресу: check-broken-links-github-github.yml.

Следующий рабочий процесс отображает содержимое каждой страницы в документации и проверка все внутренние ссылки, чтобы убедиться, что они подключены правильно.

YAML
name: 'Link Checker: All English'

Это определяет имя рабочего процесса, как оно будет отображаться на вкладке "Действия" репозитория GitHub .

on:

The on key lets you define the events that trigger when the workflow is run. You can define multiple events here. For more information, see "Активация рабочего процесса."

  workflow_dispatch:

Add the workflow_dispatch event if you want to be able to manually run this workflow from the UI. For more information, see workflow_dispatch.

  push:
    branches:
      - main

Add the push event, so that the workflow runs automatically every time a commit is pushed to a branch called main. For more information, see push.

  pull_request:

Add the pull_request event, so that the workflow runs automatically every time a pull request is created or updated. For more information, see pull_request.

permissions:
  contents: read
  pull-requests: read

This modifies the default permissions granted to GITHUB_TOKEN. This will vary depending on the needs of your workflow. For more information, see "Назначение разрешений для заданий."

In this example, the pull-requests: read permission is needed for the trilom/file-changes-action action that is used later in this workflow.

concurrency:
  group: '${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}'
  cancel-in-progress: true

The concurrency key ensures that only a single workflow in the same concurrency group will run at the same time. For more information, see "Использование параллелизма." concurrency.group generates a concurrency group name from the workflow name and pull request information. The || operator is used to define fallback values. concurrency.cancel-in-progress cancels any currently running job or workflow in the same concurrency group.

jobs:

The jobs key groups together all the jobs that run in the workflow file.

  check-links:

This line defines a job with the ID check-links that is stored within the jobs key.

    runs-on: ${{ fromJSON('["ubuntu-latest", "self-hosted"]')[github.repository == 'github/docs-internal'] }}

The runs-on key in this example configures the job to run on a GitHub-hosted runner or a self-hosted runner, depending on the repository running the workflow.

In this example, the job will run on a self-hosted runner if the repository is named docs-internal and is within the github organization. If the repository doesn't match this path, then it will run on an ubuntu-latest runner hosted by GitHub. For more information on these options, see "Выбор средства выполнения тестов для задания."

    steps:

The steps key groups together all the steps that will run as part of the check-links job. Each job in a workflow has its own steps section.

      - name: Checkout
        uses: actions/checkout@v4

The uses key tells the job to retrieve the action named actions/checkout. This is an action that checks out your repository and downloads it to the runner, allowing you to run actions against your code (such as testing tools). You must use the checkout action any time your workflow will use the repository's code or you are using an action defined in the repository.

      - name: Setup node
        uses: actions/setup-node@v4
        with:
          node-version: 16.13.x
          cache: npm

This step uses the actions/setup-node action to install the specified version of the Node.js software package on the runner, which gives you access to the npm command.

      - name: Install
        run: npm ci

The run key tells the job to execute a command on the runner. In this example, npm ci is used to install the npm software packages for the project.

      - name: Gather files changed
        uses: trilom/file-changes-action@a6ca26c14274c33b15e6499323aac178af06ad4b
        with:
          fileOutput: 'json'

This step uses the trilom/file-changes-action action to gather all the changed files. This example is pinned to a specific version of the action, using the a6ca26c14274c33b15e6499323aac178af06ad4b SHA.

In this example, this step creates the file "${{ env.HOME }}/files.json", among others.

      - name: Show files changed
        run: cat $HOME/files.json

To help with verification, this step lists the contents of files.json. This will be visible in the workflow run's log, and can be useful for debugging.

      - name: Link check (warnings, changed files)
        run: |
          ./script/rendered-content-link-checker.mjs \
            --language en \
            --max 100 \
            --check-anchors \
            --check-images \
            --verbose \
            --list $HOME/files.json

This step uses the run command to execute a script that is stored in the repository at script/rendered-content-link-checker.mjs and passes all the parameters it needs to run.

      - name: Link check (critical, all files)
        run: |
          ./script/rendered-content-link-checker.mjs \
            --language en \
            --exit \
            --verbose \
            --check-images \
            --level critical

This step also uses run command to execute a script that is stored in the repository at script/rendered-content-link-checker.mjs and passes a different set of parameters.

# Это определяет имя рабочего процесса, как оно будет отображаться на вкладке "Действия" репозитория GitHub .
name: 'Link Checker: All English'

# The `on` key lets you define the events that trigger when the workflow is run. You can define multiple events here. For more information, see "[AUTOTITLE](/actions/using-workflows/triggering-a-workflow#using-events-to-trigger-workflows)."
on:
# Add the `workflow_dispatch` event if you want to be able to manually run this workflow from the UI. For more information, see [`workflow_dispatch`](/actions/using-workflows/events-that-trigger-workflows#workflow_dispatch).
  workflow_dispatch:
  # Add the `push` event, so that the workflow runs automatically every time a commit is pushed to a branch called `main`. For more information, see [`push`](/actions/using-workflows/events-that-trigger-workflows#push).
  push:
    branches:
      - main
  # Add the `pull_request` event, so that the workflow runs automatically every time a pull request is created or updated. For more information, see [`pull_request`](/actions/using-workflows/events-that-trigger-workflows#pull_request).
  pull_request:

# This modifies the default permissions granted to `GITHUB_TOKEN`. This will vary depending on the needs of your workflow. For more information, see "[AUTOTITLE](/actions/using-jobs/assigning-permissions-to-jobs)."
#
# In this example, the `pull-requests: read` permission is needed for the `trilom/file-changes-action` action that is used later in this workflow.
permissions:
  contents: read
  pull-requests: read
# The `concurrency` key ensures that only a single workflow in the same concurrency group will run at the same time. For more information, see "[AUTOTITLE](/actions/using-jobs/using-concurrency)."
# `concurrency.group` generates a concurrency group name from the workflow name and pull request information. The `||` operator is used to define fallback values. 
# `concurrency.cancel-in-progress` cancels any currently running job or workflow in the same concurrency group.
concurrency:
  group: '${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}'
  cancel-in-progress: true

# The `jobs` key groups together all the jobs that run in the workflow file.
jobs:
  # This line defines a job with the ID `check-links` that is stored within the `jobs` key.
  check-links:
    # The `runs-on` key in this example configures the job to run on a GitHub-hosted runner or a self-hosted runner, depending on the repository running the workflow. 
    # 
    # In this example, the job will run on a self-hosted runner if the repository is named `docs-internal` and is within the `github` organization. If the repository doesn't match this path, then it will run on an `ubuntu-latest` runner hosted by GitHub. For more information on these options, see "[AUTOTITLE](/actions/using-jobs/choosing-the-runner-for-a-job)."
    runs-on: ${{ fromJSON('["ubuntu-latest", "self-hosted"]')[github.repository == 'github/docs-internal'] }}
    # The `steps` key groups together all the steps that will run as part of the `check-links` job. Each job in a workflow has its own `steps` section.
    steps:
      # The `uses` key tells the job to retrieve the action named `actions/checkout`. This is an action that checks out your repository and downloads it to the runner, allowing you to run actions against your code (such as testing tools). You must use the checkout action any time your workflow will use the repository's code or you are using an action defined in the repository.
      - name: Checkout
        uses: actions/checkout@v4

      # This step uses the `actions/setup-node` action to install the specified version of the Node.js software package on the runner, which gives you access to the `npm` command.
      - name: Setup node
        uses: actions/setup-node@v4
        with:
          node-version: 16.13.x
          cache: npm

      # The `run` key tells the job to execute a command on the runner. In this example, `npm ci` is used to install the npm software packages for the project.
      - name: Install
        run: npm ci

      # This step uses the `trilom/file-changes-action` action to gather all the changed files. This example is pinned to a specific version of the action, using the `a6ca26c14274c33b15e6499323aac178af06ad4b` SHA.
      # 
      # In this example, this step creates the file "${{ env.HOME }}/files.json", among others.
      - name: Gather files changed
        uses: trilom/file-changes-action@a6ca26c14274c33b15e6499323aac178af06ad4b
        with:
          fileOutput: 'json'

      # To help with verification, this step lists the contents of `files.json`. This will be visible in the workflow run's log, and can be useful for debugging.
      - name: Show files changed
        run: cat $HOME/files.json

      # This step uses the `run` command to execute a script that is stored in the repository at `script/rendered-content-link-checker.mjs` and passes all the parameters it needs to run.
      - name: Link check (warnings, changed files)
        run: |
          ./script/rendered-content-link-checker.mjs \
            --language en \
            --max 100 \
            --check-anchors \
            --check-images \
            --verbose \
            --list $HOME/files.json

      # This step also uses `run` command to execute a script that is stored in the repository at `script/rendered-content-link-checker.mjs` and passes a different set of parameters.
      - name: Link check (critical, all files)
        run: |
          ./script/rendered-content-link-checker.mjs \
            --language en \
            --exit \
            --verbose \
            --check-images \
            --level critical

Следующие шаги