def __check_limits(self):
        if self.locust_start_time is None:
            self.locust_start_time = time.time()

        # Only raise an exception if the actual test is running
        if self.locust_stop_time is None:
            if time.time() - self.locust_start_time >= self.locust_duration:
                raise StopUser('Duration limit reached')

            if self.num_requests <= 0:
                raise StopUser('Request limit reached')
Esempio n. 2
0
    def on_start(self):
        #Get username /pwd
        self.userName=""
        self.Password=""

        self.userName = random.choice(my_reader)['UserName']
        self.Password = random.choice(my_reader)['Password']

        with self.client.get("/", name="launchURL", catch_response=True) as resp:
            time.sleep(2)
            if resp.status_code == 200:
                resp.success()
                logger.info("URL Launched")
            else:
                resp.failure("failed to launch URL")
                logger.critical("failed to launch URL")
                #Exit test run
                self.parent.environment.runner.quit()



        with self.client.post("/login.php", name="login", data={"action": "process","userName": self.userName,
                                                           "password": self.Password,"login.x": "41","login.y": "12"}, catch_response=True) as resp:

            time.sleep(2)
            if ("Find a Flight") in resp.text:
                resp.success()
                logger.info("login successful \t" +self.userName)
            else:
                resp.failure("failed to login")
                logger.critical("login failed \t" +self.userName)
                #Exit User
                raise StopUser()
Esempio n. 3
0
def wrap_for_locust(request_type, name, func, *args, **kwargs):
    """
    Wrap Selenium activity function with Locust's event fail/success
    method

    :param request_type: the type of request
    :param name: name to be reported to events.request_*.fire
    :param func: callable to be timed and logged
    :return result: Result of the provided function if doesn't raise exception
    """
    try:
        start_time = time.time()
        result = func(*args, **kwargs)
    except Exception as event_exception:
        total_time = int((time.time() - start_time) * 1000)
        events.request_failure.fire(request_type=request_type,
                                    name=name,
                                    response_time=total_time,
                                    response_length=0,
                                    exception=event_exception)
        raise StopUser()
    else:
        total_time = int((time.time() - start_time) * 1000)
        events.request_success.fire(request_type=request_type,
                                    name=name,
                                    response_time=total_time,
                                    response_length=0)
        return result
Esempio n. 4
0
    def wait(self):
        """
        Make the running user sleep for a duration defined by the Locust.wait_time
        function (or TaskSet.wait_time function if it's been defined).

        The user can also be killed gracefully while it's sleeping, so calling this
        method within a task makes it possible for a user to be killed mid-task, even if you've
        set a stop_timeout. If this behaviour is not desired you should make the user wait using
        gevent.sleep() instead.
        """
        if self.user._state == LOCUST_STATE_STOPPING:
            raise StopUser()
        self.user._state = LOCUST_STATE_WAITING
        self._sleep(self.wait_time())
        if self.user._state == LOCUST_STATE_STOPPING:
            raise StopUser()
        self.user._state = LOCUST_STATE_RUNNING
 def run(self):
     if self.environment.runner:
         self.host = self.environment.runner.dmt_test_url
         self.logged_user = self.environment.runner.dmt_logged_user
     if self.host is None:
         raise StopUser("DMT: test_url for " + self.__class__.__name__ +
                        " is None.")
     super(DMTUser, self).run()
def add_item_to_order(session, item_idx: int):
    with session.client.post(
            f"{ORDER_URL}/orders/addItem/{session.order_id}/{session.item_ids[item_idx]}",
            name="/orders/addItem/[order_id]/[item_id]",
            json={},
            catch_response=True) as response:
        if 400 <= response.status_code < 500:
            response.failure(response.text)
            raise StopUser()
        else:
            response.success()
    def on_start(self):
        # load single hh per user
        self.zmq_consumer = ZMQRequester(FEEDER_ADDR)
        data = self.zmq_consumer.await_data()
        if data == {}:
            logging.info("No more data. Stopping user.")
            raise StopUser()
        else:
            self.household = data

        self.pgp_pair = create_test_gpg_keypair(
            self.household['pds_card_number'])
Esempio n. 8
0
 def wrapped(self, task):
     if runner.iterations_started == options.iterations:
         if not runner.iteration_target_reached:
             runner.iteration_target_reached = True
             logging.info(
                 f"Iteration limit reached ({options.iterations}), stopping Users at the start of their next task run"
             )
         if runner.user_count == 1:
             logging.info("Last user stopped, quitting runner")
             runner.quit()
         raise StopUser()
     runner.iterations_started = runner.iterations_started + 1
     method(self, task)
Esempio n. 9
0
 def execute_next_task_with_iteration_limit(self: TaskSet):
     if runner.iterations_started == environment.parsed_options.iterations:
         if not runner.iteration_target_reached:
             runner.iteration_target_reached = True
             logging.info(
                 f"Iteration limit reached ({environment.parsed_options.iterations}), stopping Users at the start of their next task run"
             )
         if runner.user_count == 1:
             logging.debug("Last user stopped, quitting runner")
             runner.quit()
         raise StopUser()
     runner.iterations_started = runner.iterations_started + 1
     _execute_next_task(self)
Esempio n. 10
0
    def get_questions_16(self):
        request_body = {"data": "Going to work is more dangerous than going to war."}

        with self.client.post("/questions",
                              json=request_body,
                              catch_response=True) as response:
            if response.text is None or not response.text.strip():
                logging.error(inspect.stack()[0][3] + " Failed: response is None")
                response.failure(inspect.stack()[0][3] + " Failed: response is None")
            else:
                logging.info(inspect.stack()[0][3] + ": " + response.text)
                response_data = response.json()
                if not response_data["success"]:
                    logging.error(inspect.stack()[0][3] + " Failed: " + response_data['message'])
                    response.failure(inspect.stack()[0][3] + " Failed: " + response_data['message'])
        raise StopUser()
Esempio n. 11
0
 def get_paraphrase_15(self):
     request_body = [
         "water and mercury can exist in all the three states of matter",
         "Going to work is more dangerous than going to war.",
         "The Burj Khalifa is so tall you can see two sunsets from it in one day."]
     with self.client.post("/paraphrases",
                           json=request_body,
                           catch_response=True) as response:
         if response.text is None or not response.text.strip():
             logging.error(inspect.stack()[0][3] + " Failed: response is None")
             response.failure(inspect.stack()[0][3] + " Failed: response is None")
         else:
             logging.info(inspect.stack()[0][3] + ": " + response.text)
             response_data = response.json()
             if not response_data["success"]:
                 logging.error(inspect.stack()[0][3] + " Failed: " + response_data['message'])
                 response.failure(inspect.stack()[0][3] + " Failed: " + response_data['message'])
     raise StopUser()
Esempio n. 12
0
def dso_login(env='dev'):
    with open(get_config_file_path(), 'r') as f:
        properties = yaml.load(f.read(), yaml.SafeLoader)
    env_property = properties[env]
    url = env_property['login_url']
    header = {
        "Authorization": env_property['login_authorization'],
        "Content-Type": "application/x-www-form-urlencoded"
    }
    body = {
        "grant_type": env_property['login_grant_type'],
        "scope": env_property['login_scope']
    }
    response = requests.post(url, data=body, headers=header)
    if response.status_code == 200:
        return response
    else:
        print(response.status_code.__str__() + " : " + response.text)
        raise StopUser()
Esempio n. 13
0
 def get_config_templates(self):
     with self.client.get(
             "/api/bot/templates/config",
             headers={"Authorization": self.user.auth_token},
             catch_response=True) as response:
         if response.text is None or not response.text.strip():
             logging.error(inspect.stack()[0][3] +
                           " Failed: response is None")
             response.failure(inspect.stack()[0][3] +
                              " Failed: response is None")
         else:
             logging.info(inspect.stack()[0][3] + ": " + response.text)
             response_data = response.json()
             if not response_data["success"]:
                 logging.error(inspect.stack()[0][3] + " Failed: " +
                               response_data['message'])
                 response.failure(inspect.stack()[0][3] + " Failed: " +
                                  response_data['message'])
     raise StopUser()
Esempio n. 14
0
    def run(self):
        try:
            self.on_start()
        except InterruptTaskSet as e:
            if e.reschedule:
                raise RescheduleTaskImmediately(e.reschedule).with_traceback(
                    e.__traceback__)
            else:
                raise RescheduleTask(e.reschedule).with_traceback(
                    e.__traceback__)

        while True:
            try:
                if not self._task_queue:
                    self.schedule_task(self.get_next_task())

                try:
                    if self.user._state == LOCUST_STATE_STOPPING:
                        raise StopUser()
                    self.execute_next_task()
                except RescheduleTaskImmediately:
                    pass
                except RescheduleTask:
                    self.wait()
                else:
                    self.wait()
            except InterruptTaskSet as e:
                self.on_stop()
                if e.reschedule:
                    raise RescheduleTaskImmediately(e.reschedule) from e
                else:
                    raise RescheduleTask(e.reschedule) from e
            except (StopUser, GreenletExit):
                self.on_stop()
                raise
            except Exception as e:
                self.user.environment.events.user_error.fire(
                    user_instance=self, exception=e, tb=e.__traceback__)
                if self.user.environment.catch_exceptions:
                    logger.error("%s\n%s", e, traceback.format_exc())
                    self.wait()
                else:
                    raise
Esempio n. 15
0
    def login(self, email, password):
        url = "/api/v1/login"
        headers = {'Content-Type': "application/json"}
        body = {
            "email": email,
            "password": password,
        }
        response = self.post(url, body, headers)

        if response.status_code != 200:
            print(
                f'StopUser: Login Request Failed: {url}, {email}, {response.status_code}, {response.text}'
            )
            raise StopUser()

        token = response.json()["token"]
        self.default_headers = {
            'Content-Type': "application/json",
            "Authorization": "Bearer " + token
        }
Esempio n. 16
0
    def reserve_tickets(self, tickets):
        # Make sure we have a clean session
        self.client.cookies.clear()

        self.client.get("/")

        resp = self.client.get("/tickets")

        html = lxml.html.fromstring(resp.content)
        form = html.get_element_by_id("choose_tickets")
        amounts = {
            i.label.text_content(): i.name
            for i in form.inputs if i.name.endswith("-amount")
        }

        data = dict(**form.fields)
        for display_name, count in tickets.items():
            data[amounts[display_name]] = count

        self.client.post("/tickets", data)

        raise StopUser()
 def index_page(self):
     # self.client.get("/")
     from selenium import webdriver
     from selenium.webdriver.common.keys import Keys
     from selenium.webdriver.common.by import By
     from selenium.webdriver.support.ui import WebDriverWait
     from selenium.webdriver.support import expected_conditions as EC
     
     options = webdriver.ChromeOptions()
     options.add_argument('window-size=1200x600')
     options.add_argument('headless')
     options.add_argument("no-sandbox")
     driver = webdriver.Chrome(options=options)
     driver.get('http://65.0.168.78:8000')
     element = WebDriverWait(driver, 20).until(
         EC.presence_of_element_located((By.CLASS_NAME, "terminal"))
     )
     terminal = driver.find_element_by_xpath("//div[@class='terminal']")
     terminal.send_keys('ls' + Keys.ENTER)
     terminal.send_keys('touch file.txt' + Keys.ENTER)
     terminal.send_keys('git clone https://github.com/vedavidhbudimuri/ib-mini-projects' + Keys.ENTER)
     terminal.send_keys('cat file.txt' + Keys.ENTER)
     raise StopUser()    
Esempio n. 18
0
 def subtask(self):
     state[0] = 1
     raise StopUser()
Esempio n. 19
0
 def request(self, exception, **_kwargs):
     if exception:
         raise StopUser()
Esempio n. 20
0
 def t(self):
     self.test_state = 1
     sleep(0.1)
     raise StopUser()
Esempio n. 21
0
 def t2(self):
     self.t2_executed = True
     raise StopUser()
Esempio n. 22
0
 def t(self):
     log.append(0)
     self.wait()
     log.append(1)
     raise StopUser()
Esempio n. 23
0
 def overwrite_user(self):
     try:
         self.user = "******"
     except AttributeError:
         MyTaskSet.raised_attribute_error = True
     raise StopUser()
Esempio n. 24
0
 def stop(self):
     raise StopUser()
Esempio n. 25
0
 def _check_stop_condition(self):
     if self.user._state == LOCUST_STATE_STOPPING:
         raise StopUser()
Esempio n. 26
0
 def t1(self):
     v[0] = 1
     raise StopUser()
Esempio n. 27
0
 def will_stop(self):
     raise StopUser()
 def stop(self):
     self.interrupt(False)
     raise StopUser()
Esempio n. 29
0
 def request_failure(self, request_type, name, response_time,
                     response_length, exception, **_kwargs):
     raise StopUser()
Esempio n. 30
0
 def t(self):
     self.client.get("/")
     raise StopUser()