class RESTHandleClientReadaccessFakedTestCase(unittest.TestCase): '''Testing methods for retrieving values and indices.''' def setUp(self): self.inst = RESTHandleClient() 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 = RECORD handle = RECORD['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 = RECORD 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 = RECORD 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 = 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 = RECORD 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 = RECORD 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 = RECORD 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 = RECORD 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 = RECORD 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!')
class RESTHandleClientNoaccessTestCase(unittest.TestCase): def setUp(self): self.inst = RESTHandleClient() def tearDown(self): pass # Init def test_constructor_no_args(self): """Test constructor without args: No exception raised.""" inst = RESTHandleClient() self.assertIsInstance(inst, RESTHandleClient, 'Not a client instance!') def test_constructor_with_url(self): """Test constructor with one arg (well-formatted server URL): No exception raised.""" inst = RESTHandleClient('http://foo.bar') self.assertIsInstance(inst, RESTHandleClient, 'Not a client instance!') def test_constructor_with_url(self): """Test constructor with one arg (ill-formatted server URL): No exception raised.""" inst = RESTHandleClient('foo') self.assertIsInstance(inst, RESTHandleClient, 'Not a client instance!') def test_instantiate_for_read_access(self): """Testing if instantiating with default handle server works. """ # Create client instance with username and password inst = RESTHandleClient.instantiate_for_read_access() self.assertIsInstance(inst, RESTHandleClient) def test_instantiate_for_read_an_search(self): """Testing if instantiating with default handle server works. """ # Try to create client instance for search without a search URL: with self.assertRaises(TypeError): inst = RESTHandleClient.instantiate_for_read_and_search( None, 'johndoe', 'passywordy') def test_instantiate_with_username_and_password_noindex(self): # Try to ceate client instance with username and password with self.assertRaises(HandleSyntaxError): inst = RESTHandleClient.instantiate_with_username_and_password( 'someurl', 'johndoe', 'passywordy') # PID generation def test_generate_PID_name_without_prefix(self): """Test PID generation without prefix.""" uuid = self.inst.generate_PID_name() self.assertFalse('/' in uuid, 'There is a slash in the generated PID, even though no prefix was specified.') def test_generate_PID_name_with_prefix(self): """Test PID generation with prefix.""" prefix = 'aprefix' uuid = self.inst.generate_PID_name(prefix) self.assertTrue(prefix+'/' in uuid, 'The specified prefix is not present in the generated PID.') # Handle syntax def test_check_handle_syntax_normal(self): """Test check handle syntax""" syntax_checked = check_handle_syntax("foo/bar") self.assertTrue(syntax_checked) def test_check_handle_syntax_two_slashes(self): """Handle Syntax: No exception if too many slashes in handle.""" check_handle_syntax("foo/bar/foo") def test_check_handle_syntax_no_slashes(self): """Handle Syntax: Exception if too many slashes in handle.""" with self.assertRaises(HandleSyntaxError): check_handle_syntax("foobar") def test_check_handle_syntax_no_prefix(self): """Handle Syntax: Exception if no prefix.""" with self.assertRaises(HandleSyntaxError): check_handle_syntax("/bar") def test_check_handle_syntax_no_suffix(self): """Handle Syntax: Exception if no suffix.""" with self.assertRaises(HandleSyntaxError): check_handle_syntax("foo/") def test_check_handle_syntax_with_index(self): """Test check handle syntax with index.""" syntax_checked = check_handle_syntax("300:foo/bar") self.assertTrue(syntax_checked, 'The syntax of the handle is not index:prefix/suffix.') def test_check_handle_syntax_none(self): """Test check handle syntax where handle is None""" with self.assertRaises(HandleSyntaxError): syntax_checked = check_handle_syntax(None) def test_check_handle_syntax_with_index_nan(self): """Handle Syntax: Exception if index not a number.""" with self.assertRaises(HandleSyntaxError): check_handle_syntax_with_index("nonumber:foo/bar") def test_check_handle_syntax_with_index_noindex(self): """Handle Syntax: Exception if index not existent.""" with self.assertRaises(HandleSyntaxError): check_handle_syntax_with_index("index/missing") def test_check_handle_syntax_with_index_twocolons(self): """Handle Syntax: Exception if two colons.""" with self.assertRaises(HandleSyntaxError): check_handle_syntax_with_index("too:many:colons") def test_check_handle_syntax_with_index_onlyindex(self): """Handle Syntax: Exception if no prefix and suffix.""" with self.assertRaises(HandleSyntaxError): check_handle_syntax_with_index("onlyindex:") def test_remove_index_from_handle(self): handle_with_index = "300:foo/bar" syntax_checked = check_handle_syntax(handle_with_index) self.assertTrue(syntax_checked, 'Test precondition failed!') index, handle = remove_index_from_handle(handle_with_index) syntax_checked = check_handle_syntax(handle) self.assertTrue(syntax_checked, 'After removing the index, the syntax of the handle should '+\ 'be prefix/suffix.') def test_remove_index_noindex(self): handle_with_index = "foo/bar" syntax_checked = check_handle_syntax(handle_with_index) self.assertTrue(syntax_checked, 'Test precondition failed!') index, handle = remove_index_from_handle(handle_with_index) syntax_checked = check_handle_syntax(handle) self.assertTrue(syntax_checked, 'After removing the index, the syntax of the handle should '+\ 'be prefix/suffix.') def test_remove_index_toomany(self): handle_with_index = "100:100:foo/bar" with self.assertRaises(HandleSyntaxError): index, handle = remove_index_from_handle(handle_with_index) # retrieve handle record (failing before any server access) def test_retrieve_handle_record_json_handlesyntax_wrong(self): """Test exception if handle syntax is wrong (retrieve_handle_record_json).""" with self.assertRaises(HandleSyntaxError): json_record = self.inst.retrieve_handle_record_json('testhandle') def test_retrieve_handle_record_when_handle_is_None(self): """Test error when retrieving a handle record with a None input.""" # Call method and check result: with self.assertRaises(HandleSyntaxError): self.inst.retrieve_handle_record(None) # make_authentication_string def test_create_authentication_string(self): auth = create_authentication_string('100:user/name', 'password123') expected = 'MTAwJTNBdXNlci9uYW1lOnBhc3N3b3JkMTIz' self.assertEquals(expected, auth, 'Authentication string is: '+auth+', but should be: '+expected)
class RESTHandleClientReadaccessPatchedTestCase(unittest.TestCase): '''Testing methods that read the 10320/loc entry.''' def setUp(self): self.inst = RESTHandleClient() def tearDown(self): pass # retrieve_handle_record_json: @mock.patch('pyhandle.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('pyhandle.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('pyhandle.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('pyhandle.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('pyhandle.handleclient.RESTHandleClient._EUDATHandleClient__send_handle_get_request') @mock.patch('pyhandle.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('pyhandle.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('pyhandle.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('pyhandle.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('pyhandle.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('pyhandle.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) # Instantiation @mock.patch('pyhandle.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 = RESTHandleClient.instantiate_with_username_and_password( 'http://someurl', '100:my/testhandle', 'passywordy') self.assertIsInstance(inst, RESTHandleClient) @mock.patch('pyhandle.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 = RESTHandleClient.instantiate_with_username_and_password( 'http://someurl', '100:john/doe', 'passywordy') @mock.patch('pyhandle.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 = pyhandle.clientcredentials.PIDClientCredentials( client='client', 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 = RESTHandleClient.instantiate_with_credentials(credentials) # If the user name has no index, exception is already thrown in credentials creation! #self.assertRaises(HandleSyntaxError, pyhandle.PIDClientCredentials, 'url', 'prefix/suffix', randompassword) @mock.patch('pyhandle.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 = pyhandle.clientcredentials.PIDClientCredentials( client='client', handle_server_url='some/url', username='******', password='******') # Run code to be tested # Create instance with credentials inst = RESTHandleClient.instantiate_with_credentials(credentials) # Check desired outcomes self.assertIsInstance(inst, RESTHandleClient) @mock.patch('pyhandle.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 = RESTHandleClient.instantiate_with_credentials(credentials) self.assertIsInstance(inst, RESTHandleClient) @mock.patch('pyhandle.handlesystemconnector.HandleSystemConnector.check_if_username_exists') @mock.patch('pyhandle.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 = RESTHandleClient.instantiate_with_credentials( credentials, REST_API_url_extension='bar/bar/bar') self.assertIsInstance(inst, RESTHandleClient) # 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)