Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove most of qiskit.test #11445

Merged
merged 1 commit into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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))
Comment on lines -103 to -114
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't used.


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()
Comment on lines -197 to -222
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inlined the one use of this still in use - checking if run_slow is in the QISKIT_TESTS environment variable.

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