def test_store_credentials_overwrite(self): """Test overwriting qiskitrc credentials.""" credentials = Credentials('QISKITRC_TOKEN', url=QE_URL, hub='HUB') credentials2 = Credentials('QISKITRC_TOKEN_2', url=QE_URL) with custom_qiskitrc(): store_credentials(credentials) # Cause all warnings to always be triggered. warnings.simplefilter("always") # Attempt overwriting. with warnings.catch_warnings(record=True) as w: store_credentials(credentials) self.assertIn('already present', str(w[0])) with no_file('Qconfig.py'), no_envs(), mock_ibmq_provider(): # Attempt overwriting. store_credentials(credentials2, overwrite=True) qiskit.IBMQ.load_accounts() # Ensure that the credentials are the overwritten ones - note that the # 'hub' parameter was removed. self.assertEqual(len(qiskit.IBMQ._accounts), 1) self.assertEqual( list(qiskit.IBMQ._accounts.values())[0].credentials.token, 'QISKITRC_TOKEN_2')
def select_credentials(self, url): if url is not None: credentials = Credentials('', url) if credentials.unique_id() in self._credentials: self._selected_credentials = self._credentials[ credentials.unique_id()] return self._selected_credentials
def set_credentials(self, token, url, proxy_urls=None): if url is not None and token is not None: proxies = {} if proxy_urls is None else {'urls': proxy_urls} credentials = Credentials(token, url, proxies=proxies) self._credentials[credentials.unique_id()] = credentials self._credentials_changed = True return credentials return None
def _get_credentials(test_object, test_options): """ Finds the credentials for a specific test and options. Args: test_object (QiskitTestCase): The test object asking for credentials test_options (dict): Options after QISKIT_TESTS was parsed by get_test_options. Returns: Credentials: set of credentials Raises: Exception: When the credential could not be set and they are needed for that set of options """ dummy_credentials = Credentials( 'dummyapiusersloginWithTokenid01', 'https://quantumexperience.ng.bluemix.net/api') if test_options['mock_online']: return dummy_credentials if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', False): # 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('IBMQ_TOKEN'), os.getenv('IBMQ_URL')) else: # 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[ dummy_credentials.unique_id()] except KeyError: pass # Use the first available credentials. return list(discovered_credentials.values())[0] # No user credentials were found. if test_options['rec']: raise Exception( 'Could not locate valid credentials. You need them for recording ' 'tests against the remote API.') test_object.log.warning( "No user credentials were detected. Running with mocked data.") test_options['mock_online'] = True return dummy_credentials
def remove_credentials(self, url): if url is not None: credentials = Credentials('', url) if credentials.unique_id() in self._credentials: del self._credentials[credentials.unique_id()] self._credentials_changed = True if self._selected_credentials is not None and self._selected_credentials.unique_id( ) == credentials.unique_id(): self._selected_credentials = None credentials = list(self._credentials.values()) if len(credentials) > 0: self._selected_credentials = credentials[0]
def test_qconfig_over_all(self): """Test order, with qconfig""" credentials = Credentials('QISKITRC_TOKEN', url=QE_URL) with custom_qiskitrc(): # Prepare the credentials: qconfig, env and qiskitrc present store_credentials(credentials) with custom_qconfig(b"APItoken='QCONFIG_TOKEN'"),\ custom_envs({'QE_TOKEN': 'ENVIRON_TOKEN'}): credentials = discover_credentials() self.assertEqual(len(credentials), 1) self.assertEqual(list(credentials.values())[0].token, 'QCONFIG_TOKEN')
def test_environ_over_qiskitrc(self): """Test order, without qconfig""" credentials = Credentials('QISKITRC_TOKEN', url=QE_URL) with custom_qiskitrc(): # Prepare the credentials: both env and qiskitrc present store_credentials(credentials) with no_file('Qconfig.py'), 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 register_and_get_operational_backends(): # update registration info using internal methods because: # at this point I don't want to save to or removecredentials from disk # I want to update url, proxies etc without removing token and # re-adding in 2 methods ibmq_backends = [] try: credentials = None preferences = Preferences() url = preferences.get_url() token = preferences.get_token() if url is not None and url != '' and token is not None and token != '': credentials = Credentials(token, url, proxies=preferences.get_proxies({})) if credentials is not None: qiskit.IBMQ._accounts[ credentials.unique_id()] = IBMQSingleProvider( credentials, qiskit.IBMQ) logger.debug("Registered with Qiskit successfully.") ibmq_backends = [ x.name() for x in qiskit.IBMQ.backends(url=url, token=token) ] except Exception as e: logger.debug("Failed to register with Qiskit: {}".format(str(e))) backends = set() aer_backends = [x.name() for x in qiskit.Aer.backends()] for aer_backend in aer_backends: backend = None for group_name, names in qiskit.Aer.grouped_backend_names().items( ): if aer_backend in names: backend = group_name break if backend is None: backend = aer_backend supported = True for unsupported_backend in QuantumAlgorithm.UNSUPPORTED_BACKENDS: if backend.startswith(unsupported_backend): supported = False break if supported: backends.add(backend) return list(backends) + ibmq_backends
def save(self): if self._credentials_changed: store_credentials(Credentials( self._token, self._url, proxies=self.get_proxies({})), overwrite=True) self._credentials_changed = False if self._logging_config_changed or self._packages_changed: with open(self._filepath, 'w') as fp: json.dump(self._preferences, fp, sort_keys=True, indent=4) self._logging_config_changed = False self._packages_changed = False
def test_store_credentials_overwrite(self): """Test overwriting qiskitrc credentials.""" credentials = Credentials('QISKITRC_TOKEN', url=QE_URL, hub='HUB') credentials2 = Credentials('QISKITRC_TOKEN_2', url=QE_URL) with custom_qiskitrc(): store_credentials(credentials) # Attempt overwriting. with self.assertRaises(QISKitError) as context_manager: store_credentials(credentials) self.assertIn('already present', str(context_manager.exception)) with no_file('Qconfig.py'), no_envs(), mock_ibmq_provider(): # Attempt overwriting. store_credentials(credentials2, overwrite=True) qiskit.IBMQ.load_accounts() # Ensure that the credentials are the overwritten ones - note that the # 'hub' parameter was removed. self.assertEqual(len(qiskit.IBMQ._accounts), 1) self.assertEqual(list(qiskit.IBMQ._accounts.values())[0].credentials.token, 'QISKITRC_TOKEN_2')
def get_credentials_with_same_key(self, url): if url is not None: credentials = Credentials('', url) return self._credentials.get(credentials.unique_id()) return False