自动化
一、java 手机自动化
首先new DesertCapabilities(这是一个类)
setCapability – 设置信息
获取appium的驱动对象 new AppiumDriver – 本机IP地址:端口号/wd/hub,前面的设置值信息
driver.findElementById() – 通过id找位置
click() – 点击 ,clear() – 清空 sendKeys() – 填内容
package com.qf.demo;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.AppiumDriver;
public class DemoAppium {
public static void main(String[] args) {
// TODO Auto-generated method stub
DesiredCapabilities desiredCapabilities=new DesiredCapabilities();
desiredCapabilities.setCapability("platformName", "Android");
desiredCapabilities.setCapability("platformVersion", "21.1.0");
desiredCapabilities.setCapability("deviceName", "yeshen");
desiredCapabilities.setCapability("appPackage", "com.qf.day63demo2");
desiredCapabilities.setCapability("udid", "127.0.0.1:62001");
desiredCapabilities.setCapability("noReset", "true");
desiredCapabilities.setCapability("appActivity", ".MainActivity");
//创建android diver的对象
try {
AppiumDriver driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), desiredCapabilities);
//找到三国,点击三国
WebElement sanguo = driver.findElementById("com.qf.day63demo2:id/sanguo");
sanguo.click();
Thread.sleep(1000);//睡眠1s
//使用dricer找到要操作的元素
//根据id找元素 com.qf.day63demo2:id/btn1
WebElement ele1 = driver.findElementById("com.qf.day63demo2:id/btn1");
ele1.click();//点击这个元素
Thread.sleep(1000);
WebElement button2 = driver.findElement(By.id("com.qf.day63demo2:id/btn2"));
button2.click();
Thread.sleep(1000);
//找到 输入框 换成太阳
WebElement edit1 = driver.findElement(By.id("com.qf.day63demo2:id/edit2"));
edit1.clear();
edit1.sendKeys("sun");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
查找包名和activity
在cmd中输入 adb logcat > 路径 在夜神中打开一个app ,在cmd中关闭logcat ,打开logcat文件 搜索activityManager
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-STFrQWv0-1679826710702)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220608153413697.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-z1ddEEZx-1679826710704)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220608153544520.png)]
第一步:导包将jar包导入到项目的lib文件夹下 --选中然后 add to build path
写配置文件
platformName=Android
platformVersion=21.1.0
deviceName=yeshen
appPackage=com.android.contacts
udid=127.0.0.1:62001
noReset=true
appActivity=.activities.PeopleActivity
将一个配置文件写成一个工具类
package tongxunlu;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.AppiumDriver;
public class PhoneTools {
public static AppiumDriver getDriver(String filename) {
AppiumDriver appiumDriver = null;
Properties properties = new Properties();
try {
properties.load(new FileReader(filename));
HashMap<String, String> map= new HashMap<>();
Set<Entry<Object, Object>> set = properties.entrySet();
for (Entry<Object, Object> entry : set) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
map.put(key, value);
}
DesiredCapabilities desiredCapabilities = new DesiredCapabilities(map);
appiumDriver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), desiredCapabilities);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return appiumDriver;
}
public static void clickById(AppiumDriver driver,String id) {
driver.findElementById(id).click();
}
public static void clickByXpath(AppiumDriver driver,String xpath) {
driver.findElementByXPath(xpath).click();
}
public static void inputContentByXpath(AppiumDriver driver,String xpath,String content) {
WebElement ele = driver.findElementByXPath(xpath);
ele.clear();
ele.sendKeys(content);
}
public static void inputContentById(AppiumDriver driver,String id,String content) {
WebElement ele = driver.findElementById(id);
ele.clear();
ele.sendKeys(content);
}
public static void inputContentByClass(AppiumDriver driver,String classname,String countent) {
WebElement ele = driver.findElementById(classname);
ele.clear();
ele.sendKeys(countent);
}
}
封装测试(页面)功能
package tongxunlu;
import java.util.List;
import org.openqa.selenium.WebElement;
import io.appium.java_client.AppiumDriver;
public class PhoneActivity {
AppiumDriver driver;
public PhoneActivity(AppiumDriver driver) {
super();
this.driver = driver;
}
//增加联系人 id com.android.contacts:id/floating_action_button
public void addContactor(String uname,String utel) {
PhoneTools.clickById(driver, "com.android.contacts:id/floating_action_button");
//class
List<WebElement> eles = driver.findElementsByClassName("android.widget.EditText");
eles.get(0).sendKeys(uname);
eles.get(1).sendKeys(utel);
//保存 id com.android.contacts:id/menu_save
PhoneTools.clickById(driver, "com.android.contacts:id/menu_save");
}
//编辑联系人
public void editContactor(String uname,String utel) {
// //android.widget.TextView[@content-desc="uu"]
PhoneTools.clickByXpath(driver, "//android.widget.TextView[@content-desc='"+uname+"']");
// com.android.contacts:id/menu_edit
PhoneTools.clickById(driver, "com.android.contacts:id/menu_edit");
//
List<WebElement> eles = driver.findElementsByClassName("android.widget.EditText");
eles.get(1).clear();
eles.get(1).sendKeys(utel);
// com.android.contacts:id/menu_save
PhoneTools.clickById(driver, "com.android.contacts:id/menu_save");
}
//删除联系人
public void delcontactor(String uname) {
PhoneTools.clickByXpath(driver, "//android.widget.TextView[@content-desc='"+uname+"']");
PhoneTools.clickByXpath(driver, "//android.widget.ImageButton[@content-desc='更多选项']");
PhoneTools.clickByXpath(driver, "/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.ListView/android.widget.LinearLayout[1]");
PhoneTools.clickById(driver, "android:id/button1");
}
}
写测试类
package tongxunlu;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import io.appium.java_client.AppiumDriver;
public class TestPhone {
static AppiumDriver driver=null;
static PhoneActivity activity=null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
driver = PhoneTools.getDriver("peizhi.properties");
activity=new PhoneActivity(driver);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
/*@Test
public void testAddContactor() {
try {
activity.addContactor("ww","112233");
} catch (Exception e) {
// TODO: handle exception
fail("失败了"+e.getMessage());
}
}*/
@Test
public void testEditContactor(){
try {
activity.editContactor("uu", "112233123");
} catch (Exception e) {
// TODO: handle exception
fail("失败了"+e.getMessage());
}
}
/*@Test
public void testDelContactor(){
try {
activity.delcontactor("uu");
} catch (Exception e) {
// TODO: handle exception
fail("失败了"+e.getMessage());
}
}*/
}
driver 的方法
driver.fineElementById
driver.fineElementByClassName/driver.fineElementsByClassName – 找到一个或多个
driver.fineElementByXpath
button.getAttribute() –
写配置文件 – 写工具类 – 封装页面功能 – 写测试类
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hBVSqXQB-1679826710704)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220610091603272.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SNo9tXf9-1679826710705)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220610091913199.png)]
二、python 手机自动化
from appium import webdriver
class ContactActivity():
def __init__(self,driver):
self.driver = driver
def add_contact(self,name,tel):
# 添加联系人
#self.driver = webdriver.Remote() -- 目的是为了后面写driver的时候会出现函数
self.driver.find_element_by_id("com.android.contacts:id/floating_action_button").click()
edits = self.driver.find_elements_by_class_name("android.widget.EditText")
edits[0].send_keys(name)
edits[1].send_keys(tel)
self.driver.find_element_by_id("com.android.contacts:id/menu_save").click()
from beice import ContactActivity
from appium import webdriver
if __name__ == "__main__":
capability = {
'platformName': 'Android',
'platformVersion': '21.1.0',
'deviceName': 'yeshen',
'appPackage': 'com.android.contacts',
'udid': '127.0.0.1:62001',
'noReset': 'true',
'appActivity': '.activities.PeopleActivity'
}
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub",capability)
activity = ContactActivity(driver)
activity.add_contact(name="zz",tel="190876")
web自动化
一、python web自动化
什么是自动化?什么时候使用自动化?什么时候使用手动?
下载浏览器 – 配置驱动 –
json 是什么? – 数据交换格式,用字符串表示js对象的一种格式
jison中的{}是什么意思?-- 一个{} 就是一个json 对象 [] 是一个数组
jison 是键值对 – 每个键值对用,号隔开 – 键和值中间用分号隔开
值可以是简单的数据类型,值也可以是一个对象,也可以是一个数组
Selenium IDE是嵌入到Firefox浏览器中的一个插件,实现简单的浏览器操作的录制与回放功能。(首先打开火狐浏览器 – 菜单 – 扩展和主题 --插件 – 搜索selenium – 选择 Selenium IDE – 选择安装)
selenium IDE – 只能录制你的操作
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vhmL8hqW-1679826710706)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220613145209211.png)]
1. 8大寻找元素的方式
根据 id 找元素 find_element_by_id()
根据 name 属性值找元素 find_element_by_name()
根据 类名 找元素 find_element_by_class_name()、find_elements_by_class_name()
根据 标签名 找元素 find_element_by_tag_name()、find_elements_by_tag_name()
根据 链接文本 找元素 find_element_by_link_text()、find_elements_by_link_text()
根据 部分连接文本 找元素 find_element_by_partial_link_text()、find_elements_by_partial_link_text()
根据 xpath路径表达式 找元素 find_element_by_xpath()、find_elements_by_xpath
根据 css选择器 找元素 find_elements_by_css_selector()、find_element_by_css_selector()
1.1 根据id找元素
driver.close
#先导包
from selenium import webdriver
import time
#获取火狐driver对象
driver = webdriver.Firefox()
#请求项目地址
driver.get("file:///E:/%E5%86%B3%E6%88%98%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88/08%20%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6/day66/testpage/page001.html")
time.sleep(3)
#使用id来寻找
driver.find_element_by_id("btn1").click()
time.sleep(3)
driver.quit()#关闭所有窗口
1.2 根据name(标签属性)找元素
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/%E5%86%B3%E6%88%98%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88/08%20%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6/day66/testpage/page002.html")
driver.find_element_by_name("uname").send_keys("killer")
driver.find_element_by_name("upw").send_keys("999")
time.sleep(5)
driver.quit()
1.3 根据classname类名来找元素
find_element_by_class_name() – 找这个界面第一个符合classname的
find_elements_by_class_name() – 找这个界面中所有符合的
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/%E5%86%B3%E6%88%98%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88/08%20%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6/day66/testpage/page003.html")
ele1 = driver.find_element_by_class_name("wd")
print(ele1.get_attribute("src"))
eles = driver.find_elements_by_class_name("wd")
for ele in eles:
print(ele.get_attribute("src"))
time.sleep(5)
driver.quit()
1.4 根据tagname 标签名来找元素 tag – 标签的意思
find_element_by_tag_name(“eg:button”) – 找这个界面第一个标签
find_elements_by_tag_name() – 找这个界面中所有标签
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/%E5%86%B3%E6%88%98%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88/08%20%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6/day66/testpage/page004.html")
#driver.find_element_by_tag_name("button").click()
buttons = driver.find_elements_by_tag_name("button")
for button in buttons:
button.click()
time.sleep(3)
driver.switch_to.alert.dismiss()#关闭弹窗
time.sleep(3)
driver.quit()
1.5 根据 linktest 来寻找元素 – 超链接中含有某些字(全包含)
find_element_by_link_text()
find_elements_by_link_text()
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/%E5%86%B3%E6%88%98%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88/08%20%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6/day66/testpage/page005.html")
time.sleep(3)
ele = driver.find_element_by_link_text("明朝那些事")
print(ele.get_attribute("herf"))
ele.click()
time.sleep(3)
driver.quit()
1.6 根据 部分链接文本 模糊匹配 含有 来寻找元素
find_element_by_partial_link_text(value)
find_elements_by_partial_link_text()
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/%E5%86%B3%E6%88%98%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88/08%20%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6/day66/testpage/page006.html")
time.sleep(3)
eles = driver.find_elements_by_partial_link_text("明朝")
for ele in eles:
print(ele.get_attribute("href"))#获取属性值
time.sleep(3)
driver.quit()
1.7 xpath 模糊匹配要找的元素
driver.refresh()#刷新
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/%E5%86%B3%E6%88%98%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88/08%20%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6/day66/testpage/page007.html")
time.sleep(5)
driver.find_element_by_xpath("//button[@id='img3']").click()
time.sleep(5)
driver.find_element_by_xpath("//div[@id='div1']/img").click()
time.sleep(5)
driver.refresh()#刷新
time.sleep(5)
imgs = driver.find_elements_by_xpath("//img")
for img in imgs:
img.click()
time.sleep(5)
driver.quit()
tomcat
D:\apache-tomcat-7.0.40\webapps\ROOT 里面可以放html文件 直接输入网址127.0.0.1:8080/文件名 就可以直接访问文件
1.8 根据css中选择器来选择元素
css 选择器:标签选择器、类选择器、id选择器
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("http://127.0.0.1:8080/page008.html")
time.sleep(3)
driver.find_element_by_css_selector("#img1").click()
time.sleep(3)
driver.refresh()
imgs = driver.find_elements_by_css_selector(".imgxx")
for img in imgs:
img.click()
time.sleep(3)
driver.refresh()
imgkks = driver.find_elements_by_css_selector("img")
for imgkk in imgkks:
imgkk.click()
time.sleep(3)
driver.quit()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1jJFOMDi-1679826710707)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220614104318392.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vKzaWd8d-1679826710708)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220614104545278.png)]
2. 页面相关操作
请求某个url driver.get(url)
刷新页面操作 refresh()
回退到之前的页面 back()
前进到之后的页面 forward()
获取当前访问页面url current_url
获取当前浏览器标题 title
保存图片 get_screenshot_as_png()/get_screenshot_as_file(file)
网页源码 page_source
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/test_html/testpage3/testpage01.html")
time.sleep(5)
driver.find_element_by_id("a1").click()
time.sleep(3)
print(driver.title)
print("+++++++++++++++++++++++")
print(driver.current_url)
print("++++++++++++++++++++++++++")
print(driver.page_source)
print("+++++++++++++++++++++++++")
liu = driver.get_screenshot_as_png()
file = open("E:\\zidonghuaceshi_log\\aa.png","wb")
file.write(liu)
time.sleep(3)
driver.forward()#前进到之后的页面
time.sleep(3)
driver.back()#返回
time.sleep(3)
driver.quit()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OH4yeygm-1679826710708)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220614110626696.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-scOZISLj-1679826710709)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220614110830752.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vje8x2Im-1679826710709)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220614111901151.png)]
3. 出错截图
python 的异常处理
try:
pass()#被检测的代码块
except:
pass()#出了异常后执行的代码
finally:
pass()# 必须执行的代码,一般是扫尾工作
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/%E5%86%B3%E6%88%98%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88/08%20%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6/day66/testpage/page001.html")
time.sleep(5)
try:
driver.find_element_by_id("a2").click()
except:
print("==出现异常了==")
driver.get_screenshot_as_file("E:\\zidonghuaceshi_log\\a.png")
finally:
driver.quit()
4. 鼠标事件
鼠标操作需要导入类,from selenium.webdriver import ActionChains,然后创建对象ActionChains(driver)
鼠标右击
el = driver.find_element_by_xxx(value)
ActionChains(driver).context_click(el).perform()
鼠标双击
el = driver.find_element_by_xxx(value)
ActionChains(driver).double_click(el).perform()
鼠标悬停
el = driver.find_element_by_xxx(value)
ActionChains(driver).move_to_element(el).perform()
from selenium import webdriver
from selenium.webdriver import ActionChains
import time
driver = webdriver.Firefox()
driver.get("file:///E:/test_html/testpage2/testpage01.html")
time.sleep(5)
# 滑动
js = "window.scrollTo(0,1500)"#准备一句js代码,x为水平拖动距离,y为垂直拖动距离
driver.execute_script(js)#用driver来执行js代码
time.sleep(3)
ele = driver.find_element_by_id("btn2")
chains = ActionChains(driver)#创建一个管理鼠标的动作链对象
# 使用动作链来调用鼠标右键
# chains.context_click(ele).perform()
div1 = driver.find_element_by_id("div1")
chains.move_to_element(div1).perform()
time.sleep(3)
driver.quit()
5. 键盘操作
导包 from selenium.webdriver.common.keys import Keys
常用键盘操作
send_keys(Keys.BACK_SPACE) 删除键(BackSpace)
send_keys(Keys.SPACE) 空格键(Space)
send_keys(Keys.TAB) 制表键(Tab)
send_keys(Keys.ESCAPE) 回退键(Esc)
send_keys(Keys.ENTER) 回车键(Enter)
send_keys(Keys.CONTROL,‘a’) 全选(Ctrl+A)
send_keys(Keys.CONTROL,‘c’) 复制(Ctrl+C)
send_keys(Keys.CONTROL,‘x’) 剪切(Ctrl+X)
send_keys(Keys.CONTROL,‘v’) 粘贴(Ctrl+V)
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/test_html/testpage2/testpage01.html")
time.sleep(5)
in1 = driver.find_element_by_id("in1")
in2 = driver.find_element_by_id("in2")
in1.send_keys("hello")
time.sleep(3)
in1.send_keys(Keys.NUMPAD7)#在后面追加一个数字7
time.sleep(3)
in1.send_keys(Keys.NUMPAD1)#在后面追加一个数字1
time.sleep(3)
in1.send_keys(Keys.BACKSPACE)#删除一个字符
time.sleep(3)
in1.send_keys(Keys.CONTROL,'a')# 相当于Ctrl + A 全选
time.sleep(3)
in1.send_keys(Keys.CONTROL,'c')#相当于Ctrl + C 复制
time.sleep(3)
in2.send_keys(Keys.CONTROL,'v')#相当于Ctrl + v 粘贴
time.sleep(3)
driver.quit()
6. 弹出框
进入到弹出框中 driver.switch_to.alert()
接收警告 accept()
关闭警告 dismiss()
发送文本到警告框 send_keys(data)
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/test_html/testpage2/testpage03.html")
time.sleep(3)
driver.find_element_by_id("btn1").click()
time.sleep(3)
#先将driver切换到弹窗里面
driver.switch_to.alert.dismiss()#关闭弹窗
time.sleep(3)
driver.find_element_by_id("btn5").click()
time.sleep(3)
driver.switch_to.alert.accept()#接收弹窗
time.sleep(3)
driver.quit()
7.下拉框
导包–from selenium.webdriver.support.select import Select
将定位到的下拉框元素传入Select类中 selobj = Select(element)
通过索引选择,index 索引从 0 开始 select_by_index()
通过值选择(option标签的一个属性值) select_by_value()
通过文本选择(下拉框的值) select_by_visible_text()
查看所有已选 all_selected_options
查看第一个已选 first_selected_option
查看是否是多选 is_multiple
查看选项元素列表 options
取消选择 deselect_by_index() /deselect_by_value()/ deselect_by_visible_text()
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
driver = webdriver.Firefox()
driver.get("file:///E:/test_html/testpage2/testpage01.html")
time.sleep(3)
s1 = driver.find_element_by_id("s1")
sObject = Select(s1)
sObject.select_by_index(3)
time.sleep(3)
sObject.select_by_visible_text("上海")
time.sleep(3)
sObject.select_by_value("xian")
time.sleep(3)
driver.quit()
8. 单选复选框
选项.is_selected() – 判断这个选项有没有选中
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
driver = webdriver.Firefox()
driver.get("file:///E:/test_html/testpage2/testpage01.html")
time.sleep(3)
eles = driver.find_elements_by_name("sex")
for ele in eles:
value = ele.get_attribute("value")
if value == "woman":
ele.click()
time.sleep(3)
duoxuans = driver.find_elements_by_name("vv")
for duoxuan in duoxuans:
value = duoxuan.get_attribute("value")
xuanze = ["ww","xx","ss"]
if value in xuanze:
duoxuan.click()
time.sleep(3)
driver.quit()
9. cookies (课下了解)
10. 窗体的切换
多标签/多窗口、多表单/多框架切换
多表单/多框架切换
直接使用id值切换进表单(界面中有iframe表单时使用)
- driver.switch_to.frame(value)
定位到表单元素,再切换进入
el = driver.find_element_by_xxx(value)
driver.switch_to.frame(el)
跳回最外层的页面 driver.switch_to.default_content()
跳回上层的页面 driver.switch_to.parent_frame()
多标签/多窗口之间的切换
获取所有窗口的句柄 handles = driver.window_handles
通过窗口的句柄进入的窗口 driver.switch_to.window(handles[n])
10.1 iframe表单切换
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
driver = webdriver.Firefox()
driver.get("file:///E:/test_html/testpage4/page1.html")
time.sleep(5)
driver.find_element_by_id("btn11").click()
frame1 = driver.find_element_by_id("f1")
driver.switch_to.frame(frame1)#进frame
time.sleep(3)
s1 = driver.find_element_by_id("s1")
sObject = Select(s1)
sObject.select_by_index(3)
time.sleep(5)
driver.switch_to.default_content()#出frame
time.sleep(3)
driver.find_element_by_id("btn22").click()
time.sleep(5)
driver.quit()
10.2 窗口跳转
多标签/多窗口之间的切换
获取所有窗口的句柄 handles = driver.window_handles
通过窗口的句柄进入的窗口 driver.switch_to.window(handles[n])
n = -1 是进入到最后一个窗体
从第一个窗体开始下标为0,1,2,3,4,5,。。。。。
也可以倒序取就是。。。,-3,-2,-1
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/test_html/testpage3/testpage01.html")
time.sleep(3)
driver.find_element_by_id("a1").click()
time.sleep(3)
handles = driver.window_handles#获取窗体历史
driver.switch_to.window(handles[-1])
driver.find_element_by_id("a2").click()
time.sleep(3)
handles = driver.window_handles
driver.switch_to.window(handles[-1])
driver.find_element_by_id("btn5").click()
time.sleep(3)
driver.switch_to.window(handles[0])
time.sleep(3)
driver.quit()
11.js
#使用driver来执行js语句
import time
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("file:///E:/test_html/testpage2/testpage03.html")
driver.execute_script("window.document.getElementById('btn1').click()")
time.sleep(3)
driver.switch_to.alert.dismiss()
time.sleep(3)
ele1 = driver.find_element_by_id("btn5")
driver.execute_script("arguments[0].click()",ele1)
time.sleep(3)
driver.switch_to.alert.dismiss()
time.sleep(3)
img1 = driver.find_element_by_id("img1")
width_value = "200px"
height_value = "200px"
#参数列表用arguments来表示, arguments是所有参数的元组
driver.execute_script("arguments[0].setAttribute('width',arguments[1])",img1,width_value)
driver.execute_script("arguments[0].setAttribute('height',arguments[1])",img1,height_value)
time.sleep(3)
style_content = "border:2px solid red"
driver.execute_script("arguments[0].setAttribute('style',arguments[1])",img1,style_content)
time.sleep(3)
#img1.style.border = "5px solid blue"
driver.execute_script("arguments[0].style.border = '5px solid blue'",img1)
time.sleep(3)
driver.quit()
12.练习
12.1 豆瓣
# https://www.douban.com/
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("https://www.douban.com/")
time.sleep(3)
driver.find_element_by_link_text("豆瓣电影").click()
time.sleep(3)
handles = driver.window_handles
driver.switch_to.window(handles[-1])
driver.find_element_by_link_text("选电影").click()
time.sleep(3)
handles = driver.window_handles
driver.switch_to.window(handles[-1])
driver.find_element_by_css_selector("label:nth-child(7)").click()
time.sleep(3)
driver.quit()
12.2 豆瓣2
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("https://movie.douban.com/")
time.sleep(3)
driver.find_element_by_link_text("影讯&购票").click()
time.sleep(3)
ele1 = driver.find_element_by_id("inp-query")
ele1.send_keys("侏罗纪世界3")
time.sleep(3)
driver.find_element_by_css_selector(".inp-btn > input").click()
time.sleep(3)
driver.find_element_by_css_selector(".sc-bZQynM:nth-child(2) .cover").click()
time.sleep(3)
driver.find_element_by_link_text("购票").click()
time.sleep(3)
driver.find_element_by_css_selector(".need-promission > .accept").click()
time.sleep(3)
driver.find_element_by_link_text("万达影城").click()
time.sleep(3)
driver.find_element_by_css_selector(".cinema-cell:nth-child(3) .cinema-address").click()
time.sleep(5)
driver.find_element_by_css_selector(".cinema-cell:nth-child(3) > .buy-btn > a").click()
time.sleep(5)
driver.quit()
13.封装(工具类、)
工具类
# 定义一个工具类
from selenium import webdriver
class Tools_Driver():
@staticmethod
#获取页面的driver的方法
def get_driver_by_page(page_url):
driver = webdriver.Firefox()
driver.get(page_url)
return driver
#定义一些点击方法
@staticmethod
def clickById(driver,id):
driver.find_element_by_id(id).click()
@staticmethod
def clickByXpath(driver,xpath):
driver.find_element_by_xpath(xpath).click()
@staticmethod
def clickByCss(driver,css):
driver.find_element_by_css_selector(css).click()
@staticmethod
def clickByLinkTest(driver,link_test):
driver.find_element_by_link_text(link_test).click()
@staticmethod
def sendKeysById(driver,id,value):
driver.find_element_by_id(id).send_keys(value)
@staticmethod
def sendKeysByXpath(driver,xpath,value):
driver.find_element_by_xpath(xpath).send_keys(value)
@staticmethod
def closeAlert(driver):
driver.switch_to.alert.dismiss()
测试功能类
movie
from selenium import webdriver
import time
from Tools.tools_douban import Tools_Driver
class move_douban():
def __init__(self,driver):
self.driver = driver
def gou_piao(self,move_name):
Tools_Driver.clickByLinkTest(self.driver,"影讯&购票")
time.sleep(5)
Tools_Driver.sendKeysById(self.driver,"inp-query",move_name)
time.sleep(5)
Tools_Driver.clickByCss(self.driver,".inp-btn > input")
time.sleep(5)
Tools_Driver.clickByCss(self.driver,".sc-bZQynM:nth-child(2) .cover")
time.sleep(5)
Tools_Driver.clickByCss(self.driver,".ticket-btn")
time.sleep(5)
Tools_Driver.clickByCss(self.driver,".need-promission > .accept")
time.sleep(5)
Tools_Driver.clickByLinkTest(self.driver,"万达影城")
time.sleep(5)
Tools_Driver.clickByCss(self.driver,".cinema-cell:nth-child(3) .cinema-address")
time.sleep(5)
Tools_Driver.clickByCss(self.driver,".cinema-cell:nth-child(3) > .buy-btn > a")
time.sleep(5)
self.driver.quit()
book
from selenium import webdriver
import time
from Tools.tools_douban import Tools_Driver
class book_douban():
def __init__(self,driver):
self.driver = driver
def sou_zuo_zhe(self,author_name):
Tools_Driver.sendKeysByXpath(self.driver,"//input[@id='inp-query']",author_name)
time.sleep(5)
Tools_Driver.clickByXpath(self.driver,"//input[@value='搜索']")
time.sleep(5)
Tools_Driver.clickByXpath(self.driver,"//a[contains(text(),'"+author_name+"')]")
time.sleep(5)
self.driver.quit()
测试 test
from selenium import webdriver
from Tools.tools_douban import Tools_Driver
from doubanmove.movedemo import move_douban
from doubanbook.bookdemo import book_douban
import time
if __name__ == "__main__":
driver_move = Tools_Driver.get_driver_by_page("https://movie.douban.com/")
movie_page = move_douban(driver_move)
movie_page.gou_piao("侏罗纪世界3")
driver_book = Tools_Driver.get_driver_by_page("https://book.douban.com/")
book_page = book_douban(driver_book)
book_page.sou_zuo_zhe("贾平凹")
14.单元测试
TestCase
TestSuit – 测试套件
TestRunner –
import unittest
# 单元测试unittest
# 导包
import unittest
#写一个用例类 继承unittest TestCase
class Page01_TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:# -> 指明返回值类型
print("所有用例执行之前")
@classmethod
def tearDownClass(cls) -> None:
print("所有用例执行之后")
@classmethod
def setUp(self) -> None:
print("每个用例执行前")
@classmethod
def tearDown(self) -> None:
print("每个用例执行之后")
#定义用例放法
def test_one(self):
print("测试用例01")
result = True
self.assertTrue(result,"实际上是假的")
def test_two(self):
print("测试用例02")
expect = 10
actual = 10
self.assertEqual(expect,actual,"测试失败了")
if __name__ == "__main__":
unittest.main()
import unittest
class Page02_TestCase(unittest.TestCase):
def test_page2_test001(self):
print("page2测试用例01")
self.assertTrue(True)
def test_page2_test002(self):
print("page02测试用例02")
self.assertEqual(2,13,"测试失败")
def test_page2_test003(self):
print("page2测试用例03")
self.assertEqual(30,30,"测试03失败")
import unittest
from danyuanceshi.test001 import Page01_TestCase
from danyuanceshi.test002 import Page02_TestCase
if __name__ == "__main__":
suit = unittest.TestSuite()
suit.addTest(Page01_TestCase("test_one"))
suit.addTest(Page01_TestCase("test_two"))
suit.addTest(Page02_TestCase("test_page2_test001"))
suit.addTest(Page02_TestCase("test_page2_test002"))
suit.addTest(Page02_TestCase("test_page2_test003"))
runner = unittest.TextTestRunner()
runner.run(suit)
可以生成报告
import HTMLTestRunner
import unittest
from danyuanceshi.test001 import Page01_TestCase
from danyuanceshi.test002 import Page02_TestCase
if __name__ == "__main__":
suit = unittest.TestSuite()
suit.addTest(Page01_TestCase("test_one"))
suit.addTest(Page01_TestCase("test_two"))
suit.addTest(Page02_TestCase("test_page2_test001"))
suit.addTest(Page02_TestCase("test_page2_test002"))
suit.addTest(Page02_TestCase("test_page2_test003"))
baogao_file = r"E:\\zidonghuaceshi_log\\a1.html"
fb = open(baogao_file,"wb")
html_runner = HTMLTestRunner.HTMLTestRunner(stream=fb,title="自动化测试报告1",description="这是page01和page02的测试报告")
html_runner.run(suit)
fb.close()
15.断言 assert
beice
class Page_Gongneng():
def first_fun(self):
return False
def sec_fun(self,a,b):
return a+b
def third_fun(self):
return "hello"
def forth_fun(self):
return None
def five_fun(self):
return "he"
def six_fun(self):
try:
print("==功能代码===")
return True
except:
return False
测试用例的名字必须以test开头
import unittest
from duanyan.beice import Page_Gongneng
class DanYuan_TestCasre(unittest.TestCase):
def test_one(self):
result = Page_Gongneng().first_fun()
self.assertTrue(result,"测试失败")
def test_two(self):
result = Page_Gongneng().sec_fun(2,3)
self.assertEqual(5,result,"计算错误")
def test_third(self):
result = Page_Gongneng().third_fun()
self.assertIs(result,"hello")
def test_forth(self):
result = Page_Gongneng().forth_fun()
self.assertIsNone(result)
def test_five(self):
result = Page_Gongneng().five_fun()
self.assertIn(result,"hello","不包含")
def test_five2(self):
self.assertIn(2,[1,2,3],"不包含")
def test_da_yu(self):
self.assertGreater(10,9,"不大于")
def test_lei_xing(self):
self.assertIsInstance(3.2,int,"不是int")
def test_xiaoyu(self):
slf.assertLess(10,9,"不小于")
16.po模型
1.写父类方法
#定义一个所有页面的父类
#在这个父类中提供子类公有的方法
from selenium import webdriver
class BasePage():
#构造函数中需要传入driver对象
def __init__(self,driver:webdriver):
self.driver = driver
#根据id点击
def clickById(self,id):
self.driver.find_element_by_id(id).click()
def clickByXpath(self,xpath):
self.driver.find_element_by_xpath(xpath).click()
def clickByLinkText(self, linktext):
self.driver.find_element_by_link_text(linktext).click()
def sendkeysById(self, id, value):
self.driver.find_element_by_id(id).send_keys(value)
def sendkeysByXpath(self, xpath, value):
self.driver.find_element_by_xpath(xpath).send_keys(value)
# 关闭alert
def close_alert(self):
self.driver.switch_to.alert().dismiss()
2.写功能方法(功能类)
#定义一个读书页面的功能 继承BasePage
#在此类中定义读书页面中所有的功能
from page.basepage import BasePage
from selenium import webdriver
import time
class Page_Book(BasePage):
def __init__(self,driver):
super().__init__(driver)
#查询作者信息的功能
#定义豆瓣读书的功能
def sou_suo_zuozhe(self,author_name):
try:
self.sendkeysByXpath("//input[@id='inp-query']", author_name)
time.sleep(5)
self.clickByXpath("//input[@value='搜索']")
time.sleep(5)
self.clickByXpath("//a[contains(text(),'" + author_name + "')]")
time.sleep(5)
return True
except:
print("+=====测试出现异常了-----")
return False
finally:
self.driver.quit()
#查询某本书的价钱
def get_book_price(self,book_name):
try:
print("====查询结果=======")
return 10
except:
print("====查询出异常了===")
return 0
finally:
self.driver.quit()
#定义一个movie page
#继承BasePage
from selenium import webdriver
from page.basepage import BasePage
import time
class Page_Movie(BasePage):
def __init__(self,driver:webdriver):
super().__init__(driver)
#定义页面功能
# 电影购票的功能
def gou_piao(self, movie_name):
try:
self.clickByLinkText( "影讯&购票")
time.sleep(5)
self.sendkeysByXpath("//input[@id='inp-query']", movie_name)
self.clickByXpath("//input[@value='搜索']")
time.sleep(5)
self.clickByXpath("//a[contains(text(),'" + movie_name + "')]")
time.sleep(5)
self.clickByLinkText("购票")
time.sleep(5)
return True
except:
print("====测试出现异常了====")
return False
finally:
self.driver.quit()
def cha_yingYuan(self,yingyuan_name):
try:
print("====查影院的功能===")
return True
except:
return False
finally:
self.driver.quit()
3.写测试方法(测试类)
#这个用例是对页面PageBook的测试用例
import unittest
from page.dushu import Page_Book
from selenium import webdriver
import time
class Book_Page_TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None: # 所有用例执行之前得到页面的对象
pass
@classmethod
def tearDownClass(cls) -> None:
pass # 所有用例执行之后关闭页面对象
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
#测试用例方法
def test_sou_author(self):
self.driver = webdriver.Firefox()
self.page_book = Page_Book(self.driver)
self.driver.get("https://book.douban.com/")
time.sleep(5)
jieguo1 = self.page_book.sou_suo_zuozhe("贾平凹")
self.assertTrue(jieguo1,"========读书页面===测试用例1失败======")
def test_book_price(self):
self.driver = webdriver.Firefox()
self.page_book = Page_Book(self.driver)
self.driver.get("https://book.douban.com/")
time.sleep(5)
jieguo2 = self.page_book.get_book_price("狼")
self.assertLess(jieguo2,50,"====读书页面===测试用例2失败===")
#这个用例是对页面PageMovie的测试用例
import unittest
from page.movie import Page_Movie
from page.dushu import Page_Book
from selenium import webdriver
import time
class Movie_Page_TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:#所有用例执行之前得到页面的对象
pass
@classmethod
def tearDownClass(cls) -> None:
pass#所有用例执行之后关闭页面对象
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def test_goupiao(self):
self.driver = webdriver.Firefox()
self.page_movie = Page_Movie(self.driver)
self.driver.get("https://movie.douban.com/")
time.sleep(5)
jieguo1 = self.page_movie.gou_piao("侏罗纪世界3")
self.assertTrue(jieguo1,"===电影页面===测试用例1失败======")
def test_chayingyuan(self):
self.driver = webdriver.Firefox()
self.page_movie = Page_Movie(self.driver)
self.driver.get("https://movie.douban.com/")
time.sleep(5)
jieguo2 = self.page_movie.cha_yingYuan("万达")
self.assertTrue(jieguo2,"===电影页面=测试用例2失败====")
4.测试套件
#使用测试套件来完成对所有页面的测试
import unittest
from testcase.movietest import Movie_Page_TestCase
from testcase.booktest import Book_Page_TestCase
import HTMLTestRunner
if __name__ == "__main__":
suit = unittest.TestSuite()
suit.addTest(Movie_Page_TestCase("test_goupiao"))
suit.addTest(Movie_Page_TestCase("test_chayingyuan"))
suit.addTest(Book_Page_TestCase("test_sou_author"))
suit.addTest(Book_Page_TestCase("test_book_price"))
#定义一个带有报告的runner
baogao_file = r"D:\\2202\\day69\\baogao2.html"#创建一个报告的文件路径
fb = open(baogao_file,"wb")#以二进制方式打开文件流
html_runner = HTMLTestRunner.HTMLTestRunner(stream=fb,title="自动化测试的报告2",description="这是豆瓣电影和豆瓣读书的测试报告")
html_runner.run(suit)
fb.close()
5 异常
"""
打印异常信息
"""
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchWindowException
try:
driver = webdriver.Firefox()
driver.get("http://www.baidu.com")
#driver.find_element_by_id("kkk").click()
driver.switch_to.window("windowkkk")
except NoSuchElementException as e:
print(e)
e.with_traceback()
except NoSuchWindowException as e:
print(e)
e.with_traceback()
6 参数
关键字传参
#参数 不定长参数 *args 1,2,3
#**xxx,xxx会被当做字典进行处理,传参的时候实参必需以key=value的方式进行传参
#**kwargs a=10 b=3 c=9
def fun1(*args):
print(args)
print("====参数列表====")
for i in range(len(args)):
print("第%d个参数是%s" % (i+1,args[i]))
fun1(1,2,3)#(1, 2, 3)
fun1(1,"hello",90)
fun1(1,[1,2,3],90)
print("++++++++++++++++++++++++")
def fun2(**kwargs):
print(kwargs)
print("====参数列表====")
for key,value in kwargs.items():
print("%s ----- %s" %(key,value))
fun2(a=10,b=9,c=90)
"""
a,b=1,c=3,d
1,2,3,4
1,b=3,c=9,9
"""
def fun2(a,c=2):
pass
def fun1(*args,**kwargs):
fun2(*args,**kwargs)
"""
"""
def fun1(*args,**kwargs):
print("====参数列表====")
for i in args:
print(i)
print("+++++++++++++++++++++++")
for key,value in kwargs.items():
print("%s===%s" %(key,value))
print("++++++++++++++++++++++++++++")
fun1(1,2)
print("+++++++++++++++")
fun1(1,a=10,c=9)
print("+++++++++++++++++++++++++++++++++++")
fun1(9,a=88,c=19)
7 装饰器
1 闭包
#闭包
def outter():
def inner():
print("====闭包功能===")
return inner
in1 = outter()
in1()
print("+++++++++++++++++++++++++++")
def outter(a):
def inner():
print("====%d===" % a)
return a+1
return inner
in2 = outter(10)
jieguo1 = in2()
print(jieguo1)
"""
基本的装饰
"""
def fun1():
print("====功能fun1===")
def outter(f1):
def inner():
print("=====fun1前增加功能====")
f1()
print("=====fun1后增强功能====")
return inner
f11 = outter(fun1)
f11()
"""
使用装饰器来完成一个方法的运行时间
"""
import time
#定义一个装饰器
def timmer_fun(f):
def inner():
start = time.time()
print("===装饰器--开始")
f()
end = time.time()
print(end-start)
print("===装饰器--结束")
return f
return inner
@timmer_fun
def fun1():
print("====fun1===开始===")
time.sleep(5)
print("====fun1===end")
fun1()
print("++++++++++++++++++++++++++++")
@timmer_fun
def fun2():
print("====fun2===开始===")
time.sleep(10)
print("====fun2===end")
fun2()
"""
被装饰函数有参数时
"""
import time
#定义一个装饰器
def timer_demo(f):
def inner(*args,**kwargs):
print("====装饰器开始====")
start = time.time()
f(*args,**kwargs)#可以接收任意参数的方法 也就是说可以装饰所有的方法
end = time.time()
print(end-start)
return f#闭包返回的是被装饰函数的对象
return inner#装饰器返回的是闭包对象
@timer_demo
def fun1(a):
print("====fun1===begin===")
time.sleep(5)
print("====fun1==end=====")
fun1(10)
print("++++++++++++++++++++++++++++++++++++++++")
@timer_demo
def fun2(a=2,b=9,c=8):
print("====fun2===begin===")
time.sleep(5)
print("====fun2==end=====")
fun2(10,8,32)
17 参数化
"""
ddt实战
首先声明一个@ddt,让程序知道我们要使用ddt了
使用@data来设定待测参数
使用@unpack来拆分数据,根据“,”来进行拆分
导入外部数据:@file_data
"""
import unittest
from ddt import ddt,data
@ddt
class Test_Case1(unittest.TestCase):
@data(1,2,3,4,5)
def test_one(self,value):
print(value)
@data((1,2,3),(4,5,6))
def test_two(self,value):
print(value)
"""
@unpack使用:拆分数据,可以拆分列表,元组,字典
"""
import unittest
from ddt import ddt,data,unpack
@ddt
class Test_case2(unittest.TestCase):
@data(("qq","123"),("ww","222"),("ss","999"))#设计的用例数据
@unpack#对用例数据进行分解
def test_one(self,value1,value2):
print("用户名 %s 密码 %s" %(value1,value2))
#参数话设计的是字典
@data({'name':'qq','pw':'123'},{'name':'ww','pw':'222'},{'name':'ss','pw':'999'})
@unpack
def test_two(self,name,pw):#定义的就是字典的键
print("====字典的数据===")
print(name,pw)
data1.txt
zhangfei,18989899
liubei,128999999
"""
2.读取文件中的内容,填入参数
"""
import unittest
from ddt import ddt,data,unpack,file_data
def read_file():
params = []#定义一个列表来接收文件内容
file1 = open("data1.txt","r",encoding="utf-8")
for line in file1.readlines():
params.append(line.strip("\n").split(","))
return params
@ddt
class Test_case3(unittest.TestCase):
@data(*read_file())
@unpack
def test_one(self,name,tel):
print("+++++++++++++++++++++++")
print(name,tel)
data2.json
{
“case1”: {“name”: “zhangfei”,“tel”: “19090909”},
“case2”: {“name”: “liubei”,“tel”: “189889888”},
“case3”: {“name”: “guanyu”,“tel”: “168888888”}
}
#参数是json文件
import unittest
from ddt import ddt,data,unpack,file_data
@ddt
class Test_Case1(unittest.TestCase):
@file_data("data2.json")
def test_one(self,name,tel):
print(name,tel)
使用@data来设定待测参数
使用@unpack来拆分数据,根据“,”来进行拆分
导入外部数据:@file_data
“”"
import unittest
from ddt import ddt,data
@ddt
class Test_Case1(unittest.TestCase):
@data(1,2,3,4,5)
def test_one(self,value):
print(value)
@data((1,2,3),(4,5,6))
def test_two(self,value):
print(value)
```python
"""
@unpack使用:拆分数据,可以拆分列表,元组,字典
"""
import unittest
from ddt import ddt,data,unpack
@ddt
class Test_case2(unittest.TestCase):
@data(("qq","123"),("ww","222"),("ss","999"))#设计的用例数据
@unpack#对用例数据进行分解
def test_one(self,value1,value2):
print("用户名 %s 密码 %s" %(value1,value2))
#参数话设计的是字典
@data({'name':'qq','pw':'123'},{'name':'ww','pw':'222'},{'name':'ss','pw':'999'})
@unpack
def test_two(self,name,pw):#定义的就是字典的键
print("====字典的数据===")
print(name,pw)
data1.txt
zhangfei,18989899
liubei,128999999
"""
2.读取文件中的内容,填入参数
"""
import unittest
from ddt import ddt,data,unpack,file_data
def read_file():
params = []#定义一个列表来接收文件内容
file1 = open("data1.txt","r",encoding="utf-8")
for line in file1.readlines():
params.append(line.strip("\n").split(","))
return params
@ddt
class Test_case3(unittest.TestCase):
@data(*read_file())
@unpack
def test_one(self,name,tel):
print("+++++++++++++++++++++++")
print(name,tel)
data2.json
{
“case1”: {“name”: “zhangfei”,“tel”: “19090909”},
“case2”: {“name”: “liubei”,“tel”: “189889888”},
“case3”: {“name”: “guanyu”,“tel”: “168888888”}
}
#参数是json文件
import unittest
from ddt import ddt,data,unpack,file_data
@ddt
class Test_Case1(unittest.TestCase):
@file_data("data2.json")
def test_one(self,name,tel):
print(name,tel)