Exemplo n.º 1
0
    def on_start(self):
        """
        测试数据初始化
        1.创建session会话,提供给后面的请求
        2.初始化请求头的信息
        3.初始化用户信息(用户信息参数化)
        4.引用自定义日志
        """
        self.session = HttpSession(base_url="http://*****:*****@qq.com", "123456"],
            1: ["*****@*****.**", "123456"],
            2: ["*****@*****.**", "123456"]
        }

        self.log = MyLog.MyLog().get_logger()
Exemplo n.º 2
0
    def create_purchase(self):
        session = HttpSession(self.base_url)
        # self.client.post('/api/v0.9/reservation/', reservation_body)
        reservation_response = session.post("/api/v0.9/reservation/", data=reservation_body)

        if reservation_response.status_code != 201:
            return

        if reservation_response.status_code == 409:
            raise StopLocust("No available tickets.")

        checkout_response = session.post("/api/v0.9/reservation/_checkout", data=checkout_body)

        if checkout_response.status_code != 200:
            return

        purchase = checkout_response.json()["purchase"]
        completion_response = session.post(
            "/api/v0.9/purchases/_complete",
            json.dumps(
                dict(
                    purchase_id=purchase["purchase_id"],
                    hash=purchase["completion_params"]["hash"],
                    processor=purchase["completion_params"]["processor"],
                    payment_ref=purchase["completion_params"]["order_ref"],
                )
            ),
        )
Exemplo n.º 3
0
 def test_slow_redirect(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     url = "/redirect?url=/redirect?delay=0.5"
     r = s.get(url)
     stats = global_stats.get(url, method="GET")
     self.assertEqual(1, stats.num_requests)
     self.assertGreater(stats.avg_response_time, 500)
Exemplo n.º 4
0
 def test_slow_redirect(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     url = "/redirect?url=/redirect?delay=0.5"
     r = s.get(url)
     stats = global_stats.get(url, method="GET")
     assert 1 == stats.num_requests
     assert stats.avg_response_time > 500
Exemplo n.º 5
0
    def create_purchase(self):
        session = HttpSession(self.base_url)
        # self.client.post('/api/v0.9/reservation/', reservation_body)
        reservation_response = session.post('/api/v0.9/reservation/',
                                            data=reservation_body)

        if reservation_response.status_code != 201:
            return

        if reservation_response.status_code == 409:
            raise StopLocust('No available tickets.')

        checkout_response = session.post('/api/v0.9/reservation/_checkout',
                                         data=checkout_body)

        if checkout_response.status_code != 200:
            return

        purchase = checkout_response.json()['purchase']
        completion_response = session.post(
            '/api/v0.9/purchases/_complete',
            json.dumps(
                dict(purchase_id=purchase['purchase_id'],
                     hash=purchase['completion_params']['hash'],
                     processor=purchase['completion_params']['processor'],
                     payment_ref=purchase['completion_params']['order_ref'])))
Exemplo n.º 6
0
 def test_slow_redirect(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     url = "/redirect?url=/redirect?delay=0.5"
     r = s.get(url)
     stats = global_stats.get(url, method="GET")
     self.assertEqual(1, stats.num_requests)
     self.assertGreater(stats.avg_response_time, 500)
Exemplo n.º 7
0
    def test_token_work(self,count):
        mobiles =self.get_mobile(count)
        Worktoken = list()
        Lovetoken = list()
        lifetoken = list()
        url = "http://"+K8sServer+":10001"
        t = HttpSession(url)
        header = {"Content-Type": "application/json"}
        for i in mobiles:
            data = {"Uid": "string", "DeviceName": "string", "Lat": 0, "Lon": 0, "Mobile": i, "Password": 123456}
            obj = t.post('/v1/logins/users', data=json.dumps(data), headers=header)
            WorkAuthorization = json.loads(obj.text).get('WorkAuthorization')
            if WorkAuthorization:
                Worktoken.append(WoAuthorization)
                Worktoken.append('\n')
            LoveAuthorization = json.loads(obj.text).get('LoveAuthorization')
            if LoveAuthorization:
                Lovetoken.append(LoAuthorization)
                Lovetoken.append('\n')
            LifeAuthorization = json.loads(obj.text).get('LifeAuthorization')
            if  LoveAuthorization:
                lifetoken.append(LiAuthorization)
                lifetoken.append('\n')

        with open('token/WoAuthorization.txt', 'w') as f:
            f.writelines(Wotoken)

        with open('token/LoAuthorization.txt','w') as l:
            l.writelines(Lotoken)

        with open('token/LiAuthorization.txt', 'w') as i:
            i.writelines(litoken)
Exemplo n.º 8
0
 def on_start(self):
     self.dataset = self.parent.dataset
     self.client.verify = False
     self.api_less_client = HttpSession(
         base_url=self.client.base_url.replace("api.", "").replace("cellxgene/", ""),
         request_success=self.client.request_success,
         request_failure=self.client.request_failure,
     )
Exemplo n.º 9
0
 def test_options(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     r = s.options("/request_method")
     self.assertEqual(200, r.status_code)
     self.assertEqual("", r.content.decode())
     self.assertEqual(
         set(["OPTIONS", "DELETE", "PUT", "GET", "POST", "HEAD", "PATCH"]),
         set(r.headers["allow"].split(", ")),
     )
Exemplo n.º 10
0
    def __init__(self, host, min_wait, max_wait, tests_type):
        self.host = host
        self.min_wait = min_wait
        self.max_wait = max_wait
        influxdbstring = env["INFLUXDB"]
        influxport = influxdbstring.split(":").pop()

        try:
            influxport = int(influxport)
        except ValueError:
            print("Invalid port number given ({}), defaulting to 8086").format(
                influxport)
            influxport = 8086

        influxhost = influxdbstring.split(":")
        influxhost.pop()
        influxhost = influxhost.pop().replace("//", "")

        self._client = InfluxDBClient(host=influxhost,
                                      port=influxport,
                                      database='data',
                                      username='******',
                                      password='******')
        self._user_count = locust.runners.locust_runner.num_clients
        # self._run_id = env["RUN_ID"]
        # self._team = env["TEAM"]
        self._hostname = socket.gethostname()
        self._finished = False
        self._points = []
        self._ps = ps.PSStats()

        self.sanity_test()
        self._client.create_database('data')

        self.tests_type = tests_type

        session = HttpSession(base_url="")
        statement = session.get(self.host + "/metadata").json()

        self.test_uuid = str(uuid.uuid4())
        self.test_start = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')

        if 'software' in statement:
            self.server_version = statement['software']['version']
            self.server_name = statement['software']['name']
        else:
            self.server_version = 'unavailable'

        self.fhir_version = statement['fhirVersion']
        self.test_name = '{} {} v{} f{}'.format(env["TEST_DATE"],
                                                self.server_name,
                                                self.server_version,
                                                self.fhir_version)
        self.write_start_annotation(tests_type)

        self._background = gevent.spawn(
            self._run)  # handle to your greenlet (think threads)
Exemplo n.º 11
0
 def test_post_redirect(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     url = "/redirect"
     r = s.post(url)
     assert 200 == r.status_code
     post_stats = global_stats.get(url, method="POST")
     get_stats = global_stats.get(url, method="GET")
     assert 1 == post_stats.num_requests
     assert 0 == get_stats.num_requests
Exemplo n.º 12
0
    def create_purchase(self):
        session = HttpSession(self.base_url)
        # self.client.post('/api/v0.9/reservation/', reservation_body)
        reservation_response = session.post('/api/v0.9/reservation/', data=reservation_body)

        if reservation_response.status_code != 201:
            return

        checkout_response = session.post('/api/v0.9/reservation/_checkout', data=checkout_body)
Exemplo n.º 13
0
 def test_post_redirect(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     url = "/redirect"
     r = s.post(url)
     self.assertEqual(200, r.status_code)
     post_stats = global_stats.get(url, method="POST")
     get_stats = global_stats.get(url, method="GET")
     self.assertEqual(1, post_stats.num_requests)
     self.assertEqual(0, get_stats.num_requests)
Exemplo n.º 14
0
 def test_options(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     r = s.options("/request_method")
     self.assertEqual(200, r.status_code)
     self.assertEqual("", r.content.decode())
     self.assertEqual(
         set(["OPTIONS", "DELETE", "PUT", "GET", "POST", "HEAD"]),
         set(r.headers["allow"].split(", ")),
     )
Exemplo n.º 15
0
 def test_post_redirect(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     url = "/redirect"
     r = s.post(url)
     self.assertEqual(200, r.status_code)
     post_stats = global_stats.get(url, method="POST")
     get_stats = global_stats.get(url, method="GET")
     self.assertEqual(1, post_stats.num_requests)
     self.assertEqual(0, get_stats.num_requests)
Exemplo n.º 16
0
 def delete(port, url, au):
     http = HttpSession(base + ":" + port)
     data = http.delete(url,
                        headers={
                            'Authorization': au,
                            'Content-Type': 'application/json',
                            'accept': 'application/json'
                        })
     return data
Exemplo n.º 17
0
 def LoadResources(self,URL):
     session = HttpSession(path)
     response = session.get(path)
     resource_urls = set()
     soup = BeautifulSoup(response.text, "html.parser")
     print(soup)
     for response in soup.find_all(src=True):
         url = response['src']
         resource_urls.add(URL)
         print ("Reading src-- > : " + url)
Exemplo n.º 18
0
 def put(port, url, data, au):
     http = HttpSession(base + ":" + port)
     data = http.put(url,
                     data=json.dumps(data),
                     headers={
                         'Authorization': au,
                         'Content-Type': 'application/json',
                         'accept': 'application/json'
                     })
     return data
Exemplo n.º 19
0
    def create_purchase(self):
        session = HttpSession(self.base_url)
        # self.client.post('/api/v0.9/reservation/', reservation_body)
        reservation_response = session.post('/api/v0.9/reservation/',
                                            data=reservation_body)

        if reservation_response.status_code != 201:
            return

        checkout_response = session.post('/api/v0.9/reservation/_checkout',
                                         data=checkout_body)
Exemplo n.º 20
0
 def __init__(self, *args, **kwargs):
     super(MicroServiceHosts, self).__init__(*args, **kwargs)
     self.profile_service_client = HttpSession(
         base_url=os.getenv("PROFILE_SVC_URL", "http://localhost:8080")
     )
     self.transaction_service_client = HttpSession(
         base_url=os.getenv("TRANSACTION_SVC_URL", "http://localhost:5050")
     )
     self.transfer_service_client = HttpSession(
         base_url=os.getenv("TRANSFER_SVC_URL", "http://localhost:5000")
     )
Exemplo n.º 21
0
    def endpoint_sanity_test(self):
        session = HttpSession(base_url="")

        with session.get(self.host + "/Patient?given=Mariano451&family=Bashirian129",
                         catch_response=True, name="Sanity test") as response:
            try:
                test.checkResponse(response.status_code, 200)
                bundle = response.json()
                test.checkTotalAboveZero(self, bundle, True)
            except ResponseError:
                sys.exit('Sanity test failed, /Patient?given=Mariano451&family=Bashirian129 returned nothing. Have you uploaded the test dataset?')
Exemplo n.º 22
0
 def login(self):
     payload = "username=user&password=user&grant_type=password&client_id=envoy"
     headers = {
         'Content-Type': "application/x-www-form-urlencoded",
     }
     client = HttpSession(
         base_url=os.environ.get("JWT_URL", "http://localhost:8080"))
     response = client.post(
         '/auth/realms/envoy/protocol/openid-connect/token',
         payload,
         headers=headers)
     self.auth_token = "Bearer " + json.loads(response.text)['access_token']
Exemplo n.º 23
0
    def __init__(self, *args, **kwargs):
        super(HttpUser, self).__init__(*args, **kwargs)
        if self.host is None:
            raise LocustError("You must specify the base host. Either in the host attribute in the User class, or on the command line using the --host option.")

        session = HttpSession(
            base_url=self.host, 
            request_success=self.environment.events.request_success, 
            request_failure=self.environment.events.request_failure,
        )
        session.trust_env = False
        self.client = session
Exemplo n.º 24
0
 def delete(port, url, au):
     # data = requests.delete(url, data=data, headers={'Authorization': au, 'Content-Type': 'application/json',
     #                                      'accept': 'application/msgpack'})
     http = HttpSession(base + ":" + port)
     data = http.delete(url,
                        headers={
                            'Authorization': au,
                            'Content-Type': 'application/json',
                            'accept': 'application/msgpack'
                        })
     if data.status_code == 400:
         return Http_esponseDecode(data)
     else:
         return data
Exemplo n.º 25
0
    def test_error_message_with_name_replacment(self):
        s = HttpSession("http://127.0.0.1:%i" % self.port)
        my_event = events.EventHook()
        kwargs = {}

        def on_my_event(**kw):
            kwargs.update(kw)

        my_event += on_my_event
        orig_events = events.request_failure
        events.request_failure = my_event
        s.request('get', '/wrong_url/01', name='replaced_url_name')
        events.request_failure = orig_events
        self.assertIn('for url: replaced_url_name', str(kwargs['exception']))
Exemplo n.º 26
0
def sendGetLegendGraphicRequest(client: locustclients.HttpSession,
                                params: dict, wmsversion: str):
    requestUrl = ""
    if "url" in params:
        # extract request url from params
        requestUrl = params["url"]
        params.pop("url")

    with client.request("GET",
                        requestUrl,
                        params=params,
                        name="WMS-{}-GetLegendGraphic".format(wmsversion),
                        catch_response=True) as response:
        #if response.history:
        #    #Response was redirected
        #    for resp in response.history:
        #        print("Redirected with code '{}' to url '{}'".format(resp.status_code,resp.url))
        if response.url is None:
            response.failure("Request failed. No response from server.")
            return
        url = urllib.parse.unquote(response.url)

        if response.status_code == 200:
            if response.headers['content-type'] != "image/png":
                errormsg = "Expected format 'image/png' but got '{}' instead\n Request URL: {}\n Request params: '{}'\nResponse: '{}'\n".format(
                    response.headers['content-type'], url, params,
                    response.text)
                vprint("Request failed:\n{}".format(errormsg))
                response.failure(errormsg)
            else:
                vprint("Request successful: {}".format(url))
                response.success()
Exemplo n.º 27
0
 def get(port, url, au):
     # data = requests.get(url, data, headers={'Authorization': au, 'Content-Type': 'application/json',
     #                                         'accept': 'application/msgpack'})
     http = HttpSession(base + ":" + port)
     data = http.get(url,
                     headers={
                         'Authorization': au,
                         'Content-Type': 'application/json',
                         'accept': 'application/msgpack'
                     })
     if data.status_code == 204:
         return data
     elif data.content == b'':  #返回值为空
         return data
     else:
         return Http_esponseDecode(data)
Exemplo n.º 28
0
 def __init__(self, *args, **kwargs):
   global _currentUser, _userLock, _users, _userTokens, _userEnvironment, _userNames
   super(Locust, self)
   TOKEN_INDEX = 0
   USERNAME_INDEX = 1
   ENVIRONMENT_INDEX = 2
   usenv = os.getenv("USER_TOKENS")
   lines = usenv.split('\n')
   _users = len(lines)
   for u in lines:
     up = u.split(';')
     _userTokens.append(up[TOKEN_INDEX])
     _userNames.append(up[USERNAME_INDEX])
     _userEnvironment.append(up[ENVIRONMENT_INDEX])
   # Async lock user to prevent two threads runing with the same user
   _userLock.acquire()
   self.taskUser = _currentUser
   self.taskUserToken = _userTokens[_currentUser]
   self.taskUserName = _userNames[_currentUser]
   self.taskUserEnvironment = _userEnvironment[_currentUser]
   print("Spawning user ["+str(self.taskUser)+"] on ["+self.taskUserEnvironment+"]")
   if _currentUser < _users - 1:
     _currentUser += 1
   else:
     _currentUser = 0
   _userLock.release()
   # User lock released, critical section end
   host = "https://che.prod-preview.openshift.io" if "prod-preview" in self.taskUserEnvironment else "https://che.openshift.io"
   self.client = HttpSession(base_url=host)
Exemplo n.º 29
0
    def __init__(self, *, user: HttpUser, size: Optional[int] = None):

        """
        Connection pool for the HttpUser, the user will use the connections
        in round robin style for every HTTP request.

        Args:
            user (HttpUser): Instance of a HttpUser, pass in self in most circumstances
            size (int, optional): [description]. Override for the pool size, value defaults to
            the input from the command line.
        """
        if size:
            self.size = size
        else:
            self.size = user.environment.parsed_options.pool_size  # type: ignore

        self._pool: List[HttpSession] = []
        self.request_name = None

        for _ in range(self.size):
            self._pool.append(
                HttpSession(
                    base_url=user.host, request_event=user.environment.events.request, user=user  # type: ignore
                )
            )

        self.pool = cycle(self._pool)
Exemplo n.º 30
0
 def __init__(self):
     super(HttpLocust, self).__init__()
     if self.host is None:
         raise LocustError("You must specify the base host. Either in the host attribute in the \
         Locust class, or on the command line using the --host option.")
     
     self.client = HttpSession(base_url=self.host)
Exemplo n.º 31
0
    def setup(self):
        NormalUserTasks.session = HttpSession(MyLocust.host)

        # get verification
        uri = '/verification/generate'
        NormalUserTasks.session.get(uri)

        # login
        username = '******'
        password = '******'
        verification = '1234'

        load = {
            "email": username,
            "password": password,
            "verificationCode": verification
        }
        uri = '/login'

        # response = self.client.post(uri, json=load, cookies=NormalUserTasks.cookies)
        # print(response.cookies, response.headers)
        response = NormalUserTasks.session.post(uri, json=load)

        NormalUserTasks.loginId = response.cookies["loginId"]
        NormalUserTasks.loginToken = response.cookies["loginToken"]
Exemplo n.º 32
0
    def __init__(self, *args, **kwargs):
        super(OAuth2Locust, self).__init__(*args, **kwargs)

        credentials, project_id = google.auth.default(scopes=API_SCOPES)
        auth = SimpleOAuth2(credentials)
        self.client = HttpSession(base_url='')
        self.client.auth = auth
Exemplo n.º 33
0
 def set_locust_host(self, host):
     if not host.startswith('http'):
         host = 'http://' + host
     from locust.clients import HttpSession
     self.HttpSession = HttpSession(host)
     print('set session ok:' + host)
     return self
Exemplo n.º 34
0
class StableCoinUser(User):
    wait_time = constant(0)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # client
        self.node_session = HttpSession(
            base_url="http://128.199.13.131:9000",
            request_success=self.environment.events.request_success,
            request_failure=self.environment.events.request_failure,
        )

        # platform
        self.platform_session = HttpSession(
            base_url="http://128.199.14.196:80",
            request_success=self.environment.events.request_success,
            request_failure=self.environment.events.request_failure,
        )

    @task
    def transfer(self):
        # 1) prepare (and sign) HSC transfer transaction
        hsc_transaction, operator, valid_start = prepare_hsc_transfer_transaction(
        )

        # 2) sign Hedera (HCS) transaction
        response = self.platform_session.post("/hedera/transaction",
                                              data=hsc_transaction)

        # 3) submit Hedera (HCS) transaction (x1000)
        send_hedera_transaction(response.content)

        # 4) wait for confirmation
        wait_for_confirmation(self.node_session, operator, valid_start)
Exemplo n.º 35
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # client
        self.node_session = HttpSession(
            base_url="http://128.199.13.131:9000",
            request_success=self.environment.events.request_success,
            request_failure=self.environment.events.request_failure,
        )

        # platform
        self.platform_session = HttpSession(
            base_url="http://128.199.14.196:80",
            request_success=self.environment.events.request_success,
            request_failure=self.environment.events.request_failure,
        )
Exemplo n.º 36
0
class DrawTask(TaskSet):
    session = None

    def on_start(self):
        host = 'https://passport.tuandai.com'
        # 设置sesssion
        self.session = HttpSession(self.host)
        res = self.session.get(
            url=host +
            '/2login?ret=http://at.tuandai.com/userActivity/midAutumn/we/index'
        )
        print(res.cookies.values())
        params = {
            'un': '15866660001',
            'pd': '123456a',
            'loadType': 2,
            'encrypt': 0,
            't': 65446446
        }
        url = '/2login'
        # 使用 session 来登录
        response = self.session.post(url=host + url, data=params)
        print("login_result:", response.status_code, response.text)

    def on_stop(self):
        pass

    @task(1)
    def FIRST_ROUND(self):
        response = self.session.get(
            url=web + '/huodong/answerQuestion/drawPrize',
            params='drawFlag=ANSWER_QUESTION_FIRST_ROUND')
        print("FIRST_ROUND:", response.status_code, response.text)

    @task(1)
    def SECOND_ROUND(self):
        response = self.session.get(
            url=web + '/huodong/answerQuestion/drawPrize',
            params='drawFlag=ANSWER_QUESTION_SECOND_ROUND')
        print("SECOND_ROUND:", response.status_code, response.text)

    @task(1)
    def THIRD_ROUND(self):
        response = self.session.get(
            url=web + '/huodong/answerQuestion/drawPrize',
            params='drawFlag=ANSWER_QUESTION_THIRD_ROUND')
        print("THIRD_ROUND:", response.status_code, response.text)
Exemplo n.º 37
0
def sendGetCapabilitiesRequest(client: locustclients.HttpSession,
                               wmsversion: str):
    params = getGetCapabilitiesRequest(wmsversion=wmsversion)

    with client.request("GET",
                        "",
                        params=params,
                        name="WMS-{}-GetCapabilities".format(wmsversion),
                        catch_response=True) as response:
        if response.url is None:
            response.failure("Request failed. No response from server.")
            return
        url = urllib.parse.unquote(response.url)

        if not response.status_code == 200:
            errormsg = "Request failed with HTTP status code: '{}'\n Request URL: {}\n Request Params: {}\n Response-Content: '{}'".format(
                response.status_code, url, params, response.content)
            vprint("Request failed:\n{}".format(errormsg))
            response.failure(errormsg)
            return

        if not hasValidGetCapabilitiesResponseType(
                response.headers['content-type']):
            response.failure(
                "Wrong response content-type encountered: '%s' (see %s)" %
                (response.headers['content-type'],
                 "https://cite.opengeospatial.org/teamengine/about/wms/1.1.1/site/OGCTestData/wms/1.1.1/spec/wms1.1.1.html#basic_elements.params.format"
                 ))
            return

        if response.content == "":
            vprint("Request failed (No data): {}".format(url))
            response.failure("No data")
            return

        try:
            capabilities = xmltodict.parse(response.content)
            vprint("Request successful: {}".format(url))
            #return capabilities
        except:
            vprint("Request failed (Failed to parse GetCapabilities XML): {}".
                   format(url))
            response.failure("Failed to parse GetCapabilities XML")
            return

        try:
            # parse the capabilities document once
            # for each WMS version
            parsed_layers = getAllLayers(capabilities=capabilities,
                                         wmsversion=wmsversion)
            return parsed_layers
        except Exception as ex:
            vprint(
                "Request failed (Failed to extract layers from GetCapabilities XML): {}"
                .format(url))
            response.failure(
                "Failed to extract layers from GetCapabilities XML version '{0}'. Error: {1}"
                .format(wmsversion, ex))
            return
Exemplo n.º 38
0
 def test_streaming_response(self):
     """
     Test a request to an endpoint that returns a streaming response
     """
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     r = s.get("/streaming/30")
     
     # verify that the time reported includes the download time of the whole streamed response
     self.assertGreater(global_stats.get("/streaming/30", method="GET").avg_response_time, 250)
     global_stats.clear_all()
     
     # verify that response time does NOT include whole download time, when using stream=True
     r = s.get("/streaming/30", stream=True)
     self.assertGreater(global_stats.get("/streaming/30", method="GET").avg_response_time, 0)
     self.assertLess(global_stats.get("/streaming/30", method="GET").avg_response_time, 250)
     
     # download the content of the streaming response (so we don't get an ugly exception in the log)
     _ = r.content
Exemplo n.º 39
0
    def create_purchase(self):
        session = HttpSession(self.base_url)
        # self.client.post('/api/v0.9/reservation/', reservation_body)
        reservation_response = session.post('/api/v0.9/reservation/', data=reservation_body)

        if reservation_response.status_code != 201:
            return

        checkout_response = session.post('/api/v0.9/reservation/_checkout', data=checkout_body)

        if checkout_response.status_code != 200:
            return

        purchase = checkout_response.json()['purchase']
        completion_response = session.post('/api/v0.9/purchases/_complete', json.dumps(dict(
            purchase_id=purchase['purchase_id'],
            hash=purchase['completion_params']['hash'],
            processor=purchase['completion_params']['processor'],
            payment_ref=purchase['completion_params']['order_ref']
        )))
Exemplo n.º 40
0
 def test_get(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     r = s.get("/ultra_fast")
     self.assertEqual(200, r.status_code)
Exemplo n.º 41
0
 def __init__(self, tq_location):
   self.tq_location = tq_location
   self.http_session = HttpSession(base_url=f'http://{tq_location}')
Exemplo n.º 42
0
class TaskqueueClient(object):
  """
  Decorates Locust HttpSession with protobuffer and REST request
  preparation and response processing for communication with TaskQueue.
  Encapsulates TaskQueue host and ProjectID.
  """

  SERVICE_NAME = 'taskqueue'

  def __init__(self, tq_location):
    self.tq_location = tq_location
    self.http_session = HttpSession(base_url=f'http://{tq_location}')

  @contextmanager
  def protobuf(self, pb_method, pb_request):
    """ Provides simplified interface for sending Protobuffer
    requests to the TaskQueue service.

    Args:
      pb_method: a str representing name of TaskQueue method.
      pb_request: an instance of ProtobufferMessage representing request.
    Returns:
      an instance of corresponding ProtobufferMessage (response).
    """
    remote_api_request = remote_api_pb2.Request()
    remote_api_request.service_name = self.SERVICE_NAME
    remote_api_request.method = pb_method
    remote_api_request.request = pb_request.SerializeToString()
    headers = {
      'protocolbuffertype': 'Request',
      'appdata': TEST_PROJECT,
      'Module': '',
      'Version': ''
    }
    body = remote_api_request.SerializeToString()
    locust_wrapped_response = self.http_session.request(
      'POST', f'http://{self.tq_location}', headers=headers, data=body,
      name=pb_method, catch_response=True
    )
    with locust_wrapped_response as resp:
      if resp.status_code >= 400:
        resp.failure(f'TaskQueue responded '
                     f'"HTTP {resp.status_code}: {resp.reason}"')
        raise api_helper.HTTPError(resp.status_code, resp.reason, resp.content)
      api_response = remote_api_pb2.Response()
      api_response.ParseFromString(resp.content)
      if api_response.HasField('application_error'):
        err = api_response.application_error
        msg = f'{err.code}: {err.detail}'
        resp.failure(msg)
        raise api_helper.ProtobufferAppError(
            msg, code=err.code, detail=err.detail)
      if api_response.HasField('exception'):
        resp.failure(api_response.exception)
        raise api_helper.ProtobufferException(api_response.exception)

      pb_resp_cls_name = f'TaskQueue{pb_method}Response'
      pb_resp_cls = getattr(taskqueue_service_pb2, pb_resp_cls_name)
      pb_resp = pb_resp_cls()
      pb_resp.ParseFromString(api_response.response)

      try:
        yield pb_resp
      finally:
        resp.success()

  @contextmanager
  def rest(self, method, *, path_suffix, params=None, json=None):
    """ Provides simplified interface for sending REST requests
    to the TaskQueue service.

    Args:
      method: a str representing HTTP method.
      path_suffix: a str to use in URL:
        http://<HOST>/taskqueue/v1beta2/projects/<PROJECT>/taskqueues/<PATH_PREFIX>.
      params: a dict containing request parameters.
      json: an object to serialise as JSON body.
    Returns:
      an instance of Taskqueue.RESTResponse.
    """
    url = f'/taskqueue/v1beta2/projects/{TEST_PROJECT}/taskqueues{path_suffix}'
    locust_wrapped_response = self.http_session.request(
      method, url, params=params, json=json,
      name=path_suffix, catch_response=True
    )
    with locust_wrapped_response as resp:
      try:
        resp.raise_for_status()
      except RequestException as err:
        resp.failure(err)
        raise
      else:
        try:
          yield resp
        finally:
          resp.success()
Exemplo n.º 43
0
 def test_connection_error(self):
     s = HttpSession("http://localhost:1")
     r = s.get("/", timeout=0.1)
     self.assertEqual(r.status_code, 0)
     self.assertEqual(None, r.content)
     self.assertRaises(RequestException, r.raise_for_status)
Exemplo n.º 44
0
 def test_cookie(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     r = s.post("/set_cookie?name=testcookie&value=1337")
     self.assertEqual(200, r.status_code)
     r = s.get("/get_cookie?name=testcookie")
     self.assertEqual('1337', r.content.decode())
Exemplo n.º 45
0
 def test_delete(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     r = s.delete("/request_method")
     self.assertEqual(200, r.status_code)
     self.assertEqual("DELETE", r.content.decode())
Exemplo n.º 46
0
 def post(self):
   session = HttpSession(self.base_url)
   reservation_response = session.post('/prod/insert-product', data=body)
Exemplo n.º 47
0
 def create_purchase(self):
     session = HttpSession(self.base_url)
     reservation_response = session.post('/api/v0.9/reservation/', data=reservation_body)
Exemplo n.º 48
0
 def test_get(self):
     s = HttpSession("http://127.0.0.1:%i" % self.port)
     r = s.get("/ultra_fast")
     assert 200 == r.status_code
Exemplo n.º 49
0
 def test_connection_error(self):
     s = HttpSession("http://localhost:1")
     r = s.get("/", timeout=0.1)
     assert r.status_code == 0
     assert None == r.content
     raises(RequestException, r.raise_for_status)