"""Opening and closing a vSphere API session. Kept apart from everything else because it is the only code that opens a socket; the tests replace it wholesale. """ from __future__ import annotations import ssl from typing import Any from pyVim.connect import Disconnect, SmartConnect def _ssl_context(verify: bool) -> ssl.SSLContext: context = ssl.create_default_context() if not verify: # ESXi hosts ship a self-signed certificate; most homelab and many # production hosts keep it. context.check_hostname = False context.verify_mode = ssl.CERT_NONE return context def connect( # pragma: no cover - opens a live session host: str, port: int, user: str, password: str, *, verify_ssl: bool, timeout: int ) -> Any: return SmartConnect( host=host, port=port, user=user, pwd=password, sslContext=_ssl_context(verify_ssl), httpConnectionTimeout=timeout, ) def disconnect(si: Any) -> None: # pragma: no cover - talks to a live session Disconnect(si) def alive(si: Any) -> bool: # pragma: no cover - talks to a live session try: si.CurrentTime() except Exception: return False return True