コード例 #1
0
    def test_custom_options(self):
        """Test custom options (request_timeout, polling_timeout, permissive_ssl) are propagated to Client."""
        request_timeout = 15
        polling_timeout = 180

        with mock.patch("dwave.cloud.config.open",
                        iterable_mock_open(config_body),
                        create=True):
            with Client.from_config('config_file', profile='custom') as client:
                # check permissive_ssl and timeouts custom params passed-thru
                self.assertFalse(client.session.verify)
                self.assertEqual(client.request_timeout, request_timeout)
                self.assertEqual(client.polling_timeout, polling_timeout)

                # verify client uses those properly
                def mock_send(*args, **kwargs):
                    self.assertEqual(kwargs.get('timeout'), request_timeout)
                    response = requests.Response()
                    response.status_code = 200
                    response._content = b'{}'
                    return response

                with mock.patch("requests.adapters.HTTPAdapter.send",
                                mock_send):
                    client.solvers()
コード例 #2
0
 def test_explicit_only(self):
     """Specify information only through function arguments."""
     with Client.from_config(endpoint='arg-url', token='arg-token') as client:
         client.session.get = GetEvent.handle
         try:
             client.get_solver('arg-solver')
         except GetEvent as event:
             self.assertTrue(event.url.startswith('arg-url'))
             return
         self.fail()
コード例 #3
0
 def test_env_args_set(self):
     """With arguments and environment variables, the environment variables should be ignored."""
     with mock.patch.dict(os.environ, {'DW_INTERNAL__HTTPLINK': 'env-url', 'DW_INTERNAL__TOKEN': 'env-token'}):
         with Client.from_config(endpoint='args-url', token='args-token') as client:
             client.session.get = GetEvent.handle
             try:
                 client.get_solver('arg-solver')
             except GetEvent as event:
                 self.assertTrue(event.url.startswith('args-url'))
                 return
             self.fail()
コード例 #4
0
 def test_only_file(self):
     """With no arguments or environment variables, the default connection from the config file should be used."""
     with mock.patch("dwave.cloud.config.open", iterable_mock_open(config_body), create=True):
         with Client.from_config('config_file') as client:
             client.session.get = GetEvent.handle
             try:
                 client.get_solver('arg-solver')
             except GetEvent as event:
                 self.assertTrue(event.url.startswith('file-prod-url'))
                 return
             self.fail()
コード例 #5
0
 def test_explicit_with_file(self):
     """With arguments and a config file, the config file should be ignored."""
     with mock.patch("dwave.cloud.config.open", iterable_mock_open(config_body), create=True):
         with Client.from_config(endpoint='arg-url', token='arg-token') as client:
             client.session.get = GetEvent.handle
             try:
                 client.get_solver('arg-solver')
             except GetEvent as event:
                 self.assertTrue(event.url.startswith('arg-url'))
                 return
             self.fail()
コード例 #6
0
 def test_env_with_file_set(self):
     """With environment variables and a config file, the config file should be ignored."""
     with mock.patch("dwave.cloud.config.open", iterable_mock_open(legacy_config_body), create=True):
         with mock.patch.dict(os.environ, {'DW_INTERNAL__HTTPLINK': 'env-url', 'DW_INTERNAL__TOKEN': 'env-token'}):
             with Client.from_config(False) as client:
                 client.session.get = GetEvent.handle
                 try:
                     client.get_solver('arg-solver')
                 except GetEvent as event:
                     self.assertTrue(event.url.startswith('env-url'))
                     return
                 self.fail()
コード例 #7
0
 def test_only_file_key(self):
     """If give a name from the config file the proper URL should be loaded."""
     with mock.patch("dwave.cloud.config.open", iterable_mock_open(config_body), create=True):
         with mock.patch("dwave.cloud.config.get_configfile_paths", lambda *x: ['file']):
             with Client.from_config(profile='alpha') as client:
                 client.session.get = GetEvent.handle
                 try:
                     client.get_solver('arg-solver')
                 except GetEvent as event:
                     self.assertTrue(event.url.startswith('file-alpha-url'))
                     return
                 self.fail()
コード例 #8
0
def ping(config_file, profile):
    """Ping the QPU by submitting a single-qubit problem."""

    try:
        client = Client.from_config(config_file=config_file, profile=profile)
    except Exception as e:
        print("Invalid config: {}".format(e))
        return 1
    if config_file:
        print("Using config file:", config_file)
    if profile:
        print("Using profile:", profile)
    print("Using endpoint:", client.endpoint)

    t0 = timer()
    try:
        solvers = client.get_solvers()
    except SolverAuthenticationError:
        print("Authentication error. Check credentials in your config file.")
        return 1
    except (InvalidAPIResponseError, UnsupportedSolverError):
        print("Invalid or unexpected API response.")
        return 2

    try:
        solver = client.get_solver()
    except (ValueError, KeyError):
        # if not otherwise defined (ValueError), or unavailable (KeyError),
        # just use the first solver
        if solvers:
            _, solver = next(iter(solvers.items()))
        else:
            print("No solvers available.")
            return 1

    t1 = timer()
    print("Using solver: {}".format(solver.id))

    timing = solver.sample_ising({0: 1}, {}).timing
    t2 = timer()

    print("\nWall clock time:")
    print(" * Solver definition fetch web request: {:.3f} ms".format(
        (t1 - t0) * 1000.0))
    print(" * Problem submit and results fetch: {:.3f} ms".format(
        (t2 - t1) * 1000.0))
    print(" * Total: {:.3f} ms".format((t2 - t0) * 1000.0))
    print("\nQPU timing:")
    for component, duration in timing.items():
        print(" * {} = {} us".format(component, duration))
    return 0
コード例 #9
0
 def test_only_file_key(self):
     """If give a name from the config file the proper URL should be loaded."""
     with mock.patch("dwave.cloud.config.open",
                     mock.mock_open(read_data=config_body),
                     create=True):
         with mock.patch(configparser_open_namespace,
                         iterable_mock_open(config_body),
                         create=True):
             # this will try parsing legacy format as new, fail,
             # then try parsing it as legacy config
             client = Client.from_config(profile='alpha')
             client.session.get = GetEvent.handle
             try:
                 client.get_solver('arg-solver')
             except GetEvent as event:
                 self.assertTrue(event.url.startswith('file-alpha-url'))
                 return
             self.fail()
コード例 #10
0
ファイル: multiple.py プロジェクト: todun/dwave-cloud-client
from __future__ import absolute_import

import logging

from dwave.cloud.qpu import Client
from dwave.cloud.computation import Future

# setup local logger
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(handler)

with Client.from_config(profile='prod') as client:
    solvers = client.get_solvers()
    logger.info("Solvers available: %r", solvers)

    solver = client.get_solver()
    comps = [solver.sample_qubo({}, num_reads=1) for _ in range(20)]

    for comp in Future.as_completed(comps):
        try:
            result = comp.result()
        except Exception as e:
            logger.info("Computation %s failed: %r", comp.id, e)

        logger.info("Computation %s succeeded:", comp.id)
        logger.info(" - time received: %s", comp.time_received)
        logger.info(" - time solved: %s", comp.time_solved)
コード例 #11
0
 def test_nonexisting_file(self):
     """With no values set, we should get an error when trying to create Client."""
     with self.assertRaises(ConfigFileReadError):
         with Client.from_config(config_file='nonexisting',
                                 legacy_config_fallback=False) as client:
             pass
コード例 #12
0
 def test_nothing(self):
     """With no values set, we should get an error when trying to create Client."""
     with self.assertRaises(ValueError):
         Client.from_config(config_file='nonexisting')