zengxuejie

导航

pytest(2):使用pycharm运行pytest

pycharm运行

  1.在pycharm里创建测试文件test_demo.py

# Author xuejie zeng
# encoding utf-8
# content of test_demo.py

def inc(x):
    return x + 1


def test_answer():
    assert inc(3) == 5

  2.,此时直接右键运行的话,并不会执行用例,因为它只是一个函数,并不是pytest测试用例

   3.根据图中的步骤,将默认运行是改成pytest,再右键查看方式变成了pytest运行,而且用例前面增加了可运行的符号。

 

   4.可以直接点击右键运行,或者在命令行里执行pytest都可以,运行结果:

 

 增加入口函数

  1.有的同学说我还是比较喜欢使用python方式执行,其实也可以实现,先导入pytest,在用例添加main函数

if __name__=="__main__":
    pytest.main(['testdemo.py'])

 

   2.创建class测试用例

 1 # Author xuejie zeng
 2 # encoding utf-8
 3 # content of test_demo.py
 4 import pytest
 5 
 6 class TestDemo:
 7     def test_a(self):
 8         print("a")
 9     def test_b(self):
10         print("b")
11     def c(self):
12         print("c")
13 if __name__=="__main__":
14     pytest.main(['testdemo.py'])

  3.查看运行结果会发现class类里面只允许了2条用例,虽然class是Test开头的

    但是类里面的方法也要符合test的规则,否则的话,pytest不会读取

   4.同样的也可以使用pytest -v testdemo.py,也是只运行了两条测试用例

   5.指定某一条测试用例:

if __name__=="__main__":
    pytest.main(['testdemo.py::TestDemo::test_a','-v'])

运行模式

pytest 文件名.py
pytest 文件名.py::类名
pytest 文件名.py::类名::方法名
 1 # Author xuejie zeng
 2 # encoding utf-8
 3 
 4 class Testone:
 5      def test_a(self):
 6          print("a")
 7      def test_b(self):
 8          print("b")
 9      def c(self):
10          print("c")
11 
12 
13 class Testtwo:
14     def test_aa(self):
15         print("a")
16 
17     def test_bb(self):
18         print("b")

  1.pytest 中可以使用  pytest 文件名.py  单独执行某个 Python 文件,只要符合用例规则的都会遍历到

  2. pytest 文件名.py::类名  单独执行某个文件中的类。

  3. pytest 文件名.py::类名::方法名  单独执行类中的某个方法。

关注公众号,获取更多信息

posted on 2020-09-11 17:32  曾小懒  阅读(765)  评论(0编辑  收藏  举报