Ejemplo n.º 1
0
    def get_machine_logo(self, machine_uuid):
        if self.silo.get_setting('get_machine_logo_error'):
            raise APIError(self._exception_msg)

        logo_path = os.path.join(WEBCATALOG_SILO_DIR, "%s.png" % machine_uuid)
        if not os.path.exists(logo_path):
            raise APIError("No logo found")
        with open(logo_path) as fp:
            return fp.read()
Ejemplo n.º 2
0
    def list_packages(self, machine_uuid):
        if self.silo.get_setting('list_packages_error'):
            raise APIError(self._exception_msg)

        packages = self.silo.get_package_silo()
        if machine_uuid not in packages:
            raise APIError('Package list empty')
        package_list = packages[machine_uuid]
        if not package_list:
            raise APIError('Package list empty')
        return json.dumps(package_list)
Ejemplo n.º 3
0
 def list_packages(self, machine_uuid):
     """List all packages for that machine"""
     package_list = self._get('packages/%s/' % machine_uuid, scheme=AUTHENTICATED_API_SCHEME)
     if not package_list:
         raise APIError('Package list empty')
     # FIXME: need to do this hack to transform the http request to a json format content
     try:
         package_list = json.loads(package_list[1:-1].replace("'", '"').replace("True", "true").replace("False", 'false'))
     except ValueError as e:
         raise APIError('Package list invalid: %s' % e)
     return package_list
Ejemplo n.º 4
0
 def list_packages(self, machine_uuid):
     """List all packages for that machine"""
     package_list = self._get('packages/%s/' % machine_uuid,
                              scheme=AUTHENTICATED_API_SCHEME)
     if not package_list:
         raise APIError('Package list empty')
     # FIXME: need to do this hack to transform the http request to a json format content
     try:
         package_list = ast.literal_eval(package_list[1:-1])
     except ValueError as e:
         raise APIError('Package list invalid: %s' % e)
     return package_list
Ejemplo n.º 5
0
    def update_machine_logo(self, machine_uuid, logo_checksum, logo_content):
        if self.silo.get_setting('update_machine_logo_error'):
            raise APIError(self._exception_msg)

        if not self.machineuuid_exist(machine_uuid):
            raise APIError('Host Not Found')
        image_path = os.path.join(WEBCATALOG_SILO_DIR, '%s.png' % machine_uuid)
        with open(image_path, 'wb+') as image_on_disk:
            image_on_disk.write(logo_content)
        hosts = self.silo.get_host_silo()
        hosts[machine_uuid]['logo_checksum'] = logo_checksum
        self.silo.save_settings(WEBCATALOG_SILO_RESULT)
        return json.dumps('Success')
Ejemplo n.º 6
0
    def update_packages(self, machine_uuid, packages_checksum, package_list):
        if self.silo.get_setting('update_packages_error'):
            raise APIError(self._exception_msg)

        if not self.machineuuid_exist(machine_uuid):
            raise APIError('Host Not Found')

        packages = self.silo.get_package_silo()
        packages[machine_uuid] = package_list
        hosts = self.silo.get_host_silo()
        hosts[machine_uuid]['packages_checksum'] = packages_checksum
        self.silo.save_settings(WEBCATALOG_SILO_RESULT)
        return json.dumps('Success')
    def submit_review(self, review):
        if self._fake_settings.get_setting('submit_review_error'):
            raise APIError(self._exception_msg)

        user = self._fake_settings.get_setting(
            'reviewer_username') or random.choice(self._USERS)
        review_id = self._fake_settings.get_setting(
            'submit_review_id') or random.randint(1, 10000)
        r = {
            "origin": review.origin,
            "rating": review.rating,
            "hide": False,
            "app_name": review.app_name,
            "language": review.language,
            "reviewer_username": user,
            "usefulness_total": 0,
            "usefulness_favorable": 0,
            "review_text": review.review_text,
            "date_deleted": None,
            "summary": review.summary,
            "version": review.version,
            "id": review_id,
            "date_created": time.strftime("%Y-%m-%d %H:%M:%S"),
            "reviewer_displayname": "Fake User",
            "package_name": review.package_name,
            "distroseries": review.distroseries
        }
        return json.dumps(r)
Ejemplo n.º 8
0
    def flag_review(self, review_id, reason, text):
        if self._fake_settings.get_setting('flag_review_error'):
            raise APIError(self._exception_msg)

        mod_id = random.randint(1, 500)
        pkg = self._fake_settings.get_setting(
            'flag_package_name') or random.choice(self._PACKAGE_NAMES)
        username = self._fake_settings.get_setting(
            'flagger_username') or random.choice(self._USERS)

        f = {
            "user_id": random.randint(1, 500),
            "description": text,
            "review_moderation_id": mod_id,
            "_user_cache": self._make_user_cache(username),
            "summary": reason,
            "_review_moderation_cache": {
                "status": 0,
                "review_id": review_id,
                "_review_cache": self._make_fake_reviews(packagename=pkg,
                                                         single_id=review_id),
                "moderation_text": text,
                "date_moderated": None,
                "moderator_id": None,
                "date_created": time.strftime("%Y-%m-%d %H:%M:%S"),
                "id": mod_id
            },
            "date_created": time.strftime("%Y-%m-%d %H:%M:%S"),
            "id": mod_id
        }

        return json.dumps(f)
    def review_stats(self,
                     origin='any',
                     distroseries='any',
                     days=None,
                     valid_days=(1, 3, 7)):
        if self._fake_settings.get_setting('review_stats_error'):
            raise APIError(self._exception_msg)

        if self._fake_settings.get_setting('packages_returned') > 15:
            quantity = 15
        else:
            quantity = self._fake_settings.get_setting('packages_returned')

        stats = []

        for i in range(0, quantity):
            s = {
                'app_name': '',
                'package_name': self._PACKAGE_NAMES[i],
                'ratings_total': str(random.randrange(1, 200)),
                'ratings_average': str(random.randrange(0, 5))
            }
            stats.append(s)

        return json.dumps(stats)
Ejemplo n.º 10
0
 def list_machines(self):
     if self.silo.get_setting('list_machines_error'):
         raise APIError(self._exception_msg)
     dict_of_hosts = self.silo.get_setting('hosts_metadata')
     # the server is returning a list
     result = []
     for hostid in dict_of_hosts:
         machine = dict_of_hosts[hostid]
         machine['uuid'] = hostid
         result.append(machine)
     return result
Ejemplo n.º 11
0
    def delete_machine(self, machine_uuid):
        if self.silo.get_setting('delete_machine_error'):
            raise APIError(self._exception_msg)

        # delete the host if exist from the entry
        hosts = self.silo.get_host_silo()
        packages = self.silo.get_package_silo()
        try:
            del (packages[machine_uuid])
        except KeyError:
            pass  # there was no package list
        logo_path = os.path.join(WEBCATALOG_SILO_DIR, "%s.png" % machine_uuid)
        try:
            os.remove(logo_path)
        except OSError:
            pass  # there was no logo
        if not self.machineuuid_exist(machine_uuid):
            raise APIError('Host Not Found')
        del hosts[machine_uuid]
        self.silo.save_settings(WEBCATALOG_SILO_RESULT)
        return json.dumps('Success')
Ejemplo n.º 12
0
def _parse_json(json_data):
    """Return a Python data structure corresponding to ``json_data``.

    Use this rather than ``json.loads`` directly to get a richer error message
    when JSON data cannot be decoded.

    :param json_data: A string containing JSON data.
    :raises ValueError: If the JSON data could not be parsed.
    :return: A Python data structure.
    """
    try:
        return json.loads(json_data)
    except ValueError:
        raise APIError('No JSON object could be decoded', body=json_data)
    def get_usefulness(self, review_id=None, username=None):
        if not username and not review_id:
            return None

        if self._fake_settings.get_setting('get_usefulness_error'):
            raise APIError(self._exception_msg)

        #just return a single fake item if the review_id was supplied
        if review_id:
            if username:
                response_user = username
            else:
                response_user = random.choice(self._USERS)

            response = {
                'username': response_user,
                'useful': random.choice(['True', 'False']),
                'review_id': review_id
            }
            return json.dumps([response])

        #set up review ids to honour requested and also add randoms
        quantity = self._fake_settings.get_setting('votes_returned')
        id_list = self._fake_settings.get_setting('required_review_ids')
        id_quantity = len(id_list)

        #figure out if we need to accomodate requested review ids
        if id_quantity == 0:
            rand_id_start = 0
        else:
            rand_id_start = max(id_list)

        votes = []

        for i in range(0, quantity):
            #assign review ids requested if any still exist
            try:
                id = id_list[i]
            except IndexError:
                id = random.randint(rand_id_start, 10000)

            u = {
                'username': username,
                'useful': random.choice(['True', 'False']),
                'review_id': id
            }
            votes.append(u)

        return json.dumps(votes)
Ejemplo n.º 14
0
    def update_machine(self, machine_uuid, hostname):
        if self.silo.get_setting('update_machine_error'):
            raise APIError(self._exception_msg)

        # update our content dictionnary with new data or creating a new entry
        hosts = self.silo.get_host_silo()
        if self.machineuuid_exist(machine_uuid):
            hosts[machine_uuid]['hostname'] = hostname
        else:
            hosts[machine_uuid] = {
                'hostname': hostname,
                'logo_checksum': None,
                'packages_checksum': None,
            }
        self.silo.save_settings(WEBCATALOG_SILO_RESULT)
        return json.dumps('Success')
Ejemplo n.º 15
0
    def get_reviews(self, packagename, language='any', origin='any',
                    distroseries='any', version='any', appname='',
                    page=1, sort='helpful'):

        # work out how many reviews to return for pagination
        if page <= self._fake_settings.get_setting('review_pages'):
            num_reviews = 10
        elif page == self._fake_settings.get_setting('review_pages') + 1:
            num_reviews = self._fake_settings.get_setting('reviews_returned')
        else:
            num_reviews = 0

        if self._fake_settings.get_setting('get_reviews_error'):
            raise APIError(self._exception_msg)

        reviews = self._make_fake_reviews(packagename, num_reviews)
        return json.dumps(reviews)
Ejemplo n.º 16
0
    def request_url(self, url, method, body='', headers=None):
        """Perform an HTTP request.

        You probably want to call one of the ``get``, ``post``, ``put``
        methods instead.
        """
        if headers is None:
            headers = {}

        # in offline mode either get it from the cache or return None
        if self._offline_mode:
            if method in ('POST', 'PUT'):
                err = "method '%s' not allowed in offline-mode" % method
                raise OfflineModeException(err)
            return self._get_from_cache(url)

        scheme = urlparse(url).scheme

        if self._auth:
            self._auth.sign_request(url, method, body, headers)
        if self._log_filename:
            self._dump_request(url, method, body, headers)
        try:
            response, response_body = self._http[scheme].request(
                url, method=method, body=body, headers=headers)
        except AttributeError as e:
            # Special case out httplib2's way of telling us unable to connect
            if e.args[0] == "'NoneType' object has no attribute 'makefile'":
                raise APIError('Unable to connect to %s' % (url, ))
            else:
                raise
        except socket.timeout as e:
            raise TimeoutError('Timed out attempting to connect to %s' %
                               (url, ))
        except socket.error as e:
            msg = 'connecting to %s: %s' % (url, e.strerror)
            raise SocketError(msg)
        if self._log_filename:
            self._dump_response(response, response_body)
        handler = self._fail_handler(url, method, body, headers)
        body = handler.handle(response, response_body)
        return body
Ejemplo n.º 17
0
 def server_status(self):
     if self.silo.get_setting('server_response_error'):
         raise APIError(self._exception_msg)
     return json.dumps('ok')
 def get_review(self, review_id):
     if self._fake_settings.get_setting('get_review_error'):
         raise APIError(self._exception_msg)
     review = self._make_fake_reviews(single_id=review_id)
     return json.dumps(review)
 def submit_usefulness(self, review_id, useful):
     if self._fake_settings.get_setting('submit_usefulness_error'):
         raise APIError(self._exception_msg)
     return json.dumps(
         self._fake_settings.get_setting('usefulness_response_string'))