示例#1
0
 def test_length_convert(self):
     logging.debug("testing length convert")
     result = Length.convert(1800, "meter", "mile")
     self.assertIsNotNone(result)
     return
示例#2
0
    def get(self, to_unit):
        """REST GET implementation for the URI:

        http://<server>:<port>/length/<to_unit>?from_unit=<from_unit>&
            from_value=<from_value>

        Parameters
        ----------
        to_unit:  str (required)
            length unit (required)

        It is assumed that this method is called within the context of an HTTP
        request.  And that the HTTP request contains query parameters
        with the request.args as containing the following:

        from_unit: str (required)
            length unit
        from_value: str (required)
            numeric value

        Returns
        -------
        str:
            A JSON string containing the response

        Raises
        ------
        BadRequest if there is an error validating the input parameters or
        some other error processing this method.
        """
        params = request.args
        if not params:
            raise BadRequest("Parameters "
                             "from_unit=<from_unit>&from_value=<_from_value> "
                             "are missing")

        if not isinstance(params, dict):
            raise BadRequest("params must be an instance of dict")

        if "from_unit" not in params:
            raise BadRequest("Missing required from_unit parameter")

        if "from_value" not in params:
            raise BadRequest("Missing required from_value parameter")

        from_unit = params.get("from_unit")

        from_value = params.get("from_value")
        if not is_number(from_value):
            raise BadRequest(("Parameter from_value=[{0}] not valid. "
                              "A numeric value must be provided.")
                             .format(from_value))

        from_value = float(from_value)

        if from_unit == to_unit:
            raise BadRequest("from_unit=[{0}] and to_unit=[{1}] units "
                             "cannot be equal".format(from_unit, to_unit))

        # pint unit registry only accepts lower case letters for length units
        from_unit = from_unit.lower().strip()
        to_unit = to_unit.lower().strip()

        result = Length.convert(from_value, from_unit, to_unit)

        data = OrderedDict()
        data["from_unit"] = from_unit
        data["from_value"] = from_value
        data["to_unit"] = to_unit
        data["to_value"] = result

        response = OrderedDict()
        response[STATUS_KEY] = STATUS_SUCCESS
        response[DATA_KEY] = data

        json_result = jsonify(response)
        return json_result