当前位置:首页 >> 编程语言 >> 【pytest】单元测试文件的写法,d7000 d7100

【pytest】单元测试文件的写法,d7000 d7100

0evadmin 编程语言 1
文件名:【pytest】单元测试文件的写法,d7000 d7100 【pytest】单元测试文件的写法 前言

可怜的宾馆,可怜得像被12月的冷雨淋湿的一条三只腿的黑狗。——《舞舞舞》


\;\\\;\\\;

目录 前言test_1或s_test格式非测试文件@pytest.fixture()装饰器pytest+selenium

test_1或s_test格式

要么 test_前缀 在前,要么 _test后缀 在后!

#test_1.pydef test_1():name='aa'assert 'bb'==namedef test_2():name='a'assert 'bcb'==namedef test_3():a = 1assert a == 2def test_4():a = 4assert a == 2assert 'a' in 'abc'assert 'a' not in 'abc'assert 'a' is not Trueassert 'a' is False

右击可以单独运行某个函数,看看哪个错了!

class TestTint:def test_5(self):a = 1assert a == 2def test_6(self):a = 1assert a == 2def test_7(self):a = 1assert a == 2

\;\\\;\\\;

非测试文件

如果是按pytest格式的文件名,但是内容不是测试的话,那么会出现(没有发现测试)

#test_calc.pya = 1b = 2print(a + b)

\;\\\;\\\;

@pytest.fixture()装饰器 import pytest@pytest.fixture(scope='function')def fixture1():print('前置步骤1')return 4@pytest.fixture(scope='function')def fixture2():print('前置步骤2')return 2@pytest.fixture(scope='function',autouse=True)def fixture3():print('前置步骤3')return 2def test_1(fixture1,fixture2):assert fixture1 == 2assert fixture2 == 2def test_2(fixture3):assert fixture3 == 2if __name__ == '__main__':pytest.main()

可以在测试函数的位置,右击运行test_1或test_2函数

\;\\\;\\\;

pytest+selenium

关于selenium使用的edge驱动器,版本要和电脑上装的edge版本一致!

pytest类要以Test为前缀!

#test_f.pyfrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom time import sleepimport pytest# 前置方法@pytest.fixture(scope='class')def driver():driver = webdriver.Edge(executable_path=r"C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Scripts\msedgedriver.exe")#C:\ProgramData\anaconda3\Scripts\msedgedriver.exereturn driverclass TestSpider:# fixture函数作为形参def test_baidu(self, driver):driver.get('https://www.baidu.com/')title = driver.titleurl = driver.current_urltext = driver.find_element(By.CSS_SELECTOR, "a[href*='news.baidu.com']").textbutton = driver.find_element(By.ID, 'su').get_attribute('value')# 检测assert title == '百度一下,你就知道'assert url == 'https://www.baidu.com/'assert text == '新闻'assert button == '百度一下'# sleep(3)# driver.close()if __name__ == '__main__':pytest.main()

运行命令 pytest test_f.py

协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接