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-8import requestsbase = ‘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-8import requestsbase = ‘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/‘说明登录成功了# 提交bugurl1 = base+"zentao/bug-create-1-0-moduleID=0.html"f = {# 参数}r = s.post(url1, data=f)print(r.content.decode("utf-8"))


# .参数关联# coding:utf-8import requestshost = ‘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/pngContent-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 MultipartEncoderimport requestsm = 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 MultipartEncoderimport requestsm = 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 MultipartEncoderimport requestsm = 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-8import requestsfrom requests_toolbelt import MultipartEncoderhost = ‘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-这是一个带附件的内容")




原文地址:https://www.cnblogs.com/zhongyehai/p/9147815.html

时间: 2024-11-07 16:37:26

python接口自动化测试七:文件上传的相关文章

python接口自动化7-post文件上传

前言 文件上传在我们软件是不可少的,最多的使用是体现在我们后台,当然我们前台也会有.但是了解过怎样上传文件吗?这篇我们以禅道文档-创建文档,上传文件为例. post请求中的:Content-Type:multipart/form-data  这种类型便是上传文件. 一.环境安装.抓包分析 1.pip install requests_toolbelt,post请求 multipart/form-data  类型 C:\Users\Administrator>pip install request

django中使用FastDFS分布式文件系统接口代码实现文件上传、下载、更新、删除

运维使用docker部署好之后FastDFS分布式文件系统之后,提供给我接口如下: fastdfs tracker 192.168.1.216 192.168.1.217 storage 192.168.1.216 192.168.1.217 我们只需要在配置文件中进行配置即可,然后利用客户端提供的接口通过简单的代码就可以将文件上传到分布式文件系统中 至于内部实现机制,可以参考我的另外一篇博客:分布式文件系统Fastdfs原理及部署 再次提醒在安装客户端可能会遇到各种不可控的因素,导致你上传失败

python+selenium+autoit实现文件上传

问题 在做web端ui层自动化的时候会碰到文件上传的操作,经常有朋友问到,这里总结一下 解决方案 第一种:type=file的上传文件,类似如下的 使用类似这样的代码就可以完成: driver.find_element('name','file').send_keys('./小强测试品牌.png') 第二种:就是第一种除外的,实现起来较为麻烦,这里用到了autoit,大致步骤如下: 1.下载并安装autoit,之后在开始菜单可以看到如下 AutoIt Windows Info 用于识别Windo

python,socket通信编程,文件上传例子

写一个file_receive.py和一个file_send.py程序,由file_send.py上传一个文件,file_receive.py接收上传的文件,写到指定的包内 #file_receive.pyimport socket,subprocess,os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sk = socket.socket() address = ('127.0.0.1',8001) sk.bind(address

python入门第二十八天——文件上传

服务端: 1 #!/usr/bin/env python3 2 #-*- coding:utf-8 -*- 3 ''' 4 Administrator 5 2018/8/1 6 ''' 7 import subprocess 8 import socket,os 9 10 # 创建一个socket: 11 #family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None 12 #创建Socket时,AF_INET指定使用IPv4协议, 13 # 如果

python——基础篇-简易文件上传

post_server import socket import os sk=socket.socket() address=('127.0.0.1',8000) sk.bind(address) sk.listen(3) print('waiting...') BASE_DIR=os.path.dirname(os.path.abspath(__file__)) while 1: conn,addr=sk.accept() while 1: data=conn.recv(1024) cmd,f

python接口自动化测试(七)-unittest-批量用例管理

我们日常项目中的接口测试案例肯定不止一个,当案例越来越多时我们如何管理这些批量案例?如何保证案例不重复?如果案例非常多(成百上千,甚至更多)时如何保证案例执行的效率?如何做(批量)测试数据的管理?如何做到数据与脚本分离? 以上这些问题才是我们自动化测试中要重点考虑的问题,单个用例其实并不难. 来看一下在unittest框架中如何管理批量案例: 一.手工加载批量用例: # -*- coding:utf-8 -*- # 批量用例执行--手工加载 import unittest class TestO

Python写的一个文件上传upload

#!/usr/bin/env python #coding:utf-8 ''' @date:2014-11-30 @filename:simpleUp.py ''' import web urls=( '/','index', '/test','mytest', '/upload','Upload', ) app = web.application(urls,locals()) class mytest: def GET(self): return "<b><h1>myt

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

获取登录的cookies:loginCookies = r.cookies 把获取到的cookies传入请求:cookies=loginCookies 此方法需每一次都调用登录方法,并且每一次发送请求都需要传Cookies,不建议使用 原文地址:https://www.cnblogs.com/dwdw/p/9553058.html