Python selenium实现断言3种方法解析

avatar 2021年2月10日10:21:27 评论 109

1.if ...else ...判断进行断言

from time import *
from selenium import webdriver
def login(user="admin",pwd="123456"):
  driver = webdriver.Chrome()
  driver.implicitly_wait(10)
  driver.get("http://192.168.1.110:8080/cms")
  driver.maximize_window()
  sleep(1)
  driver.find_element_by_id("userAccount").send_keys(user)
  sleep(1)
  driver.find_element_by_id("loginPwd").send_keys(pwd)
  sleep(1)
  driver.find_element_by_id("loginBtn").click()  #登录
  sleep(1)
  users = driver.find_element_by_class_name("c-white").text  #获取用户名
  sleep(1)
  driver.quit()
  if users[6:] == user:
    pass
  else:
    raise AssertionError

if __name__ == '__main__':
  login()
from time import *
from selenium import webdriver
def login(user="admin",pwd="123456"):
  driver = webdriver.Chrome()
  driver.implicitly_wait(10)
  driver.get("http://192.168.1.110:8080/cms")
  driver.maximize_window()
  sleep(1)
  driver.find_element_by_id("userAccount").send_keys(user)
  sleep(1)
  driver.find_element_by_id("loginPwd").send_keys(pwd)
  sleep(1)
  driver.find_element_by_id("loginBtn").click()  #登录
  sleep(1)
  users = driver.find_element_by_class_name("c-white").text  #获取用户名
  sleep(1)
  driver.quit()
  if users[6:7] == user:
    pass
  else:
    assert False

if __name__ == '__main__':
  login()

2.try ... except ...断言

from time import *
from selenium import webdriver
def fatie(title,body):
  dr = login()
  sleep(2)
  dr.find_element_by_partial_link_text("版块").click()
  sleep(1)
  dr.find_element_by_id("subject").send_keys(title)
  sleep(1)
  dr.find_element_by_id("fastpostmessage").send_keys(body)
  sleep(2)
  dr.find_element_by_name("topicsubmit").click()
  sleep(2)
  try:
    dr.find_element_by_id("thread_subject")
  except:
    raise AssertionError
  else:
    pass
  sleep(3)
  dr.quit()

3.assert断言(基于unittest)

  • assertIn(arg1, arg2, msg=None)   验证 arg1 是 arg2 的子串,不是则 fail
  • assertNotIn(arg1, arg2, msg=None)   验证 arg1 不是 arg2 的子串,是则 fail
  • assertEqual(arg1, arg2, msg=None)   验证 arg1=arg2,不等则 fail
  • assertNotEqual(arg1, arg2, msg=None)   验证 arg1 != arg2, 相等则 fail

文章来源于互联网:Python selenium实现断言3种方法解析

avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: