예제 #1
0
    def _(*args, **kwargs):
        # pylint: disable=invalid-name
        if SKIP_ONLINE_TESTS:
            raise unittest.SkipTest('Skipping online tests')

        # Cleanup the credentials, as this file is shared by the tests.
        from qiskit.wrapper import _wrapper
        _wrapper._DEFAULT_PROVIDER = DefaultQISKitProvider()

        # Attempt to read the standard credentials.
        account_name = get_account_name(IBMQProvider)
        discovered_credentials = discover_credentials()
        if account_name in discovered_credentials.keys():
            credentials = discovered_credentials[account_name]
            kwargs.update({
                'QE_TOKEN': credentials.get('token'),
                'QE_URL': credentials.get('url'),
                'hub': credentials.get('hub'),
                'group': credentials.get('group'),
                'project': credentials.get('project'),
            })
        else:
            raise Exception('Could not locate valid credentials')

        return func(*args, **kwargs)
예제 #2
0
    def __init__(self):
        """Create Preferences object."""
        self._preferences = {
            'version': Preferences._VERSION
        }
        self._packages_changed = False
        self._credentials_changed = False
        self._logging_config_changed = False
        self._token = None
        self._url = Preferences.URL
        self._proxy_urls = None

        credentials = discover_credentials()
        if credentials is not None:
            credentials = credentials.get(get_account_name(IBMQProvider))
            if credentials is not None:
                if 'token' in credentials:
                    self._token = credentials['token']
                if 'url' in credentials:
                    self._url = credentials['url']
                if 'proxies' in credentials and isinstance(credentials['proxies'], dict) and 'urls' in credentials['proxies']:
                    self._proxy_urls = credentials['proxies']['urls']

        home = os.path.expanduser("~")
        self._filepath = os.path.join(home, Preferences._FILENAME)
        try:
            with open(self._filepath) as json_pref:
                self._preferences = json.load(json_pref)
        except:
            pass
예제 #3
0
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:
        dict: Credentials in a dictionary

    Raises:
        Exception: When the credential could not be set and they are needed for that set of options
    """

    dummy_credentials = {
        'qe_token': 'dummyapiusersloginWithTokenid01',
        'qe_url': '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.
        test_object.using_ibmq_credentials = True
        return {
            'qe_token': os.getenv('IBMQ_TOKEN'),
            'qe_url': os.getenv('IBMQ_URL')
        }
    else:
        # Attempt to read the standard credentials.
        account_name = get_account_name(IBMQProvider)
        discovered_credentials = discover_credentials()
        if account_name in discovered_credentials.keys():
            credentials = discovered_credentials[account_name]
            if all(item in credentials.get('url')
                   for item in ['Hubs', 'Groups', 'Projects']):
                test_object.using_ibmq_credentials = True
            return {
                'qe_token': credentials.get('token'),
                'qe_url': credentials.get('url')
            }

    # 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
예제 #4
0
    def test_environ_over_qiskitrc(self):
        """Test order, without qconfig"""
        with custom_qiskitrc():
            # Prepare the credentials: both env and qiskitrc present
            qiskit.wrapper.store_credentials('QISKITRC_TOKEN')
            with no_file('Qconfig.py'), custom_envs({'QE_TOKEN': 'ENVIRON_TOKEN'}):
                credentials = discover_credentials()

        self.assertIn(self.ibmq_account_name, credentials)
        self.assertEqual(credentials[self.ibmq_account_name]['token'], 'ENVIRON_TOKEN')
예제 #5
0
def register(*args, provider_class=IBMQProvider, **kwargs):
    """
    Authenticate against an online backend provider.
    This is a factory method that returns the provider that gets registered.

    Note that if no parameters are passed, this method will try to
    automatically discover the credentials for IBMQ in the following places,
    in order::

        1. in the `Qconfig.py` file in the current working directory.
        2. in the environment variables.
        3. in the `qiskitrc` configuration file.

    Args:
        args (tuple): positional arguments passed to provider class initialization
        provider_class (BaseProvider): provider class
        kwargs (dict): keyword arguments passed to provider class initialization.
            For the IBMQProvider default this can include things such as:

                * token (str): The token used to register on the online backend such
                    as the quantum experience.
                * url (str): The url used for online backend such as the quantum
                    experience.
                * hub (str): The hub used for online backend.
                * group (str): The group used for online backend.
                * project (str): The project used for online backend.
                * proxies (dict): Proxy configuration for the API, as a dict with
                    'urls' and credential keys.
                * verify (bool): If False, ignores SSL certificates errors.

    Returns:
        BaseProvider: the provider instance that was just registered.

    Raises:
        QISKitError: if the provider could not be registered (e.g. due to
        conflict, or if no credentials were provided.)
    """
    # Try to autodiscover credentials if not passed.
    if not args and not kwargs and provider_class == IBMQProvider:
        kwargs = credentials.discover_credentials().get(
            credentials.get_account_name(IBMQProvider)) or {}
        if not kwargs:
            raise QISKitError(
                'No IBMQ credentials found. Please pass them explicitly or '
                'store them before calling register() with store_credentials()'
            )

    try:
        provider = provider_class(*args, **kwargs)
    except Exception as ex:
        raise QISKitError(
            "Couldn't instantiate provider! Error: {0}".format(ex))

    _DEFAULT_PROVIDER.add_provider(provider)
    return provider
예제 #6
0
    def test_qconfig_over_all(self):
        """Test order, with qconfig"""
        with custom_qiskitrc():
            # Prepare the credentials: qconfig, env and qiskitrc present
            qiskit.wrapper.store_credentials('QISKITRC_TOKEN')
            with custom_qconfig(b"APItoken='QCONFIG_TOKEN'"),\
                    custom_envs({'QE_TOKEN': 'ENVIRON_TOKEN'}):
                credentials = discover_credentials()

        self.assertIn(self.ibmq_account_name, credentials)
        self.assertEqual(credentials[self.ibmq_account_name]['token'], 'QCONFIG_TOKEN')
예제 #7
0
    def _(*args, **kwargs):
        # pylint: disable=invalid-name
        if SKIP_ONLINE_TESTS:
            raise unittest.SkipTest('Skipping online tests')

        # Cleanup the credentials, as this file is shared by the tests.
        from qiskit.wrapper import _wrapper
        _wrapper._DEFAULT_PROVIDER = DefaultQISKitProvider()

        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.
            kwargs.update({
                'QE_TOKEN': os.getenv('IBMQ_TOKEN'),
                'QE_URL': os.getenv('IBMQ_URL'),
                'hub': os.getenv('IBMQ_HUB'),
                'group': os.getenv('IBMQ_GROUP'),
                'project': os.getenv('IBMQ_PROJECT'),
            })
            args[0].using_ibmq_credentials = True
        else:
            # Attempt to read the standard credentials.
            account_name = get_account_name(IBMQProvider)
            discovered_credentials = discover_credentials()
            if account_name in discovered_credentials.keys():
                credentials = discovered_credentials[account_name]
                kwargs.update({
                    'QE_TOKEN': credentials.get('token'),
                    'QE_URL': credentials.get('url'),
                    'hub': credentials.get('hub'),
                    'group': credentials.get('group'),
                    'project': credentials.get('project'),
                })
                if (credentials.get('hub') and credentials.get('group')
                        and credentials.get('project')):
                    args[0].using_ibmq_credentials = True
            else:
                raise Exception('Could not locate valid credentials')

        return func(*args, **kwargs)