我在实现一个在..gitlab ci.yml中运行pytest的玩具示例时遇到了困难
gitlab_ci是一个包含单个文件test_hello.py
的回购程序。
gitlab_ci/
test_hello.py
test_hello.py
# test_hello.py
import pytest
def hello():
print("hello")
def hello_test():
assert hello() == 'hello'
.gitlab-ci.yml
# .gitlab-ci.yml
pytest:
image: python:3.6
script:
- apt-get update -q -y
- pip install pytest
- pytest # if this is removed, the job outputs 'Success'
CI/CD终端输出
$ pytest
=== test session starts ===
platform linux -- Python 3.6.9, pytest-5.2.0, py-1.8.0, pluggy-0.13.0
rootdir: /builds/kunov/gitlab_ci
collected 0 items
=== no tests ran in 0.02s ===
ERROR: Job failed: exit code 1
我不知道为什么测试不运行..。pytest似乎不认识test_hello.py
溶液
将python文件放入新创建的测试文件夹中:
gitlab_ci/
.gitlab-ci.yml
tests/
test_hello.py
以下列方式修改gitlab-ci.yml:
# .gitlab-ci.yml
pytest:
image: python:3.6
script:
- apt-get update -q -y
- pip install pytest
- pwd
- ls -l
- export PYTHONPATH="$PYTHONPATH:."
- python -c "import sys;print(sys.path)"
- pytest
test_hello.py
会和以前一样。
发布于 2019-10-02 04:27:25
发布于 2022-02-08 16:21:06
对PYTHONPATH
变量的操作被一些人认为是一种不好的做法(例如,这个关于堆栈溢出的答案或这个水平上编码站)。虽然这在GitLab CI作业的范围内不是一个很大的问题,但是这里有一个基于阿尔贝托·马尔德根在上述博客文章中的评论的解决方案,不需要摆弄PYTHONPATH
(也比较干净):
pytest:
stage: Test
script:
- pwd
- ls -l
- python -m pytest
为什么要这么做?来自[医]脓性文档
您可以通过命令行通过Python解释器调用测试: python -m pytest ..。 这几乎等同于直接调用命令行脚本
pytest [...]
,但通过python
调用也会将当前目录添加到sys.path
。
发布于 2022-09-11 07:53:13
test_hello.py
def test_hello():#func名称必须以"test_“开头,而不是"hello_test”
https://stackoverflow.com/questions/58195130
复制相似问题