Skip to content

test_tfplot fails when no $DISPLAY environment variable is defined

When running the tests with nosetests in an environment with no $DISPLAY variable defined (in particular in a Docker container) the following error occurs:

======================================================================
ERROR: Check that the all the plotting sections of tfplot can be run
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/ltfatpy/ltfatpy/tests/gabor/test_tfplot.py", line 183, in test_plot
    tfplot(coef, step, yr, plottype=plottype)
  File "/ltfatpy/ltfatpy/gabor/tfplot.py", line 230, in tfplot
    interpolation='nearest', origin='lower')
  File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 2881, in imshow
    ax = gca()
  File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 803, in gca
    ax =  gcf().gca(**kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 450, in gcf
    return figure()
  File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 423, in figure
    **kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 79, in new_figure_manager
    return new_figure_manager_given_figure(num, figure)
  File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 87, in new_figure_manager_given_figure
    window = Tk.Tk()
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1854, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
nose.proxy.TclError: no display name and no $DISPLAY environment variable
-------------------- >> begin captured stdout << ---------------------

This happens despite the fact that the tests are not doing any actual display with matplotlib (matplotlib.pyplot.show() is never called).

The solution is to force the use of a non-interactive backend for matplotlib, for example the backend ps. The function matplotlib.pyplot.switch_backend can be used to switch the backend.