Skip to content

Commit

Permalink
Remove most of qiskit.test (Qiskit#11445)
Browse files Browse the repository at this point in the history
This removes large tracts of `qiskit.test` that Qiskit itself is no
longer using, or inlines a couple of components that were either
exceptionally simple or used only once.  A few tests that made heavier
use of the removed features have been removed rather than replacing the
functionality, since those had not actually been running due to
dependencies on IBMQ that have not been fulfilled for a long time.

This prepares for a more complete removal of `qiskit.test`, if we choose
to, but such a change raises the possibility of rather more merge
conflicts (due to the need to touch every test file), so is best done
separately.
  • Loading branch information
jakelishman authored and ShellyGarion committed Jan 18, 2024
1 parent 8514d8b commit ed2596b
Show file tree
Hide file tree
Showing 16 changed files with 135 additions and 504 deletions.
4 changes: 1 addition & 3 deletions qiskit/test/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,4 @@
"""Functionality and helpers for testing Qiskit."""

from .base import QiskitTestCase
from .decorators import requires_aer_provider, slow_test
from .reference_circuits import ReferenceCircuits
from .utils import Path
from .decorators import slow_test
35 changes: 18 additions & 17 deletions qiskit/test/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
from qiskit.utils import optionals as _optionals
from qiskit.circuit import QuantumCircuit
from .decorators import enforce_subclasses_call
from .utils import Path, setup_test_logging


__unittest = True # Allows shorter stack trace for .assertDictAlmostEqual
Expand Down Expand Up @@ -100,19 +99,6 @@ def tearDown(self):
)
self.__teardown_called = True

@staticmethod
def _get_resource_path(filename, path=Path.TEST):
"""Get the absolute path to a resource.
Args:
filename (string): filename or relative path to the resource.
path (Path): path used as relative to the filename.
Returns:
str: the absolute path to the resource.
"""
return os.path.normpath(os.path.join(path.value, filename))

def assertQuantumCircuitEqual(self, qc1, qc2, msg=None):
"""Extra assertion method to give a better error message when two circuits are unequal."""
if qc1 == qc2:
Expand Down Expand Up @@ -195,9 +181,24 @@ def setUpClass(cls):
super().setUpClass()
# Set logging to file and stdout if the LOG_LEVEL envar is set.
cls.log = logging.getLogger(cls.__name__)
if os.getenv("LOG_LEVEL"):
filename = "%s.log" % os.path.splitext(inspect.getfile(cls))[0]
setup_test_logging(cls.log, os.getenv("LOG_LEVEL"), filename)

if log_level := os.getenv("LOG_LEVEL"):
log_fmt = f"{cls.log.name}.%(funcName)s:%(levelname)s:%(asctime)s: %(message)s"
formatter = logging.Formatter(log_fmt)
file_handler = logging.FileHandler(f"{os.path.splitext(inspect.getfile(cls))[0]}.log")
file_handler.setFormatter(formatter)
cls.log.addHandler(file_handler)

if os.getenv("STREAM_LOG"):
# Set up the stream handler.
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
cls.log.addHandler(stream_handler)

# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
cls.log.setLevel(level)

warnings.filterwarnings("error", category=DeprecationWarning)
warnings.filterwarnings("error", category=QiskitWarning)
Expand Down
92 changes: 3 additions & 89 deletions qiskit/test/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,68 +13,12 @@

"""Decorator for using with Qiskit unit tests."""

import collections.abc
import functools
import socket
import sys
from typing import Union, Callable, Type, Iterable
import os
import unittest
from typing import Union, Callable, Type, Iterable

from qiskit.utils import wrap_method
from .testing_options import get_test_options

HAS_NET_CONNECTION = None


def _has_connection(hostname, port):
"""Checks if internet connection exists to host via specified port.
If any exception is raised while trying to open a socket this will return
false.
Args:
hostname (str): Hostname to connect to.
port (int): Port to connect to
Returns:
bool: Has connection or not
"""
try:
host = socket.gethostbyname(hostname)
socket.create_connection((host, port), 2).close()
return True
except Exception: # pylint: disable=broad-except
return False


def is_aer_provider_available():
"""Check if the C++ simulator can be instantiated.
Returns:
bool: True if simulator executable is available
"""
# TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC
if sys.platform == "darwin":
return False
try:
import qiskit.providers.aer # pylint: disable=unused-import
except ImportError:
return False
return True


def requires_aer_provider(test_item):
"""Decorator that skips test if qiskit aer provider is not available
Args:
test_item (callable): function or class to be decorated.
Returns:
callable: the decorated function.
"""
reason = "Aer provider not found, skipping test"
return unittest.skipIf(not is_aer_provider_available(), reason)(test_item)


def slow_test(func):
Expand All @@ -89,10 +33,8 @@ def slow_test(func):

@functools.wraps(func)
def _wrapper(*args, **kwargs):
skip_slow = not TEST_OPTIONS["run_slow"]
if skip_slow:
if "run_slow" in os.environ.get("QISKIT_TESTS", ""):
raise unittest.SkipTest("Skipping slow tests")

return func(*args, **kwargs)

return _wrapper
Expand Down Expand Up @@ -192,31 +134,3 @@ def decorator(cls):
return cls

return decorator


class _TestOptions(collections.abc.Mapping):
"""Lazy-loading view onto the test options retrieved from the environment."""

__slots__ = ("_options",)

def __init__(self):
self._options = None

def _load(self):
if self._options is None:
self._options = get_test_options()

def __getitem__(self, key):
self._load()
return self._options[key]

def __iter__(self):
self._load()
return iter(self._options)

def __len__(self):
self._load()
return len(self._options)


TEST_OPTIONS = _TestOptions()
16 changes: 0 additions & 16 deletions qiskit/test/providers/__init__.py

This file was deleted.

75 changes: 0 additions & 75 deletions qiskit/test/providers/backend.py

This file was deleted.

59 changes: 0 additions & 59 deletions qiskit/test/providers/provider.py

This file was deleted.

41 changes: 0 additions & 41 deletions qiskit/test/reference_circuits.py

This file was deleted.

Loading

0 comments on commit ed2596b

Please sign in to comment.