code: def test_grid_labels_tight():
      # Ensure tight layout accounts for gridlines
      fig = plt.figure(figsize=(7, 5))
  
      crs_pc = ccrs.PlateCarree()
      crs_merc = ccrs.Mercator()
  
      ax = fig.add_subplot(2, 2, 1, projection=crs_pc)
      ax.coastlines(resolution="110m")
      ax.gridlines(draw_labels=True)
  
      ax = fig.add_subplot(2, 2, 2, projection=crs_merc)
      ax.coastlines(resolution="110m")
      ax.gridlines(draw_labels=True)
  
      # Matplotlib tight layout is also incorrect if cartopy fails
      # to adjust aspect ratios first. Relevant when aspect ratio has
      # changed due to set_extent.
      ax = fig.add_subplot(2, 2, 3, projection=crs_pc)
      ax.set_extent([-20, 10.0, 45.0, 70.0])
      ax.coastlines(resolution="110m")
      ax.gridlines(draw_labels=True)
  
      ax = fig.add_subplot(2, 2, 4, projection=crs_merc)
      ax.set_extent([-20, 10.0, 45.0, 70.0], crs=crs_pc)
      ax.coastlines(resolution="110m")
      gl = ax.gridlines(draw_labels=True)
      gl.rotate_labels = False
  
      # Apply tight layout
      fig.tight_layout()
  
      # Ensure gridliners were drawn
      num_gridliners_drawn = 0
      for ax in fig.axes:
          for artist in ax.artists:
              if isinstance(artist, Gridliner) and getattr(
                  artist, "_drawn", False
              ):
                  num_gridliners_drawn += 1
  
      assert num_gridliners_drawn == 4
  
      return fig
  
imports: import io
  from unittest import mock
  from matplotlib.collections import PolyCollection
  import matplotlib.pyplot
  import matplotlib.ticker
  import numpy
  import pytest
  from shapely.geos import geos_version
  import cartopy.crs
  from cartopy.mpl import _MPL_36
  from cartopy.mpl.geoaxes import GeoAxes
  from cartopy.mpl.gridliner import LATITUDE_FORMATTER, LONGITUDE_FORMATTER, Gridliner, classic_formatter, classic_locator
  from cartopy.mpl.ticker import LongitudeFormatter, LongitudeLocator
label_desc: Use image node_id 4 for calling a global function with example usage: test_grid_labels_tight() and returns: fig