0%

GitLab CI配置代码质量检查

怎样保证代码质量?

保证代码质量有三种常用的方法:Code Review、编码规范和单元测试。

Code Review需要别人帮助Review,现在可以找ChatGPT帮助Review。
而对于编码规范检查和运行单元测试,是可以通过CI流水线自动完成的。
本文中,我们学习在GitLab CI流水线中配置编码规范检查和运行单元测试。

编码规范检查

参考文档:

GitLab官方给的文档,使用codeclimate进行编码规范检查。
针对python,我们不使用codeclimate,而是使用更加常用的pylint或者flake8。

示例:

1
2
3
4
5
6
7
8
9
10
stages:
- code_check

code_check:
stage: code_check
image: python:3.7.10-slim-buster
before_script:
- pip install pylint -i https://pypi.tuna.tsinghua.edu.cn/simple
script:
- pylint **/*.py

单元测试

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
stages:
- unittest

unittest:
stage: unittest
image: python:3.7.10-slim-buster
before_script:
- pip install pytest -i https://pypi.tuna.tsinghua.edu.cn/simple
script:
- pytest --junitxml=report.xml tests/
artifacts:
reports:
junit: report.xml

下载report.xml的方法:进入CI/CD Pipelines页面,找到Job对应的Pipeline,最右边三个点,点击下载artifacts。

参考文档:

单元测试覆盖率

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
stages:
- unittest

unittest:
stage: unittest
image: python:3.7.10-slim-buster
before_script:
- pip install pytest pytest-cov -i https://pypi.tuna.tsinghua.edu.cn/simple
script:
- pytest --cov-report xml --cov=. tests/
- coverage report --precision=2
coverage: '/\d+\.\d+%$/'
artifacts:
reports:
cobertura: coverage.xml

其中coverage report输出内容结构为:

1
2
3
4
5
6
Name    Stmts    Miss   Cover
-----------------------------
...
main.py 36 36 0%
-----------------------------
TOTAL 3130 3127 0.10%

正则匹配coverage,最终输出到UI的是最后一个匹配到的值0.10

下载coverage.xml的方法:进入CI/CD Pipelines页面,找到Job对应的Pipeline,最右边三个点,点击下载artifacts。

查看单测覆盖率的方法:进入CI/CD Pipelines页面,进入Job对应的Pipeline详情,点击Jobs,可以看到Coverage。

查看单测覆盖率的方法2:Job详情页,直接查看coverage report命令的输出内容。

单元测试和单元测试覆盖率,可以合并为一个stage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
stages:
- unittest

unittest:
stage: unittest
image: python:3.7.10-slim-buster
before_script:
- pip install pytest pytest-cov -i https://pypi.tuna.tsinghua.edu.cn/simple
script:
#- export PYTHONPATH="$CI_PROJECT_DIR"
- pytest --junitxml=report.xml --cov-report xml --cov=. tests/
- coverage report --precision=2
coverage: '/\d+\.\d+%$/'
artifacts:
reports:
junit: report.xml
cobertura: coverage.xml

参考文档:

扩展

git hooks

Git钩子是一些在Git执行特定操作时触发的脚本,可以用于自定义和自动化工作流程,不同的Git钩子有不同的调用时间。

客户端钩子:

  • pre-commit:在每次提交之前运行。
  • pre-push:在git push之前运行。
  • post-commit:在每次提交之后运行。
  • post-checkout:在切换分支或检出文件后运行。
  • post-merge:在合并操作完成后运行。

服务器端钩子:

  • pre-receive:在远程仓库接收到推送前运行。
  • update:在远程仓库接收到推送后,对每个要更新的引用(分支或标签)运行一次。
  • post-receive:在远程仓库接收到推送后,对所有要更新的引用运行一次。

每个项目的.git/hooks的目录中,看到这些钩子的官方示例。
示例文件以.sample结尾,去掉.sample后缀可激活该钩子脚本。

参考文档: