pytest模板

project/
    module/
        __init__.py - 空
        main.py
    tests/
        test_XXX.py
    conftest.py      - 空

其中main.py为普通的python模组代码,test_XXX.py内容为:

import module.main

def test_xxx1():
    assert module.main.xxx() == 1

使用指令pytest即可运行测试,pytest会自动将conftest.py所在路径加入搜索路径。

test fixture

fixture是测试的资源,在测试函数中名字为某一fixture的参数会被自动填上对应的函数的返回值。

import pytest

@pytest.fixture
def one():
    return 1

def test_one(one);
    assert one == 1

GitHub Actions模板

此模板要求使用pipenv来管理包。创建文件.github/workflows/app.yaml

name: PyTest
on: push

jobs:
  test:
    runs-on: windows-latest
    timeout-minutes: 10

    steps:
      - name: Check out repository code
        uses: actions/checkout@v2

      # Setup Python (faster than using Python container)
      - name: Setup Python
        uses: actions/setup-python@v2
        with:
          python-version: "3.x"

      - name: Install pipenv
        run: |
          python -m pip install --upgrade pipenv wheel
      - id: cache-pipenv
        uses: actions/cache@v1
        with:
          path: ~/.local/share/virtualenvs
          key: ${{ runner.os }}-pipenv-${{ hashFiles('**/Pipfile.lock') }}

      - name: Install dependencies
        if: steps.cache-pipenv.outputs.cache-hit != 'true'
        run: |
          pipenv install --deploy --dev
      - name: Run test suite
        run: |
          pipenv run test -v

对应的徽章是

[![CI](https://github.com/用户名/仓库/actions/workflows/app.yaml/badge.svg)](https://github.com/用户名/仓库/actions/workflows/app.yaml/)

VSCode

参见:https://code.visualstudio.com/docs/python/testing

coverage

总之就是想办法添加pytest-cov库,然后运行pytest --cov=目录 --cov-report=xml然后上传,可以直接在上面的app.yaml后面加上

- name: Generate coverage report
  run: |
    pipenv run pytest --cov=./ --cov-report=xml

- name: "Upload coverage to Codecov"
  uses: codecov/codecov-action@v2
  with:
    fail_ci_if_error: true
    token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos

目录是./的时候似乎测试文件也会被统计到,或许改成具体的项目会更好。