title: 测试覆盖率 date: 2023-04-27 14:53:46 tags: python


coverage视频介绍

本地先做些测试, 其中 MarkdownParser 是我的python库的名字

创建一个如下的类, 写一些测试程序

import MarkdownParser
import unittest

class TestMyMdParser(unittest.TestCase):

    def test_parse_heading(self):
        MarkdownParser.parse("")
        MarkdownParser.parse("# Heading")
        MarkdownParser.parseFile("./testfiles/test1.md")
        MarkdownParser.parseFile("./testfiles/test2.md")
        MarkdownParser.parseFile("./testfiles/test3.md")
        MarkdownParser.parseFile("./testfiles/test4.md")
        MarkdownParser.parseFile("./testfiles/test5.md")
        MarkdownParser.parseFile("./testfiles/test6.md")
        MarkdownParser.parseFile("./testfiles/test7.md")

安装 covergae

pip install coverage

运行, 得到 .coverage

这里省略了 ommit source 之类的, 见视频

coverage run -m unittest

查看代码覆盖率

coverage html

Codecov

官网: https://about.codecov.io/

通过 github 登录进去之后点进对应的仓库可以看到如下的 TOKEN

20230427190256

根据它的提示, step1 添加你的密钥

20230427190452

step2 安装 codecov

step3, 本地新建一个 .github/workflows/test.yml

name: Test with Coverage

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v2

    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: 3.9

    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install coverage

    - name: Run tests with coverage
      run: |
        coverage run -m unittest
        coverage xml -i
      env:
        COVERAGE_RUN: True

    - name: Upload coverage report to Codecov
      uses: codecov/codecov-action@v3
      with:
        file: ./coverage.xml

其中 pip install coverage 如果你还需要别的库的依赖, 写一个 requirements.txt, 我这个库没有其他依赖. 关键步骤是 coverage run -m unittestcoverage xml -i, 最后将 ./coverage.xml 上传到 codecov

push 上去就可以了, 然后可以在 README 里面加一个 badge, 名字对着改一下就行了

[![codecov](https://codecov.io/gh/luzhixing12345/MarkdownParser/branch/main/graph/badge.svg?)](https://codecov.io/gh/luzhixing12345/MarkdownParser)

codecov

zood