Пример #1
0
    def test_if_enabled(self):
        """Test if spinner is enabled
        """
        spinner = Halo(text="foo", enabled=False, stream=self._stream)
        spinner.start()
        time.sleep(1)
        spinner.clear()
        spinner.fail()

        output = self._get_test_output()['text']
        self.assertEqual(len(output), 0)
        self.assertEqual(output, [])
Пример #2
0
 def search(self, time_now=datetime.now()):
     """
     This method takes datetime object and searches all the Food trucks that are open at the time that is passed
     as argument. If no value is passed then it takes the current time as default.
     :param time_now: Python datetime object. Default value is current time
     :return: None
     """
     # getting day of the week. this is used to filter the 'dayorder' field in Socrata data
     current_day_order = time_now.isoweekday()
     # formatting time stamp into HH:MM format. this will be used as a filter out food trucks whose start and end
     # time do not contain current timestamp
     time_str = "'{}'".format(time_now.strftime('%H:%M'))
     self.display_message("\nTime is: {}".format(time_now.strftime("%c")))
     try:
         # initialize Halo spinner object to display spinner in console while we fetch data from the SODA API
         spinner = Halo()
         spinner.start("Finding food trucks for you...")
         # here the query is selecting 'applicant', 'location', 'start24', 'end24', 'dayorder', 'dayofweekstr' only
         # it is also filtering the result where 'start24' of the food truck data is less than the current time and
         # 'end24' is greater than equal to current time (start24 <= time_str <= end24). It is also filtering the
         # result by the day of the week by specifying dayorder=current_day_order. And finally it orders the result
         # in ascending order of 'applicant' field which is the name of the Food Truck. I am assuming the 'applicant'
         # field is the name of the Food Truck
         socrata_data = self.api_service.select([
             'applicant', 'location', 'start24', 'end24', 'dayorder',
             'dayofweekstr'
         ]).where(start24__lte=time_str,
                  end24__gte=time_str,
                  dayorder=current_day_order).order_by('applicant').query(
                      self.socrata_dataset_id)
         # stop and clear the spinner from the console to clean it up before printing the final output
         spinner.stop()
         spinner.clear()
         # parse and convert the response JSON into a List of SocrataData model object
         socrata_data_list = parse_obj_as(List[SocrataData], socrata_data)
         # for some Food trucks, there are multiple entries in the result because of different timings in the day
         # I only need any one out of these. As we are getting already filtered result that fit our criteria from the
         # API, I can sure that all these entries are valid. To remove duplicate I am using a python dictionary where
         # the key is a unique combination of 'applicant' and 'location' field. I am using a dictionary instead of
         # hash set because I want maintain the insertion order of the already sorted result. In Python3, sets don't
         # guarantee insertion order but by default a dictionary is ordered in Python 3.
         for data in socrata_data_list:
             self.foodtruck_dataset[(data.applicant, data.location)] = data
         self.total_foodtrucks_open = len(self.foodtruck_dataset)
         # Once I have the dictionary of the dataset, I am updating the PrettyTable rows with the data
         self.__update_ptable()
     except requests.exceptions.HTTPError as ex:
         logging.error(str(ex))
     except:
         traceback.print_exc()
         logging.error(
             "unhandled exception occurred while searching food trucks")
Пример #3
0
    def test_if_enabled(self):
        """Test if spinner is enabled
        """
        stdout_ = sys.stdout
        sys.stdout = self._stream
        spinner = Halo(text="foo", enabled=False)
        spinner.start()
        time.sleep(1)
        spinner.clear()
        spinner.stop()
        sys.stdout = stdout_

        output = self._get_test_output()
        self.assertEqual(len(output), 0)
        self.assertEqual(output, [])
Пример #4
0
    def _run_test(cls, test_dict: dict):
        """
        A generic method handling the run of both disruptive and non
        disruptive tests.
        """

        spinner = Halo(spinner='dots', text_color='yellow')
        tc_class = test_dict["testClass"]
        volume_type = test_dict["volType"]
        mname = test_dict["moduleName"][:-3]

        tc_log_path = (f"{cls.base_log_path+test_dict['modulePath'][5:-3]}/"
                       f"{volume_type}/{mname}.log")

        # to calculate time spent to execute the test
        start = time.time()

        spinner.succeed(text=f"Running test case : {mname}-{volume_type}")
        runner_thread_obj = RunnerThread(tc_class, cls.param_obj, volume_type,
                                         mname, cls.logger, cls.env_obj,
                                         tc_log_path, cls.log_level)

        test_stats = runner_thread_obj.run_thread()

        test_stats['timeTaken'] = time.time() - start
        test_stats['tcNature'] = test_dict['tcNature']
        spinner.clear()
        result_text = f"{test_dict['moduleName'][:-3]}-{test_dict['volType']}"
        if test_stats['testResult'][0] is True:
            test_stats['testResult'] = "PASS"
            result_text += " PASS"
            spinner = Halo(spinner='dots', text_color='green')
            spinner.succeed(text=f"{mname}-{volume_type} Succeeded")
        elif test_stats['testResult'][0] is False:
            result_text += " FAIL"
            test_stats['testResult'] = "FAIL"
            spinner = Halo(spinner='dots', text_color='red')
            spinner.fail(f"{mname}-{volume_type} Failed")
        else:
            result_text += " SKIP"
            test_stats['testResult'] = "SKIP"
            spinner = Halo(spinner='dots', text_color='cyan')
            spinner.info(f"{mname}-{volume_type} SKIP")
        test_stats['component'] = tc_log_path.split('/')[-4]

        result_value = {test_dict["moduleName"][:-3]: test_stats}
        cls.job_result_queue.put(result_value)