コード例 #1
0
class EUDATHandleClientReadaccessPatchedTestCase(unittest.TestCase):
    '''Testing methods that read the 10320/loc entry.'''
    def setUp(self):
        self.inst = EUDATHandleClient()

    def tearDown(self):
        pass

    # retrieve_handle_record_json:

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_json_normal(self, getpatch):
        """Test if retrieve_handle_record_json returns the correct things.."""

        # Test variables:
        handlerecord = RECORD
        expected = json.loads(handlerecord)

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord)
        getpatch.return_value = mock_response

        # Call method and check result:
        received = self.inst.retrieve_handle_record_json(expected['handle'])
        self.assertEqual(received, expected,
                         'Unexpected return from handle retrieval.')

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_json_handle_does_not_exist(self, getpatch):
        """Test return value (None) if handle does not exist (retrieve_handle_record_json)."""

        # Test variables:
        testhandle = 'dont/exist'

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        json_record = self.inst.retrieve_handle_record_json(testhandle)
        self.assertIsNone(
            json_record,
            'The return value should be None if the handle does not exist, not: '
            + str(json_record))

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_json_handle_empty(self, getpatch):
        """Test return value if handle is empty (retrieve_handle_record_json)."""

        # Test variables:
        testhandle = 'dont/exist'

        # Define the replacement for the patched method:
        mock_response = MockResponse(empty=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        json_record = self.inst.retrieve_handle_record_json(testhandle)
        self.assertEquals(json_record['responseCode'], 200,
                          'Unexpected return value: ' + str(json_record))

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_json_genericerror(self, getpatch):
        """Test exception if retrieve_handle_record_json returns a strange HTTP code."""

        # Test variables:
        testhandle = 'dont/exist'

        # Define the replacement for the patched method:
        mock_response = MockResponse(status_code=99999)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(GenericHandleError):
            json_record = self.inst.retrieve_handle_record_json(testhandle)

    # retrieve_handle_record:

    #@mock.patch('b2handle.handleclient.EUDATHandleClient._EUDATHandleClient__send_handle_get_request')
    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_when_json_not_given(self, getpatch):
        """Test retrieving a handle record"""

        # Test variables
        handlerecord_string = RECORD
        handlerecord_json = json.loads(handlerecord_string)
        testhandle = handlerecord_json['handle']

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        dict_record = self.inst.retrieve_handle_record(testhandle)
        self.assertIn('TEST1', dict_record,
                      'Key "test1" not in handlerecord dictionary!')
        self.assertIn('TEST2', dict_record,
                      'Key "test2" not in handlerecord dictionary!')
        self.assertIn('TESTDUP', dict_record,
                      'Key "TESTDUP" not in handlerecord dictionary!')
        self.assertIn('HS_ADMIN', dict_record,
                      'Key "HS_ADMIN" not in handlerecord dictionary!')

        self.assertEqual(dict_record['TEST1'], 'val1',
                         'The value of "test1" is not "val1.')
        self.assertEqual(dict_record['TEST2'], 'val2',
                         'The value of "test2" is not "val2.')
        self.assertIn(
            dict_record['TESTDUP'], ("dup1", "dup2"),
            'The value of the duplicate key "TESTDUP" should be "dup1" or "dup2".'
        )
        self.assertIn(
            'permissions', dict_record['HS_ADMIN'],
            'The HS_ADMIN has no permissions: ' + dict_record['HS_ADMIN'])

        self.assertEqual(
            len(dict_record), 4,
            'The record should have a length of 5 (as the duplicate is ignored.'
        )

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_when_handle_is_wrong(self, getpatch):
        """Test error when retrieving a handle record with contradicting inputs."""

        # Test variable
        testhandle = 'something/else'
        handlerecord_string = RECORD
        handlerecord_json = json.loads(handlerecord_string)

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(GenericHandleError):
            self.inst.retrieve_handle_record(testhandle)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_when_handle_is_None(self, getpatch):
        """Test error when retrieving a handle record with a None input."""

        # Test variable
        testhandle = None

        # Call method and check result:
        with self.assertRaises(HandleSyntaxError):
            self.inst.retrieve_handle_record(testhandle)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_when_handle_is_wrong(self, getpatch):
        """Test error when retrieving a nonexistent handle record."""

        # Test variable
        testhandle = 'who/cares'

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        hrec = self.inst.retrieve_handle_record(testhandle)
        self.assertIsNone(
            hrec, 'The handle record for a nonexistent handle should be None!')

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_when_handlerecord_is_None(self, getpatch):
        """Test error when retrieving a handle record, giving a None type."""

        # Test variable
        handlerecord_string = RECORD
        handlerecord_json = json.loads(handlerecord_string)
        testhandle = handlerecord_json['handle']
        givenrecord = None

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        dict_record = self.inst.retrieve_handle_record(testhandle, givenrecord)
        self.assertIn('TEST1', dict_record,
                      'Key "test1" not in handlerecord dictionary!')
        self.assertIn('TEST2', dict_record,
                      'Key "test2" not in handlerecord dictionary!')
        self.assertIn('TESTDUP', dict_record,
                      'Key "TESTDUP" not in handlerecord dictionary!')
        self.assertIn('HS_ADMIN', dict_record,
                      'Key "HS_ADMIN" not in handlerecord dictionary!')

        self.assertEqual(dict_record['TEST1'], 'val1',
                         'The value of "test1" is not "val1.')
        self.assertEqual(dict_record['TEST2'], 'val2',
                         'The value of "test2" is not "val2.')
        self.assertIn(
            dict_record['TESTDUP'], ("dup1", "dup2"),
            'The value of the duplicate key "TESTDUP" should be "dup1" or "dup2".'
        )
        self.assertIn(
            'permissions', dict_record['HS_ADMIN'],
            'The HS_ADMIN has no permissions: ' + dict_record['HS_ADMIN'])

        self.assertEqual(
            len(dict_record), 4,
            'The record should have a length of 5 (as the duplicate is ignored.'
        )

    # get_value_from_handle

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_get_value_from_handle_when_handle_inexistent(self, getpatch):
        """Test error when retrieving a handle record, giving a None type."""

        # Test variables
        testhandle = 'who/cares'
        key = 'foo'

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.get_value_from_handle(testhandle, key=key)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_is_10320LOC_empty_handle_does_not_exist(self, getpatch):
        """Test exception"""

        # Test variables
        testhandle = 'who/cares'

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.is_10320LOC_empty(testhandle)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_is_url_contained_in_10320LOC_handle_does_not_exist(
            self, getpatch):
        """Test exception"""

        # Test variables
        testhandle = 'who/cares'
        one_url = 'http://bla'
        list_of_urls = ['http://bla', 'http://foo.foo']

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.is_URL_contained_in_10320LOC(testhandle, url=one_url)
        with self.assertRaises(HandleNotFoundException):
            self.inst.is_URL_contained_in_10320LOC(testhandle,
                                                   url=list_of_urls)

    # Instantiation

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_instantiate_with_username_and_password_wrongpw(self, getpatch):

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True)
        getpatch.return_value = mock_response

        inst = EUDATHandleClient.instantiate_with_username_and_password(
            'http://someurl', '100:my/testhandle', 'passywordy')

        self.assertIsInstance(inst, EUDATHandleClient)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_instantiate_with_username_and_password_inexistentuser(
            self, getpatch):

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        with self.assertRaises(HandleNotFoundException):
            inst = EUDATHandleClient.instantiate_with_username_and_password(
                'http://someurl', '100:john/doe', 'passywordy')

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_instantiate_with_credentials_inexistentuser(self, getpatch):
        """Test instantiation of client: Exception if username does not exist."""

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Test variables
        testusername_inexistent = '100:john/doe'
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            handle_server_url='some/url',
            username=testusername_inexistent,
            password='******')

        # Run code to be tested + check exception:
        # Create instance with credentials
        with self.assertRaises(HandleNotFoundException):
            inst = EUDATHandleClient.instantiate_with_credentials(credentials)

        # If the user name has no index, exception is already thrown in credentials creation!
        #self.assertRaises(HandleSyntaxError, b2handle.PIDClientCredentials, 'url', 'prefix/suffix', randompassword)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_instantiate_with_credentials(self, getpatch):
        """Test instantiation of client: No exception if password wrong."""

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True)
        getpatch.return_value = mock_response

        # Test variables
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            handle_server_url='some/url',
            username='******',
            password='******')

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(credentials)

        # Check desired outcomes
        self.assertIsInstance(inst, EUDATHandleClient)

    @mock.patch(
        'b2handle.handlesystemconnector.HandleSystemConnector.check_if_username_exists'
    )
    def test_instantiate_with_credentials_config(self, checkpatch):
        """Test instantiation of client: No exception if password wrong."""

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True)
        checkpatch.return_value = mock_response

        # Test variables
        credentials = MockCredentials(restapi='foobar')

        self.assertEqual(credentials.get_config()['REST_API_url_extension'],
                         'foobar', 'Config: ' + str(credentials.get_config()))

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(credentials)
        self.assertIsInstance(inst, EUDATHandleClient)

    @mock.patch(
        'b2handle.handlesystemconnector.HandleSystemConnector.check_if_username_exists'
    )
    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_instantiate_with_credentials_config_override(
            self, getpatch, checkpatch):
        """Test instantiation of client: We pass a config value in the credentials
        and also as an arg in the instantiation. We want the latter to override the
        first one.
        """

        # Define the replacement for the patched method:
        # We pretend the username exists!
        mock_response = MockResponse(success=True)
        checkpatch.return_value = mock_response

        # Define the replacement for the patched GET:
        cont = {
            "responseCode":
            1,
            "handle":
            "my/testhandle",
            "values": [{
                "index": 111,
                "type": "TEST1",
                "data": {
                    "format": "string",
                    "value": "val1"
                },
                "ttl": 86400,
                "timestamp": "2015-09-30T15:08:49Z"
            }, {
                "index": 2222,
                "type": "TEST2",
                "data": {
                    "format": "string",
                    "value": "val2"
                },
                "ttl": 86400,
                "timestamp": "2015-09-30T15:08:49Z"
            }, {
                "index": 333,
                "type": "TEST3",
                "data": {
                    "format": "string",
                    "value": "val3"
                },
                "ttl": 86400,
                "timestamp": "2015-09-30T15:08:49Z"
            }, {
                "index": 4,
                "type": "TEST4",
                "data": {
                    "format": "string",
                    "value": "val4"
                },
                "ttl": 86400,
                "timestamp": "2015-09-30T15:08:49Z"
            }]
        }
        mock_response = MockResponse(success=True, content=json.dumps(cont))
        getpatch.return_value = mock_response

        # Test variables
        # Passing mock credentials, give them the value "foobar", which
        # should be overridden!
        credentials = MockCredentials(restapi='foobar')
        self.assertEqual(credentials.get_config()['REST_API_url_extension'],
                         'foobar', 'Config: ' + str(credentials.get_config()))

        # Run code to be tested
        # Create instance with credentials. It gets the "REST_API_url_extention"
        # from both the credentials and as a param.
        inst = EUDATHandleClient.instantiate_with_credentials(
            credentials, REST_API_url_extension='bar/bar/bar')
        self.assertIsInstance(inst, EUDATHandleClient)

        # How to know now which one was used?
        # Call a read and check its url! Did it get foobar or barbarbar appended?
        inst.get_value_from_handle('my/testhandle', 'key')
        positional_args_passed = getpatch.call_args_list[
            len(getpatch.call_args_list) - 1][0]
        passed_url = positional_args_passed[0]

        # Compare with expected URL:
        self.assertIn('bar/bar/bar', passed_url,
                      'bar/bar/bar is not specified in the URL ' + passed_url)
コード例 #2
0
class EUDATHandleClientReadaccessPatchedTestCase(unittest.TestCase):
    '''Testing methods that read the 10320/loc entry.'''

    def setUp(self):
        self.inst = EUDATHandleClient()

    def tearDown(self):
        pass

    # retrieve_handle_record_json:

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_json_normal(self, getpatch):
        """Test if retrieve_handle_record_json returns the correct things.."""

        # Test variables:
        handlerecord = RECORD
        expected = json.loads(handlerecord)

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord)
        getpatch.return_value = mock_response

        # Call method and check result:
        received = self.inst.retrieve_handle_record_json(expected['handle'])
        self.assertEqual(received, expected,
            'Unexpected return from handle retrieval.')

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_json_handle_does_not_exist(self, getpatch):
        """Test return value (None) if handle does not exist (retrieve_handle_record_json)."""

        # Test variables:
        testhandle = 'dont/exist'

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        json_record = self.inst.retrieve_handle_record_json(testhandle)
        self.assertIsNone(json_record,
            'The return value should be None if the handle does not exist, not: '+str(json_record))

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_json_handle_empty(self, getpatch):
        """Test return value if handle is empty (retrieve_handle_record_json)."""

        # Test variables:
        testhandle = 'dont/exist'

        # Define the replacement for the patched method:
        mock_response = MockResponse(empty=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        json_record = self.inst.retrieve_handle_record_json(testhandle)
        self.assertEquals(json_record['responseCode'],200,
            'Unexpected return value: '+str(json_record))

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_json_genericerror(self, getpatch):
        """Test exception if retrieve_handle_record_json returns a strange HTTP code."""

        # Test variables:
        testhandle = 'dont/exist'

        # Define the replacement for the patched method:
        mock_response = MockResponse(status_code=99999)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(GenericHandleError):
            json_record = self.inst.retrieve_handle_record_json(testhandle)

    # retrieve_handle_record:

    #@mock.patch('b2handle.handleclient.EUDATHandleClient._EUDATHandleClient__send_handle_get_request')
    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_when_json_not_given(self, getpatch):
        """Test retrieving a handle record"""

        # Test variables
        handlerecord_string = RECORD
        handlerecord_json = json.loads(handlerecord_string)
        testhandle = handlerecord_json['handle']
        
        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        dict_record = self.inst.retrieve_handle_record(testhandle)
        self.assertIn('TEST1', dict_record,
            'Key "test1" not in handlerecord dictionary!')
        self.assertIn('TEST2', dict_record,
            'Key "test2" not in handlerecord dictionary!')
        self.assertIn('TESTDUP', dict_record,
            'Key "TESTDUP" not in handlerecord dictionary!')
        self.assertIn('HS_ADMIN', dict_record,
            'Key "HS_ADMIN" not in handlerecord dictionary!')

        self.assertEqual(dict_record['TEST1'], 'val1',
            'The value of "test1" is not "val1.')
        self.assertEqual(dict_record['TEST2'], 'val2',
            'The value of "test2" is not "val2.')
        self.assertIn(dict_record['TESTDUP'], ("dup1", "dup2"),
            'The value of the duplicate key "TESTDUP" should be "dup1" or "dup2".')
        self.assertIn('permissions', dict_record['HS_ADMIN'],
            'The HS_ADMIN has no permissions: '+dict_record['HS_ADMIN'])

        self.assertEqual(len(dict_record), 4,
            'The record should have a length of 5 (as the duplicate is ignored.')

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_when_handle_is_wrong(self, getpatch):
        """Test error when retrieving a handle record with contradicting inputs."""
        
        # Test variable
        testhandle = 'something/else'
        handlerecord_string = RECORD
        handlerecord_json = json.loads(handlerecord_string)

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(GenericHandleError):
            self.inst.retrieve_handle_record(testhandle)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_when_handle_is_None(self, getpatch):
        """Test error when retrieving a handle record with a None input."""

        # Test variable
        testhandle = None

        # Call method and check result:
        with self.assertRaises(HandleSyntaxError):
            self.inst.retrieve_handle_record(testhandle)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_when_handle_is_wrong(self, getpatch):
        """Test error when retrieving a nonexistent handle record."""
        
        # Test variable
        testhandle = 'who/cares'

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        hrec = self.inst.retrieve_handle_record(testhandle)
        self.assertIsNone(hrec,
            'The handle record for a nonexistent handle should be None!')

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_retrieve_handle_record_when_handlerecord_is_None(self, getpatch):
        """Test error when retrieving a handle record, giving a None type."""

        # Test variable
        handlerecord_string = RECORD
        handlerecord_json = json.loads(handlerecord_string)
        testhandle = handlerecord_json['handle']
        givenrecord = None

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        dict_record = self.inst.retrieve_handle_record(testhandle, givenrecord)
        self.assertIn('TEST1', dict_record,
            'Key "test1" not in handlerecord dictionary!')
        self.assertIn('TEST2', dict_record,
            'Key "test2" not in handlerecord dictionary!')
        self.assertIn('TESTDUP', dict_record,
            'Key "TESTDUP" not in handlerecord dictionary!')
        self.assertIn('HS_ADMIN', dict_record,
            'Key "HS_ADMIN" not in handlerecord dictionary!')

        self.assertEqual(dict_record['TEST1'], 'val1',
            'The value of "test1" is not "val1.')
        self.assertEqual(dict_record['TEST2'], 'val2',
            'The value of "test2" is not "val2.')
        self.assertIn(dict_record['TESTDUP'], ("dup1", "dup2"),
            'The value of the duplicate key "TESTDUP" should be "dup1" or "dup2".')
        self.assertIn('permissions', dict_record['HS_ADMIN'],
            'The HS_ADMIN has no permissions: '+dict_record['HS_ADMIN'])

        self.assertEqual(len(dict_record), 4,
            'The record should have a length of 5 (as the duplicate is ignored.')

    # get_value_from_handle

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_get_value_from_handle_when_handle_inexistent(self, getpatch):
        """Test error when retrieving a handle record, giving a None type."""
        
        # Test variables
        testhandle = 'who/cares'
        key = 'foo'

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.get_value_from_handle(testhandle, key=key)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_is_10320LOC_empty_handle_does_not_exist(self, getpatch):
        """Test exception"""

        # Test variables
        testhandle = 'who/cares'

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.is_10320LOC_empty(testhandle)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_is_url_contained_in_10320LOC_handle_does_not_exist(self, getpatch):
        """Test exception"""

        # Test variables
        testhandle = 'who/cares'
        one_url = 'http://bla'
        list_of_urls = ['http://bla','http://foo.foo']

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.is_URL_contained_in_10320LOC(testhandle, url=one_url)
        with self.assertRaises(HandleNotFoundException):
            self.inst.is_URL_contained_in_10320LOC(testhandle, url=list_of_urls)

    # Instantiation

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_instantiate_with_username_and_password_wrongpw(self, getpatch):
        

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True)
        getpatch.return_value = mock_response

        inst = EUDATHandleClient.instantiate_with_username_and_password(
                'http://someurl', '100:my/testhandle', 'passywordy')

        self.assertIsInstance(inst, EUDATHandleClient)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_instantiate_with_username_and_password_inexistentuser(self, getpatch):
        
        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        with self.assertRaises(HandleNotFoundException):
            inst = EUDATHandleClient.instantiate_with_username_and_password(
                'http://someurl', '100:john/doe', 'passywordy')

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_instantiate_with_credentials_inexistentuser(self, getpatch):
        """Test instantiation of client: Exception if username does not exist."""

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Test variables
        testusername_inexistent = '100:john/doe'
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            handle_server_url='some/url',
            username=testusername_inexistent,
            password='******')

        # Run code to be tested + check exception:
        # Create instance with credentials
        with self.assertRaises(HandleNotFoundException):
            inst = EUDATHandleClient.instantiate_with_credentials(credentials)

        # If the user name has no index, exception is already thrown in credentials creation!
        #self.assertRaises(HandleSyntaxError, b2handle.PIDClientCredentials, 'url', 'prefix/suffix', randompassword)

    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_instantiate_with_credentials(self, getpatch):
        """Test instantiation of client: No exception if password wrong."""

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True)
        getpatch.return_value = mock_response

        # Test variables
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            handle_server_url='some/url',
            username='******',
            password='******')

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(credentials)

        # Check desired outcomes
        self.assertIsInstance(inst, EUDATHandleClient)

    @mock.patch('b2handle.handlesystemconnector.HandleSystemConnector.check_if_username_exists')
    def test_instantiate_with_credentials_config(self, checkpatch):
        """Test instantiation of client: No exception if password wrong."""

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True)
        checkpatch.return_value = mock_response

        # Test variables
        credentials = MockCredentials(restapi='foobar')

        self.assertEqual(credentials.get_config()['REST_API_url_extension'],'foobar',
            'Config: '+str(credentials.get_config()))

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(credentials)
        self.assertIsInstance(inst, EUDATHandleClient)

    @mock.patch('b2handle.handlesystemconnector.HandleSystemConnector.check_if_username_exists')
    @mock.patch('b2handle.handleclient.requests.Session.get')
    def test_instantiate_with_credentials_config_override(self, getpatch, checkpatch):
        """Test instantiation of client: We pass a config value in the credentials
        and also as an arg in the instantiation. We want the latter to override the
        first one.
        """

        # Define the replacement for the patched method:
        # We pretend the username exists!
        mock_response = MockResponse(success=True)
        checkpatch.return_value = mock_response

        # Define the replacement for the patched GET:
        cont = {"responseCode":1,"handle":"my/testhandle","values":[{"index":111,"type":"TEST1","data":{"format":"string","value":"val1"},"ttl":86400,"timestamp":"2015-09-30T15:08:49Z"},{"index":2222,"type":"TEST2","data":{"format":"string","value":"val2"},"ttl":86400,"timestamp":"2015-09-30T15:08:49Z"},{"index":333,"type":"TEST3","data":{"format":"string","value":"val3"},"ttl":86400,"timestamp":"2015-09-30T15:08:49Z"},{"index":4,"type":"TEST4","data":{"format":"string","value":"val4"},"ttl":86400,"timestamp":"2015-09-30T15:08:49Z"}]}
        mock_response = MockResponse(success=True, content=json.dumps(cont))
        getpatch.return_value = mock_response

        # Test variables
        # Passing mock credentials, give them the value "foobar", which
        # should be overridden!
        credentials = MockCredentials(restapi='foobar')
        self.assertEqual(credentials.get_config()['REST_API_url_extension'],'foobar',
            'Config: '+str(credentials.get_config()))

        # Run code to be tested
        # Create instance with credentials. It gets the "REST_API_url_extention"
        # from both the credentials and as a param.
        inst = EUDATHandleClient.instantiate_with_credentials(
            credentials,
            REST_API_url_extension='bar/bar/bar')
        self.assertIsInstance(inst, EUDATHandleClient)

        # How to know now which one was used?
        # Call a read and check its url! Did it get foobar or barbarbar appended?
        inst.get_value_from_handle('my/testhandle', 'key')
        positional_args_passed = getpatch.call_args_list[len(getpatch.call_args_list)-1][0]
        passed_url = positional_args_passed[0]

        # Compare with expected URL:
        self.assertIn('bar/bar/bar',passed_url,
            'bar/bar/bar is not specified in the URL '+passed_url)
コード例 #3
0
class EUDATHandleClientReadaccessFaked10320LOCTestCase(unittest.TestCase):
    '''Testing methods that read the 10320/LOC entry.'''
    def setUp(self):
        self.inst = EUDATHandleClient()

    def tearDown(self):
        pass

    # is_10320LOC_empty

    def test_is_10320LOC_empty_notempty(self):
        """Test if presence of 10320/LOC is detected."""
        handlerecord = json.load(
            open('resources/handlerecord_with_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_10320LOC_empty(handle, handlerecord)

        self.assertFalse(
            answer,
            'The record contains a 10320/LOC, but the is_empty does not return False.'
        )

    def test_is_10320LOC_empty_no10320LOC(self):
        """Test if absence of 10320/LOC is detected."""
        handlerecord = json.load(
            open('resources/handlerecord_without_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_10320LOC_empty(handle, handlerecord)

        self.assertTrue(
            answer,
            'The record contains no 10320/LOC, but the is_empty does not return True.'
        )

    def test_is_10320LOC_empty_empty10320LOC(self):
        """Test if emptiness of 10320/LOC is detected."""
        handlerecord = json.load(
            open('resources/handlerecord_with_empty_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_10320LOC_empty(handle, handlerecord)

        self.assertTrue(
            answer,
            'The record contains an empty 10320/LOC, but the is_empty does not return True.'
        )

    # is_URL_contained_in_1302loc

    def test_is_URL_contained_in_10320LOC_true(self):
        """Test if presence of URL is found in 10320/LOC."""
        handlerecord = json.load(
            open('resources/handlerecord_with_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(
            handle, 'http://foo.bar', handlerecord)
        val = self.inst.get_value_from_handle(handle, '10320/LOC',
                                              handlerecord)
        self.assertTrue(
            answer,
            'The URL exists in the 10320/LOC, and still the method does not return True:\n'
            + str(val))

    def test_is_URL_contained_in_10320LOC_false(self):
        """Test if absence of URL is detected in existing 10320/LOC."""
        handlerecord = json.load(
            open('resources/handlerecord_with_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(
            handle, 'http://bar.bar', handlerecord)
        self.assertFalse(
            answer,
            'The 10320/LOC does not contain the URL, and still the method does not return False.'
        )

    def test_is_URL_contained_in_inexistent_10320LOC(self):
        """Test if absence of URL is detected if 10320/LOC does not exist."""
        handlerecord = json.load(
            open('resources/handlerecord_without_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(
            handle, 'http://whatever.foo', handlerecord)
        self.assertFalse(
            answer,
            'The 10320/LOC does not exist, and still the method does not return False.'
        )

    def test_is_URL_contained_in_empty_10320LOC(self):
        """Test if absence of URL is detected if 10320/LOC is empty."""
        handlerecord = json.load(
            open('resources/handlerecord_with_empty_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(
            handle, 'http://whatever.foo', handlerecord)
        self.assertFalse(
            answer,
            'The 10320/LOC is empty, and still the method does not return False.'
        )
コード例 #4
0
class EUDATHandleClientReadaccessTestCase(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)

        # Read resources from file:
        self.testvalues = RESOURCES_FILE

        # Test values that need to be given by user:
        self.handle = self.testvalues['handle_for_read_tests']
        self.handle_global = self.testvalues['handle_globally_resolvable']
        self.user = self.testvalues['user']

        # Optional:
        self.https_verify = True
        if 'HTTPS_verify' in self.testvalues:
            self.https_verify = self.testvalues['HTTPS_verify']
        self.url = 'http://hdl.handle.net'
        if 'handle_server_url_read' in self.testvalues.keys():
            self.url = self.testvalues['handle_server_url_read']
        self.path_to_api = None
        if 'url_extension_REST_API' in self.testvalues.keys():
            self.path_to_api = self.testvalues['url_extension_REST_API']

        # Others
        prefix = self.handle.split('/')[0]
        self.inexistent_handle = prefix + '/07e1fbf3-2b72-430a-a035-8584d4eada41'
        self.randompassword = '******'

    def setUp(self):
        """ For most test, provide a client instance with the user-specified
        handle server url."""

        self.inst = EUDATHandleClient(HTTPS_verify=self.https_verify,
                                      handle_server_url=self.url,
                                      url_extension_REST_API=self.path_to_api)

        # Before being able to run these tests without write access,
        # the handle that we use for testing must exist. With this code,
        # you can create it. You only need to create it once and leave it
        # on the server, it will not be modified and can be used eternally.
        if False:
            # This should always be false!!! Except for creating the
            # required handle once!
            self.create_required_test_handles()

    def tearDown(self):
        pass
        pass

    def create_required_test_handles(self):

        # Creating an instance that knows how to write:
        pw = self.testvalues['password']
        inst = EUDATHandleClient.instantiate_with_username_and_password(
            self.testvalues['handle_server_url_write'],
            self.user,
            pw,
            HTTPS_verify=self.https_verify)

        authstring = b2handle.utilhandle.create_authentication_string(
            self.user, pw)
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + authstring
        }

        list_of_all_entries = [{
            "index": 100,
            "type": "HS_ADMIN",
            "data": {
                "format": "admin",
                "value": {
                    "handle": "21.T14999/B2HANDLE_INTEGRATION_TESTS",
                    "index": 300,
                    "permissions": "011111110011"
                }
            }
        }, {
            "index": 111,
            "type": "TEST1",
            "data": "val1"
        }, {
            "index": 2222,
            "type": "TEST2",
            "data": "val2"
        }, {
            "index": 333,
            "type": "TEST3",
            "data": "val3"
        }, {
            "index": 4,
            "type": "TEST4",
            "data": "val4"
        }]

        testhandle = self.handle
        url = self.testvalues['handle_server_url_write'] + self.testvalues[
            'url_extension_REST_API'] + testhandle
        veri = self.https_verify
        head = headers
        data = json.dumps({'values': list_of_all_entries})
        resp = requests.put(url, data=data, headers=head, verify=veri)

    # retrieve_handle_record_json

    def test_retrieve_handle_record_json(self):
        """Test reading handle record from server."""

        rec = self.inst.retrieve_handle_record_json(self.handle)

        received_type = rec['values'][2]['type']
        received_value = rec['values'][2]['data']['value']

        self.assertEqual(
            received_type, 'TEST1',
            'The type should be "TEST3" but was "%s" (%s).' %
            (received_type, self.handle))
        self.assertEqual(
            received_value, 'val1',
            'The value should be "val3" but is "%s" (%s).' %
            (received_value, self.handle))

    # get_value_from_handle

    def test_get_value_from_handle_normal(self):
        """Test reading existent and inexistent handle value from server."""
        val = self.inst.get_value_from_handle(self.handle, 'TEST1')
        self.assertEqual(
            val, 'val1',
            'Retrieving "TEST1" from %s should lead to "val1", but it lead to "%s"'
            % (self.handle, val))

    def test_get_value_from_handle_inexistent_key(self):
        val = self.inst.get_value_from_handle(self.handle, 'TEST100')
        self.assertIsNone(
            val,
            'Retrieving "TEST100" from %s should lead to "None", but it lead to "%s"'
            % (self.handle, val))

    def test_get_value_from_handle_inexistent_record(self):
        """Test reading handle value from inexistent handle."""
        with self.assertRaises(HandleNotFoundException):
            val = self.inst.get_value_from_handle(self.inexistent_handle,
                                                  'anykey')

    # instantiate

    def test_instantiate_with_username_and_wrong_password(self):
        """Test instantiation of client: No exception if password wrong."""

        # Create client instance with username and password
        inst = EUDATHandleClient.instantiate_with_username_and_password(
            self.url,
            self.user,
            self.randompassword,
            HTTPS_verify=self.https_verify)
        self.assertIsInstance(inst, EUDATHandleClient)

    def test_instantiate_with_username_without_index_and_password(self):
        """Test instantiation of client: Exception if username has no index."""
        testusername_without_index = self.user.split(':')[1]

        # Run code to be tested + check exception:
        with self.assertRaises(HandleSyntaxError):

            # Create client instance with username and password
            inst = EUDATHandleClient.instantiate_with_username_and_password(
                self.url,
                testusername_without_index,
                self.randompassword,
                HTTPS_verify=self.https_verify)

    def test_instantiate_with_nonexistent_username_and_password(self):
        """Test instantiation of client: Exception if username does not exist."""
        testusername_inexistent = '100:' + self.inexistent_handle

        # Run code to be tested + check exception:
        with self.assertRaises(HandleNotFoundException):

            # Create client instance with username and password
            inst = EUDATHandleClient.instantiate_with_username_and_password(
                self.url,
                testusername_inexistent,
                self.randompassword,
                HTTPS_verify=self.https_verify)

    def test_instantiate_with_credentials(self):
        """Test instantiation of client: No exception if password wrong."""

        # Test variables
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            handle_server_url=self.url,
            username=self.user,
            password=self.randompassword)

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(
            credentials, HTTPS_verify=self.https_verify)

        # Check desired outcomes
        self.assertIsInstance(inst, EUDATHandleClient)

    def test_instantiate_with_credentials_inexistentuser(self):
        """Test instantiation of client: Exception if username does not exist."""

        # Test variables
        testusername_inexistent = '100:' + self.inexistent_handle
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            handle_server_url=self.url,
            username=testusername_inexistent,
            password=self.randompassword)

        # Run code to be tested + check exception:
        # Create instance with credentials
        with self.assertRaises(HandleNotFoundException):
            inst = EUDATHandleClient.instantiate_with_credentials(
                credentials, HTTPS_verify=self.https_verify)

        # If the user name has no index, exception is already thrown in credentials creation!
        #self.assertRaises(HandleSyntaxError, b2handle.PIDClientCredentials, 'url', 'prefix/suffix', randompassword)

    def test_instantiate_with_credentials_config_override(self):
        """Test instantiation of client: No exception if password wrong."""

        # Test variables
        credentials = mock.MagicMock()
        config_from_cred = {}
        valuefoo = 'foo/foo/foo/'  # passed via credentials
        valuebar = 'bar/bar/bar'  # passed directly to constructor
        config_from_cred['REST_API_url_extension'] = valuefoo

        credentials = b2handle.clientcredentials.PIDClientCredentials(
            handle_server_url=self.url,
            username=self.user,
            password=self.randompassword,
            handleowner=self.user,
            REST_API_url_extension=valuefoo)

        self.assertEqual(credentials.get_config()['REST_API_url_extension'],
                         valuefoo, 'Config: ' + str(credentials.get_config()))

        # foo/foo/ from the credentials should be overridden by bar/bar/ which is directly passed

        # Run code to be tested - we expect an exception, as it will try to do a GET on the bogus rest api:
        with self.assertRaises(GenericHandleError):
            inst = EUDATHandleClient.instantiate_with_credentials(
                credentials,
                HTTPS_verify=self.https_verify,
                REST_API_url_extension=valuebar)

            # So this code can only be reached if something went wrong:
            self.assertIsInstance(inst, EUDATHandleClient)
            # Check if bar/bar instead of foo/foo was stored as path!
            serverconn = inst._EUDATHandleClient__handlesystemconnector
            self.assertIn(
                '/bar/',
                serverconn._HandleSystemConnector__REST_API_url_extension)
            self.assertNotIn(
                '/foo/',
                serverconn._HandleSystemConnector__REST_API_url_extension)
            self.assertEquals(
                serverconn._HandleSystemConnector__REST_API_url_extension,
                valuebar)

    def test_instantiate_with_credentials_config(self):
        """Test instantiation of client: No exception if password wrong."""

        # Test variables
        credentials = mock.MagicMock()
        config_from_cred = {}
        valuefoo = 'foo/foo/foo/'
        config_from_cred['REST_API_url_extension'] = valuefoo
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            handle_server_url=self.url,
            username=self.user,
            password=self.randompassword,
            handleowner=self.user,
            REST_API_url_extension=valuefoo)

        self.assertEqual(credentials.get_config()['REST_API_url_extension'],
                         valuefoo, 'Config: ' + str(credentials.get_config()))

        # foo/foo/ from the credentials should override default api/handles/

        # Run code to be tested - we expect an exception, as it will try to do a GET on the bogus rest api:
        with self.assertRaises(GenericHandleError):
            inst = EUDATHandleClient.instantiate_with_credentials(
                credentials, HTTPS_verify=self.https_verify)

            # So this code can only be reached if something went wrong:
            self.assertIsInstance(inst, EUDATHandleClient)
            # Check if foo/foo instead of api/handles was stored as path!
            serverconn = inst._EUDATHandleClient__handlesystemconnector
            self.assertIn(
                '/foo/',
                serverconn._HandleSystemConnector__REST_API_url_extension)
            self.assertEquals(
                serverconn._HandleSystemConnector__REST_API_url_extension,
                valuefoo)

    def test_global_resolve(self):
        """Testing if instantiating with default handle server'works
        and if a handle is correctly retrieved. """

        # Create instance with default server url:
        inst = EUDATHandleClient(HTTPS_verify=self.https_verify)
        rec = inst.retrieve_handle_record_json(self.handle_global)

        self.assertIn('handle', rec, 'Response lacks "handle".')
        self.assertIn('responseCode', rec, 'Response lacks "responseCode".')

    def test_instantiate_for_read_access(self):
        """Testing if instantiating with default handle server works
        and if a handle is correctly retrieved. """

        # Create client instance with username and password
        inst = EUDATHandleClient.instantiate_for_read_access(
            HTTPS_verify=self.https_verify)
        rec = self.inst.retrieve_handle_record_json(self.handle)
        self.assertIsInstance(inst, EUDATHandleClient)
        self.assertIn('handle', rec, 'Response lacks "handle".')
        self.assertIn('responseCode', rec, 'Response lacks "responseCode".')
コード例 #5
0
class EUDATHandleClientReadaccessFakedTestCase(unittest.TestCase):
    '''Testing methods for retrieving values and indices.'''

    def setUp(self):
        self.inst = EUDATHandleClient()

    def tearDown(self):
        pass

    # get_value_from_handle

    def test_get_value_from_handle_normal(self):
        """Test retrieving a specific value from a handle record."""

        handlerecord = json.load(open('resources/handlerecord_for_reading.json'))
        handle = handlerecord['handle']

        val = self.inst.get_value_from_handle(handle,
                                              'test1',
                                              handlerecord)
        self.assertEquals(val, 'val1',
            'The value of "test1" should be "val1".')

    def test_get_value_from_handle_inexistentvalue(self):
        """Test retrieving an inexistent value from a handle record."""

        handlerecord = json.load(open('resources/handlerecord_for_reading.json'))
        handle = handlerecord['handle']

        val = self.inst.get_value_from_handle(handle,
                                              'test100',
                                              handlerecord)
        self.assertIsNone(val,
            'The value of "test100" should be None.')

    def test_get_value_from_handle_HS_ADMIN(self):
        """Test retrieving an HS_ADMIN value from a handle record."""

        handlerecord = json.load(open('resources/handlerecord_for_reading.json'))
        handle = handlerecord['handle']

        val = self.inst.get_value_from_handle(handle,
                                              'HS_ADMIN',
                                              handlerecord)
        self.assertIn('handle', val,
            'The HS_ADMIN has no entry "handle".')
        self.assertIn('index', val,
            'The HS_ADMIN has no entry "index".')
        self.assertIn('permissions', val,
            'The HS_ADMIN has no entry "permissions".')
        syntax_ok = self.inst.check_handle_syntax(val['handle'])
        self.assertTrue(syntax_ok,
            'The handle in HS_ADMIN is not well-formatted.')
        self.assertIsInstance(val['index'], (int, long),
            'The index of the HS_ADMIN is not an integer.')
        self.assertEqual(str(val['permissions']).replace('0','').replace('1',''), '',
            'The permission value in the HS_ADMIN contains not just 0 and 1.')

    def test_get_value_from_handle_duplicatekey(self):
        """Test retrieving a value of a duplicate key."""

        handlerecord = json.load(open('resources/handlerecord_for_reading.json'))
        handle = handlerecord['handle']

        val = self.inst.get_value_from_handle(handle,
                                              'testdup',
                                              handlerecord)
        self.assertIn(val, ("dup1", "dup2"),
            'The value of the duplicate key "testdup" should be "dup1" or "dup2".')

    # retrieve_handle_record

    def test_retrieve_handle_record_normal(self):

        handlerecord = json.load(open('resources/handlerecord_for_reading.json'))
        handle = handlerecord['handle']

        dict_record = self.inst.retrieve_handle_record(handle, handlerecord)

        self.assertIn('test1', dict_record,
            'Key "test1" not in handlerecord dictionary!')
        self.assertIn('test2', dict_record,
            'Key "test2" not in handlerecord dictionary!')
        self.assertIn('testdup', dict_record,
            'Key "testdup" not in handlerecord dictionary!')
        self.assertIn('HS_ADMIN', dict_record,
            'Key "HS_ADMIN" not in handlerecord dictionary!')

        self.assertEqual(dict_record['test1'], 'val1',
            'The value of "test1" is not "val1.')
        self.assertEqual(dict_record['test2'], 'val2',
            'The value of "test2" is not "val2.')
        self.assertIn(dict_record['testdup'], ("dup1", "dup2"),
            'The value of the duplicate key "testdup" should be "dup1" or "dup2".')
        self.assertIn('permissions', dict_record['HS_ADMIN'],
            'The HS_ADMIN has no permissions: '+dict_record['HS_ADMIN'])

        self.assertEqual(len(dict_record), 4,
            'The record should have a length of 5 (as the duplicate is ignored.')


    # get_handlerecord_indices_for_key

    def test_get_indices_for_key_normal(self):
        """Test getting the indices for a specific key."""

        handlerecord = json.load(open('resources/handlerecord_for_reading.json'))
        handle = handlerecord['handle']

        indices = self.inst.get_handlerecord_indices_for_key('test1', handlerecord['values'])
        self.assertEqual(len(indices),1,
            'There is more or less than 1 index!')
        self.assertEqual(indices[0], 3,
            'The index of "test1" is not 3.')

    def test_get_indices_for_key_duplicatekey(self):
        """Test getting the indices for a duplicate key."""

        handlerecord = json.load(open('resources/handlerecord_for_reading.json'))
        handle = handlerecord['handle']

        indices = self.inst.get_handlerecord_indices_for_key('testdup', handlerecord['values'])
        self.assertEqual(len(indices),2,
            'There is more or less than 2 indices!')
        self.assertIn(5, indices,
            '5 is not in indices for key "testdup".')
        self.assertIn(6, indices,
            '6 is not in indices for key "testdup".')

    def test_get_indices_for_key_inexistentkey(self):
        """Test getting the indices for an inexistent key."""

        handlerecord = json.load(open('resources/handlerecord_for_reading.json'))
        handle = handlerecord['handle']

        indices = self.inst.get_handlerecord_indices_for_key('test100', handlerecord['values'])
        self.assertEqual(len(indices),0,
            'There is more than 0 index!')
        self.assertEqual(indices,[],
            'Indices should be an empty list!')

# is_10320LOC_empty

    def test_is_10320LOC_empty_notempty(self):
        """Test if presence of 10320/LOC is detected."""
        handlerecord = json.load(open('resources/handlerecord_with_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_10320LOC_empty(handle, handlerecord)

        self.assertFalse(answer,
            'The record contains a 10320/LOC, but the is_empty does not return False.')

    def test_is_10320LOC_empty_no10320LOC(self):
        """Test if absence of 10320/LOC is detected."""
        handlerecord = json.load(open('resources/handlerecord_without_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_10320LOC_empty(handle, handlerecord)

        self.assertTrue(answer,
            'The record contains no 10320/LOC, but the is_empty does not return True.')

    def test_is_10320LOC_empty_empty10320LOC(self):
        """Test if emptiness of 10320/LOC is detected."""
        handlerecord = json.load(open('resources/handlerecord_with_empty_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_10320LOC_empty(handle, handlerecord)

        self.assertTrue(answer,
            'The record contains an empty 10320/LOC, but the is_empty does not return True.')

    # is_URL_contained_in_1302loc

    def test_is_URL_contained_in_10320LOC_true(self):
        """Test if presence of URL is found in 10320/LOC."""
        handlerecord = json.load(open('resources/handlerecord_with_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(handle,
                                                        'http://foo.bar',
                                                        handlerecord)
        val = self.inst.get_value_from_handle(handle, '10320/LOC', handlerecord)
        self.assertTrue(answer,
            'The URL exists in the 10320/LOC, and still the method does not return True:\n'+str(val))

    def test_is_URL_contained_in_10320LOC_false(self):
        """Test if absence of URL is detected in existing 10320/LOC."""
        handlerecord = json.load(open('resources/handlerecord_with_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(handle,
                                                        'http://bar.bar',
                                                        handlerecord)
        self.assertFalse(answer,
            'The 10320/LOC does not contain the URL, and still the method does not return False.')

    def test_is_URL_contained_in_inexistent_10320LOC(self):
        """Test if absence of URL is detected if 10320/LOC does not exist."""
        handlerecord = json.load(open('resources/handlerecord_without_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(handle,
                                                        'http://whatever.foo',
                                                        handlerecord)
        self.assertFalse(answer,
            'The 10320/LOC does not exist, and still the method does not return False.')

    def test_is_URL_contained_in_empty_10320LOC(self):
        """Test if absence of URL is detected if 10320/LOC is empty."""
        handlerecord = json.load(open('resources/handlerecord_with_empty_10320LOC.json'))
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(handle,
                                                        'http://whatever.foo',
                                                        handlerecord)
        self.assertFalse(answer,
            'The 10320/LOC is empty, and still the method does not return False.')
コード例 #6
0
class EUDATHandleClientReadaccessTestCase(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)

        # Read resources from file:
        self.testvalues = json.load(open(RESOURCES_FILE))

        # Test values that need to be given by user:
        self.handle = self.testvalues['handle_for_read_tests']
        self.handle_global = self.testvalues['handle_globally_resolvable']
        self.user = self.testvalues['user']

        # Optional:
        self.https_verify = True
        if 'HTTPS_verify' in self.testvalues:
            self.https_verify = self.testvalues['HTTPS_verify']
        self.url = 'http://hdl.handle.net'
        if 'handle_server_url_read' in self.testvalues.keys():
            self.url = self.testvalues['handle_server_url_read']
        self.path_to_api = None
        if 'url_extension_REST_API' in self.testvalues.keys():
            self.path_to_api = self.testvalues['url_extension_REST_API']

        # Others
        prefix = self.handle.split('/')[0]
        self.inexistent_handle = prefix+'/07e1fbf3-2b72-430a-a035-8584d4eada41'
        self.randompassword = '******'

    def setUp(self):
        """ For most test, provide a client instance with the user-specified
        handle server url."""

        self.inst = EUDATHandleClient(
            HTTPS_verify=self.https_verify,
            handle_server_url=self.url,
            url_extension_REST_API=self.path_to_api)

        # Before being able to run these tests without write access,
        # the handle that we use for testing must exist. With this code,
        # you can create it. You only need to create it once and leave it
        # on the server, it will not be modified and can be used eternally.
        if False:
            # This should always be false!!! Except for creating the
            # required handle once! 
            self.create_required_test_handles()

    def tearDown(self):
        pass
        pass

    def create_required_test_handles(self):

        # Creating an instance that knows how to write:
        pw = self.testvalues['password']
        inst = EUDATHandleClient.instantiate_with_username_and_password(
            self.testvalues['handle_server_url_write'],
            self.user,
            pw,
            HTTPS_verify=self.https_verify)

        authstring = self.inst.create_authentication_string(self.user, pw)
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Basic '+authstring
        }

        list_of_all_entries = [
            {
                "index":111,
                "type":"test1",
                "data":"val1"
            },
            {
                "index":2222,
                "type":"test2",
                "data":"val2"
            },
            {
                "index":333,
                "type":"test3",
                "data":"val3"
            },
            {
                "index":4,
                "type":"test4",
                "data":"val4"
            }
        ]

        testhandle = self.handle
        url = inst.make_handle_URL(testhandle)
        veri = self.https_verify
        head = headers
        data = json.dumps({'values':list_of_all_entries})
        resp = requests.put(url, data=data, headers=head, verify=veri)


    # retrieve_handle_record_json

    def test_retrieve_handle_record_json(self):
        """Test reading handle record from server."""

        rec = self.inst.retrieve_handle_record_json(self.handle)

        self.assertEqual(rec['values'][2]['type'], 'test3',
            'The type should be "test3".')
        self.assertEqual(rec['values'][2]['data']['value'], 'val3',
            'The value should be "val3".')

    # get_value_from_handle

    def test_get_value_from_handle_normal(self):
        """Test reading existent and inexistent handle value from server."""
        val = self.inst.get_value_from_handle(self.handle, 'test1')
        self.assertEqual(val, 'val1',
            'Retrieving "test1" should lead to "val1", but it lead to: '+str(val))

    def test_get_value_from_handle_inexistent_key(self):
        val = self.inst.get_value_from_handle(self.handle, 'test100')
        self.assertIsNone(val,
            'Retrieving "test100" should lead to "None", but it lead to: '+str(val))

    def test_get_value_from_handle_inexistent_record(self):
        """Test reading handle value from inexistent handle."""
        with self.assertRaises(HandleNotFoundException):
            val = self.inst.get_value_from_handle(self.inexistent_handle, 'anykey')

    # instantiate

    def test_instantiate_with_username_and_wrong_password(self):
        """Test instantiation of client: No exception if password wrong."""

        # Create client instance with username and password
        inst = EUDATHandleClient.instantiate_with_username_and_password(
            self.url,
            self.user,
            self.randompassword,
            HTTPS_verify=self.https_verify)
        self.assertIsInstance(inst, EUDATHandleClient)
        
    def test_instantiate_with_username_without_index_and_password(self):
        """Test instantiation of client: Exception if username has no index."""
        testusername_without_index = self.user.split(':')[1]

        # Run code to be tested + check exception:
        with self.assertRaises(HandleSyntaxError):

            # Create client instance with username and password
            inst = EUDATHandleClient.instantiate_with_username_and_password(
                self.url,
                testusername_without_index,
                self.randompassword,
                HTTPS_verify=self.https_verify)

    def test_instantiate_with_nonexistent_username_and_password(self):
        """Test instantiation of client: Exception if username does not exist."""
        testusername_inexistent = '100:'+self.inexistent_handle

        # Run code to be tested + check exception:
        with self.assertRaises(HandleNotFoundException):

            # Create client instance with username and password
            inst = EUDATHandleClient.instantiate_with_username_and_password(
                self.url,
                testusername_inexistent,
                self.randompassword,
                HTTPS_verify=self.https_verify)

    def test_instantiate_with_credentials(self):
        """Test instantiation of client: No exception if password wrong."""

        # Test variables
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            self.url,
            self.user,
            self.randompassword)

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(
            credentials,
            HTTPS_verify=self.https_verify)

        # Check desired outcomes
        self.assertIsInstance(inst, EUDATHandleClient)

    def test_instantiate_with_credentials_inexistentuser(self):
        """Test instantiation of client: Exception if username does not exist."""

        # Test variables
        testusername_inexistent = '100:'+self.inexistent_handle
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            self.url,
            testusername_inexistent,
            self.randompassword)

        # Run code to be tested + check exception:
        # Create instance with credentials
        with self.assertRaises(HandleNotFoundException):
            inst = EUDATHandleClient.instantiate_with_credentials(credentials,
                HTTPS_verify=self.https_verify)

        # If the user name has no index, exception is already thrown in credentials creation!
        #self.assertRaises(HandleSyntaxError, b2handle.PIDClientCredentials, 'url', 'prefix/suffix', randompassword)

    def test_instantiate_with_credentials_config_override(self):
        """Test instantiation of client: No exception if password wrong."""

        # Test variables
        credentials = MagicMock()
        config_from_cred = {}
        valuefoo = 'foo/foo/foo/'
        config_from_cred['REST_API_url_extension'] = valuefoo
        credentials.get_config = MagicMock(return_value=config_from_cred)
        credentials.get_username = MagicMock(return_value=self.user)
        credentials.get_password = MagicMock(return_value=self.randompassword)
        credentials.get_server_URL = MagicMock(return_value=self.url)

        self.assertEqual(credentials.get_config()['REST_API_url_extension'],valuefoo,
            'Config: '+str(credentials.get_config()))

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(
            credentials,
            HTTPS_verify=self.https_verify,
            REST_API_url_extension='api/handles')

        # If this raises an exception, it is because /foo/foo from the
        # credentials config was used as path. /foo/foo should be overridden
        # by the standard stuff.

        # Check desired outcomes
        self.assertIsInstance(inst, EUDATHandleClient)
        val = self.inst.get_value_from_handle(self.handle, 'test1')
        self.assertEqual(val, 'val1',
            'Retrieving "test1" should lead to "val1", but it lead to: '+str(val))

    def test_instantiate_with_credentials_config(self):
        """Test instantiation of client: No exception if password wrong."""

        # Test variables
        credentials = MagicMock()
        config_from_cred = {}
        valuefoo = 'foo/foo/foo/'
        config_from_cred['REST_API_url_extension'] = valuefoo
        credentials.get_config = MagicMock(return_value=config_from_cred)
        credentials.get_username = MagicMock(return_value=self.user)
        credentials.get_password = MagicMock(return_value=self.randompassword)
        credentials.get_server_URL = MagicMock(return_value=self.url)

        self.assertEqual(credentials.get_config()['REST_API_url_extension'],valuefoo,
            'Config: '+str(credentials.get_config()))

        # Run code to be tested
        # Create instance with credentials
        with self.assertRaises(GenericHandleError):
            inst = EUDATHandleClient.instantiate_with_credentials(
                credentials,
                HTTPS_verify=self.https_verify)

        # If this raises an exception, it is because /foo/foo from the
        # credentials config was used as path. /foo/foo should be overridden
        # by the standard stuff.

    def test_global_resolve(self):
        """Testing if instantiating with default handle server'works
        and if a handle is correctly retrieved. """

        # Create instance with default server url:
        inst = EUDATHandleClient(HTTPS_verify=self.https_verify)
        rec = inst.retrieve_handle_record_json(self.handle_global)

        self.assertIn('handle', rec,
            'Response lacks "handle".')
        self.assertIn('responseCode', rec,
            'Response lacks "responseCode".')

    def test_instantiate_for_read_access(self):
        """Testing if instantiating with default handle server works
        and if a handle is correctly retrieved. """

        # Create client instance with username and password
        inst = EUDATHandleClient.instantiate_for_read_access(HTTPS_verify=self.https_verify)
        rec = self.inst.retrieve_handle_record_json(self.handle)
        self.assertIsInstance(inst, EUDATHandleClient)
        self.assertIn('handle', rec,
            'Response lacks "handle".')
        self.assertIn('responseCode', rec,
            'Response lacks "responseCode".')
コード例 #7
0
class EUDATHandleClientReadaccessPatchedTestCase(unittest.TestCase):
    """Testing methods that read the 10320/loc entry."""

    def setUp(self):
        self.inst = EUDATHandleClient()

    def tearDown(self):
        pass

    # retrieve_handle_record_json:

    @patch("b2handle.handleclient.requests.get")
    def test_retrieve_handle_record_json_normal(self, getpatch):
        """Test if retrieve_handle_record_json returns the correct things.."""

        # Test variables:
        handlerecord = open("resources/handlerecord_for_reading.json").read()
        expected = json.loads(handlerecord)

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord)
        getpatch.return_value = mock_response

        # Call method and check result:
        received = self.inst.retrieve_handle_record_json(expected["handle"])
        self.assertEqual(received, expected, "Unexpected return from handle retrieval.")

    @patch("b2handle.handleclient.requests.get")
    def test_retrieve_handle_record_json_handle_does_not_exist(self, getpatch):
        """Test return value (None) if handle does not exist (retrieve_handle_record_json)."""

        # Test variables:
        testhandle = "dont/exist"

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        json_record = self.inst.retrieve_handle_record_json(testhandle)
        self.assertIsNone(
            json_record, "The return value should be None if the handle does not exist, not: " + str(json_record)
        )

    @patch("b2handle.handleclient.requests.get")
    def test_retrieve_handle_record_json_handle_empty(self, getpatch):
        """Test return value if handle is empty (retrieve_handle_record_json)."""

        # Test variables:
        testhandle = "dont/exist"

        # Define the replacement for the patched method:
        mock_response = MockResponse(empty=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        json_record = self.inst.retrieve_handle_record_json(testhandle)
        self.assertEquals(json_record["responseCode"], 200, "Unexpected return value: " + str(json_record))

    @patch("b2handle.handleclient.requests.get")
    def test_retrieve_handle_record_json_genericerror(self, getpatch):
        """Test exception if retrieve_handle_record_json returns a strange HTTP code."""

        # Test variables:
        testhandle = "dont/exist"

        # Define the replacement for the patched method:
        mock_response = MockResponse(status_code=99999)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(GenericHandleError):
            json_record = self.inst.retrieve_handle_record_json(testhandle)

    # retrieve_handle_record:

    # @patch('b2handle.handleclient.EUDATHandleClient._EUDATHandleClient__send_handle_get_request')
    @patch("b2handle.handleclient.requests.get")
    def test_retrieve_handle_record_when_json_not_given(self, getpatch):
        """Test retrieving a handle record"""

        # Test variables
        handlerecord_string = open("resources/handlerecord_for_reading.json").read()
        handlerecord_json = json.loads(handlerecord_string)
        testhandle = handlerecord_json["handle"]

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        dict_record = self.inst.retrieve_handle_record(testhandle)
        self.assertIn("test1", dict_record, 'Key "test1" not in handlerecord dictionary!')
        self.assertIn("test2", dict_record, 'Key "test2" not in handlerecord dictionary!')
        self.assertIn("testdup", dict_record, 'Key "testdup" not in handlerecord dictionary!')
        self.assertIn("HS_ADMIN", dict_record, 'Key "HS_ADMIN" not in handlerecord dictionary!')

        self.assertEqual(dict_record["test1"], "val1", 'The value of "test1" is not "val1.')
        self.assertEqual(dict_record["test2"], "val2", 'The value of "test2" is not "val2.')
        self.assertIn(
            dict_record["testdup"],
            ("dup1", "dup2"),
            'The value of the duplicate key "testdup" should be "dup1" or "dup2".',
        )
        self.assertIn(
            "permissions", dict_record["HS_ADMIN"], "The HS_ADMIN has no permissions: " + dict_record["HS_ADMIN"]
        )

        self.assertEqual(len(dict_record), 4, "The record should have a length of 5 (as the duplicate is ignored.")

    @patch("b2handle.handleclient.requests.get")
    def test_retrieve_handle_record_when_handle_is_wrong(self, getpatch):
        """Test error when retrieving a handle record with contradicting inputs."""

        # Test variable
        testhandle = "something/else"
        handlerecord_string = open("resources/handlerecord_for_reading.json").read()
        handlerecord_json = json.loads(handlerecord_string)

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(GenericHandleError):
            self.inst.retrieve_handle_record(testhandle)

    @patch("b2handle.handleclient.requests.get")
    def test_retrieve_handle_record_when_handle_is_None(self, getpatch):
        """Test error when retrieving a handle record with a None input."""

        # Test variable
        testhandle = None

        # Call method and check result:
        with self.assertRaises(HandleSyntaxError):
            self.inst.retrieve_handle_record(testhandle)

    @patch("b2handle.handleclient.requests.get")
    def test_retrieve_handle_record_when_handle_is_wrong(self, getpatch):
        """Test error when retrieving a nonexistent handle record."""

        # Test variable
        testhandle = "who/cares"

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        hrec = self.inst.retrieve_handle_record(testhandle)
        self.assertIsNone(hrec, "The handle record for a nonexistent handle should be None!")

    @patch("b2handle.handleclient.requests.get")
    def test_retrieve_handle_record_when_handlerecord_is_None(self, getpatch):
        """Test error when retrieving a handle record, giving a None type."""

        # Test variable
        handlerecord_string = open("resources/handlerecord_for_reading.json").read()
        handlerecord_json = json.loads(handlerecord_string)
        testhandle = handlerecord_json["handle"]
        givenrecord = None

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        dict_record = self.inst.retrieve_handle_record(testhandle, givenrecord)
        self.assertIn("test1", dict_record, 'Key "test1" not in handlerecord dictionary!')
        self.assertIn("test2", dict_record, 'Key "test2" not in handlerecord dictionary!')
        self.assertIn("testdup", dict_record, 'Key "testdup" not in handlerecord dictionary!')
        self.assertIn("HS_ADMIN", dict_record, 'Key "HS_ADMIN" not in handlerecord dictionary!')

        self.assertEqual(dict_record["test1"], "val1", 'The value of "test1" is not "val1.')
        self.assertEqual(dict_record["test2"], "val2", 'The value of "test2" is not "val2.')
        self.assertIn(
            dict_record["testdup"],
            ("dup1", "dup2"),
            'The value of the duplicate key "testdup" should be "dup1" or "dup2".',
        )
        self.assertIn(
            "permissions", dict_record["HS_ADMIN"], "The HS_ADMIN has no permissions: " + dict_record["HS_ADMIN"]
        )

        self.assertEqual(len(dict_record), 4, "The record should have a length of 5 (as the duplicate is ignored.")

    # get_value_from_handle

    @patch("b2handle.handleclient.requests.get")
    def test_get_value_from_handle_when_handle_inexistent(self, getpatch):
        """Test error when retrieving a handle record, giving a None type."""

        # Test variables
        testhandle = "who/cares"
        key = "foo"

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.get_value_from_handle(testhandle, key=key)

    # check if username exists

    @patch("b2handle.handleclient.requests.get")
    def test_check_if_username_exists_normal(self, getpatch):
        """Test whether username exists."""

        # Test variables
        handlerecord_string = open("resources/handlerecord_for_reading.json").read()
        handlerecord_json = json.loads(handlerecord_string)
        testhandle = "100:" + handlerecord_json["handle"]

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        res = self.inst.check_if_username_exists(testhandle)
        self.assertTrue(res, 'The handle exists, so "check_if_username_exists" should return true!')

    @patch("b2handle.handleclient.requests.get")
    def test_check_if_username_exists_inconsistent_info(self, getpatch):
        """Test exception when contradictory inputs are given."""

        # Test variables
        handlerecord_string = open("resources/handlerecord_for_reading.json").read()
        testhandle = "who/cares"

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(GenericHandleError):
            self.inst.check_if_username_exists(testhandle)

    @patch("b2handle.handleclient.requests.get")
    def test_check_if_username_exists_it_doesnot(self, getpatch):
        """Test exception"""

        # Test variables
        testhandle = "who/cares"

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.check_if_username_exists(testhandle)

    @patch("b2handle.handleclient.requests.get")
    def test_is_10320LOC_empty_handle_does_not_exist(self, getpatch):
        """Test exception"""

        # Test variables
        testhandle = "who/cares"

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.is_10320LOC_empty(testhandle)

    @patch("b2handle.handleclient.requests.get")
    def test_is_url_contained_in_10320LOC_handle_does_not_exist(self, getpatch):
        """Test exception"""

        # Test variables
        testhandle = "who/cares"
        one_url = "http://bla"
        list_of_urls = ["http://bla", "http://foo.foo"]

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.is_URL_contained_in_10320LOC(testhandle, url=one_url)
        with self.assertRaises(HandleNotFoundException):
            self.inst.is_URL_contained_in_10320LOC(testhandle, url=list_of_urls)

    # Instantiation

    @patch("b2handle.handleclient.requests.get")
    def test_instantiate_with_username_and_password_wrongpw(self, getpatch):

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True)
        getpatch.return_value = mock_response

        inst = EUDATHandleClient.instantiate_with_username_and_password(
            "http://someurl", "100:my/testhandle", "passywordy"
        )

        self.assertIsInstance(inst, EUDATHandleClient)

    @patch("b2handle.handleclient.requests.get")
    def test_instantiate_with_username_and_password_inexistentuser(self, getpatch):

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        with self.assertRaises(HandleNotFoundException):
            inst = EUDATHandleClient.instantiate_with_username_and_password(
                "http://someurl", "100:john/doe", "passywordy"
            )

    @patch("b2handle.handleclient.requests.get")
    def test_instantiate_with_credentials_inexistentuser(self, getpatch):
        """Test instantiation of client: Exception if username does not exist."""

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Test variables
        testusername_inexistent = "100:john/doe"
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            "some/url", testusername_inexistent, "some_password"
        )

        # Run code to be tested + check exception:
        # Create instance with credentials
        with self.assertRaises(HandleNotFoundException):
            inst = EUDATHandleClient.instantiate_with_credentials(credentials)

        # If the user name has no index, exception is already thrown in credentials creation!
        # self.assertRaises(HandleSyntaxError, b2handle.PIDClientCredentials, 'url', 'prefix/suffix', randompassword)

    @patch("b2handle.handleclient.requests.get")
    def test_instantiate_with_credentials(self, getpatch):
        """Test instantiation of client: No exception if password wrong."""

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True)
        getpatch.return_value = mock_response

        # Test variables
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            "some/url", "100:my/testhandle", "some_password_123"
        )

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(credentials)

        # Check desired outcomes
        self.assertIsInstance(inst, EUDATHandleClient)

    @patch("b2handle.handleclient.EUDATHandleClient.check_if_username_exists")
    def test_instantiate_with_credentials_config(self, checkpatch):
        """Test instantiation of client: No exception if password wrong."""

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True)
        checkpatch.return_value = mock_response

        # Test variables
        credentials = MockCredentials(restapi="foobar")

        self.assertEqual(
            credentials.get_config()["REST_API_url_extension"], "foobar", "Config: " + str(credentials.get_config())
        )

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(credentials)
        self.assertIsInstance(inst, EUDATHandleClient)

    @patch("b2handle.handleclient.EUDATHandleClient.check_if_username_exists")
    @patch("b2handle.handleclient.requests.get")
    def test_instantiate_with_credentials_config_override(self, getpatch, checkpatch):
        """Test instantiation of client: We pass a config value in the credentials
        and also as an arg in the instantiation. We want the latter to override the
        first one.
        """

        # Define the replacement for the patched method:
        # We pretend the username exists!
        mock_response = MockResponse(success=True)
        checkpatch.return_value = mock_response

        # Define the replacement for the patched GET:
        cont = {
            "responseCode": 1,
            "handle": "my/testhandle",
            "values": [
                {
                    "index": 111,
                    "type": "test1",
                    "data": {"format": "string", "value": "val1"},
                    "ttl": 86400,
                    "timestamp": "2015-09-30T15:08:49Z",
                },
                {
                    "index": 2222,
                    "type": "test2",
                    "data": {"format": "string", "value": "val2"},
                    "ttl": 86400,
                    "timestamp": "2015-09-30T15:08:49Z",
                },
                {
                    "index": 333,
                    "type": "test2",
                    "data": {"format": "string", "value": "val3"},
                    "ttl": 86400,
                    "timestamp": "2015-09-30T15:08:49Z",
                },
                {
                    "index": 4,
                    "type": "test4",
                    "data": {"format": "string", "value": "val4"},
                    "ttl": 86400,
                    "timestamp": "2015-09-30T15:08:49Z",
                },
            ],
        }
        mock_response = MockResponse(success=True, content=json.dumps(cont))
        getpatch.return_value = mock_response

        # Test variables
        # Passing mock credentials, give them the value "foobar", which
        # should be overridden!
        credentials = MockCredentials(restapi="foobar")
        self.assertEqual(
            credentials.get_config()["REST_API_url_extension"], "foobar", "Config: " + str(credentials.get_config())
        )

        # Run code to be tested
        # Create instance with credentials. It gets the "REST_API_url_extention"
        # from both the credentials and as a param.
        inst = EUDATHandleClient.instantiate_with_credentials(credentials, REST_API_url_extension="bar/bar/bar")
        self.assertIsInstance(inst, EUDATHandleClient)

        # How to know now which one was used?
        # Call a read and check its url! Did it get foobar or barbarbar appended?
        inst.get_value_from_handle("my/testhandle", "key")
        positional_args_passed = getpatch.call_args_list[len(getpatch.call_args_list) - 1][0]
        passed_url = positional_args_passed[0]

        # Compare with expected URL:
        self.assertIn("bar/bar/bar", passed_url, "bar/bar/bar is not specified in the URL " + passed_url)
class EUDATHandleClientReadaccessFaked10320LOCTestCase(unittest.TestCase):
    '''Testing methods that read the 10320/LOC entry.'''

    def setUp(self):
        self.inst = EUDATHandleClient()

    def tearDown(self):
        pass

    # is_10320LOC_empty

    def test_is_10320LOC_empty_notempty(self):
        """Test if presence of 10320/LOC is detected."""
        handlerecord = RECORD_WITH
        handle = handlerecord['handle']
        answer = self.inst.is_10320LOC_empty(handle, handlerecord)

        self.assertFalse(answer,
            'The record contains a 10320/LOC, but the is_empty does not return False.')

    def test_is_10320LOC_empty_no10320LOC(self):
        """Test if absence of 10320/LOC is detected."""
        handlerecord = RECORD_WITHOUT
        handle = handlerecord['handle']
        answer = self.inst.is_10320LOC_empty(handle, handlerecord)

        self.assertTrue(answer,
            'The record contains no 10320/LOC, but the is_empty does not return True.')

    def test_is_10320LOC_empty_empty10320LOC(self):
        """Test if emptiness of 10320/LOC is detected."""
        handlerecord = RECORD_WITH_EMPTY
        handle = handlerecord['handle']
        answer = self.inst.is_10320LOC_empty(handle, handlerecord)

        self.assertTrue(answer,
            'The record contains an empty 10320/LOC, but the is_empty does not return True.')

    # is_URL_contained_in_1302loc

    def test_is_URL_contained_in_10320LOC_true(self):
        """Test if presence of URL is found in 10320/LOC."""
        handlerecord = RECORD_WITH
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(handle,
                                                        'http://foo.bar',
                                                        handlerecord)
        val = self.inst.get_value_from_handle(handle, '10320/LOC', handlerecord)
        self.assertTrue(answer,
            'The URL exists in the 10320/LOC, and still the method does not return True:\n'+str(val))

    def test_is_URL_contained_in_10320LOC_false(self):
        """Test if absence of URL is detected in existing 10320/LOC."""
        handlerecord = RECORD_WITH
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(handle,
                                                        'http://bar.bar',
                                                        handlerecord)
        self.assertFalse(answer,
            'The 10320/LOC does not contain the URL, and still the method does not return False.')

    def test_is_URL_contained_in_inexistent_10320LOC(self):
        """Test if absence of URL is detected if 10320/LOC does not exist."""
        handlerecord = RECORD_WITHOUT
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(handle,
                                                        'http://whatever.foo',
                                                        handlerecord)
        self.assertFalse(answer,
            'The 10320/LOC does not exist, and still the method does not return False.')

    def test_is_URL_contained_in_empty_10320LOC(self):
        """Test if absence of URL is detected if 10320/LOC is empty."""
        handlerecord = RECORD_WITH_EMPTY
        handle = handlerecord['handle']
        answer = self.inst.is_URL_contained_in_10320LOC(handle,
                                                        'http://whatever.foo',
                                                        handlerecord)
        self.assertFalse(answer,
            'The 10320/LOC is empty, and still the method does not return False.')
コード例 #9
0
class EUDATHandleClientReadaccessTestCase(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)

        # Read resources from file:
        self.testvalues = json.load(open(RESOURCES_FILE))

        # Test values that need to be given by user:
        self.handle = self.testvalues['handle_for_read_tests']
        self.handle_global = self.testvalues['handle_globally_resolvable']
        self.user = self.testvalues['user']

        # Optional:
        self.https_verify = True
        if 'HTTPS_verify' in self.testvalues:
            self.https_verify = self.testvalues['HTTPS_verify']
        self.url = 'http://hdl.handle.net'
        if 'handle_server_url_read' in self.testvalues.keys():
            self.url = self.testvalues['handle_server_url_read']
        self.path_to_api = None
        if 'url_extension_REST_API' in self.testvalues.keys():
            self.path_to_api = self.testvalues['url_extension_REST_API']

        # Others
        prefix = self.handle.split('/')[0]
        self.inexistent_handle = prefix + '/07e1fbf3-2b72-430a-a035-8584d4eada41'
        self.randompassword = '******'

    def setUp(self):
        """ For most test, provide a client instance with the user-specified
        handle server url."""

        self.inst = EUDATHandleClient(HTTPS_verify=self.https_verify,
                                      handle_server_url=self.url,
                                      url_extension_REST_API=self.path_to_api)

        # Before being able to run these tests without write access,
        # the handle that we use for testing must exist. With this code,
        # you can create it. You only need to create it once and leave it
        # on the server, it will not be modified and can be used eternally.
        if False:
            # This should always be false!!! Except for creating the
            # required handle once!
            self.create_required_test_handles()

    def tearDown(self):
        pass
        pass

    def create_required_test_handles(self):

        # Creating an instance that knows how to write:
        pw = self.testvalues['password']
        inst = EUDATHandleClient.instantiate_with_username_and_password(
            self.testvalues['handle_server_url_write'],
            self.user,
            pw,
            HTTPS_verify=self.https_verify)

        authstring = self.inst.create_authentication_string(self.user, pw)
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + authstring
        }

        list_of_all_entries = [{
            "index": 111,
            "type": "test1",
            "data": "val1"
        }, {
            "index": 2222,
            "type": "test2",
            "data": "val2"
        }, {
            "index": 333,
            "type": "test3",
            "data": "val3"
        }, {
            "index": 4,
            "type": "test4",
            "data": "val4"
        }]

        testhandle = self.handle
        url = inst.make_handle_URL(testhandle)
        veri = self.https_verify
        head = headers
        data = json.dumps({'values': list_of_all_entries})
        resp = requests.put(url, data=data, headers=head, verify=veri)

    # retrieve_handle_record_json

    def test_retrieve_handle_record_json(self):
        """Test reading handle record from server."""

        rec = self.inst.retrieve_handle_record_json(self.handle)

        self.assertEqual(rec['values'][2]['type'], 'test3',
                         'The type should be "test3".')
        self.assertEqual(rec['values'][2]['data']['value'], 'val3',
                         'The value should be "val3".')

    # get_value_from_handle

    def test_get_value_from_handle_normal(self):
        """Test reading existent and inexistent handle value from server."""
        val = self.inst.get_value_from_handle(self.handle, 'test1')
        self.assertEqual(
            val, 'val1',
            'Retrieving "test1" should lead to "val1", but it lead to: ' +
            str(val))

    def test_get_value_from_handle_inexistent_key(self):
        val = self.inst.get_value_from_handle(self.handle, 'test100')
        self.assertIsNone(
            val,
            'Retrieving "test100" should lead to "None", but it lead to: ' +
            str(val))

    def test_get_value_from_handle_inexistent_record(self):
        """Test reading handle value from inexistent handle."""
        with self.assertRaises(HandleNotFoundException):
            val = self.inst.get_value_from_handle(self.inexistent_handle,
                                                  'anykey')

    # instantiate

    def test_instantiate_with_username_and_wrong_password(self):
        """Test instantiation of client: No exception if password wrong."""

        # Create client instance with username and password
        inst = EUDATHandleClient.instantiate_with_username_and_password(
            self.url,
            self.user,
            self.randompassword,
            HTTPS_verify=self.https_verify)
        self.assertIsInstance(inst, EUDATHandleClient)

    def test_instantiate_with_username_without_index_and_password(self):
        """Test instantiation of client: Exception if username has no index."""
        testusername_without_index = self.user.split(':')[1]

        # Run code to be tested + check exception:
        with self.assertRaises(HandleSyntaxError):

            # Create client instance with username and password
            inst = EUDATHandleClient.instantiate_with_username_and_password(
                self.url,
                testusername_without_index,
                self.randompassword,
                HTTPS_verify=self.https_verify)

    def test_instantiate_with_nonexistent_username_and_password(self):
        """Test instantiation of client: Exception if username does not exist."""
        testusername_inexistent = '100:' + self.inexistent_handle

        # Run code to be tested + check exception:
        with self.assertRaises(HandleNotFoundException):

            # Create client instance with username and password
            inst = EUDATHandleClient.instantiate_with_username_and_password(
                self.url,
                testusername_inexistent,
                self.randompassword,
                HTTPS_verify=self.https_verify)

    def test_instantiate_with_credentials(self):
        """Test instantiation of client: No exception if password wrong."""

        # Test variables
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            self.url, self.user, self.randompassword)

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(
            credentials, HTTPS_verify=self.https_verify)

        # Check desired outcomes
        self.assertIsInstance(inst, EUDATHandleClient)

    def test_instantiate_with_credentials_inexistentuser(self):
        """Test instantiation of client: Exception if username does not exist."""

        # Test variables
        testusername_inexistent = '100:' + self.inexistent_handle
        credentials = b2handle.clientcredentials.PIDClientCredentials(
            self.url, testusername_inexistent, self.randompassword)

        # Run code to be tested + check exception:
        # Create instance with credentials
        with self.assertRaises(HandleNotFoundException):
            inst = EUDATHandleClient.instantiate_with_credentials(
                credentials, HTTPS_verify=self.https_verify)

        # If the user name has no index, exception is already thrown in credentials creation!
        #self.assertRaises(HandleSyntaxError, b2handle.PIDClientCredentials, 'url', 'prefix/suffix', randompassword)

    def test_instantiate_with_credentials_config_override(self):
        """Test instantiation of client: No exception if password wrong."""

        # Test variables
        credentials = MagicMock()
        config_from_cred = {}
        valuefoo = 'foo/foo/foo/'
        config_from_cred['REST_API_url_extension'] = valuefoo
        credentials.get_config = MagicMock(return_value=config_from_cred)
        credentials.get_username = MagicMock(return_value=self.user)
        credentials.get_password = MagicMock(return_value=self.randompassword)
        credentials.get_server_URL = MagicMock(return_value=self.url)

        self.assertEqual(credentials.get_config()['REST_API_url_extension'],
                         valuefoo, 'Config: ' + str(credentials.get_config()))

        # Run code to be tested
        # Create instance with credentials
        inst = EUDATHandleClient.instantiate_with_credentials(
            credentials,
            HTTPS_verify=self.https_verify,
            REST_API_url_extension='api/handles')

        # If this raises an exception, it is because /foo/foo from the
        # credentials config was used as path. /foo/foo should be overridden
        # by the standard stuff.

        # Check desired outcomes
        self.assertIsInstance(inst, EUDATHandleClient)
        val = self.inst.get_value_from_handle(self.handle, 'test1')
        self.assertEqual(
            val, 'val1',
            'Retrieving "test1" should lead to "val1", but it lead to: ' +
            str(val))

    def test_instantiate_with_credentials_config(self):
        """Test instantiation of client: No exception if password wrong."""

        # Test variables
        credentials = MagicMock()
        config_from_cred = {}
        valuefoo = 'foo/foo/foo/'
        config_from_cred['REST_API_url_extension'] = valuefoo
        credentials.get_config = MagicMock(return_value=config_from_cred)
        credentials.get_username = MagicMock(return_value=self.user)
        credentials.get_password = MagicMock(return_value=self.randompassword)
        credentials.get_server_URL = MagicMock(return_value=self.url)

        self.assertEqual(credentials.get_config()['REST_API_url_extension'],
                         valuefoo, 'Config: ' + str(credentials.get_config()))

        # Run code to be tested
        # Create instance with credentials
        with self.assertRaises(GenericHandleError):
            inst = EUDATHandleClient.instantiate_with_credentials(
                credentials, HTTPS_verify=self.https_verify)

        # If this raises an exception, it is because /foo/foo from the
        # credentials config was used as path. /foo/foo should be overridden
        # by the standard stuff.

    def test_global_resolve(self):
        """Testing if instantiating with default handle server'works
        and if a handle is correctly retrieved. """

        # Create instance with default server url:
        inst = EUDATHandleClient(HTTPS_verify=self.https_verify)
        rec = inst.retrieve_handle_record_json(self.handle_global)

        self.assertIn('handle', rec, 'Response lacks "handle".')
        self.assertIn('responseCode', rec, 'Response lacks "responseCode".')

    def test_instantiate_for_read_access(self):
        """Testing if instantiating with default handle server works
        and if a handle is correctly retrieved. """

        # Create client instance with username and password
        inst = EUDATHandleClient.instantiate_for_read_access(
            HTTPS_verify=self.https_verify)
        rec = self.inst.retrieve_handle_record_json(self.handle)
        self.assertIsInstance(inst, EUDATHandleClient)
        self.assertIn('handle', rec, 'Response lacks "handle".')
        self.assertIn('responseCode', rec, 'Response lacks "responseCode".')