Pytest测试框架_setup&teardown方法

setup_method初始化打开浏览器,输入账号完成登录,teardown_method关闭浏览器。
import os.path
import time
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By


class Test_Django_login():
    # 登录初始化
    def setup_method(self):
        self.url = "http://testplt.share.atstudy.com/admin/login/?next=/admin/#"

        # 不自动关闭浏览器
        self.options = webdriver.ChromeOptions()
        self.options.add_experimental_option('detach', True)
        self.driver = webdriver.Chrome(options=self.options)

        # 最大化浏览器窗口,并等待几秒以确认最大化操作已完成
        self.driver.maximize_window()
        time.sleep(3)

        self.driver.get(self.url)

    @pytest.mark.parametrize('uname,pwd', [("atstudy", "51testing"), ("atstudy1", "51testing")])
    def test_login(self, uname, pwd):
        self.driver.find_element(By.NAME, 'username').send_keys(uname)
        self.driver.find_element(By.NAME, 'password').send_keys(pwd)
        # time.sleep(1)
        self.driver.find_element(By.XPATH, '//*[@id="login-form"]/div[3]/input').click()
        # time.sleep(5)
        try:
            result = self.driver.find_element(By.XPATH, '//*[@id="content-main"]/div[1]/table/caption/a').text
            print(result)
            # 断言
            assert result == "测试平台"
        except Exception as e:
            result = self.driver.find_element(By.XPATH, '//*[@id="content"]/p').text
            print(result)
            assert "请输入" in result

    def teardown_method(self):
        # 关闭浏览器
        self.driver.close()


if __name__ == '__main__':
    file_path = os.path.abspath(__file__)
    pytest.main(["-vs", file_path])

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
pytest和unittest都是Python中常用的测试框架。其中,setup和teardown是两个常用的测试用例执行前和执行后的钩子函数。 在pytest中,setup和teardown可以通过pytest.fixture装饰器来使用。装饰器可以被附加到函数、方法或类上,以标记其为fixture。当测试函数需要使用fixture时,它们可以将fixture名称作为输入参数,pytest将自动查找和运行fixture函数,并将其输出值传递给测试函数。例如: ```python import pytest @pytest.fixture def setup(): print("执行setup操作") yield print("执行teardown操作") def test_example(setup): print("执行测试操作") ``` 在这个例子中,setup函数被标记为fixture,test_example函数接收setup作为输入参数。在运行test_example函数之前,pytest将自动运行setup函数,然后运行测试函数,最后再运行teardown函数。 在unittest中,setup和teardown可以通过setUp和tearDown方法来实现。这些方法被定义在unittest.TestCase类中,并在每次运行测试方法之前和之后自动调用。例如: ```python import unittest class TestExample(unittest.TestCase): def setUp(self): print("执行setup操作") def tearDown(self): print("执行teardown操作") def test_example(self): print("执行测试操作") ``` 在这个例子中,TestExample类继承自unittest.TestCase类,并覆盖了setUp和tearDown方法。在运行test_example方法之前,unittest将自动调用setUp方法,然后运行测试方法,最后再调用tearDown方法。 总体而言,pytest和unittest都提供了简单易用的setup和teardown机制来帮助测试人员编写可靠的测试用例。但是,pytest相对于unittest更加灵活,可以通过fixture装饰器来定义setup和teardown函数,同时也提供了更多的扩展性和定制化选项。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值