如何使用HP ALM REST API在IMC中将IMAGE作为运行附件上载

时间:2017-07-12 17:28:27

标签: python rest attachment alm hp-quality-center

我已经搜索了几天并试图自己解决问题,但没有成功。

我发现可以将文件附加到QC Run(使用Python或Ruby)这样的东西(在Rest请求中发送):

内容示例

headers = {'accept': 'application/xml', 'Content-Type': 'multipart/form-data; boundary=exampleboundary'}

--exampleboundary
Content-Disposition: form-data; name="filename"
example.txt

--exampleboundary
Content-Disposition: form-data; name="description"
Here is the text that describes example.txt

--exampleboundary
Content-Disposition: form-data; name="file"; filename="example.txt"
Content-Type: text/plain
ContentOfFile

--exampleboundary--

这确实有效,但(显然)仅适用于文本文件(.txt)。我真的需要上传一些图片,如测试证据/截图。

我怎样才能实现这一目标?任何人都可以帮我解决这个问题吗?

我发送的请求内容如下:

import requests
#login
response = requests.get("http://"+server+"/qcbin/authentication-point/authenticate", auth=(user,pwd))

# Get ALM token in dict format
token = response.cookies.get_dict()

requests.post(url, content, cookies=token, headers=headers_image)

谢谢。

3 个答案:

答案 0 :(得分:1)

参考Barney的评论,我在这里留下解决问题的答案。

def upload_result_file(self, run_id, report_file, token):

    url = "http://%s/qcbin/rest/domains/%s/projects/%s/runs/%s/attachments" % (server, domain, project, run_id)

    payload = open(report_file, 'rb')
    headers_file = {}
    headers_file['Content-Type'] = "application/octet-stream"
    headers_file['slug'] = "test-results." + report_file[report_file.rfind(".")+1: ]

    response = requests.post(url, headers=headers_file, data=payload, cookies=token)
    if not (response.status_code == 200 or response.status_code == 201):
        print "Attachment step failed!", response.text, response.url, response.status_code
    return

自: https://github.com/macroking/ALM-Integration/blob/master/ALM_Integration_Util.py

答案 1 :(得分:0)

在API中:

if not request.form:
    abort(405)
request.form.get('file', "")
file = file.read().encode("base64")

在POST电话中:

 -F 'file=@/var/path/to/my/file/test.png' http://xxx.xx.xx.xxx:8080/todo/api/v1.0/tasks

答案 2 :(得分:0)

感谢koxta分享此解决方案。

使用此解决方案,我可以将RobotFramework的日志文件作为测试运行的附件成功上传。

分享我的代码:

def upload_log(self, entity_type, entity_id, file_name):
    qurl = '%s/qcbin/rest/domains/%s/projects/%s/%s/%s/attachments' %(self._url, self._domain, self._project, entity_type, entity_id)

    headers = self._headers
    headers['Content-Type'] = 'application/octet-stream'
    headers['slug'] = 'log.' +file_name[file_name.rfind(".")+1: ]
    print (headers)

    if os.path.isfile(file_name):
        with open(file_name, 'rb') as log_file:
            binary_data = log_file.read()
    print (binary_data)

    response = self.session.post(qurl, data=binary_data, headers=headers)
    print (response.text)
    if response.status_code != 201:
        raise Exception('Failed to upload %s - code=%s message=%s' %(file_name, response.status_code, response.text))