【pytest-3】python代码中调用pytest

1.pycharm配置pytest

File——>settings——>Python Intergrated Tools—>Default test runner设置成pytest

 

2.pycharm写pytest代码

运行test_a.py

#encoding:utf-8
#@Time:2020/11/26 14:22
#@Author:sunny

import pytest
class Test_class:
    def test_one(self):
        a = "hello"
        assert hasattr(a,"tock")
    def test_three(self):
        c = "hello"
        d = "o"
        assert d in c
    def test_four(self):
        c = 3+6
        d = 4+4
        assert c==d

if __name__ == '__main__':
    pytest.main("-p test_a.py")

运行结果:

Testing started at 16:00 ...
D:\Python37\python.exe "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pycharm\_jb_pytest_runner.py" --path F:/AAM_project/exercise_v1/demo_pytest/common/aa.py
Launching pytest with arguments F:/AAM_project/exercise_v1/demo_pytest/common/aa.py in F:\AAM_project\exercise_v1\demo_pytest\common

============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.5.0, py-1.9.0, pluggy-0.13.1
rootdir: F:\AAM_project\exercise_v1\demo_pytest\common
plugins: allure-pytest-2.8.6, celery-4.3.0, PyTestReport-0.1.9.3, html-2.0.1, metadata-1.8.0, requests-mock-1.7.0collected 3 items

aa.py F
aa.py:6 (Test_class.test_one)
self = <common.aa.Test_class object at 0x000002438583FE10>

    def test_one(self):
        a = "hello"
>       assert hasattr(a,"tock")
E       AssertionError

aa.py:9: AssertionError
.F
aa.py:13 (Test_class.test_four)
self = <common.aa.Test_class object at 0x000002438588F400>

    def test_four(self):
        c = 3+6
        d = 4+4
>       assert c==d
E       AssertionError

aa.py:17: AssertionError
                                                                [100%]

================================== FAILURES ===================================
_____________________________ Test_class.test_one _____________________________

self = <common.aa.Test_class object at 0x000002438583FE10>

    def test_one(self):
        a = "hello"
>       assert hasattr(a,"tock")
E       AssertionError

aa.py:9: AssertionError
____________________________ Test_class.test_four _____________________________

self = <common.aa.Test_class object at 0x000002438588F400>

    def test_four(self):
        c = 3+6
        d = 4+4
>       assert c==d
E       AssertionError

aa.py:17: AssertionError
===================== 2 failed, 1 passed in 0.06 seconds ======================
Process finished with exit code 0

3.配置好了之后,直接右击运行

 3.1如果脚本是以xx.py,也可以直接运行

3.2.如果py脚本不是以test_*.py的格式,也可以直接运行。

3.3.如果是unittest,也可以当作pytest去运行,pytest兼容unittest。

4.pytest.main(),main中参数

pytest.main():main中传入不同指令用以执行指定测试用例

  • -s:显示程序中的print/logging输出。
  • -v:丰富信息模式,输出更详细的用例执行信息。
  • -q:简化控制台输出,安静模式。
  • -k:关键字匹配,用and区分:匹配范围(文件名,类名,函数名)。
  • -m:pytest -m ”标记“ 说明:执行特定的测试用例。

示例:

pytest.main(['-s','test_*.py'])#-s:显示程序中的print/logging输出
posted @ 2020-11-26 16:09  做一只热爱生活的小透明  阅读(465)  评论(0)    收藏  举报