Skip to content
Snippets Groups Projects
Commit ab0bb40f authored by nugget's avatar nugget
Browse files

Improve code quality of unittests by adding docstrings.

parent 40a05b46
No related branches found
No related tags found
3 merge requests!12v.0.1 for alpha release,!11Draft: Merge version0.1 changes into dev,!10Version0.1
Pipeline #725313 passed
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
"""
Unittests for CreateID
'''
"""
import unittest
from create_id import create_id
class TestCreateID(unittest.TestCase):
"""
Class for all unittests of the create_id module.
"""
def test_existence(self):
"""Test if create_id returns a string."""
self.assertIsInstance(create_id(1), str)
self.assertIsInstance(create_id(2), str)
def test_errors(self):
""" Test if Errors are raised when id_method is wrong. """
with self.assertRaises(ValueError):
create_id(3)
with self.assertRaises(ValueError):
create_id('h')
def test_length(self):
""" Test if figure_id has the correct length. """
self.assertEqual(len(create_id(1)), 10)
self.assertEqual(len(create_id(2)), 8)
......
# -*- coding: utf-8 -*-
'''
Unittests for Publish
'''
"""
Unittests for publish
"""
import unittest
import os
import sys
import shutil
import base64
import matplotlib.pyplot as plt
from unittest.mock import patch
import matplotlib.pyplot as plt
from publish import publish
SRC_DIR = 'test_src_folder'
IMG_DATA = b'iVBORw0KGgoAAAANSUhEUgAAAUAAAAFAAgMAAACw/k05AAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAAxQTFRFAAAAHBwcVFRU////6irJIAAAAIVJREFUeNrt3TERACAQBLHTgQlMU6GQDkz8MF9kBcTCJmrY2IWtJPMWdoBAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAv+A5RMHtesBZRvjTSF8ofkAAAAASUVORK5CYII=' # noqa: E501
PIC_NAME = 'test_picture'
DST_DIR = 'test_dst_folder'
DST_PARENT_DIR = 'test_parent'
......@@ -24,27 +22,32 @@ fig = plt.figure()
class TestPublish(unittest.TestCase):
"""
Class for all unittests of the publish module.
"""
def setUp(self):
""" Generate source and destination directory and test image. """
os.makedirs(SRC_DIR, exist_ok=True)
os.makedirs(DST_PARENT_DIR, exist_ok=True)
with open(PIC_NAME, "wb") as test_pic:
test_pic.write(base64.decodebytes(IMG_DATA))
# Skip test if tests are run from command line.
@unittest.skipIf(not os.path.isfile(sys.argv[0]), 'Publish is not called '
'from a Python script. Therefore, the script cannot be '
'copied.')
def test_publish(self):
""" Test publish and check if an exported picture file exists. """
publish(SRC_DIR, DST_PATH, fig, PIC_NAME, 'individual')
assert os.path.isfile(os.path.join(DST_PATH, PIC_NAME + '.png'))
def test_src_directory(self):
""" Test if Error is raised when source directory does not exist."""
with self.assertRaises(FileNotFoundError):
publish('not_existing_folder', DST_PATH, fig,
PIC_NAME, 'individual')
def test_dst_directory(self):
""" Test if Error is raised when destination dir does not exist."""
with self.assertRaises(FileNotFoundError):
publish(SRC_DIR, 'not_existing_folder',
fig, PIC_NAME, 'individual')
......@@ -54,6 +57,10 @@ class TestPublish(unittest.TestCase):
'from a Python script. Therefore, the script cannot be '
'copied.')
def test_dst_already_exists_yes(self):
"""
Test if publish succeeds if the user wants to overwrite an existing
destination directory.
"""
os.mkdir(DST_PATH)
# Mock user input as 'yes'
with patch('builtins.input', return_value='yes'):
......@@ -64,6 +71,10 @@ class TestPublish(unittest.TestCase):
'from a Python script. Therefore, the script cannot be '
'copied.')
def test_dst_already_exists_no(self):
"""
Test if publish exits with error if the user does not want to overwrite
an existing destination directory by user input 'no'.
"""
os.mkdir(DST_PATH)
# Mock user input as 'no'
with patch('builtins.input', return_value='no'):
......@@ -75,6 +86,10 @@ class TestPublish(unittest.TestCase):
'from a Python script. Therefore, the script cannot be '
'copied.')
def test_dst_already_exists_empty(self):
"""
Test if publish exits with error if the user does not want to overwrite
an existing destination directory by missing user input.
"""
os.mkdir(DST_PATH)
# Mock user input as empty (no should be default).
with patch('builtins.input', return_value=''):
......@@ -86,21 +101,29 @@ class TestPublish(unittest.TestCase):
'from a Python script. Therefore, the script cannot be '
'copied.')
def test_dst__invisible_already_exists(self):
"""
Test if publish succeeds when there is already an invisible
directory from a previous run (delete the folder and proceed).
"""
os.mkdir(INVISIBLE_PATH)
publish(SRC_DIR, DST_PATH, fig, PIC_NAME, 'individual')
def test_picture(self):
""" Test if Error is raised if fig is not a valid figure object. """
with self.assertRaises(TypeError):
publish(SRC_DIR, DST_PATH, 'fig', PIC_NAME, 'individual')
def test_data_storage(self):
"""
Test if Error is raised when unsupported storage method was chosen.
"""
with self.assertRaises(ValueError):
publish(SRC_DIR, DST_PATH, fig, PIC_NAME, 'none_existing_method')
def tearDown(self):
""" Delete all files created in setUp. """
shutil.rmtree(SRC_DIR)
shutil.rmtree(DST_PARENT_DIR)
os.remove(PIC_NAME)
if __name__ == '__main__':
......
# -*- coding: utf-8 -*-
'''
"""
Unittests for save_plot
'''
"""
import os
import unittest
import matplotlib.pyplot as plt
from save_plot import save_plot
figure = plt.figure()
plot_name = 'PLOT_NAME'
FIGURE = plt.figure()
PLOT_NAME = 'PLOT_NAME'
class TestSave_Plot(unittest.TestCase):
class TestSavePlot(unittest.TestCase):
"""
Class for all unittests of the save_plot module.
"""
def test_save_plot(self):
save_plot(figure, plot_name, extension='jpg')
os.remove(plot_name + '.jpg')
""" Test if save_plot succeeds with valid arguments. """
save_plot(FIGURE, PLOT_NAME, extension='jpg')
os.remove(PLOT_NAME + '.jpg')
def test_wrong_fig_type(self):
""" Test if Error is raised when not a figure object is given. """
with self.assertRaises(TypeError):
save_plot('figure', 'PLOT_NAME', extension='jpg')
......
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
"""
Unittests for tagplot
'''
"""
import unittest
import numpy as np
import matplotlib.pyplot as plt
from tagplot import tagplot
# %% Create data
x = np.linspace(0, 10, 100)
y = np.random.rand(100) + 2
y_2 = np.sin(x) + 2
# %% Create figure
color1 = 'black'
color2 = 'yellow'
# 1.Figure
fig1 = plt.figure()
plt.plot(x, y, color=color1)
plt.plot(x, y_2, color=color2)
# 2.Figure
fig2 = plt.figure()
plt.plot(x, y, color=color2)
plt.plot(x, y_2, color=color1)
fig = [fig1, fig2]
# Constants for tests
ProjectID = "MR01"
plot_engine = "matplotlib"
method = 1
FIG1 = plt.figure()
FIG2 = plt.figure()
FIGS_AS_LIST = [FIG1, FIG2]
PROJECT_ID = "MR01"
PLOT_ENGINE = "matplotlib"
METHOD = 1
class Test_tagplot(unittest.TestCase):
class TestTagplot(unittest.TestCase):
"""
Class for all unittests of the tagplot module.
"""
def test_figures(self):
"""
Test if Errors are raised when the provided figure is not given
as list.
"""
with self.assertRaises(TypeError):
tagplot('fig', ProjectID, plot_engine, method)
tagplot('fig', PLOT_ENGINE, PROJECT_ID, METHOD)
with self.assertRaises(TypeError):
tagplot(fig1, plot_engine, prefix=ProjectID)
tagplot(FIG1, PLOT_ENGINE, prefix=PROJECT_ID)
def test_prefix(self):
""" Test if Error is raised if prefix is not a string. """
with self.assertRaises(TypeError):
tagplot(fig, plot_engine, 3, method)
tagplot(FIGS_AS_LIST, PLOT_ENGINE, 3, METHOD)
def test_plotengine(self):
"""
Test if Errors are raised if the provided plot engine is not supported.
"""
with self.assertRaises(ValueError):
tagplot(fig, 1, ProjectID, method)
tagplot(FIGS_AS_LIST, 1, PROJECT_ID, METHOD)
with self.assertRaises(ValueError):
tagplot(fig, 'xyz', ProjectID, method)
tagplot(FIGS_AS_LIST, 'xyz', PROJECT_ID, METHOD)
def test_idmethod(self):
"""
Test if Errors are raised if the id_method is not an integer.
"""
with self.assertRaises(TypeError):
tagplot(fig, plot_engine, ProjectID, method='(0,1)')
tagplot(FIGS_AS_LIST, PLOT_ENGINE, PROJECT_ID, id_method='(0,1)')
with self.assertRaises(TypeError):
tagplot(fig, plot_engine, ProjectID, method='h')
tagplot(FIGS_AS_LIST, PLOT_ENGINE, PROJECT_ID, id_method='h')
with self.assertRaises(TypeError):
tagplot(fig, plot_engine, ProjectID, method='[0,1]')
tagplot(FIGS_AS_LIST, PLOT_ENGINE, PROJECT_ID, id_method='[0,1]')
def test_location(self):
"""
Test if Errors are raised if the provided location is not supported.
"""
with self.assertRaises(TypeError):
tagplot(fig, plot_engine, ProjectID, method, location=1)
tagplot(FIGS_AS_LIST, PLOT_ENGINE, PROJECT_ID, METHOD, location=1)
with self.assertWarns(Warning):
tagplot(fig, plot_engine, ProjectID, method, location='up')
tagplot(FIGS_AS_LIST, PLOT_ENGINE, PROJECT_ID, METHOD,
location='up')
if __name__ == '__main__':
......
......@@ -6,53 +6,45 @@ Unittests for TagPlot_matplotlib
import unittest
from tagplot_matplotlib import tagplot_matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from tagplot import PlotOptions
from plotoptions import PlotOptions
# %% Create data
x = np.linspace(0, 10, 100)
y = np.random.rand(100) + 2
y_2 = np.sin(x) + 2
# %% Create figure
color1 = 'black'
color2 = 'yellow'
# 1.Figure
fig1 = plt.figure()
plt.plot(x, y, color=color1)
plt.plot(x, y_2, color=color2)
# 2.Figure
fig2 = plt.figure()
plt.plot(x, y, color=color2)
plt.plot(x, y_2, color=color1)
fig = [fig1, fig2]
FIG1 = plt.figure()
FIG2 = plt.figure()
FIGS_AS_LIST = [FIG1, FIG2]
# Constants for tests
ProjectID = "MR01"
method = 1
rotation = 90
position = (0.975, 0.35)
PROJECT_ID = "MR01"
METHOD = 1
ROTATION = 90
POSITION = (0.975, 0.35)
class Test_tagplot_matplotlib(unittest.TestCase):
class TestTagplotMatplotlib(unittest.TestCase):
"""
Class for all unittests of the tagplot_matplotlib module.
"""
def test_mplfigures(self):
options = PlotOptions(fig, ProjectID, method, rotation, position)
[figs, ID] = tagplot_matplotlib(options)
""" Test of returned objects. Check if they are matplotlib figures. """
options = PlotOptions(FIGS_AS_LIST, PROJECT_ID, METHOD, ROTATION,
POSITION)
[figs, _] = tagplot_matplotlib(options)
self.assertIsInstance(figs[0], Figure)
self.assertIsInstance(figs[1], Figure)
def test_mplerror(self):
options = PlotOptions(3, ProjectID, method, rotation, position)
""" Test if Error is raised if wrong type of figures is given. """
options = PlotOptions(3, PROJECT_ID, METHOD, ROTATION, POSITION)
with self.assertRaises(TypeError):
tagplot_matplotlib(options)
def test_mpl_plotoptions(self):
"""
Test if Error is raised if not an instance of PlotOptions is passed.
"""
with self.assertRaises(TypeError):
tagplot_matplotlib('wrong_object')
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment