python自动化测试REST API TEST Simulator

test_cfg.txt

[Notification Server]
URL=/mdmi/ns.py
REST_InstallProfile=/mdmi/rg9Z9UduPoEK2oQIhZFUcqeriGR12Es7/v1/profile/install
REST_RemoveProfile=/mdmi/rg9Z9UduPoEK2oQIhZFUcqeriGR12Es7/v1/profile/remove
REST_InstallProfile2=/mdmi/mZAg49qdRmAK2oQIhZFUcu2zPd7l8nQW/v1/profile/install
REST_RemoveProfile2=/mdmi/mZAg49qdRmAK2oQIhZFUcu2zPd7l8nQW/v1/profile/remove
REST_InstallProfile3=/mdmi/a51wJAWKV6gK2oQIhZFUclvo7+OoGKtu/v1/profile/install
REST_RemoveProfile3=/mdmi/a51wJAWKV6gK2oQIhZFUclvo7+OoGKtu/v1/profile/remove
REST_InstallProfile4=/mdmi/+9LHUbARmrcK2oQIhZFUckU6mhPB!NkS/v1/profile/install
REST_RemoveProfile4=/mdmi/+9LHUbARmrcK2oQIhZFUckU6mhPB!NkS/v1/profile/remove
REST_TestConnection=/mdmi/mZAg49qdRmAK2oQIhZFUcu2zPd7l8nQW/v1
#Hybrid account
REST_InstallProfile5=/mdmi/V8SFqNmmLE4K2oQIhZFUcj0exWHIjDp!/v1/profile/install
REST_RemoveProfile5=/mdmi/V8SFqNmmLE4K2oQIhZFUcj0exWHIjDp!/v1/profile/remove


[Connection]
Host=127.0.0.1
#Host=10.230.48.21
#Host=es-cn-mobile-end.odd.blackspider.com
Port=443
Username=ericadmin@websense.com
Username2=zhiadmin@websense.com
Username3=zhuangadmin@websense.com
Username4=jiaadmin@websense.com
#Username=yongpengadmin@websense.com
Username5=hybridweb1@mdmi.com
Password=Wsws1234
Password2=Qaqa1234
WrongPassword=1234

-------------------------------------------------------------------------------------------------------

#! /usr/bin/python

#FileName: NotificationSimu.py
import urllib
import httplib
import base64
import json
import ConfigParser
import uuid


CFG_DATA = "../tms_enroll/test_cfg.txt"
TEST_DATA = ConfigParser.ConfigParser()
TEST_DATA.read(CFG_DATA)
INSTALL_PROFILE_IOS = "../tms_enroll/installprofile_ios.json"
INSTALL_PROFILE_ARD = "../tms_enroll/installprofile_ard.json"
REMOVE_PROFILE_IOS = "../tms_enroll/removeprofile_ios.json"
REMOVE_PROFILE_ARD = "../tms_enroll/removeprofile_ard.json"


class NotificationSimu():
def __init__(self, flag=0):
self.host = TEST_DATA.get("Connection", "Host")
self.port = TEST_DATA.get("Connection", "Port")
self.username = TEST_DATA.get("Connection", "Username2")
self.password = TEST_DATA.get("Connection", "Password")
self.wrongpassword = TEST_DATA.get("Connection", "WrongPassword")
if flag == 0:
print "initial Simulator host:%s, userName:%s, password:%s"%(self.host, self.username, self.password)
else:
print "initial Simulator host:%s, userName:%s, password:%s"%(self.host, self.username, self.wrongpassword)


def get_json_data(self, filepath):
try:
fp1 = open(filepath, 'r')
except Exception, e:
print "Exception: %s" % str(e)
if fp1:
rest = json.load(fp1)
fp1.close()
return rest


def rest_removeprofile(self):
"""
this method is used for simulating air-watch call to remove device profile to REST Service
"""
params = self.get_json_data(REMOVE_PROFILE_IOS)


ns_url = TEST_DATA.get("Notification Server", "REST_RemoveProfile2")
response = self.execute_request('POST', ns_url, params, 0, 0)
print response
return response


def rest_removeprofile_ard(self):
"""
this method is used for simulating air-watch call to remove device profile to REST Service
"""
params = self.get_json_data(REMOVE_PROFILE_ARD)


ns_url = TEST_DATA.get("Notification Server", "REST_RemoveProfile2")
response = self.execute_request('POST', ns_url, params, 0, 0)
print response
return response


def rest_removeprofile_406(self):
"""
this method is used for simulating air-watch call to remove device profile to REST Service
"""
params = self.get_json_data(REMOVE_PROFILE_IOS)


ns_url = TEST_DATA.get("Notification Server", "REST_RemoveProfile2")
response = self.execute_request('POST', ns_url, params, 1, 0)
print response
return response


def rest_removeprofile_401(self):
"""
this method is used for simulating air-watch call to remove device profile to REST Service
"""
params = self.get_json_data(REMOVE_PROFILE_IOS)

ns_url = TEST_DATA.get("Notification Server", "REST_RemoveProfile2")
response = self.execute_request('POST', ns_url, params, 0, 1)
print response
return response


def rest_installprofile(self):
"""
this method is used for simulating air-watch call to install device profile to REST Service
"""
params = self.get_json_data(INSTALL_PROFILE_IOS)


request_id = base64.b64encode(uuid.uuid4().get_bytes())
params["RequestID"] = request_id

ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile2")
response = self.execute_request('POST', ns_url, params, 0, 0)
print response
return response


def rest_installprofile_ard(self):
"""
this method is used for simulating air-watch call to install device profile to REST Service
"""
params = self.get_json_data(INSTALL_PROFILE_ARD)

ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile2")
response = self.execute_request('POST', ns_url, params, 0, 0)
print response
return response


def rest_installprofile_406(self):
"""
this method is used for simulating air-watch call to install device profile to REST Service
"""
params = self.get_json_data(INSTALL_PROFILE_IOS)

ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile2")
response = self.execute_request('POST', ns_url, params, 1, 0)
print response
return response

def rest_installprofile_401(self):
"""
this method is used for simulating air-watch call to install device profile to REST Service
"""
params = self.get_json_data(INSTALL_PROFILE_IOS)

ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile2")
response = self.execute_request('POST', ns_url, params, 0, 1)
print response
return response


def rest_test_connection_200(self):
"""
this method is used for test http connection to REST Service
"""
params = {}
ns_url = TEST_DATA.get("Notification Server", "REST_TestConnection")
response = self.execute_request('GET', ns_url, params, 0, 0)
print response
return response


def execute_request(self, requestMethod, requestURI, params, contentflag=0, passwdflag=0):
if contentflag == 0:
headers = {"Content-Type": "application/json", "Accept": "application/json"}
else:
headers = {"Content-Type": "application/xml", "Accept": "application/json"}

status = 200
try:
conn = httplib.HTTPSConnection(self.host, self.port)
if passwdflag == 0:
auth = base64.b64encode(self.username + ':' + self.password)
else:
auth = base64.b64encode(self.username + ':' + self.wrongpassword)
headers["Authorization"] = "Basic "+auth
conn.request(requestMethod, requestURI, json.dumps(params), headers)
response = conn.getresponse()
print response.status
status = response.status
except Exception, e:
print repr(e)
finally:
if conn:
  conn.close()
return status 


if __name__ == '__main__':
print "start testing......"
dev = NotificationSimu()
dev.deviceEnrollSimu() 
print "testing ended......"


-------------------------------------------------------------------------------------------------------

test_ns_rest.py - test cases script


#!/usr/bin/env python2.6
#encoding=utf-8
import json
import base64
import os
import sys
import time
import string
import unittest
import xmlrunner
import ConfigParser


if '/home/autotest/mdmi/utils' not in sys.path:
sys.path.append("/home/autotest/mdmi/utils")
from common_task import CommonTask
from NotificationSimu_REST import NotificationSimu
from update_tqp_config import UpdateTQPConfig


sys.path.append("/opt/mdmi/modules")
#from utils import dictutils
from utils.vpn_profile import VPNProfile
from utils.android_profile import AndroidProfile
from utils.openssl import *
#from utils import tmslog
from hosteddb.hosted_taskqueue import HostedTaskQueue
from hosteddb.hosted_device import HostedDevice
from hosteddb.hosted_user import HostedUser
from hosteddb import hosted_info
from airwatch.device import AirwatchDevice 
from hosteddb.hosted_account import HostedAccount
from hosteddb.hosted_vpn_bypass import HostedVpnInfo
from utils import logger


sys.path.append("/opt/mailcontrol/modules/TQPlugin")
#import iosdeployutils
#import androiddeployutils
from deploy_base import DeployBase
from deploy_ios import IOSDeploy
from deploy_android import AndroidDeploy


CFG_DATA = "../tms_enroll/test_cfg.txt"
TEST_DATA = ConfigParser.ConfigParser()
TEST_DATA.read(CFG_DATA)


#Get Admin user account id from Hosted DB
username = TEST_DATA.get("Connection", "Username2")
# The superclass of HostedUser needs accountId to initial object
adminUser = HostedUser(1).get_admin(username)
ACCOUNT_ID = int(adminUser["attributes"]["account"])


NAMESPACES = ["mobile", "email"]
EMAIL_CFG_NAME = ["EmailTasks"]
TQS_CFG_NAME = ["UserGroupTasks", "UserGroupRetryTasks", "EnrollmentTasks", "EnrollmentRetryTasks", "iOSDeployment", "iOSDeployment_retry", "UserGroupPendingTasks", "androidDeployment", "androidDeployment_retry", "UserGroupPeriodicTasks"]
USERGROUP_TQS = ["usergroup", "usergrouppending", "usergroupretry", "usergrouperror"]
ENROLL_TQS = ["enrollment", "enrollmentRetry", "enrollmentError"]
IOS_TQS = ["iosdeploy", "iosdeployretry", "iosdeployerror"]
ARD_TQS = ["androiddeploy", "androiddeployretry", "androiddeployerror"]
EMAIL_TQS = ["email", "error"]
TQS_FOR_CLEAR = ["usergroup", "usergrouppending", "usergroupretry", "usergrouperror", "enrollment", "enrollmentRetry", "enrollmentError", "iosdeploy", "iosdeployretry", "iosdeployerror", "androiddeploy", "androiddeployretry", "androiddeployerror"]


class TestNotificationServer(unittest.TestCase):
#class TestNotificationServer():
"""
"""
def setUp(self):
"""The constructor.
Create a new CommonTask instance.
"""
self.account_id = ACCOUNT_ID 
self.task = CommonTask()
self.taskqueue = HostedTaskQueue()
self.updatetqconfig = UpdateTQPConfig('/etc/sysconfig/tqp/plugins.json')
self.ns = NotificationSimu()
self.vpnprofilename = '../tms_rest/vpn.mobileconfig'
self.ard_vpnprofilename = '../tms_rest/vpn_ard.mobileconfig'
self.pacfileURL = ''
#self.disable_all_tqps()
#self.syncusergroup_for_ini()
self.clearTaskQueues(account=1, namespace=NAMESPACES[0])
self.vpn_bypass = []
pass


def tearDown(self):
"""
The destructor.
remove the created CommonTask instance.
"""
#Enable all TQPs
#self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=1)
if self.task:
del self.task
if self.taskqueue:
del self.taskqueue
if self.updatetqconfig:
del self.updatetqconfig
if self.ns:
del self.ns


def get_vpn_exception_lst(self, task):
try:
vpn = HostedVpnInfo()
vpninfo = vpn.get_vpninfo(task["account"])
vpn_bypass = json.loads(vpninfo.content)


if len(vpn_bypass) > 0:
if not isinstance(vpn_bypass, list):
self.vpn_bypass = [vpn_bypass]
self.vpn_bypass = vpn_bypass
task["vpnexceptlst"] = []
logger.debug("vpn exception list for account %s is %s" % (task["account"], vpn_bypass))
else:
haccount = HostedAccount(task["account"])
policyid = haccount.get_policyid_by_email(task["payload"]["EnrollmentEmailAddress"])
vpnexceptlst = haccount.get_vpn_exceptlst_by_policyid(policyid)
if not isinstance(vpnexceptlst, list):
vpnexceptlst = [vpnexceptlst]
task["vpnexceptlst"] = vpnexceptlst
logger.debug("vpn exception list for account %s is %s" % (task["account"], vpnexceptlst))
except Exception, e:
task["vpnexceptlst"] = []
logger.error("get vpn exception list from rs by account %s error %s" % (task["account"], repr(e)))


def syncusergroup_for_ini(self):
print 'Send one Airwatch call(Install Profile) for user group sync to REST Notification Server by Simulator...'
status = self.ns.rest_installprofile()
#print status
self.assertEqual(status,200)
round = 10
print "Waiting for %d seconds for Notification Server Processing ... " % round
while round:
time.sleep(1)
round = round - 1
print 'Enable User Group TQP and pending TQP...'
self.updateTQPConfig(tqplist=[TQS_CFG_NAME[0], TQS_CFG_NAME[6]], flag=1)
print('-'*20)


round = 30
print "Waiting for %d seconds for Device enrollment process complete ... " % round
while round:
time.sleep(1)
round = round - 1


def updateTQPConfig(self, tqplist=None, flag=1, secs=30):
"""
"""
self.updatetqconfig.set_tqp_switch(tqpList=tqplist, flag=flag)
#self.updatetqconfig.restart_service("/etc/init.d/task-processor")
print 'Wait for changes to TQ Processor taking effect...'
time.sleep(secs)

def clearTaskQueues(self, account=1, namespace=NAMESPACES[0]):
"""
To do:
clear tqs which name in the tq names list.
"""
data = {"description" : "", "max_leases" : "30", "max_age" : "0"}
tqnames = TQS_FOR_CLEAR
if self.task:
del self.task
self.task = CommonTask()
for tq in tqnames:
tq_desc = "%s task queue" % tq
data['description'] = tq_desc
self.task.do_clearTaskQueue(account=account, tqname=tq, namespace=namespace, desc=data)
print "task queue:%s is cleared!" % tq


def createTaskQueue(self, account=1, namespace=NAMESPACES[0], tqname=None):
"""
To do:
create.
"""
data = {"description" : "", "max_leases" : "30", "max_age" : "0"}
if self.task:
del self.task
self.task = CommonTask()
tq_desc = "%s task queue" % tqname
data['description'] = tq_desc
self.task.do_createTaskQueue(account=account, tqname=tqname, namespace=namespace, desc=data)
print "task queue:%s is creatd!" % tqname


def addTask(self, account=None, tqname=None, namespace=None, creator=3, type=1, evt=None):
"""
To do:
Simulate to add Enrollment task in enrollment decision task queue by User and Group Sync TQP
Param:
creator : 
1 - Notification Service
3 - User and Group Sync TQP
4 - Enrollment Decision TQP
type : 
1 - Enrollment task
2 - De-enrollment task
3 - Wipe task
Status : 
1 - Normal task
2 - Retry task
3 - Error task
"""
evt = json.dumps(evt)
del self.task
self.task = CommonTask()
self.task.do_add(account=account, tqname=tqname, namespace=namespace, creator=creator, type=type, evt=evt)
pass


def getTaskFromTQ(self, account=None,tqname=None, namespace=None, tags=None):
del self.task
self.task = CommonTask()


tk = self.task.do_getTask_cycle(account=account, tqname=tqname, namespace=namespace,tags=tags)
if tk:
print 'Got task name is', tk['name']
print tk
return tk
else:
return None
pass


def getEventFromTask(self, task=None):
event = self.task.do_getEventFromTask(task=task)
return event
pass


def delTaskQueue(self, account=None,tqname=None, namespace=None):
if self.task:
del self.task
self.task = CommonTask()


result = self.task.do_delTaskQueue(account=account, tqname=tqname, namespace=namespace)
print "Del task queue %s is %s" % (tqname, result)



def Non_test_getEventFromTaskByName(self, account=ACCOUNT_ID, tqname=EMAIL_TQS[1], namespace=NAMESPACES[1], taskname='3678'):
if self.task:
del self.task
self.task = CommonTask()

tk = self.task.do_getTaskByName(tqname=tqname, namespace=namespace, account=account, taskname=taskname)


if tk:
print 'Got task name is', tk['name']
print tk
event = self.task.do_getEventFromTask(task=tk)
print event
return event
pass


def getDeviceInfoFromAW(self, device_id):
"""
To do:
Get device info. from Airwatch by device id.
"""
device = AWDevice(self.account_id2)
d = device.get(device_id)
#utils.tmslog.log("test_enrollment decision_tqp.py - device info. from aw is : %s" % d)
#print d
return d


def getDeviceInfoFromRS(self, device_udid):
"""
To do:
Get device info. from Hosted RS DB by device udid.
"""
hosted_device = HostedDevice(device_udid)
d = hosted_device.do_get()
#print d
return d


def addEnrollmentTask(self, account=None, namespace=NAMESPACES[0], tqname=ENROLL_TQS[0], type=1):
evt = {
"EventId":148,
"MACAddress":"System.Byte[]",
"EventTime":"/Date(1368076195887)/",
"ComplianceStatus":"Compliant",
"Udid":"",
"EventType":"MDMEnrollmentComplete",
"SerialNumber":"861348SXA4S",
"CompromisedStatus":"",
"EnrollmentEmailAddress":"hdu@websense.com",
"DeviceFriendlyName":"iPhone3,1-42a65c8289b7ddbcc8ab0fd342bb237534ba60c9",
"PhoneNumber":"+8613426192820",
"DeviceId":616,
"EnrollmentStatus":"Enrolled",
"EnrollmentUserName":"Hang",
"CompromisedTimeStamp":"/Date(1368076202626)/"
}
self.addTask(account=account, namespace=namespace, tqname=tqname, creator=3, type=type, evt=evt)

def getPacFileUrl(self, accountID, email):
response = None
try:
response = hosted_info.hosted_get_pacfileurl_by_email(accountID, email)
except Exception, e:
response = None
#tmslog.log("test_iosdeploy_tqp.py - access hosted os get pac file url error %s" % e)
return response

def generateVPNFile(self, webpolicy, accountID, eventPayLoad):
vprofile = None
try:
paclist = json.loads(webpolicy)
#tmslog.log("test_iosdeploy_tqp.py - generate VPN profile start")
pacfileURL = paclist[0]["attributes"]["policyPacUrl"][0]
self.pacfileURL = pacfileURL
#tmslog.log("test_iosdeploy_tqp.py - pac file url from account %s is %s" % (accountID, pacfileURL))
vpnProfile = VPNProfile()

# scanopt default value is 2, TODO need to update the value when Hosted DB ready
userinfo = "Username:%s;AccountID:%s;DeviceID:%s;DeviceType:%s;DeviceClass:%s;scanopt:2" %(eventPayLoad["EnrollmentEmailAddress"], accountID, eventPayLoad["Udid"], eventPayLoad["Model"], eventPayLoad["Ownership"])
print 'info sent to vpn profile is : %s' % userinfo
print '-'*20
if eventPayLoad.has_key('OperationCallbackURL') and eventPayLoad['OperationCallbackURL']:
#tmslog.log("test_iosdeployTQP.py - generate VPN profile format is json")
#vprofile = vpnProfile.dumps(userinfo, pacfileURL, 'json')
vprofile = vpnProfile.dumps(userinfo, pacfileURL)
else:  
vprofile = vpnProfile.dumps(userinfo, pacfileURL)
#tmslog.log("test_iosdeploy_tqp.py - generate VPN profile file end")
#tmslog.log("test_iosdeploy_tqp.py - the VPN profile file is %s " % vprofile)
except Exception, e:
vprofile = None
#tmslog.log("test_iosdeploy_tqp.py - generate vpn file error %s " % e)
return vprofile

def save_file(self, filename, content):
if filename and content:
fd = open(filename, 'w')
fd.write(content)
fd.close()


def check_pac_url(self, filename, pacurl):
"""
read pac file url
"""
f = open(filename,'r')
pac = f.readlines()
print "pac[0] in vpn profile is %s\npac url got from host db is %s" % (pac[0], pacurl)
#self.assertEqual(pac[0], pacurl)
f.close()


def test_connection_REST_200_HIGH(self):
status = self.ns.rest_test_connection_200()
self.assertEqual(status,200)


def test_removeprofile_REST_HIGH(self):
#print 'Clear task queues...'
#self.clearTaskQueues(account=1, namespace=NAMESPACES[0])
#print('-'*20)
print 'Disable all TQPs...'
self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=0)
print('-'*20)


#print 'Del task queue %s ...' % ENROLL_TQS[0]
#self.delTaskQueue(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=ENROLL_TQS[0])


print 'Send one Airwatch call(Remove Profile) to REST Notification Server by Simulator...'
status = self.ns.rest_removeprofile()
#print status
self.assertEqual(status,200)
round = 10
print "Waiting for %d seconds for Notification Server Processing ... " % round
while round:
time.sleep(1)
round = round - 1
tags = []
tags.append("creator=1")
print 'Got task from %s task queue...' % ENROLL_TQS[0]
task = self.getTaskFromTQ(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=ENROLL_TQS[0], tags=tags
)
event = self.getEventFromTask(task)
print event
print('-'*20)
tags = task['tags']
restServiceFlag = 'restServiceFlag=1'
self.assertTrue(restServiceFlag in tags)
event = json.loads(event)
self.assertTrue(event.has_key("User"))
self.assertTrue(len(event['User']) > 0)
self.assertTrue(event.has_key("Device"))
self.assertTrue(len(event['Device']) > 0)
#self.assertTrue(event.has_key("RequestID"))
#self.assertTrue(len(event['RequestID']) > 0)

#print 'Enable all TQPs...'
#self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=1)
#print('-'*20)


def test_removeprofile_REST_ard_HIGH(self):
#print 'Clear task queues...'
#self.clearTaskQueues(account=1, namespace=NAMESPACES[0])
#print('-'*20)
print 'Disable all TQPs...'
self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=0)
print('-'*20)


#print 'Del task queue %s ...' % ENROLL_TQS[0]
#self.delTaskQueue(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=ENROLL_TQS[0])


print 'Send one Airwatch call(Remove Profile) to REST Notification Server by Simulator...'
status = self.ns.rest_removeprofile_ard()
#print status
self.assertEqual(status,200)
round = 10
print "Waiting for %d seconds for Notification Server Processing ... " % round
while round:
time.sleep(1)
round = round - 1
tags = []
tags.append("creator=1")
print 'Got task from %s task queue...' % ENROLL_TQS[0]
task = self.getTaskFromTQ(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=ENROLL_TQS[0], tags=tags
)
event = self.getEventFromTask(task)
print event
print('-'*20)
tags = task['tags']
restServiceFlag = 'restServiceFlag=1'
self.assertTrue(restServiceFlag in tags)
event = json.loads(event)
self.assertTrue(event.has_key("User"))
self.assertTrue(len(event['User']) > 0)
self.assertTrue(event.has_key("Device"))
self.assertTrue(len(event['Device']) > 0)
#self.assertTrue(event.has_key("RequestID"))
#self.assertTrue(len(event['RequestID']) > 0)

#print 'Enable all TQPs...'
#self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=1)
#print('-'*20)


def test_removeprofile_REST_500_MEDIUM(self):
print 'Disable all TQPs...'
self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=0)
print('-'*20)


print 'Del task queue %s ...' % ENROLL_TQS[0]
self.delTaskQueue(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=ENROLL_TQS[0])
time.sleep(5)


print 'Send one Airwatch call(Remove Profile) to REST Notification Server by Simulator...'
status = self.ns.rest_removeprofile()
self.assertEqual(status,500)


print 'Create task queue %s ...' % ENROLL_TQS[0]
self.createTaskQueue(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=ENROLL_TQS[0])
time.sleep(5)


def test_removeprofile_REST_406_MEDIUM(self):
#print 'Clear task queues...'
#self.clearTaskQueues(account=1, namespace=NAMESPACES[0])
#print('-'*20)


print 'Send one Airwatch call(Remove Profile) to REST Notification Server by Simulator...'
status = self.ns.rest_removeprofile_406()
self.assertEqual(status,406)


def test_removeprofile_REST_401_MEDIUM(self):
#print 'Clear task queues...'
#self.clearTaskQueues(account=1, namespace=NAMESPACES[0])
#print('-'*20)


print 'Send one Airwatch call(Remove Profile) to REST Notification Server by Simulator...'
status = self.ns.rest_removeprofile_401()
self.assertEqual(status,401)


def disable_all_tqps(self):
print 'Disable all TQPs...'
self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=0)
print('-'*20)


def test_installprofile_REST_HIGH(self):
#print 'Clear task queues...'
#self.clearTaskQueues(account=1, namespace=NAMESPACES[0])
#print('-'*20)
print 'Disable all TQPs...'
self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=0)
print('-'*20)


print 'Send one Airwatch call(Install Profile) to REST Notification Server by Simulator...'
status = self.ns.rest_installprofile()
#print status
self.assertEqual(status,200)
round = 10
print "Waiting for %d seconds for Notification Server Processing ... " % round
while round:
time.sleep(1)
round = round - 1
tags = []
tags.append("creator=1")
print 'Got task from %s task queue...' % USERGROUP_TQS[0]
task = self.getTaskFromTQ(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=USERGROUP_TQS[0], tags=tags)
event = self.getEventFromTask(task)
print event
print('-'*20)
tags = task['tags']
restServiceFlag = 'restServiceFlag=1'
self.assertTrue(restServiceFlag in tags)
event = json.loads(event)
self.assertTrue(event.has_key("requestPayload"))
self.assertTrue(event.has_key("email"))
self.assertTrue(len(event['email']) > 0)
self.assertTrue(event.has_key("deviceId"))
self.assertTrue(len(event['deviceId']) > 0)
requestPayload = event['requestPayload']
requestPayload = json.loads(requestPayload)
self.assertTrue(requestPayload.has_key("User"))
self.assertTrue(len(requestPayload['User']) > 0)
self.assertTrue(requestPayload.has_key("Device"))
self.assertTrue(len(requestPayload['Device']) > 0)
self.assertTrue(requestPayload.has_key("RequestID"))
self.assertTrue(len(requestPayload['RequestID']) > 0)
self.assertTrue(requestPayload.has_key("OperationCallbackURL"))
self.assertTrue(len(requestPayload['OperationCallbackURL']) > 0)
self.assertTrue(requestPayload.has_key("AwProfileId"))
self.assertTrue(len(requestPayload['AwProfileId']) > 0)


#Enable User Group TQP and pending TQP
print 'Enable User Group TQP and pending TQP...'
self.updateTQPConfig(tqplist=[TQS_CFG_NAME[0], TQS_CFG_NAME[6]], flag=1)
print('-'*20)


tags = []
tags.append("creator=3")
round = 20
print "Waiting for %d seconds for User Group TPQ Processing ... " % round
while round:
time.sleep(1)
round = round - 1
print 'Got task from %s task queue...' % ENROLL_TQS[0]
task = self.getTaskFromTQ(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=ENROLL_TQS[0], tags=tags)
event = self.getEventFromTask(task)
print event
print('-'*20)
tags = task['tags']
restServiceFlag = 'restServiceFlag=1'
self.assertTrue(restServiceFlag in tags)
event = json.loads(event)
self.assertTrue(event.has_key("User"))
self.assertTrue(len(event['User']) > 0)
self.assertTrue(event.has_key("Device"))
self.assertTrue(len(event['Device']) > 0)
self.assertTrue(event.has_key("RequestID"))
self.assertTrue(len(event['RequestID']) > 0)
self.assertTrue(event.has_key("OperationCallbackURL"))
self.assertTrue(len(event['OperationCallbackURL']) > 0)
self.assertTrue(event.has_key("AwProfileId"))
self.assertTrue(len(event['AwProfileId']) > 0)
print 'Enable Enrollment Decision TQP...'
self.updateTQPConfig(tqplist=[TQS_CFG_NAME[2]], flag=1)
print('-'*20)


tags = []
tags.append("creator=4")
round = 20
print "Waiting for %d seconds for Enrollment Decision TPQ Processing ... " % round
while round:
time.sleep(1)
round = round - 1
print 'Got task from %s task queue...' % IOS_TQS[0]
task = self.getTaskFromTQ(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=IOS_TQS[0], tags=tags)
event = self.getEventFromTask(task)
print event
print('-'*20)
tags = task['tags']
restServiceFlag = 'restServiceFlag=1'
self.assertTrue(restServiceFlag in tags)
#event = json.loads(event)
event = eval(event)
self.assertTrue(event.has_key("RequestID"))
self.assertTrue(len(event['RequestID']) > 0)
self.assertTrue(event.has_key("OperationCallbackURL"))
self.assertTrue(len(event['OperationCallbackURL']) > 0)
self.assertTrue(event.has_key("AwProfileId"))
self.assertTrue(len(event['AwProfileId']) > 0)
self.assertTrue(event.has_key("Udid"))
self.assertTrue(len(event['Udid']) > 0)
self.assertTrue(event.has_key("EnrollmentEmailAddress"))
self.assertTrue(len(event['EnrollmentEmailAddress']) > 0)
self.assertTrue(event.has_key("Model"))
self.assertTrue(len(event['Model']) > 0)
self.assertTrue(event.has_key("Ownership"))
self.assertTrue(len(str(event['Ownership'])) > 0)


print 'Enable iOS deployment TQP...'
self.updateTQPConfig(tqplist=[TQS_CFG_NAME[4]], flag=1)
print('-'*20)


tags = []
round = 20
print "Waiting for %d seconds for iOS Deployment TPQ Processing ... " % round
while round:
time.sleep(1)
round = round - 1


#print 'Got task from %s task queue...' % EMAIL_TQS[0]
#event = self.getEventFromTask(account=ACCOUNT_ID, namespace=NAMESPACES[1], tqname=EMAIL_TQS[0], tags=tags)
#print event
#print('-'*20)
#event = json.loads(event)
#self.assertEqual(evt['EnrollmentEmailAddress'], event['rcptto'])
#print 'Enable EMAIL TQP...'

#Save VPN profile to file
#tmslog.log("test_iosdeploy_tqp.py - get PAC file url from hosted DB start")
#response = self.getPacFileUrl(accountID=ACCOUNT_ID, email=event["EnrollmentEmailAddress"])
deploy = IOSDeploy()
deploy.task = task
deploy.task['payload'] = event
#deploy.get_pacfile_url()


response = self.getPacFileUrl(accountID=ACCOUNT_ID, email=event["EnrollmentEmailAddress"])
#tmslog.log("test_iosdeploy_tqp.py - get PAC file url from hosted DB end")
print 'accout is %d' % deploy.task['account']
print 'payload is %s' % event


if deploy.task['payload']['policyPacUrl']:
#tmslog.log("test_iosdeploy_tqp.py - web policy from hosted DB is %s" % response)
print 'web policy from hosted DB is %s' % response
print '-'*20
paclist = json.loads(response)


pacfileURL = paclist[0]["attributes"]["policyPacUrl"]
if isinstance(pacfileURL, list):
self.pacfileURL = pacfileURL[0]
else:
self.pacfileURL = pacfileURL


self.get_vpn_exception_lst(deploy.task)


pkey = generate_key(1)
user_info = "Username:%s;AccountID:%s;DeviceID:%s;DeviceType:%s;DeviceClass:%s;scanopt:2" % (deploy.task['payload']['EnrollmentEmailAddress'], deploy.task['account'], deploy.task['payload']['Udid'], deploy.task['payload']['Model'], deploy.task['payload']['Ownership'])
user_info = user_info.encode('utf8')
vpn_profile = VPNProfile(deploy.task["account"])
profile, notAfter = vpn_profile.dumps(user_info, deploy.task['payload']['policyPacUrl'], deploy.task["vpnexceptlst"], pkey[0], self.vpn_bypass)
#profile, notAfter = vpn_profile.dumps(user_info, deploy.task['payload']['policyPacUrl'], pkey[0])
if profile:
filename = self.vpnprofilename
self.save_file(filename, profile)
print 'Save vpn profile complete!'
print '-'*20
print 'parse saved ios vpn profile file:%s ...' % filename
time.sleep(5)
os.system('sh ../tms_rest/parse_vpn_profile.sh')
time.sleep(1)
self.check_pac_url('/tmp/vpn/pacfile', self.pacfileURL)
del deploy
#else:
# generate vpn profile error, move the task to retry queue
#tmslog.log("test_iosdeploy_tqp.py - generate VPN profile failed.")


#print 'Enable all TQPs...'
#self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=1)
#print('-'*20)


def test_installprofile_REST_ard_HIGH(self):
#print 'Clear task queues...'
#self.clearTaskQueues(account=1, namespace=NAMESPACES[0])
#print('-'*20)
print 'Disable all TQPs...'
self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=0)
print('-'*20)


print 'Send one Airwatch call(Install Profile) to REST Notification Server by Simulator...'
status = self.ns.rest_installprofile_ard()
#print status
self.assertEqual(status,200)
round = 10
print "Waiting for %d seconds for Notification Server Processing ... " % round
while round:
time.sleep(1)
round = round - 1
tags = []
tags.append("creator=1")
print 'Got task from %s task queue...' % USERGROUP_TQS[0]
task = self.getTaskFromTQ(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=USERGROUP_TQS[0], tags=tags)
event = self.getEventFromTask(task)
print event
print('-'*20)
tags = task['tags']
restServiceFlag = 'restServiceFlag=1'
self.assertTrue(restServiceFlag in tags)
event = json.loads(event)
self.assertTrue(event.has_key("requestPayload"))
self.assertTrue(event.has_key("email"))
self.assertTrue(len(event['email']) > 0)
self.assertTrue(event.has_key("deviceId"))
self.assertTrue(len(event['deviceId']) > 0)
requestPayload = event['requestPayload']
requestPayload = json.loads(requestPayload)
self.assertTrue(requestPayload.has_key("User"))
self.assertTrue(len(requestPayload['User']) > 0)
self.assertTrue(requestPayload.has_key("Device"))
self.assertTrue(len(requestPayload['Device']) > 0)
self.assertTrue(requestPayload.has_key("RequestID"))
self.assertTrue(len(requestPayload['RequestID']) > 0)
self.assertTrue(requestPayload.has_key("OperationCallbackURL"))
self.assertTrue(len(requestPayload['OperationCallbackURL']) > 0)
self.assertTrue(requestPayload.has_key("AwProfileId"))
self.assertTrue(len(requestPayload['AwProfileId']) > 0)


#Enable User Group TQP and pending TQP
print 'Enable User Group TQP and pending TQP...'
self.updateTQPConfig(tqplist=[TQS_CFG_NAME[0], TQS_CFG_NAME[6]], flag=1)
print('-'*20)


tags = []
tags.append("creator=3")
round = 20
print "Waiting for %d seconds for User Group TPQ Processing ... " % round
while round:
time.sleep(1)
round = round - 1
print 'Got task from %s task queue...' % ENROLL_TQS[0]
task = self.getTaskFromTQ(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=ENROLL_TQS[0], tags=tags)
event = self.getEventFromTask(task)
print event
print('-'*20)
tags = task['tags']
restServiceFlag = 'restServiceFlag=1'
self.assertTrue(restServiceFlag in tags)
event = json.loads(event)
self.assertTrue(event.has_key("User"))
self.assertTrue(len(event['User']) > 0)
self.assertTrue(event.has_key("Device"))
self.assertTrue(len(event['Device']) > 0)
self.assertTrue(event.has_key("RequestID"))
self.assertTrue(len(event['RequestID']) > 0)
self.assertTrue(event.has_key("OperationCallbackURL"))
self.assertTrue(len(event['OperationCallbackURL']) > 0)
self.assertTrue(event.has_key("AwProfileId"))
self.assertTrue(len(event['AwProfileId']) > 0)
print 'Enable Enrollment Decision TQP...'
self.updateTQPConfig(tqplist=[TQS_CFG_NAME[2]], flag=1)
print('-'*20)


tags = []
tags.append("creator=4")
round = 20
print "Waiting for %d seconds for Enrollment Decision TPQ Processing ... " % round
while round:
time.sleep(1)
round = round - 1
print 'Got task from %s task queue...' % ARD_TQS[0]
task = self.getTaskFromTQ(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=ARD_TQS[0], tags=tags)
event = self.getEventFromTask(task)
print event
print('-'*20)
tags = task['tags']
restServiceFlag = 'restServiceFlag=1'
self.assertTrue(restServiceFlag in tags)
#event = json.loads(event)
event = eval(event)
self.assertTrue(event.has_key("RequestID"))
self.assertTrue(len(event['RequestID']) > 0)
self.assertTrue(event.has_key("OperationCallbackURL"))
self.assertTrue(len(event['OperationCallbackURL']) > 0)
self.assertTrue(event.has_key("AwProfileId"))
self.assertTrue(len(event['AwProfileId']) > 0)
self.assertTrue(event.has_key("Udid"))
self.assertTrue(len(event['Udid']) > 0)
self.assertTrue(event.has_key("EnrollmentEmailAddress"))
self.assertTrue(len(event['EnrollmentEmailAddress']) > 0)
self.assertTrue(event.has_key("Model"))
self.assertTrue(len(event['Model']) > 0)
self.assertTrue(event.has_key("Ownership"))
self.assertTrue(len(str(event['Ownership'])) > 0)


print 'Enable android deployment TQP...'
self.updateTQPConfig(tqplist=[TQS_CFG_NAME[7]], flag=1)
print('-'*20)


tags = []
round = 20
print "Waiting for %d seconds for android Deployment TPQ Processing ... " % round
while round:
time.sleep(1)
round = round - 1


deploy = AndroidDeploy()
deploy.task = task
deploy.task['payload'] = event
#eploy.get_pacfile_url()
response = self.getPacFileUrl(accountID=ACCOUNT_ID, email=event["EnrollmentEmailAddress"])
print 'accout is %d' % deploy.task['account']
print 'payload is %s' % event


if deploy.task['payload']['policyPacUrl']:
print 'web policy from hosted DB is %s' % response
print '-'*20
paclist = json.loads(response)

pacfileURL = paclist[0]["attributes"]["policyPacUrl"]
if isinstance(pacfileURL, list):
self.pacfileURL = pacfileURL[0]
else:
self.pacfileURL = pacfileURL


#vprofile = androiddeployutils.generate_profile(response, accountID=ACCOUNT_ID, eventPayLoad=event)
vpn_profile = AndroidProfile()
profile = vpn_profile.dumps("Username:%s;AccountID:%s;DeviceID:%s;DeviceType:%s;DeviceClass:%s;scanopt:2" % (deploy.task['payload']['EnrollmentEmailAddress'], deploy.task['account'], deploy.task['payload']['Udid'], deploy.task['payload']['Model'], deploy.task['payload']['Ownership']), deploy.task['payload']['policyPacUrl'])
if profile:
filename = self.ard_vpnprofilename
self.save_file(filename, profile)
print 'Save vpn profile complete!'
print '-'*20
print 'parse saved android vpn profile file:%s ...' % filename
time.sleep(5)
os.system('sh ../tms_rest/parse_vpnprofile_ard.sh')
time.sleep(1)
self.check_pac_url('/tmp/vpn/pacfile', self.pacfileURL)


#print 'Enable all TQPs...'
#self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=1)
#print('-'*20)


def test_installprofile_REST_500_MEDIUM(self):
print 'Disable all TQPs...'
self.updateTQPConfig(tqplist=TQS_CFG_NAME, flag=0)
print('-'*20)


print 'Del task queue %s ...' % USERGROUP_TQS[0]
self.delTaskQueue(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=USERGROUP_TQS[0])
time.sleep(5)

print 'Send one Airwatch call(Install Profile) to REST Notification Server by Simulator...'
status = self.ns.rest_installprofile()
#print status
self.assertEqual(status,500)


print 'Create task queue %s ...' % USERGROUP_TQS[0]
self.createTaskQueue(account=ACCOUNT_ID, namespace=NAMESPACES[0], tqname=USERGROUP_TQS[0])
time.sleep(5)


def test_installprofile_REST_406_MEDIUM(self):
#print 'Clear task queues...'
#self.clearTaskQueues(account=1, namespace=NAMESPACES[0])
#print('-'*20)


print 'Send one Airwatch call(Install Profile) to REST Notification Server by Simulator...'
status = self.ns.rest_installprofile_406()
#print status
self.assertEqual(status,406)


def test_installprofile_REST_401_MEDIUM(self):
#print 'Clear task queues...'
#self.clearTaskQueues(account=1, namespace=NAMESPACES[0])
#print('-'*20)


print 'Send one Airwatch call(Install Profile) to REST Notification Server by Simulator...'
if self.ns:
del self.ns
self.ns = NotificationSimu(1)
status = self.ns.rest_installprofile_401()
#print status
self.assertEqual(status,401)




if __name__=='__main__':
#unittest.main(testRunner=xmlrunner.XMLTestRunner(output='/tmp/output/test-reports'))
unittest.main()
#if __name__ == "__main__":
# try:
# eventpayload = {'Model': 'iPhone', 'DeviceId': 70, 'OperationCallbackURL': 'https://127.0.0.1/cgi-py/installvpn.py', 'Udid': '4B6D5E40DFB22BD57EC4AF54DA1F297A3221388B', 'EnrollmentEmailAddress': 'xwang@websense.com', 'RequestID': '123456789abcdef', 'EnrollmentStatus': 'Unenrolled', 'Ownership': 4, 'EnrollmentUserName': 'test_xwang', 'OperatingSystem': '7.0.2', 'AwProfileId': '123456789'}
# webpolicy = '[{"href":"https://cog01o:8085/rs/v-1/account-86/mail-enduser3%40ntpr.com","attributes":{"policyPacUrl":["http://webdefence-cn-mobile-it.odd.blackspider.com:8082/proxy.pac?p=22kk6289"],"cn":["Mr EndUser3"],"account":["86"],"objectClass":["hostedUser"],"endUserStatus":["Active"],"mail":["enduser3@ntpr.com"],"accountType":["webdefence"],"o":["Neat&tidy Piano Removers"]},"dn":"mail=enduser3@ntpr.com,account=86,dc=blackspider,dc=com"}]'
# profile = TestNotificationServer()
# vpn = profile.generateVPNFile(webpolicy, 86, eventpayload)
# file = open('corporate.mobilconfig', 'w')
# file.write(vpn)
# file.close()
# except Exception,e:
# print e










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值