Skip to content
Open
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
50 changes: 23 additions & 27 deletions cuda_bindings_12/tests/test_graphics_apis.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,33 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import os
import sys

import pytest
from cuda_python_test_helpers.graphics import gl_context

from cuda.bindings import runtime as cudart


# This test is not currently run in any CI job
def test_graphics_api_smoketest():
if sys.platform.startswith("linux") and not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
pytest.skip("No display available for the OpenGL smoke test")

# Due to lazy importing in pyglet, pytest.importorskip doesn't work
try:
import pyglet

tex = pyglet.image.Texture.create(512, 512)
except (ImportError, AttributeError, OSError):
pytest.skip("pyglet not available or could not create GL context")
# return to make linters happy
return

err, gfx_resource = cudart.cudaGraphicsGLRegisterImage(
tex.id, tex.target, cudart.cudaGraphicsRegisterFlags.cudaGraphicsRegisterFlagsWriteDiscard
)
error_name = cudart.cudaGetErrorName(err)[1].decode()
if error_name == "cudaSuccess":
assert int(gfx_resource) != 0
else:
assert error_name in ("cudaErrorInvalidValue", "cudaErrorUnknown")
pytestmark = pytest.mark.thread_unsafe(reason="pyglet/OpenGL context is process-global")


@pytest.mark.parametrize(
"flags",
[
cudart.cudaGraphicsRegisterFlags.cudaGraphicsRegisterFlagsNone,
cudart.cudaGraphicsRegisterFlags.cudaGraphicsRegisterFlagsWriteDiscard,
],
)
def test_cuda_gl_register_image_smoketest(flags):
with gl_context() as (tex_id, tex_target):
# gl_context() skips unless the GL context is on an NVIDIA GPU, so
# registration must succeed here.
err, resource = cudart.cudaGraphicsGLRegisterImage(tex_id, tex_target, flags)
name = cudart.cudaGetErrorName(err)[1].decode()
assert name == "cudaSuccess", f"cudaGraphicsGLRegisterImage returned {name}"
assert int(resource) != 0

(err,) = cudart.cudaGraphicsUnregisterResource(resource)
name = cudart.cudaGetErrorName(err)[1].decode()
assert name == "cudaSuccess", f"cudaGraphicsUnregisterResource returned {name}"


def test_cuda_register_image_invalid():
Expand Down
108 changes: 9 additions & 99 deletions cuda_bindings_13/tests/test_graphics_apis.py
Original file line number Diff line number Diff line change
@@ -1,100 +1,14 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import contextlib
import ctypes
import ctypes.util
import os
import sys

import pyglet
import pytest
from cuda_python_test_helpers.graphics import (
gl_context_not_on_nvidia_gpu_reason,
is_gl_context_unavailable,
open_gl_window,
select_headless_egl_device_for_cuda,
tcc_skip_reason,
)
from cuda_python_test_helpers.graphics import gl_context

from cuda.bindings import runtime as cudart

pytestmark = pytest.mark.thread_unsafe(reason="pyglet/OpenGL context is process-global")


def _configure_pyglet_headless():
"""On headless Linux: enable EGL mode, matched to CUDA device 0, or skip if EGL is absent."""
if sys.platform.startswith("linux") and not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
if ctypes.util.find_library("EGL") is None:
pytest.skip("No DISPLAY and no EGL runtime available for headless context.")
pyglet.options["headless"] = True

# CUDA_VISIBLE_DEVICES does not reorder EGL's device enumeration, so on
# headless multi-GPU systems EGL device 0 may not be the physical GPU
# behind CUDA device 0, which these tests register against. Pick the
# EGL device that the driver reports as corresponding to it.
egl_device = select_headless_egl_device_for_cuda(0)
if egl_device is not None:
pyglet.options["headless_device"] = egl_device


def _allocate_gl_texture(win):
"""Allocate a 2-D RGBA8 texture. Caller must have a current GL context.

Deletes the generated texture if a later GL call fails, so a partial
resource does not leak.
"""
from pyglet.gl import gl as _gl

tex_id = _gl.GLuint(0)
try:
_gl.glGenTextures(1, ctypes.byref(tex_id))
target = _gl.GL_TEXTURE_2D
_gl.glBindTexture(target, tex_id.value)
_gl.glTexParameteri(target, _gl.GL_TEXTURE_MIN_FILTER, _gl.GL_NEAREST)
_gl.glTexParameteri(target, _gl.GL_TEXTURE_MAG_FILTER, _gl.GL_NEAREST)
width, height = 16, 16
_gl.glTexImage2D(target, 0, _gl.GL_RGBA8, width, height, 0, _gl.GL_RGBA, _gl.GL_UNSIGNED_BYTE, None)
return tex_id, target
except Exception:
if tex_id.value:
with contextlib.suppress(Exception):
_gl.glDeleteTextures(1, ctypes.byref(tex_id))
raise


@contextlib.contextmanager
def _gl_context():
"""Yield ``(tex_id, tex_target)`` with a current GL context, or skip if GL is unavailable."""
if reason := tcc_skip_reason():
pytest.skip(reason)
_configure_pyglet_headless()

try:
win = open_gl_window()
except Exception as e:
if is_gl_context_unavailable(e):
pytest.skip(f"Could not create GL context: {type(e).__name__}: {e}")
raise

tex_id = None
try:
if reason := gl_context_not_on_nvidia_gpu_reason():
pytest.skip(reason)
tex_id, target = _allocate_gl_texture(win)
yield int(tex_id.value), int(target)
finally:
if tex_id is not None:
with contextlib.suppress(Exception):
from pyglet.gl import gl as _gl

if tex_id.value:
_gl.glDeleteTextures(1, ctypes.byref(tex_id))
with contextlib.suppress(Exception):
if win is not None:
win.close()


@pytest.mark.parametrize(
"flags",
[
Expand All @@ -103,21 +17,17 @@ def _gl_context():
],
)
def test_cuda_gl_register_image_smoketest(flags):
with _gl_context() as (tex_id, tex_target):
# Register
with gl_context() as (tex_id, tex_target):
# gl_context() skips unless the GL context is on an NVIDIA GPU, so
# registration must succeed here.
err, resource = cudart.cudaGraphicsGLRegisterImage(tex_id, tex_target, flags)
name = cudart.cudaGetErrorName(err)[1].decode()
assert name == "cudaSuccess", f"cudaGraphicsGLRegisterImage returned {name}"
assert int(resource) != 0

# Map error expectations by environment:
# - success: we actually exercised the API
# - operating-system: typical when the driver/runtime refuses interop (e.g., no GPU/driver in CI container)
acceptable = {"cudaSuccess", "cudaErrorOperatingSystem"}

assert name in acceptable, f"cudaGraphicsGLRegisterImage returned {name}"
if name == "cudaSuccess":
assert int(resource) != 0
# Unregister to be tidy
cudart.cudaGraphicsUnregisterResource(resource)
(err,) = cudart.cudaGraphicsUnregisterResource(resource)
name = cudart.cudaGetErrorName(err)[1].decode()
assert name == "cudaSuccess", f"cudaGraphicsUnregisterResource returned {name}"


def test_cuda_register_image_invalid():
Expand Down
84 changes: 84 additions & 0 deletions cuda_python_test_helpers/cuda_python_test_helpers/graphics.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,16 @@
import creates the shadow window, and in headless mode the shadow window opens
the EGL display on ``pyglet.options["headless_device"]`` before the caller has
had a chance to set it.
``pytest`` is also imported only by the helpers that skip, because the
``cuda_core`` samples import this module outside of pytest.
"""

import contextlib
import ctypes
import ctypes.util
import os
import sys


def _is_pyglet_missing_function_exception(exc: BaseException) -> bool:
Expand Down Expand Up @@ -229,3 +235,81 @@ def is_gl_context_unavailable(exc: BaseException) -> bool:
# exact messages above from pyglet/lib.py. A different ImportError
# from our own code does not match.
return isinstance(exc, ImportError) and str(exc) in _PYGLET_GL_LIBRARY_IMPORT_ERRORS


def configure_pyglet_headless() -> None:
"""On headless Linux: enable EGL mode, matched to CUDA device 0, or skip if EGL is absent."""
if sys.platform.startswith("linux") and not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
import pyglet
import pytest

if ctypes.util.find_library("EGL") is None:
pytest.skip("No DISPLAY and no EGL runtime available for headless context.")
pyglet.options["headless"] = True

# CUDA_VISIBLE_DEVICES does not reorder EGL's device enumeration, so on
# headless multi-GPU systems EGL device 0 may not be the physical GPU
# behind CUDA device 0, which these tests register against. Pick the
# EGL device that the driver reports as corresponding to it.
egl_device = select_headless_egl_device_for_cuda(0)
if egl_device is not None:
pyglet.options["headless_device"] = egl_device


def allocate_gl_texture():
"""Allocate a 2-D RGBA8 texture. Caller must have a current GL context.
Deletes the generated texture if a later GL call fails, so a partial
resource does not leak.
"""
from pyglet.gl import gl as _gl

tex_id = _gl.GLuint(0)
try:
_gl.glGenTextures(1, ctypes.byref(tex_id))
target = _gl.GL_TEXTURE_2D
_gl.glBindTexture(target, tex_id.value)
_gl.glTexParameteri(target, _gl.GL_TEXTURE_MIN_FILTER, _gl.GL_NEAREST)
_gl.glTexParameteri(target, _gl.GL_TEXTURE_MAG_FILTER, _gl.GL_NEAREST)
width, height = 16, 16
_gl.glTexImage2D(target, 0, _gl.GL_RGBA8, width, height, 0, _gl.GL_RGBA, _gl.GL_UNSIGNED_BYTE, None)
return tex_id, target
except Exception:
if tex_id.value:
with contextlib.suppress(Exception):
_gl.glDeleteTextures(1, ctypes.byref(tex_id))
raise


@contextlib.contextmanager
def gl_context():
"""Yield ``(tex_id, tex_target)`` with a current GL context, or skip if GL is unavailable."""
import pytest

if reason := tcc_skip_reason():
pytest.skip(reason)
configure_pyglet_headless()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

important: Move configure_pyglet_headless() into the try in gl_context.

When libEGL is found but one of its dependencies fails to load, the EGL import in select_headless_egl_device_for_cuda raises ImportError('Library "EGL" not found.'). That import (lines 62-63) runs before the helper's own try, so the error propagates through configure_pyglet_headless() and out of gl_context(). is_gl_context_unavailable() handles this error only inside the try that wraps open_gl_window(). The test therefore errors instead of skipping. Before this change, the CUDA 12 test skipped in this headless environment. Both CUDA roots use gl_context(), so both are affected.

Move the call inside the existing try. The classifier then skips on this error, and other exceptions still propagate.

Suggested fix

--- "a/cuda_python_test_helpers/cuda_python_test_helpers/graphics.py"
+++ "b/cuda_python_test_helpers/cuda_python_test_helpers/graphics.py"
@@ -288,10 +288,9 @@
 
     if reason := tcc_skip_reason():
         pytest.skip(reason)
-    configure_pyglet_headless()
-
     try:
+        configure_pyglet_headless()
         win = open_gl_window()
     except Exception as e:
         if is_gl_context_unavailable(e):
             pytest.skip(f"Could not create GL context: {type(e).__name__}: {e}")


try:
win = open_gl_window()
except Exception as e:
if is_gl_context_unavailable(e):
pytest.skip(f"Could not create GL context: {type(e).__name__}: {e}")
raise

tex_id = None
try:
if reason := gl_context_not_on_nvidia_gpu_reason():
pytest.skip(reason)
tex_id, target = allocate_gl_texture()
yield int(tex_id.value), int(target)
finally:
if tex_id is not None:
with contextlib.suppress(Exception):
from pyglet.gl import gl as _gl

if tex_id.value:
_gl.glDeleteTextures(1, ctypes.byref(tex_id))
with contextlib.suppress(Exception):
if win is not None:
win.close()
Loading