def test_verify_param(self): """Test 'verify' arg is acknowledged.""" false_verify_expected_result = {'verify': False} false_verify_credentials = Credentials( 'dummy_token', 'https://dummy_url', verify=False) result = false_verify_credentials.connection_parameters() self.assertDictEqual(false_verify_expected_result, result)
def test_store_credentials_overwrite(self): """Test overwriting qiskitrc credentials.""" credentials = Credentials('QISKITRC_TOKEN', url=QE2_AUTH_URL) credentials2 = Credentials('QISKITRC_TOKEN_2', url=QE2_AUTH_URL) factory = IBMQFactory() with custom_qiskitrc(): store_credentials(credentials) # Cause all warnings to always be triggered. warnings.simplefilter("always") # Get the logger for `store_credentials`. config_rc_logger = logging.getLogger(store_credentials.__module__) # Attempt overwriting. with self.assertLogs(logger=config_rc_logger, level='WARNING') as log_records: store_credentials(credentials) self.assertIn('already present', log_records.output[0]) with no_envs(CREDENTIAL_ENV_VARS), mock_ibmq_provider(): # Attempt overwriting. store_credentials(credentials2, overwrite=True) factory.load_account() # Ensure that the credentials are the overwritten ones. self.assertEqual(factory._credentials, credentials2)
def test_proxies_param_with_ntlm(self): """Test proxies with NTLM credentials.""" urls = {'http': 'localhost:8080', 'https': 'localhost:8080'} proxies_with_ntlm_dict = { 'urls': urls, 'username_ntlm': 'domain\\username', 'password_ntlm': 'password' } ntlm_expected_result = { 'verify': True, 'proxies': urls, 'auth': HttpNtlmAuth('domain\\username', 'password') } proxies_with_ntlm_credentials = Credentials( 'dummy_token', 'https://dummy_url', proxies=proxies_with_ntlm_dict) result = proxies_with_ntlm_credentials.connection_parameters() # Verify the NTLM credentials. self.assertEqual( ntlm_expected_result['auth'].username, result['auth'].username) self.assertEqual( ntlm_expected_result['auth'].password, result['auth'].password) # Remove the HttpNtlmAuth objects for direct comparison of the dicts. ntlm_expected_result.pop('auth') result.pop('auth') self.assertDictEqual(ntlm_expected_result, result)
def test_proxy_param(self): """Test using only proxy urls (no NTLM credentials).""" urls = {'http': 'localhost:8080', 'https': 'localhost:8080'} proxies_only_expected_result = {'verify': True, 'proxies': urls} proxies_only_credentials = Credentials( 'dummy_token', 'https://dummy_url', proxies={'urls': urls}) result = proxies_only_credentials.connection_parameters() self.assertDictEqual(proxies_only_expected_result, result)
def test_malformed_proxy_param(self): """Test input with malformed nesting of the proxies dictionary.""" urls = {'http': 'localhost:8080', 'https': 'localhost:8080'} malformed_nested_proxies_dict = {'proxies': urls} malformed_nested_credentials = Credentials( 'dummy_token', 'https://dummy_url', proxies=malformed_nested_proxies_dict) # Malformed proxy entries should be ignored. expected_result = {'verify': True} result = malformed_nested_credentials.connection_parameters() self.assertDictEqual(expected_result, result)
def test_environ_over_qiskitrc(self): """Test credential discovery order.""" credentials = Credentials('QISKITRC_TOKEN', url=QE2_AUTH_URL) with custom_qiskitrc(): # Prepare the credentials: both env and qiskitrc present store_credentials(credentials) with custom_envs({'QE_TOKEN': 'ENVIRON_TOKEN', 'QE_URL': 'ENVIRON_URL'}): credentials, _ = discover_credentials() self.assertEqual(len(credentials), 1) self.assertEqual(list(credentials.values())[0].token, 'ENVIRON_TOKEN')
def test_multiple_credentials(self): """Test converting multiple credentials.""" with custom_qiskitrc(): store_credentials(Credentials('A', url=QE2_AUTH_URL)) store_credentials(Credentials('B', url=IBMQ_TEMPLATE.format('a', 'b', 'c'))) store_credentials(Credentials('C', url=IBMQ_TEMPLATE.format('d', 'e', 'f'))) _ = update_credentials(force=True) # Assert over the stored (updated) credentials. loaded_accounts, _ = read_credentials_from_qiskitrc() # We don't assert over the token, as it depends on the order of # the qiskitrc, which is not guaranteed. self.assertCorrectApi2Credentials(None, loaded_accounts)
def test_malformed_ntlm_params(self): """Test input with malformed NTLM credentials.""" urls = {'http': 'localhost:8080', 'https': 'localhost:8080'} malformed_ntlm_credentials_dict = { 'urls': urls, 'username_ntlm': 1234, 'password_ntlm': 5678 } malformed_ntlm_credentials = Credentials( 'dummy_token', 'https://dummy_url', proxies=malformed_ntlm_credentials_dict) # Should raise when trying to do username.split('\\', <int>) # in NTLM credentials due to int not facilitating 'split'. with self.assertRaises(AttributeError): _ = malformed_ntlm_credentials.connection_parameters()
def _get_credentials(): """Finds the credentials for a specific test and options. Returns: Credentials: set of credentials Raises: Exception: When the credential could not be set and they are needed for that set of options. """ if os.getenv('USE_STAGING_CREDENTIALS', ''): # Special case: instead of using the standard credentials mechanism, # load them from different environment variables. This assumes they # will always be in place, as is used by the Travis setup. return Credentials(os.getenv('QE_STAGING_TOKEN'), os.getenv('QE_STAGING_URL')) # Attempt to read the standard credentials. discovered_credentials, _ = discover_credentials() if discovered_credentials: # Decide which credentials to use for testing. if len(discovered_credentials) > 1: try: # Attempt to use QE credentials. return discovered_credentials[(None, None, None)] except KeyError: pass # Use the first available credentials. return list(discovered_credentials.values())[0] raise Exception('Unable to locate valid credentials.')
def test_auth2_credentials(self): """Test converting already API 2 auth credentials.""" with custom_qiskitrc(): store_credentials(Credentials('A', url=QE2_AUTH_URL)) credentials = update_credentials(force=True) # No credentials should be returned. self.assertIsNone(credentials)
def test_proxy_urls(self, qe_token, qe_url): """Test different forms of the proxy urls.""" test_urls = [ 'http://{}:{}'.format(ADDRESS, PORT), '//{}:{}'.format(ADDRESS, PORT), 'http:{}:{}'.format(ADDRESS, PORT), 'http://*****:*****@{}:{}'.format(ADDRESS, PORT) ] for proxy_url in test_urls: with self.subTest(proxy_url=proxy_url): credentials = Credentials( qe_token, qe_url, proxies={'urls': { 'https': proxy_url }}) version_finder = VersionClient( credentials.base_url, **credentials.connection_parameters()) version_finder.version()
def test_api2_non_auth_credentials(self): """Test converting api 2 non auth credentials.""" with custom_qiskitrc(): store_credentials(Credentials('A', url=QE2_URL)) _ = update_credentials(force=True) # Assert over the stored (updated) credentials. loaded_accounts, _ = read_credentials_from_qiskitrc() self.assertCorrectApi2Credentials('A', loaded_accounts)
def test_qconsole_credentials(self): """Test converting Qconsole credentials.""" with custom_qiskitrc(): store_credentials(Credentials('A', url=IBMQ_TEMPLATE.format('a', 'b', 'c'))) _ = update_credentials(force=True) # Assert over the stored (updated) credentials. loaded_accounts, _ = read_credentials_from_qiskitrc() self.assertCorrectApi2Credentials('A', loaded_accounts)
def __init__(self, access_token: str, credentials: Credentials) -> None: """ExperimentClient constructor. Args: access_token: IBM Quantum Experience access token. credentials: Account credentials. """ self._session = RetrySession(credentials.experiment_url, access_token, **credentials.connection_parameters()) self.base_api = Api(self._session)
def test_unknown_credentials(self): """Test converting credentials with an unknown URL.""" with custom_qiskitrc(): store_credentials(Credentials('A', url='UNKNOWN_URL')) credentials = update_credentials(force=True) # No credentials should be returned nor updated. self.assertIsNone(credentials) loaded_accounts, _ = read_credentials_from_qiskitrc() self.assertEqual(list(loaded_accounts.values())[0].url, 'UNKNOWN_URL')
def __init__( self, access_token: str, credentials: Credentials, ) -> None: """RandomClient constructor. Args: access_token: IBM Quantum Experience access token. credentials: Account credentials. """ self._session = RetrySession(credentials.extractor_url, access_token, **credentials.connection_parameters()) self.random_api = Random(self._session)
def test_proxy_credentials(self): """Test converting credentials with proxy values.""" with custom_qiskitrc(): store_credentials(Credentials('A', url=IBMQ_TEMPLATE.format('a', 'b', 'c'), proxies=PROXIES)) _ = update_credentials(force=True) # Assert over the stored (updated) credentials. loaded_accounts, _ = read_credentials_from_qiskitrc() self.assertCorrectApi2Credentials('A', loaded_accounts) # Extra assert on preserving proxies. credentials = list(loaded_accounts.values())[0] self.assertEqual(credentials.proxies, PROXIES)
def test_no_proxy_params(self): """Test when no proxy parameters are passed.""" no_params_expected_result = {'verify': True} no_params_credentials = Credentials('dummy_token', 'https://dummy_url') result = no_params_credentials.connection_parameters() self.assertDictEqual(no_params_expected_result, result)