python笔记4

1.断言

from selenium import webdriver
import unittest

class BaiduTest(unittest.TestCase):
    def setUp(self) -> None:
        self.driver=webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://www.baidu.com/')
        self.driver.implicitly_wait(30)

(1)断言的详解

1)assertEqual():验证两个值的数据类型与内容是否相等

    def tearDown(self) -> None:
        '''验证百度标题'''
        self.assertEqual(self.driver.title,'百度一下,你就知道')

2)assertTrue():返回的是bool类型,验证的是被测试对象返回的内容是True

    def test_baidu_seaech(self):
        search=self.driver.find_element_by_id('kw')
        self.assertTrue(search.is_enabled())

3)assertIn():一个值是否包含在另一个值里面

    def test_baidu_in(self) -> None:
        '''assertIn:验证一个值是否包含在另外一个值里面'''
        self.assertIn('百度一下',self.driver.title)

(2)断言的注意事项

1)if条件语句的错误使用

    def test_baidu_if(self):
        '''if条件语句不合理'''
        title=self.driver.title
        if title=='百度一下你就知道':
         print('测试通过')
        else:
         print('测试不通过')

2)try语句的异常

    def test_baidu_try(self):
        '''try语句异常'''
        title=self.driver.title
        try:
            self.assertEqual(title,'百度一下,你就知道')
        except Exception as e:
            print(e.args[0])

if __name__ == '__main__':
    unittest.main(verbosity=2)

2.(1)设置IDE的编码为UTF-8

   (2)读取文件的时候,设置编码:

            utf-8

            gbk

            gb2312

3.数据驱动:将测试数据分离出来

(1)JSON(sina实战)

先在data下创建编写sina.json

pathUtils

jsonUtils

在测试层改变

1)base.py

import time as t

from selenium.webdriver.common.by import  By
from selenium.webdriver.support.expected_conditions import  NoSuchFrameException
from selenium.webdriver.support.wait import WebDriverWait
from selenium import  webdriver

class webDriver:
    def __str__(self):
        #driver指的是webdriver实例化后的对象
        return 'driver'
    #单种元素定位,*loc:识别元素属性,ctr+鼠标放置到元素+左键:判断定位元素属性的方法是否正确
    def findElement(self,*loc):
        return  self.driver.find_element(*loc)
    # 多种元素定位
    def findElements(self,*loc):
        return self.driver.find_element(*loc)

    def findFrame(self, frameID):
        return self.driver.switch_to.frame(frameID)

    @property
    def getTitle(self):
        t.sleep(3)
        return self.driver.title

    @property
    def getUrl(self):
        t.sleep(3)
        return self.driver.current_url

2)sina.json(必须使用双引号)

{
    "login":
        {
            "notEmail":"请输入邮箱名",
            "formatEmail":"您输入的邮箱名格式不正确",
            "errorEmail":"登录名或密码错误",
            "username": "wuya1303@sina.com",
            "password": "admin123",
            "url": "https://m0.mail.sina.com.cn/classic/index.php#title=%25E9%2582%25AE%25E7%25AE%25B1%25E9%25A6%2596%25E9%25A1%25B5&action=mailinfo",
            "text": "test"
        }
}

3)sian.py

from selenium.webdriver.common.by import By
from base.base import webDriver
import time as t

class Sina(webDriver):
    username_loc=(By.ID,'freename')
    password_loc=(By.ID,'freepassword')
    login_loc=(By.LINK_TEXT,'登录')
    '''sina错误信息提示位置'''
    divText=(By.XPATH,'/html/body/div[3]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]')
    nick=(By.XPATH,'//*[@id="user_id"]/em[2]')
    nickName=(By.XPATH,'//*[@id="greeting"]/span')

    def username(self,username):
        '''输入用户名'''
        self.findElement(*self.username_loc).send_keys(username)

    def password(self,password):
        '''输入密码'''
        self.findElement(*self.password_loc).send_keys(password)

    @property
    def clickLogin(self):
        self.findElement(*self.login_loc).click()

    def login(self,username,password):
        self.username(username)
        self.password(password)
        self.clickLogin

    @property
    def getDivText(self):
        t.sleep(3)
        return self.findElement(*self.divText).text

    @property
    def getNick(self):
        t.sleep(3)
        return self.findElement(*self.nick).text

    def getNickName(self):
        t.sleep(3)
        return self.findElement(*self.nickName).text

4)test_sina_json.py

import time as t
from page.sina import Sina
from page.init import InitSina
from utils.jsonUtils import readJson
import unittest

class SinaTest(InitSina,Sina):
    def test_sina_login_001(self):
        '''登录验证:帐户和密码为空'''
        self.login(username='',password='')
        self.assertEqual(self.getDivText,readJson()['login']['notEmail'])

    def test_sina_login_002(self):
        '''登录验证:用户名和密码不规范'''
        self.login(username='@#$%Efdg',password='qwuob%$')
        self.assertEqual(self.getDivText,readJson()['login']['formatEmail'])

    def test_sina_login_003(self):
        '''登录验证:帐户或密码错误'''
        self.login(username='1874468142@sina.com',password='liuxun')
        self.assertEqual(self.getDivText,readJson()['login']['errorEmail'])

    def test_sina_login_004(self):
        '''登录成功:校验昵称'''
        self.login(
        username=readJson()['login']['username'],
        password=readJson()['login']['password']
        )
        self.assertEqual(self.getNick, readJson()['login']['username'])

    def test_login_005(self):
'''登录成功:校验url是否正确''' self.login( username
=readJson()['login']['username'], password=readJson()['login']['password'] ) self.assertEqual(self.getUrl,readJson()['login']['url']) def test_login_006(self):
'''登录成功:校验昵称名字''' self.login( username
=readJson()['login']['username'], password=readJson()['login']['password'] ) self.assertEqual(self.getNickName(), readJson()['login']['text']) if __name__ == '__main__': unittest.main(verbosity=2)

5)pathUtils.py

import os

def base_dir(_file_=None):
    #获取当前工程的路径
    return os.path.dirname(os.path.dirname(__file__))

def filePath(directory='data',fileName=None):
    '''找到具体的文件路径'''
    return os.path.join(base_dir(),directory,fileName)

6)jsonUtils.py

import json
from utils.pathUtils import base_dir,filePath
import os
def readJson():
    return json.load(open(filePath(directory='data',fileName='sina.json'),encoding='UTF-8'))
print(readJson())

(2)Yaml(sina实战)

先在data下创建编写sina.yaml

pathUtils

yamlUtils

在测试层改变

注意事项:config.yaml和yamlUtils.py是分离链接地址的作用

1)base包下的base.py

import time as t

from selenium.webdriver.common.by import  By
from selenium.webdriver.support.expected_conditions import  NoSuchFrameException
from selenium.webdriver.support.wait import WebDriverWait
from selenium import  webdriver

class webDriver:
    def __str__(self):
        #driver指的是webdriver实例化后的对象
        return 'driver'
    #单种元素定位,*loc:识别元素属性,ctr+鼠标放置到元素+左键:判断定位元素属性的方法是否正确
    def findElement(self,*loc):
        return  self.driver.find_element(*loc)
    # 多种元素定位
    def findElements(self,*loc):
        return self.driver.find_element(*loc)

    def findFrame(self, frameID):
        return self.driver.switch_to.frame(frameID)

    @property
    def getTitle(self):
        t.sleep(3)
        return self.driver.title

    @property
    def getUrl(self):
        t.sleep(3)
        return self.driver.current_url

2)config包下的config.yaml

url:
  sina: https://mail.sina.com.cn/

3)data包下的sina.yaml(冒号后,必须空格一位)

login:
   notEmail: 请输入邮箱名
   formatEmail: 您输入的邮箱名格式不正确
   errorEmail: 登录名或密码错误
   username: wuya1303@sina.com
   password: admin123

4)page包下的init.py

import unittest
from selenium import webdriver
from utils.yamlUtils import getUrl

class Init(unittest.TestCase):
    def setUp(self)->None:
        self.driver=webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://file.qq.com/')
        self.driver.implicitly_wait(30)

    def tearDown(self)->None:
        self.driver.quit()

class InitSina(unittest.TestCase):
    def setUp(self) -> None:
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get(getUrl())
        self.driver.implicitly_wait(30)

    def tearDown(self) -> None:
        self.driver.quit()

5)page包下的sian.py

from selenium.webdriver.common.by import By
from base.base import webDriver
import time as t

class Sina(webDriver):
    username_loc=(By.ID,'freename')
    password_loc=(By.ID,'freepassword')
    login_loc=(By.LINK_TEXT,'登录')
    '''sina错误信息提示位置'''
    divText=(By.XPATH,'/html/body/div[3]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]')
    nick=(By.XPATH,'//*[@id="user_id"]/em[2]')
    nickName=(By.XPATH,'//*[@id="greeting"]/span')

    def username(self,username):
        '''输入用户名'''
        self.findElement(*self.username_loc).send_keys(username)

    def password(self,password):
        '''输入密码'''
        self.findElement(*self.password_loc).send_keys(password)

    @property
    def clickLogin(self):
        self.findElement(*self.login_loc).click()

    def login(self,username,password):
        self.username(username)
        self.password(password)
        self.clickLogin

    @property
    def getDivText(self):
        t.sleep(3)
        return self.findElement(*self.divText).text

    @property
    def getNick(self):
        t.sleep(3)
        return self.findElement(*self.nick).text

    def getNickName(self):
        t.sleep(3)
        return self.findElement(*self.nickName).text

6)utils包下的yamlUtils.py

import yaml
from utils.pathUtils import filePath

def readYaml():
    '''读取yaml文件里的内容'''
    return yaml.load(open(filePath(fileName='sina.yaml'),encoding='UTF-8'))

def getUrl():
    return yaml.load(open(filePath(directory='config',fileName='config.yaml'),encoding='utf-8'))['url']['sina']

print(getUrl())

7)test包下的test_sina_yaml.py

import time as t
from page.sina import Sina
from page.init import InitSina
from utils.yamlUtils import readYaml
from utils.yamlUtils import getUrl
import unittest

class SinaTest(InitSina,Sina):
    def test_sina_login_001(self):
        '''登录验证'''
        self.login(username='',password='')
        self.assertEqual(self.getDivText,readYaml()['login']['notEmail'])

    def test_sina_login_002(self):
        '''登录验证:用户名和密码不规范'''
        self.login(username='@#$%Efdg',password='qwuob%$')
        self.assertEqual(self.getDivText,readYaml()['login']['formatEmail'])

    def test_sina_login_003(self):
        '''帐户或密码错误'''
        self.login(username='1874468142@sina.com',password='liuxun')
        self.assertEqual(self.getDivText,readYaml()['login']['errorEmail'])

    def test_sina_login_004(self):
        '''登录验证:校验登录成功'''
        self.login(
        username=readYaml()['login']['username'],
        password=readYaml()['login']['password']
        )
        self.assertEqual(self.getNick, readYaml()['login']['username'])

    def test_login_005(self):
        self.login(
            username=readYaml()['login']['username'],
            password=readYaml()['login']['password']
        )
        self.assertEqual(self.getUrl,readYaml()['login']['url'])

    def test_login_006(self):
        self.login(
            username=readYaml()['login']['username'],
            password=readYaml()['login']['password']
        )
        self.assertEqual(self.getTitle, readYaml()['login']['text'])

if __name__ == '__main__':
    unittest.main(verbosity=2)

4.pytest

先输入安装命令pip install pytest,安装成功后,编写如下代码

def add(a,b):
    return a+b

def test_add_001():
    assert add(1,1)==2

def test_add_003():
    assert add('hello',' world')=='hello world'

命令窗口中,在该test_add.py模块的目录下,输入python -m pytest -v test_add.py,回车运行,会有如下截图:

 

posted @ 2021-08-23 18:30  liuxun0223  阅读(50)  评论(0)    收藏  举报