python--利用列表推导式快速生成xml格式数据

在接口自动化测试中,我们经常将要发送的数据放到excel里。

json数据放至excel方便,但最近的一个测试,数据是xml格式发送的

如下:

 

属性

 

必选/可选

描述

1.

Message

Element

M

信息开始,XML根元素

2.

 

Version

Attribute

M

协议版本信息,取值为1.0

3.

Header

Element

M

消息头

5.

 

MsgType

Attribute

M

取值为包头的命令字值

 

 

 

MsgSeq

Attribute

M

取值为包头的消息序列号

例如:

<?xml version="1.0" encoding="UTF-8"?>

<Message Version="1.0">

    <Header MsgType="0x4001" MsgSeq=""/>

     ....

</Message>

 

 

在实际测试中不可能将所有数据放至excel中,这样太麻烦,更改也痛苦,所以将数据设成如下:

Name Data url Method MsgType Response token
用户登陆-正确密码 LogonId:15622222222
Password:k4y5eMcjTbNp/ncsaaD8OA==
UserType:1
/spi/login POST LoginRequest
 <Result RetCode="200" RetDesc="操作成功"/>
 <LoginResponse>
  <SessionId>xxxx</SessionId> 
 </LoginResponse>
用户登陆-错误密码 LogonId:156222222
Password:111111
UserType:0
/spi/login POST LoginRequest
 <Result RetCode="200" RetDesc="操作成功"/>
 <LoginResponse>
  <SessionId>xxxx</SessionId> 
 </LoginResponse>
用户登陆-错误的用户类型 LogonId:156222222
Password:111111
UserType:3
/spi/login POST LoginRequest
 <Result RetCode="200" RetDesc="操作成功"/>
 <LoginResponse>
  <SessionId>xxxx</SessionId> 
 </LoginResponse>

在python中使用列表推导式,一句话就生成相应的xml数据,简单实现,截取的部分代码如下:

读取excel这里不罗列

            dd=testDate.strip().split()
            aa=dict(tuple(item.split(':') for item in dd))
            xmlheader='<?xml version="1.0" encoding="utf-8"?><Message Version="1.0"><Header MsgType="%s"  MsgSeq="1"/><%s>' % (infoType,infoType)
            xmlbody="".join([ '<%s>%s</%s>' % (i,v,i)  for (i,v) in aa.items()]) #形成XML文件
            xmltail='</%s></Message>' % infoType
            xml=xmlheader+xmlbody+xmltail

小技巧,供有需要的人参考

posted @ 2016-05-18 15:28  Believer007  阅读(554)  评论(0)    收藏  举报