code: def test_find_free_port():
      from dtale.app import find_free_port
  
      with ExitStack() as stack:
          mock_socket = stack.enter_context(
              mock.patch("socket.socket", mock.Mock())
          )
  
          assert find_free_port() == 40000
          mock_socket.assert_called_once()
          mock_socket.return_value.bind.assert_called_once()
  
      class MockSocket(object):
          def bind(self, addr):
              (host, port) = addr
              if port == 40000:
                  raise Exception("cannot connect!")
              return 1
  
          def close(self):
              pass
  
      with ExitStack() as stack:
          stack.enter_context(
              mock.patch(
                  "socket.socket", mock.Mock(return_value=MockSocket())
              )
          )
          assert find_free_port() == 40001
  
      class MockSocket2(object):
          def bind(self, _addr):
              raise Exception("cannot connect!")
  
          def close(self):
              pass
  
      with ExitStack() as stack:
          stack.enter_context(
              mock.patch(
                  "socket.socket", mock.Mock(return_value=MockSocket2())
              )
          )
          with pytest.raises(IOError) as excinfo:
              find_free_port()
          assert (
              "D-Tale could not find an open port from 40000 to 49000, please increase your range by altering "
              "the environment variables DTALE_MIN_PORT & DTALE_MAX_PORT."
          ) in str(excinfo)
  
imports: import getpass
  from collections import namedtuple
  from flask import Flask
  import mock
  import numpy
  import os
  import pandas
  import pytest
  from tests import ExitStack, pdt
label_desc: Use image node_id 2 for calling a global function with example usage: test_find_free_port() and returns: int