13
13
14
14
"""Decorator for using with Qiskit unit tests."""
15
15
16
- import collections .abc
17
16
import functools
18
17
import os
19
- import socket
20
- import sys
21
- from typing import Union , Callable , Type , Iterable
22
18
import unittest
19
+ from typing import Union , Callable , Type , Iterable
23
20
24
21
from qiskit .utils import wrap_method
25
- from .testing_options import get_test_options
26
-
27
- HAS_NET_CONNECTION = None
28
-
29
-
30
- def _has_connection (hostname , port ):
31
- """Checks if internet connection exists to host via specified port.
32
-
33
- If any exception is raised while trying to open a socket this will return
34
- false.
35
-
36
- Args:
37
- hostname (str): Hostname to connect to.
38
- port (int): Port to connect to
39
-
40
- Returns:
41
- bool: Has connection or not
42
-
43
- """
44
- try :
45
- host = socket .gethostbyname (hostname )
46
- socket .create_connection ((host , port ), 2 ).close ()
47
- return True
48
- except Exception : # pylint: disable=broad-except
49
- return False
50
-
51
-
52
- def is_aer_provider_available ():
53
- """Check if the C++ simulator can be instantiated.
54
-
55
- Returns:
56
- bool: True if simulator executable is available
57
- """
58
- # TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC
59
- if sys .platform == "darwin" :
60
- return False
61
- try :
62
- import qiskit .providers .aer # pylint: disable=unused-import
63
- except ImportError :
64
- return False
65
- return True
66
-
67
-
68
- def requires_aer_provider (test_item ):
69
- """Decorator that skips test if qiskit aer provider is not available
70
-
71
- Args:
72
- test_item (callable): function or class to be decorated.
73
-
74
- Returns:
75
- callable: the decorated function.
76
- """
77
- reason = "Aer provider not found, skipping test"
78
- return unittest .skipIf (not is_aer_provider_available (), reason )(test_item )
79
22
80
23
81
24
def slow_test (func ):
@@ -90,100 +33,13 @@ def slow_test(func):
90
33
91
34
@functools .wraps (func )
92
35
def _wrapper (* args , ** kwargs ):
93
- skip_slow = not TEST_OPTIONS ["run_slow" ]
94
- if skip_slow :
36
+ if "run_slow" in os .environ .get ("QISKIT_TESTS" , "" ):
95
37
raise unittest .SkipTest ("Skipping slow tests" )
96
-
97
38
return func (* args , ** kwargs )
98
39
99
40
return _wrapper
100
41
101
42
102
- def _get_credentials ():
103
- """Finds the credentials for a specific test and options.
104
-
105
- Returns:
106
- Credentials: set of credentials
107
-
108
- Raises:
109
- SkipTest: when credentials can't be found
110
- """
111
- try :
112
- from qiskit .providers .ibmq .credentials import Credentials , discover_credentials
113
- except ImportError as ex :
114
- raise unittest .SkipTest (
115
- "qiskit-ibmq-provider could not be found, "
116
- "and is required for executing online tests. "
117
- 'To install, run "pip install qiskit-ibmq-provider" '
118
- "or check your installation."
119
- ) from ex
120
-
121
- if os .getenv ("IBMQ_TOKEN" ) and os .getenv ("IBMQ_URL" ):
122
- return Credentials (os .getenv ("IBMQ_TOKEN" ), os .getenv ("IBMQ_URL" ))
123
- elif os .getenv ("QISKIT_TESTS_USE_CREDENTIALS_FILE" ):
124
- # Attempt to read the standard credentials.
125
- discovered_credentials = discover_credentials ()
126
-
127
- if discovered_credentials :
128
- # Decide which credentials to use for testing.
129
- if len (discovered_credentials ) > 1 :
130
- raise unittest .SkipTest (
131
- "More than 1 credential set found, use: "
132
- "IBMQ_TOKEN and IBMQ_URL env variables to "
133
- "set credentials explicitly"
134
- )
135
-
136
- # Use the first available credentials.
137
- return list (discovered_credentials .values ())[0 ]
138
- raise unittest .SkipTest (
139
- "No IBMQ credentials found for running the test. This is required for running online tests."
140
- )
141
-
142
-
143
- def online_test (func ):
144
- """Decorator that signals that the test uses the network (and the online API):
145
-
146
- It involves:
147
- * determines if the test should be skipped by checking environment
148
- variables.
149
- * if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is
150
- set, it reads the credentials from an alternative set of environment
151
- variables.
152
- * if the test is not skipped, it reads `qe_token` and `qe_url` from
153
- `Qconfig.py`, environment variables or qiskitrc.
154
- * if the test is not skipped, it appends `qe_token` and `qe_url` as
155
- arguments to the test function.
156
-
157
- Args:
158
- func (callable): test function to be decorated.
159
-
160
- Returns:
161
- callable: the decorated function.
162
- """
163
-
164
- @functools .wraps (func )
165
- def _wrapper (self , * args , ** kwargs ):
166
- # To avoid checking the connection in each test
167
- global HAS_NET_CONNECTION # pylint: disable=global-statement
168
-
169
- if TEST_OPTIONS ["skip_online" ]:
170
- raise unittest .SkipTest ("Skipping online tests" )
171
-
172
- if HAS_NET_CONNECTION is None :
173
- HAS_NET_CONNECTION = _has_connection ("qiskit.org" , 443 )
174
-
175
- if not HAS_NET_CONNECTION :
176
- raise unittest .SkipTest ("Test requires internet connection." )
177
-
178
- credentials = _get_credentials ()
179
- self .using_ibmq_credentials = credentials .is_ibmq ()
180
- kwargs .update ({"qe_token" : credentials .token , "qe_url" : credentials .url })
181
-
182
- return func (self , * args , ** kwargs )
183
-
184
- return _wrapper
185
-
186
-
187
43
def enforce_subclasses_call (
188
44
methods : Union [str , Iterable [str ]], attr : str = "_enforce_subclasses_call_cache"
189
45
) -> Callable [[Type ], Type ]:
@@ -278,31 +134,3 @@ def decorator(cls):
278
134
return cls
279
135
280
136
return decorator
281
-
282
-
283
- class _TestOptions (collections .abc .Mapping ):
284
- """Lazy-loading view onto the test options retrieved from the environment."""
285
-
286
- __slots__ = ("_options" ,)
287
-
288
- def __init__ (self ):
289
- self ._options = None
290
-
291
- def _load (self ):
292
- if self ._options is None :
293
- self ._options = get_test_options ()
294
-
295
- def __getitem__ (self , key ):
296
- self ._load ()
297
- return self ._options [key ]
298
-
299
- def __iter__ (self ):
300
- self ._load ()
301
- return iter (self ._options )
302
-
303
- def __len__ (self ):
304
- self ._load ()
305
- return len (self ._options )
306
-
307
-
308
- TEST_OPTIONS = _TestOptions ()
0 commit comments