Пример #1
0
 def test_refresh_access_token_raises(self, monkeypatch):
     """Test that an error is raised when the access token could not be
     generated while creating the Connection object."""
     monkeypatch.setattr(requests, "post", mock_return(MockResponse(500, {})))
     conn = Connection(token=test_token, host=test_host)
     with pytest.raises(RequestFailedError, match="Could not retrieve access token"):
         conn._refresh_access_token()
Пример #2
0
    def test_init(self):
        """Tests that a ``Connection`` is initialized correctly."""
        token, host, port, use_ssl = "token", "host", 123, True
        connection = Connection(token, host, port, use_ssl)

        assert connection.token == token
        assert connection.host == host
        assert connection.port == port
        assert connection.use_ssl == use_ssl

        # pylint: disable=protected-access
        assert connection._url("/abc") == "https://host:123/abc"
Пример #3
0
    def test_configuration_deleted_integration(self, monkeypatch, tmpdir):
        """Check that once two Connection instances indeed differ in their
        configuration if the configuration is being deleted in the meantime.

        The logic of the test goes as follows:
        1. Two temporary paths and files are being created
        2. The directories to be checked are mocked out to the temporary paths
        3. A connection object is created, using the configuration from the
        first config
        4. The first configuration is deleted, leaving the second config as
        default
        5. Another connection object is created, using the configuration from the
        second config
        6. Checks for the configuration for each Connection instances
        """
        test_file_name = "config.toml"

        # Creating the two temporary paths and files
        path1 = tmpdir.mkdir("sub1")
        path2 = tmpdir.mkdir("sub2")

        file1 = path1.join(test_file_name)
        file2 = path2.join(test_file_name)

        with open(file1, "w") as f:
            f.write(TEST_CONFIG_FILE_1)

        with open(file2, "w") as f:
            f.write(TEST_CONFIG_FILE_2)

        with monkeypatch.context() as m:
            m.setattr(os, "getcwd", lambda: path1)
            m.delenv("SF_CONF", raising=False)
            m.setattr(conf, "user_config_dir", lambda *args: path2)

            a = Connection()
            assert os.path.exists(file1)

            assert a.token == "DummyToken"
            assert a.host == "DummyHost"
            assert a.port == 1234
            assert a.use_ssl == False
            conf.delete_config(directory=path1)

            assert not os.path.exists(file1)

            b = Connection()
            assert b.token == "071cdcce-9241-4965-93af-4a4dbc739135"
            assert b.host == "platform.strawberryfields.ai"
            assert b.port == 443
            assert b.use_ssl == True
Пример #4
0
    def test_wrapped_request_refreshes(self, mocker, monkeypatch):
        """Test that the _request method refreshes the access token when
        getting a 401 response."""
        # Mock post function used while refreshing
        monkeypatch.setattr(requests, "post", mock_return(MockResponse(200, {})))

        # Mock request function used for general requests
        monkeypatch.setattr(requests, "request", mock_return(MockResponse(401, {})))

        conn = Connection(token=test_token, host=test_host)

        spy = mocker.spy(conn, "_refresh_access_token")
        conn._request("SomeRequestMethod", "SomePath")
        spy.assert_called_once_with()
Пример #5
0
def ping():
    """Tests the connection to the remote backend."""
    if Connection().ping():
        sys.stdout.write(
            "You have successfully authenticated to the platform!\n")
    else:
        sys.stdout.write(
            "There was a problem when authenticating to the platform!\n")
Пример #6
0
 def __init__(self,
              target: str,
              connection: Connection = None,
              backend_options: dict = None):
     self._target = self.DEFAULT_TARGETS.get(target, target)
     self._spec = None
     self._connection = connection or Connection()
     self._backend_options = backend_options or {}
     self.log = create_logger(__name__)
Пример #7
0
    def test_refresh_access_token(self, mocker, monkeypatch):
        """Test that the access token is created by passing the expected headers."""
        path = "/auth/realms/platform/protocol/openid-connect/token"

        data={
            "grant_type": "refresh_token",
            "refresh_token": test_token,
            "client_id": "public",
        }

        monkeypatch.setattr(requests, "post", mock_return(MockResponse(200, {})))
        spy = mocker.spy(requests, "post")

        conn = Connection(token=test_token, host=test_host)
        conn._refresh_access_token()
        expected_headers = {'Accept-Version': conn.api_version}
        expected_url = f"https://{test_host}:443{path}"
        spy.assert_called_once_with(expected_url, headers=expected_headers, data=data)
Пример #8
0
    def __init__(self, target: str, connection: Connection = None, backend_options: dict = None):
        self._target = self.DEFAULT_TARGETS.get(target, target)

        if self._target not in self.VALID_TARGETS:
            raise ValueError(
                "Invalid engine target: {} (valid targets: {})".format(
                    target, tuple(self.DEFAULT_TARGETS.keys()) + self.VALID_TARGETS
                )
            )

        self._connection = connection or Connection()
        self._backend_options = backend_options or {}
        self.log = create_logger(__name__)
Пример #9
0
def connection():
    """A mock connection object."""
    return Connection(token="token", host="host", port=123, use_ssl=True)