Tuesday, February 25, 2025

hello world plot with unit test in python

this simple example has 3 files all saved in a folder called HelloWorldPlot. the __init__.py file is empty:

HelloWorldPlot
	__init__.py
	core.py
	testing.py
#core.py

from matplotlib import pyplot

class SimplePlot(object):
    def __init__(self, x, y):
        """
        Args:
            x (list of floats): x values
            y (list of floats): y values
        """
        self._x = x
        self._y = y
    
    def setX(self, val):
        """
        Args:
            val (list): list of floats
        """
        self._x = val

    def setY(self, val):
        """
        Args:
            val (list): list of floats
        """
        self._y = val
        
    def build(self, **kwargs):
        """build the plot
        Args:
            kwargs : option pyplot plot keyword arguments            
        """
        pyplot.plot(self._x, self._y, **kwargs)
        pyplot.show()
        
        return True
#testing.py

import unittest
from . import core as CORE

class SimpleData(object):
    """simple data generator
    """
    x = [0, 1, 2]
    y = [2, 4, 6]
    

class TestSimplePlot(unittest.TestCase):
    def test_plot(self):
        data = SimpleData()
        plotObj = CORE.SimplePlot(data.x, data.y)
        status = plotObj.build(marker='o')
        self.assertTrue(status)
        
if __name__ == '__main__':
    unittest.main()
    
#testing on command line:
#python -m HelloWorldPlot.testing -v



#inspired by
#https://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-import-in-non-package-even-with-init-py 
 
Thanks for looking