Python 稳定性测试 - REST requests simulator - 多进程并发

#! /usr/bin/python
#-*- coding: utf-8 -*-
#FileName: NotificationSimu.py
from BaseModule import BaseSimu
import urllib
import httplib
import base64
import json
import string
import ConfigParser
import multiprocessing
import uuid
import time
from datetime import datetime
import tmslog

CFG_DATA = "test_cfg.txt"
DEVICES_DATA = "devices_s_ard.txt"
#DEVICES_DATA = "view_devices.txt"
SIMU_LOG = 'mdmi_simu_log.txt'
TEST_DATA = ConfigParser.ConfigParser()
TEST_DATA.read(CFG_DATA)

class NotificationSimu(BaseSimu):
    def __init__(self, flag=0, acct_index=0):
        BaseSimu.__init__(self)    
        if flag == 0:
            if acct_index == 0:
                print "initial Simulator host:%s, userName:%s, password:%s"%(self.host, self.username, self.password)
            elif acct_index == 1:
                print "initial Simulator host:%s, userName:%s, password:%s"%(self.host, self.username2, self.password)
            elif acct_index == 2:
                print "initial Simulator host:%s, userName:%s, password:%s"%(self.host, self.username3, self.password)
            elif acct_index == 3:
                print "initial Simulator host:%s, userName:%s, password:%s"%(self.host, self.username4, self.password)
                
        else:
            print "initial Simulator host:%s, userName:%s, password:%s"%(self.host, self.username, self.wrongpassword)

    def rest_removeprofile(self):
        """
        this method is used for simulating air-watch call to remove device profile to REST Service
        """
        params = {
                "RequestID": "123456789abcdef",
                "User": {
                      "Email": "xwang@websense.com"
                    },
                "Device": {
                      "Udid": "4B6D5E40DFB22BD57EC4AF54DA1F297A3221388B"
                    }
                }        

        ns_url = TEST_DATA.get("Notification Server", "REST_RemoveProfile")
        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 = {
                "RequestID": "123456789abcdef",
                "User": {
                      "Email": "xwang@websense.com"
                    },
                "Device": {
                      "Udid": "4B6D5E40DFB22BD57EC4AF54DA1F297A3221388B"
                    }
                }        

        ns_url = TEST_DATA.get("Notification Server", "REST_RemoveProfile")
        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 = {
                "RequestID": "123456789abcdef",
                "User": {
                      "Email": "xwang@websense.com"
                    },
                "Device": {
                      "Udid": "4B6D5E40DFB22BD57EC4AF54DA1F297A3221388B"
                    }
                }        

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

    def update_params(self, rnd, i, device, params, acct_index):
        """
        this method is used to update the params payload with the device info.
        """
        total = 12000
        intval = 100
        rnd = rnd % (total/intval)

        device = device.split()
        #print "%s - Account:%d " % (device, acct_index)
        request_id = base64.b64encode(uuid.uuid4().get_bytes())
        callback_url = "http://10.230.48.19:80/cgi-py/installvpn.py?requestid=%s" % request_id
        params['RequestID'] = request_id
        #params['OperationCallbackURL'] = callback_url
        #Update the params with the user info. got
        if i >= rnd*intval and i <= rnd*intval+(intval-1): #insert 100 new users    
            params['User']['UserName'] = "enduser_%s" % str(uuid.uuid4())[:8]
            params['User']['Email'] = "enduser_%s@websense.com" % str(uuid.uuid4())[:8]
        else:
            params['User']['UserName'] = device[9]
            params['User']['Email'] = device[10]
        params['User']['Group'] = device[6]
        #params['User']['LdapDN'] = 'mail=%s,%s' %(device[10], params['User']['LdapDN'])
        #params['User']['LdapGuid'] = base64.b64encode(uuid.uuid4().get_bytes())
        #Update the params with the deviec info. got    
        params['Device']['UserName'] = device[9]
        params['Device']['UserEmailAddress'] = device[10]
        params['Device']['Id'] = device[0]
        params['Device']['Udid'] = device[1]
        params['Device']['AssetNmber'] = device[1]
        params['Device']['Platform'] = device[12]
        params['Device']['OperatingSystem'] = device[14]
        params['Device']['LocationGroupName'] = device[6]
        params['Device']['Ownership'] = device[11]
        params['Device']['Model'] = device[13]
        params['Device']['EnrollmentStatus'] = device[15]
        params['Device']['LocationGroupId']['Name'] = device[6]
        print "%s - %s " % (params['User']['UserName'], params['User']['Email'])
        return params

    def rest_installprofiles(self, devicelist, acct_index=0):
        """
        this method is used for simulating air-watch call to install device profile to REST Service
        """
        params = {
                "RequestID":"123456789abcdef",
                "OperationCallbackURL":"https://127.0.0.1/cgi-py/installvpn.py",
                "AwProfileId":"123456789",
                "User":{
                    "UserName":"test_xwang",
                    #"UserName":"test_e2e_3",
                    "Status":True,
                    "Group":"deviceqa",
                    "FirstName":"Xiaobo",
                    "LastName":"Wang",
                    "EmailUserName":None,
                    "SecurityType":2,
                    "Id":2,
                    #"Id":125,
                    "MessageTemplateId":0,
                    "ContactNumber":None,
                    "Role":"Full Access",
                    "MessageType":0,
                    "EnrolledDevicesCount":"0",
                    "Password":None,
                    "Email":"xwang1@websense.com",
                    #"Email":"daliu3@websense.com",
                    #"LdapDN":"dn=something,dc=com",
                    #"LdapGuid":"12ab1242bedf3414dac"
                   },
                "Device":{
                    "UserName":None,
                    "UserEmailAddress":None,
                    "LastCompromisedCheckOn":"2013-09-24T10:12:25.523",
                    "SerialNmber":"861348SXA4S",
                    "DeviceFriendlyName":"Hang's iPhone",
                    "Platform":"Apple",
                    "LastEnrolledOn":"2013-10-09T05:52:23.6",
                    "OperatingSystem":"7.0.2",
                    "LocationGroupName":"autotest",
                    "MacAddress":"148FC625C228",
                    "ComplianceStatus":"NotAvailable",
                    "PlatformId":{
                            "Name":"Apple",
                            "Location":None
                    },
                "UserId":None,
                "CompromisedStatus":False,
                "LastSeen":"2013-10-09T06:02:07.353",
                "Ownership":"Undefined",
                "Imei":"012760007845071",
                "ComplianceSmmary":None,
                "LastComplianceCheckOn":None,
                "Udid":"04D8CFD680D639302810460DAC8E3599152C5973",
                "PhoneNmber":"+8613426192820",
                "Model":"iPhone",
                "ModelId":{
                    "Name":"iPhone",
                    "Location":None
                    },
                "AssetNmber":"04D8CFD680D639302810460DAC8E3599152C5973",
                "EnrollmentStatus":"Unenrolled",
                "Id":2,
                "LocationGroupId":{
                    "Name":"autotest",
                    "Location":None
                }       
            }   
        }
        
        for device in devicelist:            
             params = self.update_params(device, params, acct_index)
            #print params

            if acct_index == 0:
                ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile")
            elif  acct_index == 1:
                ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile2")
            elif  acct_index == 2:
                ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile3")
            elif  acct_index == 3:
                ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile4")

            response = self.execute_request('POST', ns_url, params, 0, 0, acct_index)
            #
        #print response
        return response


    def rest_installprofile(self, rnd, i, device, acct_index=0):
        """
        this method is used for simulating air-watch call to install device profile to REST Service
        """
        params = {
                "RequestID":"123456789abcdef",
                "OperationCallbackURL":"https://127.0.0.1/cgi-py/installvpn.py",
                "AwProfileId":"123456789",
                "User":{
                    "UserName":"test_xwang",
                    #"UserName":"test_e2e_3",
                    "Status":True,
                    "Group":"deviceqa",
                    "FirstName":"Xiaobo",
                    "LastName":"Wang",
                    "EmailUserName":None,
                    "SecurityType":2,
                    "Id":2,
                    #"Id":125,
                    "MessageTemplateId":0,
                    "ContactNumber":None,
                    "Role":"Full Access",
                    "MessageType":0,
                    "EnrolledDevicesCount":"0",
                    "Password":None,
                    "Email":"xwang1@websense.com",
                    #"Email":"daliu3@websense.com",
                    #"LdapDN":"dn=something,dc=com",
                    #"LdapGuid":"12ab1242bedf3414dac"
                   },
                "Device":{
                    "UserName":None,
                    "UserEmailAddress":None,
                    "LastCompromisedCheckOn":"2013-09-24T10:12:25.523",
                    "SerialNmber":"861348SXA4S",
                    "DeviceFriendlyName":"Hang's iPhone",
                    "Platform":"Apple",
                    "LastEnrolledOn":"2013-10-09T05:52:23.6",
                    "OperatingSystem":"7.0.2",
                    "LocationGroupName":"autotest",
                    "MacAddress":"148FC625C228",
                    "ComplianceStatus":"NotAvailable",
                    "PlatformId":{
                            "Name":"Apple",
                            "Location":None
                    },
                "UserId":None,
                "CompromisedStatus":False,
                "LastSeen":"2013-10-09T06:02:07.353",
                "Ownership":"Undefined",
                "Imei":"012760007845071",
                "ComplianceSmmary":None,
                "LastComplianceCheckOn":None,
                "Udid":"04D8CFD680D639302810460DAC8E3599152C5973",
                "PhoneNmber":"+8613426192820",
                "Model":"iPhone",
                "ModelId":{
                    "Name":"iPhone",
                    "Location":None
                    },
                "AssetNmber":"04D8CFD680D639302810460DAC8E3599152C5973",
                "EnrollmentStatus":"Unenrolled",
                "Id":2,
                "LocationGroupId":{
                    "Name":"autotest",
                    "Location":None
                }       
            }   
        }
        
        params = self.update_params(rnd, i, device, params, acct_index)
        #print params

        if acct_index == 0:
            ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile")
        elif  acct_index == 1:
            ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile2")
        elif  acct_index == 2:
            ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile3")
        elif  acct_index == 3:
            ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile4")

        response = self.execute_request('POST', ns_url, params, 0, 0, acct_index)
        #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 = {
                "RequestID":"123456789abcdef",
                "OperationCallbackURL":"http://callback.hostname.info/do/something/requestID",
                "AwProfileId":"123456789",
                "User":{
                    "UserName":"dave",
                    "Status":True,
                    "Group":"Engineering Test",
                    "FirstName":"Dave",
                    "LastName":"Usher",
                    "EmailUserName":None,
                    "SecurityType":2,
                    "Id":163,
                    "MessageTemplateId":0,
                    "ContactNumber":None,
                    "Role":"Full Access",
                    "MessageType":0,
                    "EnrolledDevicesCount":"0",
                    "Password":None,
                    "Email":"xwang@websense.com",
                    "LdapDN":"dn=something,dc=com",
                    "LdapGuid":"12ab1242bedf3414dac"
                   },
                "Device":{
                    "UserName":None,
                    "UserEmailAddress":None,
                    "LastCompromisedCheckOn":"2013-09-24T10:12:25.523",
                    "SerialNmber":"861348SXA4S",
                    "DeviceFriendlyName":"Hang's iPhone",
                    "Platform":"Apple",
                    "LastEnrolledOn":"2013-10-09T05:52:23.6",
                    "OperatingSystem":"7.0.2",
                    "LocationGropName":"Engineering Test",
                    "MacAddress":"148FC625C228",
                    "ComplianceStats":"NotAvailable",
                    "PlatformId":{
                            "Name":"Apple",
                            "Location":None
                    },
                "UserId":None,
                "CompromisedStats":False,
                "LastSeen":"2013-10-09T06:02:07.353",
                "Ownership":"Undefined",
                "Imei":"012760007845071",
                "ComplianceSmmary":None,
                "LastComplianceCheckOn":None,
                "Udid":"4B6D5E40DFB22BD57EC4AF54DA1F297A3221388B",
                "PhoneNmber":"+8613426192820",
                "Model":"iPhone",
                "ModelId":{
                    "Name":"iPhone",
                    "Location":None
                    },
                "AssetNmber":"42a65c8289b7ddbcc8ab0fd342bb237534ba60c9",
                "EnrollmentStats":"Unenrolled",
                "Id":56,
                "LocationGropId":{
                    "Name":"Engineering Test",
                    "Location":None
                }       
            }   
        }
        
        ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile")
        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 = {
                "RequestID":"123456789abcdef",
                "OperationCallbackURL":"http://callback.hostname.info/do/something/requestID",
                "AwProfileId":"123456789",
                "User":{
                    "UserName":"dave",
                    "Status":True,
                    "Group":"Engineering Test",
                    "FirstName":"Dave",
                    "LastName":"Usher",
                    "EmailUserName":None,
                    "SecurityType":2,
                    "Id":163,
                    "MessageTemplateId":0,
                    "ContactNumber":None,
                    "Role":"Full Access",
                    "MessageType":0,
                    "EnrolledDevicesCount":"0",
                    "Password":None,
                    "Email":"xwang@websense.com",
                    "LdapDN":"dn=something,dc=com",
                    "LdapGuid":"12ab1242bedf3414dac"
                   },
                "Device":{
                    "UserName":None,
                    "UserEmailAddress":None,
                    "LastCompromisedCheckOn":"2013-09-24T10:12:25.523",
                    "SerialNmber":"861348SXA4S",
                    "DeviceFriendlyName":"Hang's iPhone",
                    "Platform":"Apple",
                    "LastEnrolledOn":"2013-10-09T05:52:23.6",
                    "OperatingSystem":"7.0.2",
                    "LocationGropName":"Engineering Test",
                    "MacAddress":"148FC625C228",
                    "ComplianceStats":"NotAvailable",
                    "PlatformId":{
                            "Name":"Apple",
                            "Location":None
                    },
                "UserId":None,
                "CompromisedStats":False,
                "LastSeen":"2013-10-09T06:02:07.353",
                "Ownership":"Undefined",
                "Imei":"012760007845071",
                "ComplianceSmmary":None,
                "LastComplianceCheckOn":None,
                "Udid":"4B6D5E40DFB22BD57EC4AF54DA1F297A3221388B",
                "PhoneNmber":"+8613426192820",
                "Model":"iPhone",
                "ModelId":{
                    "Name":"iPhone",
                    "Location":None
                    },
                "AssetNmber":"42a65c8289b7ddbcc8ab0fd342bb237534ba60c9",
                "EnrollmentStats":"Unenrolled",
                "Id":56,
                "LocationGropId":{
                    "Name":"Engineering Test",
                    "Location":None
                }       
            }   
        }
        
        ns_url = TEST_DATA.get("Notification Server", "REST_InstallProfile")
        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, acct_index=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:
                if acct_index == 0:
                    auth = base64.b64encode(self.username + ':' + self.password)
                elif  acct_index == 1:
                    auth = base64.b64encode(self.username2 + ':' + self.password)
                elif  acct_index == 2:
                    auth = base64.b64encode(self.username3 + ':' + self.password)
                elif  acct_index == 3:
                    auth = base64.b64encode(self.username4 + ':' + self.password)
            else:
                auth = base64.b64encode(self.username + ':' + self.wrongpassword)
            headers["Authorization"] = "Basic "+auth
            conn.request(requestMethod, requestURI, json.dumps(params), headers)
            #tmslog.log("NotificationSimu_REST_Stab.py send out REST request - Request ID : %s on %s" %(params['RequestID'],datetime.now()))
            #starttime = time.time()
            response = conn.getresponse()
            #tmslog.log("NotificationSimu_REST_Stab.py get response from REST request - Request ID : %s with response %s" %(params['RequestID'], response.status))
            #endtime = time.time()    
            #sec_cost = endtime - starttime
            #output = "time cost for REST request ID : %s and response is : %s seconds." %(params['RequestID'],  str(sec_cost))
            #tmslog.log(output)
            #tmslog.log('-'*20)
            status = response.status
            #return response.read().strip()
        except Exception, e:
            print repr(e)
        finally:
            if conn:
                conn.close()
        return status

def save_perf_log(filename, content):
        if filename and content:
            fd = open(filename, 'a')
            fd.write(content)
            fd.close()

def call_rest_install(rnd, i, device, acct_index, many=False):
    ns = NotificationSimu(0, acct_index)
    #print device
    if not many:
        return ns.rest_installprofile(rnd, i, device, acct_index)
    else:
        return ns.rest_installprofiles(device, acct_index)

def multiple_process_installprofile():
    
    rnd = 0
    while True:
        #Get out devices info. from txt file
        fd = open(DEVICES_DATA, 'r')
        devices  = fd.readlines()
        fd.close()
    
        #con_num = int(TEST_DATA.get("Concurrence", "CONCURRENCE_NUM"))
        con_num = 40
        #loop_num = int(TEST_DATA.get("Concurrence", "LOOP_NUM"))
        loop_num = 12000
        #block_size = loop_num / 4
        block_size = 3000
        starttime = time.time()
        stime = datetime.now()
        output  =  "mdmi REST simulator Start time : %s\n" %stime
        print output
        #perf_log_content = output
        speed = 40
        sleep_round = 1

        pool = multiprocessing.Pool(processes=con_num)
        results = []
        i = 0
        for i in xrange(loop_num):
            #acct_index = i % 4
            #results.append(pool.apply_async(call_rest_install, (devices[(4*i)+1:(4*i)+5], acct_index, True, )))
            #if ((i+1)*4) % speed == 0:
            #    time.sleep(sleep_round)
            acct_index = i / block_size
            results.append(pool.apply_async(call_rest_install, (rnd, i, devices[i], acct_index, False, )))
            if (i+1) % speed == 0:
                time.sleep(sleep_round)
        pool.close()
        pool.join()
        print '======================================================'
        print 'res size: %d' %len(results)
        for res in results:
            print res.get()
        print "Sub-process(es) done."
        endtime = time.time()
        etime = datetime.now()
        output = "mdmi REST simulator End time : %s\n" % etime
        print output
        #perf_log_content = perf_log_content + output
        sec_cost = endtime - starttime
        output = "mdmi REST simulaotr sent %d request with time cost: %d seconds.\n" % ((i+1), sec_cost)
        print output
        #perf_log_content = perf_log_content + output
        output = '-'*40 + '\n'
        print output
        #perf_log_content = perf_log_content + output
        #save_perf_log(SIMU_LOG, perf_log_content)
        rnd = rnd + 1
        time.sleep(60)

if __name__ == '__main__':
    multiple_process_installprofile()
    



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值