python接口自动化测试七:文件上传

Posted zhongyehai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python接口自动化测试七:文件上传相关的知识,希望对你有一定的参考价值。

 技术分享图片

技术分享图片

 

 

 

# 文件上传:content-Type:  multipart/form-data类型
import unittest
import requests

class SendFile():
   
def __init__(self, s):
       
self.s = s

    def sendImg(self, jpgpath, jpgname=‘1.jpg‘, jpgtype=‘image/jpeg‘):

       
# 登录并更新cookies
        f = open(‘1.jpg‘, ‘rb‘# 绝对路径
        url2 = ‘‘
       
body = {
           
‘localurl‘: (None, jpgname),
            ‘imgFile‘: (‘1.jpg‘, open(jpgpath, ‘rb‘), jpgtype)
           
# 1、绝对路径  2、open(‘1.jpg‘, ‘rb‘)  3、content-type的值
            }
       
# 上传图片的时候,不data和json,用files
        r = self.s.post(url2, files=body)    # 1、调用全局的s,用self.s   2、files
        print(r.text)
       
# 上传到服务器,每传一次地址都不一样


        # 解决抛异常
        try:
           
jpg_url = r,json()[‘url‘]   # (相对路径)
            print(jpg_url)
           
return jpg_url

        except Exception as msg:    # 返回报错信息
            print(图片上传失败,原因:%s‘%msg)   # 打印报错信息
        #    raise   # 主动抛原始异常
        #    raise  ··· # 抛出异常内容为:“···”
            return ‘‘

if __name__==‘__main__‘:
   
s = requests.session()
   
from test.test_009_003_zentaologin import LoginZentao
    # 调登录方法
    login = LoginZentao(s)      # 实例化类LoginZentao为对象
    login.login()
   
# 上传文件
    send = SendFile(s)      # 把类sendfile()实例化为对象
    send.sendImg()          # 调用sendfile()里面的sendImg方法


 

 

import requests
class LoginZentao():

   
def __init__(self, s):      # 初始化
        self.s = s              # 定义一个全局的s

    def login(self):
       
r = self.s.post()        # self.s调用全局的s
        pass

if
__name__==‘__main__‘:
   
s = requests.session()
   
zentao = LoginZentao(s# 类实例化为对象,传入参数s
    zentao.login()          # 调用zentao里面的login() 方法

 技术分享图片

 

 

import unittest
import requests
from test.test_009_003_zentaologin import LoginZentao   # 从文件夹.文件名导入LoginZentao类
from test.test_009_002_sendfile import SendFile         # 从文件夹.文件名导入sendfile类
import os

# 获取文件路径
parpath = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))  # 定位当前文件夹
jpgpath = os.path.join(parpath, ‘testdata‘, ‘1.jpg‘)    # “testdata”:存放文件的文件夹名,“1.jpg”:文件名


class TestSendFile(unittest.TestCase):

   
@classmethod
    def setUpClass(cls):
       
cls.s = requests.session()
       
# 实例化调用的类
        cls.login = LoginZentao(cls.s # 实例化类LoginZentao为对象
        cls.send = SendFile(cls.s)   # 把类sendfile()实例化为对象

    def test_01(self):
       
# 上传文件:第一步,登录
        self.login.login()
       
# 第二步,传文件
        result = self.send.sendImg(jpgpath)
       
# 第三步:断言:返回的结果里面包含‘.jpg‘
        self.assertIn(‘.jpg‘, result)

   
# # 调登录方法
    # login = LoginZentao(s)      # 实例化类LoginZentao为对象
    # login.login()
    # # 上传文件
    # send = SendFile(s)      # 把类sendfile()实例化为对象
    # send.sendImg()          # 调用sendfile()里面的sendImg方法

技术分享图片

 


 


# 添加多个附件参数化
files = [("1.png", "1.png")
         (
"2.png", "2.png")
       
]
def addFiles(files, n=1):
   
file = []
   
for i in list(range(n)):
       
a =("files[]", (files[i][1], open(files[i][2], "rb"), "image/png"))
       
b = ("labels[]", (None, 附件标题1‘)),
        ("files[]", ("2.png", open("d:\\\\2.png", "rb"), "image/png")),
        ("labels[]", "tu2"),
        file.append(a)
       
file.append(b)
       
return file

技术分享图片

 


 

# 上传图片代码
# coding:utf-8
import requests
base = ‘http://127.0.0.1:81/‘ # 禅道的服务器地址
loginUrl = base+"/zentao/user-login.html"
h = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
"Accept-Encoding": "gzip, deflate",
"Referer": "http://127.0.0.1/zentao/user-login.html",
# "Cookie": # 头部没登录前不用传cookie,因为这里cookie就是保持登录的
"Connection": "keep-alive",
"Content-Type": "application/x-www-form-urlencoded",
}
body = {
"account":"admin",
"password":"e10adc3949ba59abbe56e057f20f883e",
"keepLogin[]":"on",
"referer":"http://127.0.0.1/zentao/my/"
}
s = requests.session() # 保持会话
r = s.post(loginUrl, data=body, headers=h)
print(r.content) # 打印结果看到location=‘http://127.0.0.1/zentao/my/‘说明登录成功了
# 上传图片
url1 = "http://127.0.0.1:81/zentao/file-ajaxUpload-5a26aca290b59.html?dir=image"
f ={
"localUrl": (None, "1.png"),
"imgFile": ("1.png", open("d:\\\\1.png", "rb"), "image/png")
}
r = s.post(url1, files=f)
try:
jpgurl = base+r.json()["url"]
print(u"上传图片后的url地址:%s" % jpgurl)
except Exception as msg:
print(u"返回值不是json格式:%s" % str(msg))
print(r.content.decode("utf-8"))

技术分享图片

 

# 参数
f = {
"product": "1",
"module": "0",
"project": "",
"openedBuild[]": "trunk",
"assignedTo": "admin",
"type": "codeerror",
"os": "all",
"browser": "all",
"color": "",
"title": "yoyoketang-这是一个bug描述1122",
"severity": "3",
"pri": "0",
"steps": ‘<p>[步骤]</p>\\
<p>1、第一步点</p>\\
<p>2、第二步点</p>\\
<p>3、点三步点</p>\\
<p>[结果]</p>\\
<p><img src="data/upload/1/201712/072254170557cdn.png" /></p>\\
<p>[期望]</p>‘,
# img src=“data/upload/1/201712/072254170557cdn.png” 这个地址是上一步图片上传的相对地址
"story": "0",
"task": "0",
"mailto[]": "",
"keywords": "",
"files[]": "",
"labels[]": "",
"uid": "5a2955c884f98",
"case": "0",
"caseVersion": "0",
"result": "0",
"testtask": "0"
}

技术分享图片

 

# coding:utf-8
import requests
base = ‘http://127.0.0.1/‘ # 禅道的服务器地址
loginUrl = base+"zentao/user-login.html"
h = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
# "Cookie": # 头部没登录前不用传cookie,因为这里cookie就是保持登录的
"Content-Type": "application/x-www-form-urlencoded",
}
body = {
"account": "admin",
"password": "e10adc3949ba59abbe56e057f20f883e",
"keepLogin[]": "on",
"referer": "http://127.0.0.1/zentao/my/"
}
s = requests.session() # 保持会话
r = s.post(loginUrl, data=body, headers=h)
print(r.content) # 打印结果看到location=‘http://127.0.0.1/zentao/my/‘说明登录成功了
# 提交bug
url1 = base+"zentao/bug-create-1-0-moduleID=0.html"
f = {
# 参数
}
r = s.post(url1, data=f)
print(r.content.decode("utf-8"))

技术分享图片

 


# .参数关联
# coding:utf-8
import requests
host = ‘http://127.0.0.1/‘ # 禅道的服务器地址
s = requests.session() # 保持会话

def login(username=‘admin‘, psw=‘e10adc3949ba59abbe56e057f20f883e‘):
‘‘‘登录禅道
username: 用户名
psw:登录密码,加密后的
‘‘‘
loginUrl = host+"zentao/user-login.html"
h = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
# "Cookie": # 头部没登录前不用传cookie,因为这里cookie就是保持登录的
"Content-Type": "application/x-www-form-urlencoded",
}
body = {
"account": username,
"password": psw,
"keepLogin[]": "on",
"referer": host+"zentao/my/"
}
r = s.post(loginUrl, data=body, headers=h)
print(r.content) # 打印结果看到location=‘http://127.0.0.1/zentao/my/‘说明登录成功了

技术分享图片

 



def upload_jpg(path="d:\\\\1.png", filename=‘1.png‘):
‘‘‘上传图片
path:上传文件路径
filename: 上传文件名称
‘‘‘
url1 = host+"zentao/file-ajaxUpload-5a26aca290b59.html?dir=image"
f ={
"localUrl": (None, filename),
"imgFile": (filename, open(path, "rb"), "image/png")
}
r = s.post(url1, files=f)
try:
jpgurl = r.json()["url"]
print(u"上传图片后的url地址:%s" % jpgurl)
return jpgurl
except Exception as msg:
print(u"返回值不是json格式:%s" % str(msg))
print(r.content)
return ‘‘

技术分享图片

 



def add_bug(title="yoyoketang-这是一个bug描述1224", jpg=‘‘):
‘‘‘提交bug
title: bug描述
jpg:上传图片的相对路径
‘‘‘
url1 = host+"zentao/bug-create-1-0-moduleID=0.html"
f = {
# 参数
}
r = s.post(url1, data=f)
print(r.content.decode("utf-8"))
if __name__ == "__main__":
# 1.先登录
login(username=‘admin‘, psw=‘e10adc3949ba59abbe56e057f20f883e‘)
# 2.图片上传,返回图片地址
jpg = upload_jpg(path="d:\\\\1.png", filename=‘1.png‘)
# 3.添加bug, 调用上个接口返回的地址作为请求参数
add_bug(title="yoyoketang-这是一个bug描述1225", jpg=jpg)

技术分享图片

 


# 上传多个附件
# 传多个文件的时候如下,这两个参数的name都是一样的,如果用字典去传key值,很显然python的key值是不能重复的
‘‘‘
Content-Disposition: form-data; name="files[]"; filename="1.png"
Content-Type: image/png
Content-Disposition: form-data; name="files[]"; filename="2.png"
Content-Type: image/png
# 2.这时候需要换个格式,传list数据
‘‘‘
# file = {
# "files[]": ("1.png", open("d:\\\\1.png", "rb"), "image/png"),
# "labels[]": "tu1",
# }
# -------------多个文件用list类型------------
file = [
("files[]", ("2.png", open("d:\\\\1.png", "rb"), "image/png")),
("labels[]", "tu1"),
("files[]", ("2.png", open("d:\\\\2.png", "rb"), "image/png")),
("labels[]", "tu2"),
]

技术分享图片

 




# multipart/form-data传文件
from requests_toolbelt import MultipartEncoder
import requests
m = MultipartEncoder(
fields={
‘field0‘: ‘value‘,
‘field1‘: ‘value‘,
‘field2‘: (‘filename‘, open(‘file.py‘, ‘rb‘), ‘text/plain‘)
}
)
r = requests.post(‘http://httpbin.org/post‘,
data=m,
headers={‘Content-Type‘: m.content_type})

技术分享图片

 




# multipart/form-data传非文件表单
from requests_toolbelt import MultipartEncoder
import requests
m = MultipartEncoder(
fields={
‘field0‘: ‘value‘,
‘field1‘: ‘value‘,
‘field2‘: (‘filename‘, open(‘file.py‘, ‘rb‘), ‘text/plain‘)
}
)
r = requests.post(‘http://httpbin.org/post‘,
data=m,
headers={‘Content-Type‘: m.content_type})

技术分享图片

 



# multipart/form-data传多个文件
from requests_toolbelt import MultipartEncoder
import requests
m = MultipartEncoder(
fields = [
(‘source‘, (‘f1.ext‘, f1, ‘application/x-example-mimetype‘),
(‘source‘, (‘f2.ext‘, f2, ‘application/x-example-mimetype‘),
]
)
r = requests.post(‘http://httpbin.org/post‘,
data=m,
headers={‘Content-Type‘: m.content_type})

技术分享图片

 


# 上传多个附件代码
# coding:utf-8
import requests
from requests_toolbelt import MultipartEncoder
host = ‘http://127.0.0.1:81‘ # 禅道的服务器地址
def login(s,user="admin",psw="e10adc3949ba59abbe56e057f20f883e"):
u‘‘‘登录禅道‘‘‘
loginUrl = host+"/zentao/user-login.html"
h = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
"Accept-Encoding": "gzip, deflate",
"Referer": host+"/zentao/user-login.html",
# "Cookie": # 头部没登录前不用传cookie,因为这里cookie就是保持登录的
"Connection": "keep-alive",
"Content-Type": "application/x-www-form-urlencoded",
}
body = {
"account": user,
"password": psw,
"keepLogin[]": "on",
"referer": host+"/zentao/my/"
}
try:
r = s.post(loginUrl, data=body, headers=h)
print(r.content) # 打印结果看到location=‘http://127.0.0.1/zentao/my/‘说明登录成功了
if "/zentao/my/" in r.content:
print("登录成功!")
return True
else:
print("登录失败:%s" % r.content)
return False
except Exception as msg:
print("登录失败:%s"%str(msg))
return False

def upload_jpg(s):
u‘‘‘上传图片‘‘‘
# url1 = host+"/zentao/file-ajaxUpload-5a26aca290b59.html?dir=image"
m = MultipartEncoder(
fields={
"localUrl": (None, "1.png"),
"imgFile": ("1.png", open("d:\\\\1.png", "rb"), "image/png")
})
try:
r1 = s.post(url1, data=m, headers={‘Content-Type‘: m.content_type})
jpg_url = r1.json()["url"]
return jpg_url
except Exception as msg:
print("上传失败:%s"%str(msg))
return ""

def submit_bug(s,jpg_url,title="yoyoketang-这是一个带附件的内容"):
# 提交bug, 带上附件
url2 = host+"/zentao/bug-create-1-0-moduleID=0.html"
m = MultipartEncoder(
fields = [
("product", "1"),
("module","0"),
("project", ""),
("openedBuild[]", "trunk"),
("assignedTo", "admin"),
("type", "codeerror"),
("os", "all"),
("browser", "all"),
("color", ""),
("title", title), # bug标题参数化
("severity", "3"),
("pri", "0"),
("steps", u‘<p>[步骤]</p>\\
<p>1、第一步点</p>\\
<p>2、第二步点</p>\\
<p>3、点三步点</p>\\
<p>[结果]</p>\\
<p><img src="%s" /></p>\\
<p>[期望]</p>‘ % jpg_url), # 正文图片地址参数
("story", "0"),
("task", "0"),
("mailto[]", ""),
("keywords", ""),
# 这里的四个参数就是上传文件附件了
("files[]", ("1.png", open("d:\\\\1.png", "rb"), "image/png")), # 附件1
("labels[]", "tu1"),
("files[]", ("2.png", open("d:\\\\2.png", "rb"), "image/png")), # 附件1
("labels[]", "tu2"),
("uid", "5a2955c884f98"),
("case", "0"),
("caseVersion", "0"),
("result", "0"),
("testtask", "0")
])
try:
r2 = s.post(url2, data=m, headers={‘Content-Type‘: m.content_type})
print(r2.content.decode("utf-8"))
except Exception as msg:
print("提交BUG失败:%s"%str(msg))
if __name__ == "__main__":
s = requests.session() # 保持会话
login(s, user="admin", psw="e10adc3949ba59abbe56e057f20f883e") # 登录
jpg = upload_jpg(s) # 上传图
# 获取上传图片后用的url地址传给提交bug的正文
submit_bug(s, jpg, title="yoyoketang-这是一个带附件的内容")

技术分享图片

 


技术分享图片

 

技术分享图片

 

技术分享图片

 































































































































































































































































































































































































































































以上是关于python接口自动化测试七:文件上传的主要内容,如果未能解决你的问题,请参考以下文章

接口自动化测试中,文件上传该如何测试?

python接口自动化测试七:获取登录的Cookies

python接口自动化测试-requests.post()

python接口自动化测试-requests.post()

java接口自动化测试--restassured如何进行文件上传接口测试

Flask 编写http接口api及接口自动化测试