import os
import tempfile
import unittest

from compClust.iplot.CanvasFactoryAgg import CanvasFactoryAgg
import compClust.iplot.Plot as Plot

class PlotTestCases(unittest.TestCase):
  def testInitializedWithCanvas(self):
    """Test when initialized with canvas factory
    """
    canvas = CanvasFactoryAgg()
    p = Plot.Plot(canvas)

    self.failUnless(canvas == p.getCanvasFactory())
    self.failUnlessRaises(ValueError, p.setCanvasFactory, self)
    p.setCanvasFactory(None)
    self.failUnless(hasattr(p, "canvas"), "we should have a canvas")

  def testInitilizeWithoutCanvas(self):
    """Test without being initalized with a canvas factory
    """
    p = Plot.Plot()
    canvas = CanvasFactoryAgg()

    self.failUnless(p.canvas == None , "there should be no canvas")
    self.failUnless(p.getCanvasFactory() == None)
    p.setCanvasFactory(canvas)
    self.failUnless(hasattr(p, "canvas"),
                    "after setting the factory we should have a canvas")

  def testSavePlot(self):
    p = Plot.Plot(CanvasFactoryAgg())
    try:
      fd, base_filename = tempfile.mkstemp()
      p.save( base_filename )
      self.failUnless(os.path.isfile(p.image_filename), 
                      "file %s not created" % (p.image_filename))
    finally:
      os.unlink(p.image_filename)
   
def suite(**kw):
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(PlotTestCases))
  return suite
    
if __name__ == "__main__":
  tests = suite()
  unittest.TextTestRunner(verbosity=2).run(tests)
