Ejemplo n.º 1
0
 def _try_get_state(  # pylint: disable=unused-argument
         self, callable_name: str, *args: Any,
         **kwargs: Any) -> Optional[JSONLike]:
     """Try to call a function on the ledger API."""
     result: Optional[JSONLike] = None
     query = "/".join(args)
     url = self.network_address + f"/{callable_name}/{query}"
     response = requests.get(url=url)
     if response.status_code == 200:
         result = response.json()
     return result
Ejemplo n.º 2
0
    def test_echo(self):
        """Run the echo skill sequence."""
        self.add_item("connection", "fetchai/http_server:0.16.0")
        self.add_item("skill", "fetchai/http_echo:0.14.0")
        self.set_config("agent.default_connection",
                        "fetchai/http_server:0.16.0")
        self.set_config(
            "vendor.fetchai.connections.http_server.config.api_spec_path",
            API_SPEC_PATH)
        self.run_install()

        process = self.run_agent()
        is_running = self.is_running(process)
        assert is_running, "AEA not running within timeout!"

        # add sending and receiving envelope from input/output files

        response = requests.get("http://127.0.0.1:8000")
        assert response.status_code == 404, "Failed to receive not found"
        # we receive a not found since the path is not available in the api spec

        response = requests.get("http://127.0.0.1:8000/pets")
        assert response.status_code == 200, "Failed to receive ok"
        assert (response.content == b'{"tom": {"type": "cat", "age": 10}}'
                ), "Wrong body on get"

        response = requests.post("http://127.0.0.1:8000/pets")
        assert response.status_code == 200
        assert response.content == b"", "Wrong body on post"

        check_strings = (
            "received http request with method=get, url=http://127.0.0.1:8000/pets and body=b''",
            "received http request with method=post, url=http://127.0.0.1:8000/pets and body=b''",
        )
        missing_strings = self.missing_from_output(process, check_strings)
        assert (
            missing_strings == []
        ), "Strings {} didn't appear in agent output.".format(missing_strings)

        assert (self.is_successfully_terminated()
                ), "Http echo agent wasn't successfully terminated."
Ejemplo n.º 3
0
 def _try_get_balance(self, address: Address) -> Optional[int]:
     """Try get the balance of a given account."""
     balance = None  # type: Optional[int]
     url = self.network_address + f"/bank/balances/{address}"
     response = requests.get(url=url)
     if response.status_code == 200:
         result = response.json()["result"]
         if len(result) == 0:
             balance = 0
         else:
             balance = int(result[0]["amount"])
     return balance
Ejemplo n.º 4
0
    def _try_get_transaction_receipt(self,
                                     tx_digest: str) -> Optional[JSONLike]:
        """
        Try get the transaction receipt for a transaction digest.

        :param tx_digest: the digest associated to the transaction.
        :return: the tx receipt, if present
        """
        result: Optional[JSONLike] = None
        url = self.network_address + f"/txs/{tx_digest}"
        response = requests.get(url=url)
        if response.status_code == 200:
            result = response.json()
        return result
Ejemplo n.º 5
0
    def _try_get_account_number_and_sequence(
            self, address: Address) -> Tuple[Optional[int], Optional[int]]:
        """
        Try get account number and sequence for an address.

        :param address: the address
        :return: a tuple of account number and sequence
        """
        result: Tuple[Optional[int], Optional[int]] = (None, None)
        url = self.network_address + f"/auth/accounts/{address}"
        response = requests.get(url=url)
        if response.status_code == 200:
            result = (
                int(response.json()["result"]["value"]["account_number"]),
                int(response.json()["result"]["value"]["sequence"]),
            )
        return result
Ejemplo n.º 6
0
def download_file(url: str, cwd: str, timeout: float = FILE_DOWNLOAD_TIMEOUT) -> str:
    """
    Download file from URL and save it in CWD (current working directory).

    :param url: str url of the file to download.
    :param cwd: str path to current working directory.
    :param timeout: float. timeout to download a file

    :return: str path to downloaded file
    """
    local_filename = url.split("/")[-1]
    filepath = os.path.join(cwd, local_filename)
    # NOTE the stream=True parameter below
    response = requests.get(url, stream=True, timeout=timeout)
    if response.status_code == 200:
        with open(filepath, "wb") as f:
            f.write(response.raw.read())
    else:
        raise click.ClickException(
            "Wrong response from server when downloading package."
        )
    return filepath
Ejemplo n.º 7
0
    def _try_check_faucet_claim(
            cls,
            uid: str,
            url: Optional[str] = None) -> Optional[CosmosFaucetStatus]:
        """
        Check the status of a faucet request

        :param uid: The request uid to be checked
        :param url: the url
        :return: None on failure otherwise a CosmosFaucetStatus for the specified uid
        """
        response = requests.get(cls._faucet_status_uri(uid, url))
        if response.status_code != 200:  # pragma: nocover
            _default_logger.warning("Response: {}, Text: {}".format(
                response.status_code, response.text))
            return None

        # parse the response
        data = response.json()
        return CosmosFaucetStatus(
            tx_digest=data.get("txDigest"),
            status=data["status"],
            status_code=data["statusCode"],
        )
Ejemplo n.º 8
0
    def _try_get_wealth(address: Address, url: Optional[str] = None) -> None:
        """
        Get wealth from the faucet for the provided address.

        :param address: the address.
        :param url: the url
        :return: None
        """
        if url is None:
            raise ValueError(
                "Url is none, no default url provided. Please provide a faucet url."
            )
        response = requests.get(url + address)
        if response.status_code // 100 == 5:
            _default_logger.error("Response: {}".format(response.status_code))
        elif response.status_code // 100 in [3, 4]:  # pragma: nocover
            response_dict = json.loads(response.text)
            _default_logger.warning("Response: {}\nMessage: {}".format(
                response.status_code, response_dict.get("message")))
        elif response.status_code // 100 == 2:
            response_dict = json.loads(response.text)
            _default_logger.info("Response: {}\nMessage: {}".format(
                response.status_code,
                response_dict.get("message")))  # pragma: no cover
Ejemplo n.º 9
0
    def test_coin_price(self):
        """Run the coin price skill sequence."""

        coin_price_feed_aea_name = self.agent_name

        self.add_item("connection", "fetchai/http_client:0.17.0")
        self.add_item("connection", "fetchai/http_server:0.16.0")
        self.add_item("connection", "fetchai/prometheus:0.3.0")
        self.add_item("skill", "fetchai/coin_price:0.5.0")
        self.set_config("agent.default_connection",
                        "fetchai/http_server:0.16.0")

        default_routing = {
            "fetchai/http:0.12.0": "fetchai/http_client:0.17.0",
            "fetchai/prometheus:0.3.0": "fetchai/prometheus:0.3.0",
        }
        setting_path = "agent.default_routing"
        self.nested_set_config(setting_path, default_routing)

        self.set_config(
            "vendor.fetchai.connections.http_server.config.api_spec_path",
            API_SPEC_PATH)
        self.set_config(
            "vendor.fetchai.skills.coin_price.models.coin_price_model.args.use_http_server",
            True,
            type_="bool",
        )

        diff = self.difference_to_fetched_agent(
            "fetchai/coin_price_feed:0.6.0", coin_price_feed_aea_name)
        assert (
            diff == []
        ), "Difference between created and fetched project for files={}".format(
            diff)

        self.run_install()

        process = self.run_agent()
        is_running = self.is_running(process)
        assert is_running, "AEA not running within timeout!"

        time.sleep(
            6)  # we wait a bit longer than the tick rate of the behaviour

        response = requests.get("http://127.0.0.1:8000/price")
        assert response.status_code == 200, "Failed to get response code 200"
        coin_price = response.content.decode("utf-8")
        assert "value" in coin_price, "Response does not contain 'value'"
        assert "decimals" in coin_price, "Response does not contain 'decimals'"

        response = requests.get("http://127.0.0.1:8000")
        assert response.status_code == 404
        assert response.content == b"", "Get request should not work without valid path"

        response = requests.post("http://127.0.0.1:8000/price")
        assert response.status_code == 404
        assert response.content == b"", "Post not allowed"

        # test prometheus metrics
        prom_response = requests.get("http://127.0.0.1:9090/metrics")
        metrics = parse_prometheus_output(prom_response.content)
        assert metrics[
            "num_retrievals"] > 0.0, "num_retrievals metric not updated"
        assert metrics[
            "num_requests"] == 1.0, "num_requests metric not equal to 1"

        self.terminate_agents()
        assert (self.is_successfully_terminated()
                ), "Http echo agent wasn't successfully terminated."