setup_class初始化打开浏览器,并输入账号完成登录,再添加用户,删除新增的用户,teardown_class关闭浏览器。
import pytest
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
import os
class Test_add_delete_user:
# 登录初始化
def setup_class(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(1)
self.driver.get(self.url)
self.driver.find_element(By.NAME, 'username').send_keys('atstudy')
self.driver.find_element(By.NAME, 'password').send_keys('51testing')
# time.sleep(1)
self.driver.find_element(By.XPATH, '//*[@id="login-form"]/div[3]/input').click()
# 添加用户
@pytest.fixture()
def test_add_user(self):
url = 'http://testplt.share.atstudy.com/admin/auth/user/add'
self.driver.get(url)
username = 'user66'
self.driver.find_element(By.ID, 'id_username').send_keys(username)
self.driver.find_element(By.ID, 'id_password1').send_keys('123456PWD')
self.driver.find_element(By.ID, 'id_password2').send_keys('123456PWD')
self.driver.find_element(By.XPATH, '//*[@id="user_form"]/div/div/input[1]').click()
time.sleep(1)
return username
# 删除用户
def test_delete_user(self, test_add_user):
url = 'http://testplt.share.atstudy.com/admin/auth/user'
self.driver.get(url)
num = len(self.driver.find_elements(By.CLASS_NAME, 'field-username'))
for i in range(1, num + 1):
# 查询列表
usname = self.driver.find_element(By.XPATH, '//*[@id="result_list"]/tbody/tr[' + str(i) + ']/th/a').text
if usname == test_add_user:
# 点击列表中匹配的用户
self.driver.find_element(By.XPATH, '//*[@id="result_list"]/tbody/tr[' + str(i) + ']/th/a').click()
# 删除
self.driver.find_element(By.XPATH, '//*[@id="user_form"]/div/div/p/a').click()
time.sleep(1)
# 二次确认页面,获取新页面的句柄
self.driver.switch_to.window(self.driver.window_handles[-1])
self.driver.find_element(By.XPATH, '//*[@id="content"]/form/div/input[2]').click()
# 跳出循环
break
def teardown_class(self):
# 关闭浏览器
self.driver.close()
if __name__ == '__main__':
file_path = os.path.abspath(__file__)
pytest.main(["-vs", file_path])