如何根据代码更改在同一个 GitLab CI 阶段执行不同的脚本

问题描述 投票:0回答:1

我有一个要求,我需要运行一个名为

test
的相同 GitLab CI 作业,并根据代码更改执行两个不同的脚本。

例如文件夹结构为:-

 - core
    - client-1
       - tests/
       - requirement-file
    - client-2
       - tests/
       - requirement-file
 - .gitlab-ci.yml
 - README.md
 - .gitignore

GitLab CI YAML 文件具有:-

stages:
  - tests

tests:
  stage: tests
  image: python:3.11
  script:
    - cd core/client-1 # run the test cases for client1
    - pip install virtualenv
    - virtualenv venv
    - source venv/bin/activate
    - export DISABLE_AUTH="True"
    - venv/bin/pytest tests/ --junitxml="testresult.xml"
    - venv/bin/coverage xml -i
    - venv/bin/coverage html

    #TODO to add some condition in the script itself to detect the code changes at this level and execute respective test cases only

    - cd core/client-2 # Run the test cases for client-2
    - venv/bin/pytest tests/ --junitxml="testresult.xml"

因此,要求是每当 client-1 代码发生更改时,仅在该阶段使用 pytest

 命令执行测试用例
,如果 client2 发生更改,则只应执行
 pytest
client-2 命令,如果两者都有更改,则让他们为两个客户端执行测试。

我知道 GitLab 有一个在像这样的阶段使用的更改概念

only: changes: - /abc/xyz/**/**
但我相信,如果我使用更改,那么我可能必须复制这些阶段,一个用于 client1,另一个用于 client2,以检测代码更改并决定是否在 GitLab Stage 级别运行,但我想要的是检测代码在脚本级别更改,这样我就不必重复测试阶段。

gitlab gitlab-ci gitlab-ci-runner
1个回答
0
投票
我找到了解决方案,可以像下面这样解决:-

stages: - tests tests: stage: tests image: python:3.11 script: - | if git diff --name-only $CI_COMMIT_BEFORE_SHA $CI_COMMIT_SHA | grep -q '^core/client-1/'; then # Run the test cases for client-1 cd core/client-1 pip install virtualenv virtualenv venv source venv/bin/activate export DISABLE_AUTH="True" venv/bin/pytest tests/ --junitxml="testresult.xml" venv/bin/coverage xml -i venv/bin/coverage html fi - | if git diff --name-only $CI_COMMIT_BEFORE_SHA $CI_COMMIT_SHA | grep -q '^core/client-2/'; then # Run the test cases for client-2 cd core/client-2 venv/bin/pytest tests/ --junitxml="testresult.xml" fi
    
© www.soinside.com 2019 - 2024. All rights reserved.