Esempio n. 1
0
    def test_ndex2_get_user_agent(self):
        ndex = Ndex2(host='localhost')
        # try with default
        res = ndex._get_user_agent()
        self.assertEqual(res, 'NDEx2-Python/' + __version__)

        ndex = Ndex2(host='localhost', user_agent='hi')
        # try with user_agent set
        res = ndex._get_user_agent()
        self.assertEqual(res, 'NDEx2-Python/' + __version__ + ' hi')
Esempio n. 2
0
 def _get_client(self, server, user, password, altclient=None):
     """
     Gets Ndex2 client
     :return: Ndex2 python client
     :rtype: :py:class:`~ndex2.client.Ndex2`
     """
     return Ndex2(server, user, password)
Esempio n. 3
0
 def get_ndex2_client(self):
     creds = self.get_ndex_credentials_as_tuple()
     return Ndex2(creds['server'],
                  creds['user'],
                  creds['password'],
                  debug=True,
                  user_agent=creds['user_agent'])
Esempio n. 4
0
    def __init__(self, uri="http://public.ndexbio.org"):

        ndex_creds = os.path.expanduser("~/.ndex")
        if os.path.exists(ndex_creds):
            with open(ndex_creds, "r") as stream:
                ndex_creds_obj = json.loads(stream.read())
                print(f"connecting to ndex as {ndex_creds_obj['username']}")
                account = ndex_creds_obj['username']
                password = ndex_creds_obj['password']
        else:
            raise ValueError("No ndex credentials found.")

        self.uri = uri
        self.session = None
        self.account = account
        self.password = password
        try:
            self.session = Ndex2(uri, account, password)
            self.session.update_status()
            networks = self.session.status.get("networkCount")
            users = self.session.status.get("userCount")
            groups = self.session.status.get("groupCount")
            print(
                f"session: networks: {networks} users: {users} groups: {groups}"
            )
        except Exception as inst:
            print(f"Could not access account {account}")
            raise inst
Esempio n. 5
0
 def test_ndex2_put_no_json_empty_resp_code_204(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         m.put(client.DEFAULT_SERVER + '/v2/hi', status_code=204)
         ndex = Ndex2()
         res = ndex.put('/hi')
         self.assertEqual(res, '')
Esempio n. 6
0
 def _create_ndex_connection(self):
     """
     creates connection to ndex
     :return:
     """
     if self._ndex is None:
         self._ndex = Ndex2(host=self._server, username=self._user,
                            password=self._pass, user_agent=self._get_user_agent())
Esempio n. 7
0
 def test_ndex2_require_auth(self):
     ndex = Ndex2(host='localhost')
     try:
         ndex._require_auth()
         self.fail('Expected exception')
     except Exception as e:
         self.assertEqual(str(e),
                          'This method requires user authentication')
Esempio n. 8
0
def create_nice_cx_from_server(server,
                               username=None,
                               password=None,
                               uuid=None,
                               ndex_client=None):
    """
    Create a :py:func:`~ndex2.nice_cx_network.NiceCXNetwork` based on a network
    retrieved from NDEx, specified by its UUID.

    .. versionchanged:: 3.5.0
        Code refactor and **ndex_client** parameter has been added


    If the network is not public, then **username** and **password** arguments
    (or **ndex_client** with username and password set) for an account on
    the server with permission to access the network must be supplied.

    Example usage:

    .. code-block:: python

        import ndex2

        # Download BioGRID: Protein-Protein Interactions (SARS-CoV) from NDEx
        # https://www.ndexbio.org/viewer/networks/669f30a3-cee6-11ea-aaef-0ac135e8bacf
        net_cx = ndex2.create_nice_cx_from_server(None, uuid='669f30a3-cee6-11ea-aaef-0ac135e8bacf')

    .. note::

        If **ndex_client** is not passed in, this function internally creates
        :py:class:`~ndex2.client.Ndex2` using values from parameters passed into
        this function.

    :param server: the URL of the NDEx server hosting the network
    :type server: str
    :param username: the user name of an account with permission to access the network
    :type username: str
    :param password: the password of an account with permission to access the network
    :type password: str
    :param uuid: the UUID of the network
    :type uuid: str
    :param ndex_client: Used as NDEx REST client overriding **server**, **username** and
                        **password** parameters if set
    :type ndex_client: :py:class:`~ndex2.client.Ndex2`
    :raises NDExError: If uuid is not specified
    :return: NiceCXNetwork
    :rtype: :py:func:`~ndex2.nice_cx_network.NiceCXNetwork`
    """
    if uuid is None:
        raise NDExError('uuid not specified')
    if ndex_client is None:
        ndex_client = Ndex2(server,
                            username=username,
                            password=password,
                            skip_version_check=True)
    client_resp = ndex_client.get_network_as_cx_stream(uuid)
    return create_nice_cx_from_raw_cx(json.loads(client_resp.content))
 def _create_ndex_connection(self):
     """
     creates connection to ndex
     """
     if self._ndex is None:
         self._ndex = Ndex2(host=self._server,
                            username=self._user,
                            password=self._pass)
     return self._ndex
Esempio n. 10
0
 def test_save_new_network_invalid_as_cx(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         ndex = Ndex2()
         try:
             ndex.save_new_network('hi')
             self.fail('expected NDExInvalidCXError')
         except NDExInvalidCXError as ice:
             self.assertEqual(str(ice), 'CX is not a list')
Esempio n. 11
0
def get_client(server, username, thepassword):
    """
    Gets Ndex2 python client

    :param server:
    :param username:
    :param thepassword:
    :return:
    """
    return Ndex2(host=server, username=username, password=thepassword)
Esempio n. 12
0
 def test_save_new_network_empty_cx(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         ndex = Ndex2()
         try:
             ndex.save_new_network([])
             self.fail('expected NDExInvalidCXError')
         except NDExInvalidCXError as ice:
             self.assertEqual(str(ice), 'CX appears to be empty')
Esempio n. 13
0
 def test_ndex2_post_multipart_with_querystring(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         m.post(client.DEFAULT_SERVER + '/v2/hi?yo=1',
               request_headers={'Connection': 'close'},
               status_code=200)
         ndex = Ndex2()
         ndex.set_debug_mode(True)
         res = ndex.post_multipart('/hi', {"x": "y"}, query_string='yo=1')
         self.assertEqual(res, '')
Esempio n. 14
0
 def test_ndex2_delete_no_data(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         m.delete(client.DEFAULT_SERVER + '/v2/hi',
               status_code=200,
               json={'hi': 'bye'},
               headers={'Content-Type': 'application/json'})
         ndex = Ndex2()
         ndex.set_debug_mode(True)
         res = ndex.delete('/hi')
         self.assertEqual(res, {'hi': 'bye'})
Esempio n. 15
0
 def test_ndex2_get_with_json_and_json_resp(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         m.get(client.DEFAULT_SERVER + '/v2/hi?x=y',
               status_code=200,
               json={'hi': 'bye'},
               headers={'Content-Type': 'application/json'})
         ndex = Ndex2()
         ndex.set_debug_mode(True)
         res = ndex.get('/hi', get_params={"x": "y"})
         self.assertEqual(res, {'hi': 'bye'})
Esempio n. 16
0
    def __init__(self, server, username, password, **attr):
        self.update_mapping = {}
        self.server = server
        self.username = username
        self.password = password
        self.network = None
        self.ndex = Ndex2(self.server, self.username, self.password)

        networks = self.ndex.get_network_summaries_for_user(self.username)
        for nk in networks:
            if nk.get('name') is not None:
                self.update_mapping[nk.get('name').upper()] = nk.get(
                    'externalId')
Esempio n. 17
0
 def test_ndex2_constructor_with_defaulthost_thatisversiontwo(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         ndex = Ndex2()
         self.assertEqual(ndex.debug, False)
         self.assertEqual(ndex.version, '2.1')
         self.assertEqual(ndex.status, {})
         self.assertEqual(ndex.username, None)
         self.assertEqual(ndex.password, None)
         self.assertEqual(ndex.user_agent, '')
         self.assertEqual(ndex.host, client.DEFAULT_SERVER + '/v2')
         self.assertTrue(ndex.s is not None)
Esempio n. 18
0
 def test_ndex2_constructor_with_defaulthost_thatisversionone(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json={"networkCount": 1321,
                     "userCount": 12,
                     "groupCount": 0,
                     "message": "Online",
                     "properties": {"ServerVersion": "1.1",
                                     "ServerResultLimit": "10000"}})
         try:
             ndex = Ndex2()
             self.fail('Expected exception')
         except Exception as e:
             self.assertEqual(str(e), 'This release only supports NDEx 2.x server.')
Esempio n. 19
0
 def test_ndex2_post_stream_withparams(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         m.post(client.DEFAULT_SERVER + '/v2/hi',
                status_code=200,
                json={'hi': 'bye'},
                request_headers={'Connection': 'close'},
                headers={'Content-Type': 'application/json'})
         ndex = Ndex2()
         ndex.set_debug_mode(True)
         res = ndex.post_stream('/hi', post_json={"x": "y"})
         self.assertEqual(res.json(), {'hi': 'bye'})
         self.assertEqual(res.status_code, 200)
Esempio n. 20
0
 def test_ndex2_constructor_that_raises_httperror(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               text='uhoh',
               reason='some error',
               status_code=404)
         ndex = Ndex2()
         self.assertEqual(ndex.debug, False)
         self.assertEqual(ndex.version, '1.3')
         self.assertEqual(ndex.status, {})
         self.assertEqual(ndex.username, None)
         self.assertEqual(ndex.password, None)
         self.assertEqual(ndex.user_agent, '')
         self.assertEqual(ndex.host, client.DEFAULT_SERVER + '/rest')
         self.assertTrue(ndex.s is not None)
Esempio n. 21
0
    def test_ndex2_constructor_with_localhost(self):

        # this is invasive, but there isn't really a good way
        # to test the constructor
        # try with nothing set
        ndex = Ndex2(host='localhost')
        self.assertEqual(ndex.debug, False)
        self.assertEqual(ndex.version, 1.3)
        self.assertEqual(ndex.status, {})
        self.assertEqual(ndex.username, None)
        self.assertEqual(ndex.password, None)
        self.assertEqual(ndex.user_agent, '')
        self.assertEqual(ndex.host, 'http://localhost:8080/ndexbio-rest')
        self.assertTrue(ndex.s is not None)
        self.assertTrue(ndex.timeout, 30)
        ndex.set_request_timeout(10)
        self.assertTrue(ndex.timeout, 30)

        # try with user, pass and user_agent set oh and host
        # with extra text prepended to localhost
        ndex = Ndex2(host='xxxlocalhost', username='******',
                     password='******', user_agent='yo', debug=True,
                     timeout=1)
        self.assertEqual(ndex.debug, True)
        self.assertEqual(ndex.version, 1.3)
        self.assertEqual(ndex.status, {})
        self.assertEqual(ndex.username, 'bob')
        self.assertEqual(ndex.password, 'smith')
        self.assertEqual(ndex.user_agent, ' yo')
        self.assertEqual(ndex.host, 'http://localhost:8080/ndexbio-rest')
        self.assertTrue(ndex.s is not None)
        self.assertTrue(ndex.timeout, 1)

        # try with user_agent set to None Issue #34
        ndex = Ndex2(user_agent=None)
        self.assertEqual(ndex.user_agent, '')
Esempio n. 22
0
 def test_ndex2_put_no_json_empty_code_200(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         m.put(client.DEFAULT_SERVER + '/v2/hi',
               status_code=200,
               text='hehe',
               request_headers={'Content-Type': 'application/json;charset=UTF-8',
                                'Accept': 'application/json',
                                'User-Agent': client.userAgent},
               headers={'Content-Type': 'application/foo'})
         ndex = Ndex2()
         ndex.set_debug_mode(True)
         res = ndex.put('/hi')
         self.assertEqual(res, 'hehe')
Esempio n. 23
0
 def test_ndex2_constructor_with_defaulthost_properties_is_none(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json={"networkCount": 1321,
                     "userCount": 12,
                     "groupCount": 0,
                     "message": "Online"})
         ndex = Ndex2()
         self.assertEqual(ndex.debug, False)
         self.assertEqual(ndex.version, '1.3')
         self.assertEqual(ndex.status, {})
         self.assertEqual(ndex.username, None)
         self.assertEqual(ndex.password, None)
         self.assertEqual(ndex.user_agent, '')
         self.assertEqual(ndex.host, client.DEFAULT_SERVER + '/rest')
         self.assertTrue(ndex.s is not None)
Esempio n. 24
0
 def __init__(self, account, password, uri="http://public.ndexbio.org"):
     self.uri = uri
     self.session = None
     self.account = account
     self.password = password
     try:
         self.session = Ndex2(uri, account, password)
         self.session.update_status()
         networks = self.session.status.get("networkCount")
         users = self.session.status.get("userCount")
         groups = self.session.status.get("groupCount")
         print(
             f"session: networks: {networks} users: {users} groups: {groups}"
         )
     except Exception as inst:
         print(f"Could not access account {account}")
         raise inst
Esempio n. 25
0
 def test_save_new_network_cx_with_no_status(self):
     with requests_mock.mock() as m:
         resurl = client.DEFAULT_SERVER + '/v2/network/asdf'
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         m.post(client.DEFAULT_SERVER + '/v2/network/asCX',
                request_headers={'Connection': 'close'},
                status_code=1,
                text=resurl)
         ndex = Ndex2(username='******', password='******')
         res = ndex.save_new_network([{'foo': '123'}])
         self.assertEqual(res, resurl)
         decode_txt = m.last_request.text.read().decode('UTF-8')
         self.assertTrue('Content-Disposition: form-data; name="CXNetworkStream"; filename="filename"' in decode_txt)
         self.assertTrue('Content-Type: application/octet-stream' in decode_txt)
         self.assertTrue('{"foo": "123"}' in decode_txt)
         self.assertTrue('{"status": [{"' in decode_txt)
         self.assertTrue('"error": ""' in decode_txt)
         self.assertTrue('"success": true' in decode_txt)
Esempio n. 26
0
 def test_ndex2_put_returns_code_500(self):
     with requests_mock.mock() as m:
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict())
         m.put(client.DEFAULT_SERVER + '/v2/hi',
               status_code=500,
               text='hehe',
               request_headers={'Content-Type': 'application/json;charset=UTF-8',
                                'Accept': 'application/json',
                                'User-Agent': client.userAgent},
               headers={'Content-Type': 'application/foo'})
         ndex = Ndex2()
         ndex.set_debug_mode(True)
         try:
             ndex.put('/hi')
             self.fail('Expected HTTPError')
         except HTTPError as he:
             self.assertEqual(he.response.status_code, 500)
             self.assertEqual(he.response.text, 'hehe')
Esempio n. 27
0
def build_ndex_client(username=None, password=None, debug=False):
    """Build an NDEx client by checking environmental variables.

    It has been requested that the :code:`ndex-client` has this functionality built-in by this GitHub
    `issue <https://github.com/ndexbio/ndex-python/issues/9>`_

    :param Optional[str] username: NDEx username
    :param Optional[str] password: NDEx password
    :param bool debug: If true, turn on NDEx client debugging
    :return: An NDEx client
    :rtype: ndex2.client.Ndex2
    """
    if username is None and NDEX_USERNAME in os.environ:
        username = os.environ[NDEX_USERNAME]
        log.info('got NDEx username from environment: %s', username)

    if password is None and NDEX_PASSWORD in os.environ:
        password = os.environ[NDEX_PASSWORD]
        log.info('got NDEx password from environment')

    return Ndex2(username=username, password=password, debug=debug)
Esempio n. 28
0
 def get_ndex2_client(self):
     return Ndex2(os.getenv('NDEX2_TEST_SERVER'),
                  os.getenv('NDEX2_TEST_USER'),
                  os.getenv('NDEX2_TEST_PASS'),
                  debug=True,
                  user_agent='ndex2-client integration test')