code: def test_bind_kernel(request):
      ctx = zmq.Context.instance()
      request.addfinalizer(ctx.destroy)
  
      class MockIPEngineApp(ipyparallel.engine.app.IPEngine):
          kernel = None
          context = ctx
  
      app = MockIPEngineApp()
      app.kernel_app = None
      app.kernel = MagicMock(spec=IPythonKernel)
  
      def socket_spec():
          spec = create_autospec(zmq.Socket, instance=True)
          spec.FD = 2
          return spec
  
      app.kernel.shell_streams = [
          zmqstream.ZMQStream(
              socket=socket_spec(),
              io_loop=create_autospec(
                  spec=ioloop.IOLoop, spec_set=True, instance=True
              ),
          )
      ]
  
      app.kernel.control_stream = zmqstream.ZMQStream(
          socket=socket_spec(),
          io_loop=create_autospec(
              spec=ioloop.IOLoop, spec_set=True, instance=True
          ),
      )
  
      # testing the case iopub_socket is not replaced with IOPubThread
      iopub_socket = socket_spec()
  
      app.kernel.iopub_socket = iopub_socket
      assert isinstance(app.kernel.iopub_socket, zmq.Socket)
      bind_kernel(app)
      assert (
          app.kernel.iopub_socket.bind_to_random_port.called
          and app.kernel.iopub_socket.bind_to_random_port.call_count
          == 1
      )
  
      # testing the case iopub_socket is replaced with IOPubThread
      class TestIOPubThread(iostream.IOPubThread):
          socket = None
  
      iopub_socket.reset_mock()
      app.kernel_app = None
      app.kernel.iopub_socket = create_autospec(
          spec=TestIOPubThread, spec_set=True, instance=True
      )
      app.kernel.iopub_socket.socket = iopub_socket
      assert isinstance(app.kernel.iopub_socket, iostream.IOPubThread)
      bind_kernel(app)
      assert (
          app.kernel.iopub_socket.socket.bind_to_random_port.called
          and app.kernel.iopub_socket.socket.bind_to_random_port.call_count
          == 1
      )
  
imports: import glob
  import json
  import os
  import sys
  import time
  import types
  from subprocess import Popen, check_call, check_output
  from unittest.mock import MagicMock, create_autospec, patch
  import pytest
  import zmq
  from ipykernel import iostream, kernelapp
  from ipykernel.ipkernel import IPythonKernel
  from IPython.core.profiledir import ProfileDir
  from tornado import ioloop
  from zmq.eventloop import zmqstream
  import ipyparallel
  import ipyparallel.engine.app
label_desc: Use image node_id 6 for calling a global function with example usage: test_bind_kernel(request) and returns: spec