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

Refine publish, skip certain tests if necessary. Rename many methods and...

Refine publish, skip certain tests if necessary. Rename many methods and functions according to style conventions.
parent 4863569f
Branches
Tags
2 merge requests!12v.0.1 for alpha release,!6Implement basic functionality of publish.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from TagPlot_matplotlib import TagPlot_matplotlib
import warnings
from TagPlot_matplotlib import TagPlot_matplotlib
def TagPlot(figs, prefix, engine, method=1, location='east'):
......@@ -89,7 +89,7 @@ def TagPlot(figs, prefix, engine, method=1, location='east'):
rotation = 90
position = (0.975, 0.35)
if engine == 'matplotlib' or engine == 'pyplot':
if engine in ('matplotlib', 'pyplot'):
return TagPlot_matplotlib(figs, prefix, method, rotation, position)
else:
raise ValueError(f'The plot engine "{engine}" is not supported.')
......
# -*- coding: utf-8 -*-
import CreateID
# from fcn_help.FST_colors import Colors
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.pyplot as plt
import create_id
# plt.style.use('./fcn_help/FST.mplstyle')
......@@ -19,22 +19,22 @@ def TagPlot_matplotlib(figs, prefix, method, rotation, position):
if isinstance(figs, matplotlib.figure.Figure):
pass
elif isinstance(figs, list):
for i in range(len(figs)):
if isinstance(figs[i], matplotlib.figure.Figure):
for figure in figs:
if isinstance(figure, matplotlib.figure.Figure):
pass
else:
raise TypeError('Figure is not a valid matplotlib-figure.')
FONTSIZE = 'small'
COLOR = 'grey'
fontsize = 'small'
color = 'grey'
IDs = []
# Loop to create and position the IDs
for fig in figs:
ID = CreateID.CreateID(method)
ID = create_id.create_id(method)
IDs.append(prefix + '_' + str(ID))
plt.figure(fig.number)
plt.figtext(x=position[0], y=position[1], s=ID, ha='left', wrap=True,
rotation=rotation, fontsize=FONTSIZE, color=COLOR)
rotation=rotation, fontsize=fontsize, color=color)
fig.tight_layout()
return [figs, IDs]
Image diff could not be displayed: it is too large. Options to address this: view the blob.
Image diff could not be displayed: it is too large. Options to address this: view the blob.
......@@ -4,7 +4,7 @@ import time
import uuid
def CreateID(method):
def create_id(method):
"""
Create an Identifier (str).
......
......@@ -13,7 +13,7 @@ from numpy import random
# import matplotlib
import matplotlib.pyplot as plt
from TagPlot import TagPlot
from Publish import Publish
from publish import publish
from fcn_help.FST_colors import Colors
plt.style.use('fcn_help/FST.mplstyle')
# %matplotlib qt
......@@ -65,5 +65,5 @@ for i, figure in enumerate(figs):
figure.savefig(name)
# %% Publish
Publish('fcn_help', '/home/chief/Dokumente/fst/plotid_python/data',
publish('fcn_help', '/home/chief/Dokumente/fst/plotid_python/data',
'/home/chief/Dokumente/fst/plotid_python/Test1.tiff', 'individual')
......@@ -7,7 +7,7 @@ import sys
import warnings
def Publish(src_datapath, dst_path, src_plot_path, data_storage):
def publish(src_datapath, dst_path, src_plot_path, data_storage):
"""
Save plot, data and measuring script.
......@@ -42,19 +42,24 @@ def Publish(src_datapath, dst_path, src_plot_path, data_storage):
raise FileNotFoundError('The specified destination directory '
'does not exist.')
# Check if src_plot_path is a string.
if not isinstance(src_plot_path, str):
raise TypeError('Path to plot must be given as string. Publishing '
'multiple plots at once is currently not supported.')
# Check if plot file exists
if not os.path.isfile(src_plot_path):
raise TypeError('The specified plot is not a file.')
# If dst dir already exists ask user if it should be overwritten or not.
if os.path.isdir(dst_path):
warnings.warn(f'Folder {dst_dirname} already exists – '
warnings.warn(f'Folder "{dst_dirname}" already exists – '
'plot has already been published.')
overwrite_dir = input('Do you want to overwrite the existing folder?'
' (yes/no[default])\n')
if overwrite_dir == 'yes' or overwrite_dir == 'y':
shutil.rmtree(dst_dirname)
if overwrite_dir in ('yes', 'y'):
shutil.rmtree(dst_path)
else:
raise RuntimeError('PlotID has finished without an export.\n'
'Rerun TagPlot if you need a new ID or '
......@@ -68,7 +73,7 @@ def Publish(src_datapath, dst_path, src_plot_path, data_storage):
match data_storage:
case 'centralized':
# Do nothing, not implemented yet
# Does nothing, not implemented yet
pass
case 'individual':
# Copy data to invisible folder
......@@ -88,4 +93,7 @@ def Publish(src_datapath, dst_path, src_plot_path, data_storage):
# If export was successful, make the directory visible
os.rename(dst_path_invisible, dst_path)
print(f'Publish was successful.\nYour plot "{src_plot_path}",\n'
f'your data "{src_datapath}"\nand your script "{sys.argv[0]}"\n'
f'were copied to {dst_path}\nin {data_storage} mode.')
return
......@@ -4,9 +4,9 @@
Unittests for TagPlot
'''
import unittest
from TagPlot import TagPlot
import numpy as np
import matplotlib.pyplot as plt
from TagPlot import TagPlot
# %% Create data
......@@ -22,13 +22,11 @@ color2 = 'yellow'
fig1 = plt.figure()
plt.plot(x, y, color=color1)
plt.plot(x, y_2, color=color2)
plt.clf # Close figure
# 2.Figure
fig2 = plt.figure()
plt.plot(x, y, color=color2)
plt.plot(x, y_2, color=color1)
plt.clf # Close figure
fig = [fig1, fig2]
......
......@@ -4,24 +4,24 @@
Unittests for CreateID
'''
import unittest
import CreateID
from create_id import create_id
class TestCreateID(unittest.TestCase):
def test_existence(self):
self.assertIsInstance(CreateID.CreateID(1), str)
self.assertIsInstance(CreateID.CreateID(2), str)
self.assertIsInstance(create_id(1), str)
self.assertIsInstance(create_id(2), str)
def test_errors(self):
with self.assertRaises(ValueError):
CreateID.CreateID(3)
create_id(3)
with self.assertRaises(ValueError):
CreateID.CreateID('h')
create_id('h')
def test_length(self):
self.assertEqual(len(CreateID.CreateID(1)), 10)
self.assertEqual(len(CreateID.CreateID(2)), 8)
self.assertEqual(len(create_id(1)), 10)
self.assertEqual(len(create_id(2)), 8)
if __name__ == '__main__':
......
......@@ -6,9 +6,11 @@ Unittests for Publish
import unittest
import os
import sys
import shutil
import base64
from Publish import Publish
from unittest.mock import patch
from publish import publish
SRC_DIR = 'test_src_folder'
IMG_DATA = b'iVBORw0KGgoAAAANSUhEUgAAAUAAAAFAAgMAAACw/k05AAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAAxQTFRFAAAAHBwcVFRU////6irJIAAAAIVJREFUeNrt3TERACAQBLHTgQlMU6GQDkz8MF9kBcTCJmrY2IWtJPMWdoBAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAv+A5RMHtesBZRvjTSF8ofkAAAAASUVORK5CYII='
......@@ -16,6 +18,7 @@ PIC_NAME = 'test_picture.png'
DST_DIR = 'test_dst_folder'
DST_PARENT_DIR = 'test_parent'
DST_PATH = os.path.join(DST_PARENT_DIR, DST_DIR)
INVISIBLE_PATH = os.path.join(DST_PARENT_DIR, '.' + DST_DIR)
class TestPublish(unittest.TestCase):
......@@ -23,36 +26,72 @@ class TestPublish(unittest.TestCase):
def setUp(self):
os.makedirs(SRC_DIR, exist_ok=True)
os.makedirs(DST_PARENT_DIR, exist_ok=True)
with open(PIC_NAME, "wb") as f:
f.write(base64.decodebytes(IMG_DATA))
with open(PIC_NAME, "wb") as test_pic:
test_pic.write(base64.decodebytes(IMG_DATA))
# This test fails if called from command line, because
# Publish then fails to copy the calling script to the destination folder.
# def test_publish(self):
# Publish(SRC_DIR, DST_PATH, PIC_NAME, 'individual')
# assert os.path.isfile(os.path.join(DST_PATH, PIC_NAME))
# 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):
publish(SRC_DIR, DST_PATH, PIC_NAME, 'individual')
assert os.path.isfile(os.path.join(DST_PATH, PIC_NAME))
def test_src_directory(self):
with self.assertRaises(FileNotFoundError):
Publish('not_existing_folder', DST_PATH, PIC_NAME, 'individual')
publish('not_existing_folder', DST_PATH, PIC_NAME, 'individual')
def test_dst_directory(self):
with self.assertRaises(FileNotFoundError):
Publish(SRC_DIR, 'not_existing_folder', PIC_NAME, 'individual')
publish(SRC_DIR, 'not_existing_folder', PIC_NAME, 'individual')
# Need mocks for this test to simulate user input
# def test_dst_already_exists(self):
# os.mkdir(DST_PATH)
# with self.assertWarns(Warning):
# Publish(SRC_DIR, DST_PATH, PIC_NAME, 'individual')
# 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_dst_already_exists_yes(self):
os.mkdir(DST_PATH)
# Mock user input as 'yes'
with patch('builtins.input', return_value='yes'):
publish(SRC_DIR, DST_PATH, PIC_NAME, 'individual')
# 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_dst_already_exists_no(self):
os.mkdir(DST_PATH)
# Mock user input as 'no'
with patch('builtins.input', return_value='no'):
with self.assertRaises(RuntimeError):
publish(SRC_DIR, DST_PATH, PIC_NAME, 'individual')
# 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_dst_already_exists_empty(self):
os.mkdir(DST_PATH)
# Mock user input as empty (no should be default).
with patch('builtins.input', return_value=''):
with self.assertRaises(RuntimeError):
publish(SRC_DIR, DST_PATH, PIC_NAME, 'individual')
# 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_dst__invisible_already_exists(self):
os.mkdir(INVISIBLE_PATH)
publish(SRC_DIR, DST_PATH, PIC_NAME, 'individual')
def test_picture(self):
with self.assertRaises(TypeError):
Publish(SRC_DIR, DST_PATH, 'none_existing_pic', 'individual')
publish(SRC_DIR, DST_PATH, 'none_existing_pic', 'individual')
def test_data_storage(self):
with self.assertRaises(ValueError):
Publish(SRC_DIR, DST_PATH, PIC_NAME, 'none_existing_method')
publish(SRC_DIR, DST_PATH, PIC_NAME, 'none_existing_method')
def tearDown(self):
shutil.rmtree(SRC_DIR)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment