code: def _configure_mock(
      N=pynvml,
      _scenario_nonexistent_pid=False,  # GH-95
      _scenario_failing_one_gpu=None,  # GH-125, GH-81
  ):
      """Define mock behaviour for pynvml and psutil.{Process,virtual_memory}."""
  
      # without following patch, unhashable NVMLError makes unit test crash
      N.NVMLError.__hash__ = lambda _: 0
      assert issubclass(N.NVMLError, BaseException)
  
      unstub(N)  # reset all the stubs
  
      when(N).nvmlInit().thenReturn()
      gpustat.nvml._initialized = (
          True  # nvmlInit() is called upon module import
      )
      when(N).nvmlShutdown().thenReturn()
      when(N).nvmlSystemGetDriverVersion().thenReturn("415.27.mock")
  
      when(N)._nvmlGetFunctionPointer(
          ...
      ).thenCallOriginalImplementation()
  
      NUM_GPUS = 3
      when(N).nvmlDeviceGetCount().thenReturn(NUM_GPUS)
  
      def _return_or_raise(v):
          """Return a callable for thenAnswer() to let exceptions re-raised."""
  
          def _callable(*args, **kwargs):
              del args, kwargs
              if isinstance(v, Exception):
                  raise v
              return v
  
          return _callable
  
      mock_memory_t = namedtuple(
          "Memory_t", ["total", "used"]
      )  # c_nvmlMemory_t
  
      for i in range(NUM_GPUS):
          handle = mock_gpu_handles[i]
          if _scenario_failing_one_gpu and i == 2:  # see #81, #125
              assert (
                  _scenario_failing_one_gpu is N.NVMLError_Unknown
                  or _scenario_failing_one_gpu is N.NVMLError_GpuIsLost
              )
              handle = _scenario_failing_one_gpu()  # see 81
  
          when(N).nvmlDeviceGetHandleByIndex(i).thenAnswer(
              _return_or_raise(handle)
          )
          when(N).nvmlDeviceGetIndex(handle).thenReturn(i)
          when(N).nvmlDeviceGetName(handle).thenReturn(
              {
                  0: "GeForce GTX TITAN 0",
                  1: "GeForce GTX TITAN 1",
                  2: "GeForce RTX 2",
              }[i].encode()
          )
          when(N).nvmlDeviceGetUUID(handle).thenReturn(
              {
                  0: b"GPU-10fb0fbd-2696-43f3-467f-d280d906a107",
                  1: b"GPU-d1df4664-bb44-189c-7ad0-ab86c8cb30e2",
                  2: b"GPU-50205d95-57b6-f541-2bcb-86c09afed564",
              }[i]
          )
  
          when(N).nvmlDeviceGetTemperature(
              handle, N.NVML_TEMPERATURE_GPU
          ).thenReturn([80, 36, 71][i])
          when(N).nvmlDeviceGetFanSpeed(handle).thenReturn(
              [16, 53, 100][i]
          )
          when(N).nvmlDeviceGetPowerUsage(handle).thenAnswer(
              _return_or_raise(
                  {0: 125000, 1: N.NVMLError_NotSupported(), 2: 250000}[
                      i
                  ]
              )
          )
          when(N).nvmlDeviceGetEnforcedPowerLimit(handle).thenAnswer(
              _return_or_raise(
                  {0: 250000, 1: 250000, 2: N.NVMLError_NotSupported()}[
                      i
                  ]
              )
          )
  
          # see also: NvidiaDriverMock
          when(N).nvmlDeviceGetMemoryInfo(handle).thenAnswer(
              _return_or_raise(
                  {
                      0: mock_memory_t(
                          total=12883853312, used=8000 * MB
                      ),
                      1: mock_memory_t(
                          total=12781551616, used=9000 * MB
                      ),
                      2: mock_memory_t(total=12781551616, used=0),
                  }[i]
              )
          )
          # this mock function assumes <510.39 behavior (#141)
          when(N, strict=False).nvmlDeviceGetMemoryInfo(
              handle, version=ANY()
          ).thenRaise(N.NVMLError_FunctionNotFound)
  
          mock_utilization_t = namedtuple(
              "Utilization_t", ["gpu", "memory"]
          )
          when(N).nvmlDeviceGetUtilizationRates(handle).thenAnswer(
              _return_or_raise(
                  {
                      0: mock_utilization_t(gpu=76, memory=0),
                      1: mock_utilization_t(gpu=0, memory=0),
                      2: N.NVMLError_NotSupported(),  # Not Supported
                  }[i]
              )
          )
  
          when(N).nvmlDeviceGetEncoderUtilization(handle).thenAnswer(
              _return_or_raise(
                  {
                      0: [88, 167000],  # [value, sample_rate]
                      1: [0, 167000],  # [value, sample_rate]
                      2: N.NVMLError_NotSupported(),  # Not Supported
                  }[i]
              )
          )
          when(N).nvmlDeviceGetDecoderUtilization(handle).thenAnswer(
              _return_or_raise(
                  {
                      0: [67, 167000],  # [value, sample_rate]
                      1: [0, 167000],  # [value, sample_rate]
                      2: N.NVMLError_NotSupported(),  # Not Supported
                  }[i]
              )
          )
  
          # running process information: a bit annoying...
          mock_process_t = namedtuple(
              "Process_t", ["pid", "usedGpuMemory"]
          )
  
          if _scenario_nonexistent_pid:
              mock_processes_gpu2_erratic = [
                  mock_process_t(99999, 9999 * MB),
                  mock_process_t(99995, 9995 * MB),  # see issue #95
              ]
          else:
              mock_processes_gpu2_erratic = N.NVMLError_NotSupported()
  
          # see NvidiaDriverMock as well
          when(N).nvmlDeviceGetComputeRunningProcesses(
              handle
          ).thenAnswer(
              _return_or_raise(
                  {
                      0: [
                          mock_process_t(48448, 4000 * MB),
                          mock_process_t(153223, 4000 * MB),
                      ],
                      1: [
                          mock_process_t(192453, 3000 * MB),
                          mock_process_t(194826, 6000 * MB),
                      ],
                      2: mock_processes_gpu2_erratic,  # Not Supported or non-existent
                  }[i]
              )
          )
  
          when(N).nvmlDeviceGetGraphicsRunningProcesses(
              handle
          ).thenAnswer(
              _return_or_raise(
                  {
                      0: [mock_process_t(48448, 4000 * MB)],
                      1: [],
                      2: N.NVMLError_NotSupported(),
                  }[i]
              )
          )
  
      # for psutil
      mock_pid_map = {  # mock/stub information for psutil...
          48448: ("user1", "python", 85.25, 3.1415),
          154213: ("user1", "caffe", 16.89, 100.00),
          38310: ("user3", "python", 26.23, 99.9653),
          153223: ("user2", "python", 15.25, 0.0000),
          194826: ("user3", "caffe", 0.0, 12.5236),
          192453: ("user1", "torch", 123.2, 0.7312),
      }
      assert 99999 not in mock_pid_map, "scenario_nonexistent_pid"
      assert 99995 not in mock_pid_map, "scenario_nonexistent_pid (#95)"
  
      def _MockedProcess(pid):
          if pid not in mock_pid_map:
              if pid == 99995:
                  # simulate a bug reported in #95
                  raise FileNotFoundError("/proc/99995/stat")
              else:
                  # for a process that does not exist, NoSuchProcess is the
                  # type of exceptions supposed to be raised by psutil
                  raise psutil.NoSuchProcess(pid=pid)
          username, cmdline, cpuutil, memutil = mock_pid_map[pid]
          p: Any = mock(strict=True)  # psutil.Process
          p.username = lambda: username
          p.cmdline = lambda: [cmdline]
          p.cpu_percent = lambda: cpuutil
          p.memory_percent = lambda: memutil
          p.pid = pid
          return p
  
      when(psutil).Process(...).thenAnswer(_MockedProcess)
      when(psutil).virtual_memory().thenReturn(
          mock_memory_t(total=8589934592, used=0)
      )
  
imports: import ctypes
  import os
  import re
  import shlex
  import sys
  import types
  from collections import namedtuple
  from io import StringIO
  from typing import Any
  import psutil
  import pytest
  from mockito import ANY, mock, unstub, when, when2
  import gpustat
  from gpustat.nvml import pynvml, pynvml_monkeypatch
label_desc: Use image node_id 2 for calling a global function with example usage: _configure_mock(N, _scenario_nonexistent_pid, _scenario_failing_one_gpu) and returns: _callable, p, v