Import and return the requested module ``modname``, or skip the current test if the module cannot be imported. :param str modname: The name of the module to import. :param str minversion: If given, the imported module's ``__version__`` attribute must be at least
(
modname: str, minversion: Optional[str] = None, reason: Optional[str] = None
)
| 253 | |
| 254 | |
| 255 | def importorskip( |
| 256 | modname: str, minversion: Optional[str] = None, reason: Optional[str] = None |
| 257 | ) -> Any: |
| 258 | """Import and return the requested module ``modname``, or skip the |
| 259 | current test if the module cannot be imported. |
| 260 | |
| 261 | :param str modname: |
| 262 | The name of the module to import. |
| 263 | :param str minversion: |
| 264 | If given, the imported module's ``__version__`` attribute must be at |
| 265 | least this minimal version, otherwise the test is still skipped. |
| 266 | :param str reason: |
| 267 | If given, this reason is shown as the message when the module cannot |
| 268 | be imported. |
| 269 | |
| 270 | :returns: |
| 271 | The imported module. This should be assigned to its canonical name. |
| 272 | |
| 273 | Example:: |
| 274 | |
| 275 | docutils = pytest.importorskip("docutils") |
| 276 | """ |
| 277 | import warnings |
| 278 | |
| 279 | __tracebackhide__ = True |
| 280 | compile(modname, "", "eval") # to catch syntaxerrors |
| 281 | |
| 282 | with warnings.catch_warnings(): |
| 283 | # Make sure to ignore ImportWarnings that might happen because |
| 284 | # of existing directories with the same name we're trying to |
| 285 | # import but without a __init__.py file. |
| 286 | warnings.simplefilter("ignore") |
| 287 | try: |
| 288 | __import__(modname) |
| 289 | except ImportError as exc: |
| 290 | if reason is None: |
| 291 | reason = f"could not import {modname!r}: {exc}" |
| 292 | raise Skipped(reason, allow_module_level=True) from None |
| 293 | mod = sys.modules[modname] |
| 294 | if minversion is None: |
| 295 | return mod |
| 296 | verattr = getattr(mod, "__version__", None) |
| 297 | if minversion is not None: |
| 298 | # Imported lazily to improve start-up time. |
| 299 | from packaging.version import Version |
| 300 | |
| 301 | if verattr is None or Version(verattr) < Version(minversion): |
| 302 | raise Skipped( |
| 303 | "module %r has __version__ %r, required is: %r" |
| 304 | % (modname, verattr, minversion), |
| 305 | allow_module_level=True, |
| 306 | ) |
| 307 | return mod |