Skip to content
Snippets Groups Projects
Commit 1f26e3db authored by Hock, Martin's avatar Hock, Martin
Browse files

Merge branch 'new-year-developments' into 'dev'

New year developments
See merge request !64
Closes #18 , #25 , #108 , #69
parents e63ca243 1b573989
No related branches found
No related tags found
2 merge requests!65Release v0.3.0,!64New year developments
Pipeline #889200 passed
Showing
with 441 additions and 71 deletions
......@@ -56,6 +56,8 @@ The argument "plot_engine" defines which plot engine was used to create the figu
tagplot returns a PlotIDTransfer object that contains the tagged figures and the corresponding IDs as strings.
Optional parameters can be used to customize the tag process.
- *figure_ids*: list of str, optional
IDs that will be printed on the plot. If empty, IDs will be generated for each plot. If this option is used, an ID for each plot has to be specified. Default: [].
- *prefix* : str, optional
Will be added as prefix to the ID.
- *id_method* : str, optional
......@@ -77,7 +79,7 @@ FIGS_AND_IDS = tagplot(FIGS_AS_LIST, "matplotlib", prefix="XY23_", id_method="ra
### publish()
Save plot, data and measuring script. It is possible to export multiple figures at once.
Save plot, data and measuring script. Modules that are imported in the script which calls plotID are exported to the file "required_imports.txt". These can later be installed via pip with the command `pip install -r /path/to/required_imports.txt`. It is possible to export multiple figures at once.
`publish(figs_and_ids, src_datapath, dst_path)`
- *figs_and_ids* must be a PlotIDTransfer object. Therefore, it can be directly passed from tagplot() to publish().
......
......
Customization of plotID
=======================
How your plot will be tagged by plotID is highly customizable. Please have a look in the documentation of the function "tagplot" to get an overview of all available keyword arguments.
To use a custom font for the ID on your plot, it is necessary to specify the absolute path to the ".otf" or ".ttf" file. You can put the file in your working directory and enter its path as argument in the script which calls plotID. You can also use fonts installed on your system. Below is a list of default locations of system wide installed fonts.
Linux:
- /usr/share/fonts
- /usr/local/share/fonts
- ~/.fonts
Windows:
- C:\\Windows\\Fonts
MacOS:
- /Library/Fonts/
......@@ -12,6 +12,7 @@ Welcome to plotID's documentation!
Overview <readme_link.rst>
Installation <installation.rst>
Customization <customization.rst>
Dependencies <dependencies.rst>
Structure and architecture <structure.rst>
About <about.rst>
......
......
......@@ -25,7 +25,12 @@ IMGS_AS_LIST = [IMG1, IMG2]
# Example for how to use tagplot with image files
FIGS_AND_IDS = tagplot(
IMGS_AS_LIST, "image", prefix=PROJECT_ID, id_method="time", location="west"
IMGS_AS_LIST,
"image",
prefix=PROJECT_ID,
id_method="time",
location="west",
qrcode=True,
)
# Required arguments: tagplot(images as list, desired plot engine)
......
......
......@@ -40,7 +40,12 @@ FIGS_AS_LIST = [FIG1, FIG2]
# Example for how to use tagplot with matplotlib figures
FIGS_AND_IDS = tagplot(
FIGS_AS_LIST, "matplotlib", location="west", id_method="random", prefix=PROJECT_ID
FIGS_AS_LIST,
"matplotlib",
location="west",
id_method="random",
prefix=PROJECT_ID,
qrcode=True,
)
# Required arguments: tagplot(images as list, desired plot engine)
......
......
......@@ -49,12 +49,26 @@ class PlotOptions:
Will be added as prefix to the ID.
id_method : str, optional
id_method for creating the ID. Create an ID by Unix time is referenced
as 'time', create a random ID with id_method='random'.
The default is 'time'.
as "time", create a random ID with id_method="random". The default is "time".
qrcode : bool, optional
Experimental status. Print qrcode on exported plot. Default: False.
Encode the ID in a QR code on the exported plot. Default: False.
qr_position : tuple, optional
Position of the bottom right corner of the QR Code on the plot in relative
(x, y) coordinates. Default: (1, 0).
qr_size: int or float, optional
Size of the QR code in arbitrary units. Default: 100.
id_on_plot: bool, optional
Print ID on the plot. Default: True.
font: str, optional
Font that will be used to print the ID. A path to an .otf or a .ttf
file has to be given. To use already installed fonts, you can search for the
standard path of fonts on your operating system and give then the path of the
desired font file to this parameter.
fontsize: int, optional
Fontsize for the displayed ID. Default: 12.
fontcolor: tuple, optional
Fontcolor for the ID. Must be given as tuple containing three rgb values with
each value between [0, 1]. Default: (0, 0, 0).
"""
def __init__(
......@@ -71,8 +85,18 @@ class PlotOptions:
self.position = position
self.prefix = kwargs.get("prefix", "")
self.id_method = kwargs.get("id_method", "time")
# Overwrite id_method if figure_ids were defined by the user
if self.figure_ids:
self.id_method = "custom"
self.qrcode = kwargs.get("qrcode", False)
self.qr_position = kwargs.get("qr_position", (1, 0))
self.qr_size = kwargs.get("qr_size", 100)
self.id_on_plot = kwargs.get("id_on_plot", True)
self.font = kwargs.get("font", False)
if self.font:
self.font = os.path.abspath(self.font)
self.fontsize = kwargs.get("fontsize", 12)
self.fontcolor = kwargs.get("fontcolor", (0, 0, 0))
def __str__(self) -> str:
"""Representation if an object of this class is printed."""
......
......
......@@ -8,10 +8,12 @@ the plot is based on. Additionally, the script that produced the plot will be
copied to the destination directory.
"""
import ast
import os
import shutil
import sys
import warnings
from importlib.metadata import version, PackageNotFoundError
from typing import TypedDict, Any
from plotid.save_plot import save_plot
from plotid.plotoptions import PlotIDTransfer, validate_list
......@@ -133,8 +135,7 @@ class PublishOptions:
" – plot has already been published."
)
overwrite_dir = input(
"Do you want to overwrite "
"the existing folder? "
"Do you want to overwrite the existing folder? "
"(yes/no[default])\n"
)
if overwrite_dir in ("yes", "y", "Yes", "YES"):
......@@ -149,14 +150,13 @@ class PublishOptions:
)
self.individual_data_storage(dst_path_invisible, plot)
self.export_imports(sys.argv[0], dst_path_invisible)
# If export was successful, make the directory visible
os.rename(dst_path_invisible, dst_path)
except FileExistsError as exc:
delete_dir = input(
"There was an error while "
"publishing the data. Should the "
"partially copied data at "
f"{dst_path_invisible} be"
"There was an error while publishing the data. Should the "
f"partially copied data at {dst_path_invisible} be"
" removed? (yes/no[default])\n"
)
if delete_dir in ("yes", "y", "Yes", "YES"):
......@@ -239,6 +239,59 @@ class PublishOptions:
os.path.join(destination, final_file_path),
)
def export_imports(self, file: str, destination: str) -> None:
"""Export all imported modules of a python script to file."""
with open(file, "r", encoding="utf-8") as source:
tree = ast.parse(source.read())
analyzer = Analyzer()
analyzer.visit(tree)
analyzer.report(destination)
class Analyzer(ast.NodeVisitor):
"""Visit and analyze nodes of Abstract Syntax Trees (AST)."""
def __init__(self) -> None:
self.stats: dict[str, list[str]] = {
"import": [],
"from_module": [],
"from": [],
}
def visit_Import(self, node: ast.Import) -> None:
"""Get modules that are imported with the 'import' statement."""
for alias in node.names:
self.stats["import"].append(alias.name)
self.generic_visit(node)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
"""Get modules that are imported with the 'from X import Y' statement."""
self.stats["from"].append(str(node.module))
self.generic_visit(node)
def report(self, dst_dir: str) -> None:
"""Create summary of imported modules."""
# Save the first part of import statement since it references the installed
# module.
imports_as_set = {module.split(".", 1)[0] for module in self.stats["import"]}
imports_as_set.update(
# Add modules imported with "from X import Y".
{module.split(".", 1)[0] for module in self.stats["from"]}
)
output_file = os.path.join(dst_dir, "required_imports.txt")
# Write every item of the set to one line.
with open(output_file, "w", encoding="utf-8") as output:
for item in imports_as_set:
try:
module_version = version(item)
output.write(f"{item}=={module_version}\n")
except PackageNotFoundError:
output.write(f"{item}\n")
output.close()
kwargs_types_publish = TypedDict(
"kwargs_types_publish",
......
......
Copyright 2020 The Open Sans Project Authors (https://github.com/googlefonts/opensans)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
File added
File added
......@@ -21,16 +21,16 @@ def save_plot(
Parameters
----------
figure : list of/single figure object
figure :
Figure that was tagged and now should be saved as picture.
plot_name : str or list of str
plot_name :
Names of the files where the plots will be saved to.
extension : str
extension :
File extension for the plot export.
Returns
-------
plot_path : list of str
plot_path :
Names of the created pictures.
"""
# Check if figs is a valid figure or a list of valid figures
......
......
......@@ -5,9 +5,6 @@ Tag your plot with an ID.
For publishing the tagged plot along your research data have a look at the
module publish.
Functions:
tagplot(figure object, string) -> list
"""
import warnings
......@@ -23,7 +20,6 @@ from plotid.tagplot_image import tagplot_image
def tagplot(
figs: plt.Figure | Image | list[plt.Figure | Image],
engine: Literal["matplotlib", "image"],
location: str = "east",
**kwargs: Any,
) -> PlotIDTransfer:
"""
......@@ -38,28 +34,57 @@ def tagplot(
Figures that should be tagged.
engine :
Plot engine which should be used to tag the plot.
location : str, optional
Location for ID to be displayed on the plot. Default is 'east'.
**kwargs : dict, optional
Extra arguments for additional plot options.
Other Parameters
----------------
figure_ids: list of str, optional
IDs that will be printed on the plot. If empty, IDs will be generated for each
plot. If this option is used, an ID for each plot has to be specified.
Default: [].
location : str, optional
Location for ID to be displayed on the plot. Default is "east".
rotation: float or int, optional
Rotation of the printed ID in degree. Overwrites the value defined by location.
position: tuple of float, optional
Position of the ID given as (x,y). x and y are relative coordinates in respect
to the figure size and must be in the intervall [0,1]. Overwrites the value
defined by location.
prefix : str, optional
Will be added as prefix to the ID.
id_method : str, optional
id_method for creating the ID. Create an ID by Unix time is referenced
as 'time', create a random ID with id_method='random'.
The default is 'time'.
qrcode : boolean, optional
Experimental support for encoding the ID in a QR Code.
as "time", create a random ID with id_method="random". The default is "time".
qrcode : bool, optional
Encode the ID in a QR code on the exported plot. Default: False.
qr_position : tuple, optional
Position of the bottom right corner of the QR Code on the plot in relative
(x, y) coordinates. Default: (1, 0).
qr_size: int or float, optional
Size of the QR code in arbitrary units. Default: 100.
id_on_plot: bool, optional
Print ID on the plot. Default: True.
font: str, optional
Font that will be used to print the ID. An absolute path to an .otf or a .ttf
file has to be given. To use already installed fonts, you can search for the
standard path of fonts on your operating system and give then the path of the
desired font file to this parameter.
fontsize: int, optional
Fontsize for the displayed ID. Default: 12.
fontcolor: tuple, optional
Fontcolor for the ID. Must be given as tuple containing three rgb values with
each value between [0, 1]. Default: (0, 0, 0).
Raises
------
TypeError
If specified location is not given as string.
If rotation was not given as number.
If position was not given as tuple containing two floats.
ValueError
If an unsupported plot engine is given.
If position tuple does not contain two items.
Returns
-------
......@@ -68,9 +93,8 @@ def tagplot(
figures were given. The first list contains the tagged figures.
The second list contains the corresponding IDs as strings.
"""
if isinstance(location, str):
pass
else:
location = kwargs.get("location", "east")
if not isinstance(location, str):
raise TypeError("Location is not a string.")
match location:
......@@ -79,7 +103,7 @@ def tagplot(
position = (0.35, 0.975)
case "east":
rotation = 90
position = (0.975, 0.35)
position = (0.95, 0.35)
case "south":
rotation = 0
position = (0.35, 0.015)
......@@ -89,9 +113,6 @@ def tagplot(
case "southeast":
rotation = 0
position = (0.75, 0.015)
case "custom":
# TODO: Get rotation and position from user input & check if valid
pass
case _:
warnings.warn(
f'Location "{location}" is not a defined '
......@@ -101,6 +122,19 @@ def tagplot(
rotation = 90
position = (0.975, 0.35)
if "rotation" in kwargs:
rotation = kwargs.pop("rotation")
if not isinstance(rotation, (int, float)):
raise TypeError("Rotation is not a float or integer.")
if "position" in kwargs:
position = kwargs.pop("position")
if not isinstance(position, tuple):
raise TypeError("Position is not a tuple of floats.")
if not len(position) == 2:
raise ValueError("Position does not contain two items.")
if not all(isinstance(item, float) for item in position):
raise TypeError("Position is not a tuple of floats.")
option_container = PlotOptions(figs, rotation, position, **kwargs)
option_container.validate_input()
......
......
# -*- coding: utf-8 -*-
"""
Tag your picture with an ID.
Functions:
tagplot_image(PlotOptions instance) -> PlotIDTransfer instance
"""
"""Tag your picture with an ID."""
import os
from PIL import Image, ImageDraw, ImageFont, ImageOps
import warnings
from importlib.resources import files
from PIL import Image, ImageDraw, ImageFont
from plotid.create_id import create_id, create_qrcode
from plotid.plotoptions import PlotOptions, PlotIDTransfer
......@@ -37,36 +34,82 @@ def tagplot_image(plotid_object: PlotOptions) -> PlotIDTransfer:
if not isinstance(img, str):
raise TypeError("Name of the image is not a string.")
if not os.path.isfile(img):
raise TypeError("File does not exist.")
raise TypeError(f"Image '{img}' does not exist.")
# Check if figs is a valid file is done by pillow internally
color = (128, 128, 128) # grey
font = ImageFont.load_default()
color = tuple(rgb_value * 255 for rgb_value in plotid_object.fontcolor)
# font = ImageFont.load_default()
font_path = (
files("plotid.resources").joinpath("OpenSans").joinpath("OpenSans-Regular.ttf")
)
font = ImageFont.truetype(str(font_path), plotid_object.fontsize)
if plotid_object.font:
try:
# Absolute path to font file (.ttf or .otf) has to be given
font = ImageFont.truetype(plotid_object.font, plotid_object.fontsize)
except OSError:
warnings.warn("Font was not found.\nplotID continues with fallback font.")
if plotid_object.font:
try:
# Absolute path to font file (.ttf or .otf) has to be given
font = ImageFont.truetype(plotid_object.font, plotid_object.fontsize)
except OSError:
warnings.warn("Font was not found.\nplotID continues with fallback font.")
for i, img in enumerate(plotid_object.figs):
for j, img in enumerate(plotid_object.figs):
if plotid_object.id_method == "custom":
# If IDs were given by the user, use them
img_id: str = str(plotid_object.figure_ids[j])
else:
# Create ID with given method
img_id = plotid_object.prefix + create_id(plotid_object.id_method)
plotid_object.figure_ids.append(img_id)
img = Image.open(img)
if plotid_object.id_on_plot:
img_txt = Image.new("L", font.getsize(img_id))
# Create temporary PIL image to get correct textsize
tmp_img = Image.new("L", (100, 100))
tmp_draw = ImageDraw.Draw(tmp_img)
textsize = tmp_draw.textsize(img_id, font)
# Create new image with white background and the size of the textbox
img_txt = Image.new("RGBA", textsize, color=(255, 255, 255, 0))
draw_txt = ImageDraw.Draw(img_txt)
draw_txt.text((0, 0), img_id, font=font, fill=255)
draw_txt.text((0, 0), img_id, font=font, fill=color)
# Rotate the image by the given angle
txt = img_txt.rotate(plotid_object.rotation, expand=1)
# Paste the txt/ID image with transparent background onto the original image
img.paste(
ImageOps.colorize(txt, (0, 0, 0), color),
txt,
(
int(img.width * plotid_object.position[0]),
int(img.height * (1 - plotid_object.position[1])),
int(img.height * (1 - plotid_object.position[1]) - txt.height),
),
txt,
)
if plotid_object.qrcode:
qrcode = create_qrcode(img_id)
qrcode.thumbnail((100, 100), Image.ANTIALIAS)
img.paste(qrcode, box=(img.width - 100, img.height - 100))
plotid_object.figs[i] = img
qrcode.thumbnail(
(plotid_object.qr_size, plotid_object.qr_size), Image.ANTIALIAS
)
img.paste(
qrcode,
box=(
int(
img.width * plotid_object.qr_position[0] - plotid_object.qr_size
),
int(
img.height * (1 - plotid_object.qr_position[1])
- plotid_object.qr_size
),
),
)
plotid_object.figs[j] = img
figs_and_ids = PlotIDTransfer(plotid_object.figs, plotid_object.figure_ids)
return figs_and_ids
# -*- coding: utf-8 -*-
"""Tag your matplotlib plot with an ID."""
from importlib.resources import files
import matplotlib
import matplotlib.pyplot as plt
from PIL import Image
......@@ -35,32 +36,54 @@ def tagplot_matplotlib(plotid_object: PlotOptions) -> PlotIDTransfer:
if not isinstance(figure, matplotlib.figure.Figure):
raise TypeError("Figure is not a valid matplotlib-figure.")
fontsize = "small"
color = "grey"
if plotid_object.font:
# Load custom font into matplotlib
matplotlib.font_manager.fontManager.addfont(plotid_object.font)
font = matplotlib.font_manager.FontProperties(fname=plotid_object.font)
else:
font = (
files("plotid.resources")
.joinpath("OpenSans")
.joinpath("OpenSans-Regular.ttf")
)
matplotlib.font_manager.fontManager.addfont(str(font))
font = matplotlib.font_manager.FontProperties(fname=font)
# Loop to create and position the IDs
for fig in plotid_object.figs:
fig_id: str = create_id(plotid_object.id_method)
for j, fig in enumerate(plotid_object.figs):
if plotid_object.id_method == "custom":
# If IDs were given by the user, use them
fig_id: str = str(plotid_object.figure_ids[j])
else:
# Create ID with given method
fig_id = create_id(plotid_object.id_method)
fig_id = plotid_object.prefix + fig_id
plotid_object.figure_ids.append(fig_id)
plt.figure(fig)
if plotid_object.id_on_plot:
plt.figtext(
x=plotid_object.position[0],
y=plotid_object.position[1],
s=fig_id,
ha="left",
wrap=True,
rotation=plotid_object.rotation,
fontsize=fontsize,
color=color,
fontsize=plotid_object.fontsize,
color=plotid_object.fontcolor,
font=font,
)
if plotid_object.qrcode:
qrcode = create_qrcode(fig_id)
qrcode.thumbnail((100, 100), Image.ANTIALIAS)
fig.figimage(qrcode, fig.bbox.xmax - 100, 0, cmap="bone")
qrcode.thumbnail(
(plotid_object.qr_size, plotid_object.qr_size), Image.ANTIALIAS
)
fig.figimage(
qrcode,
fig.bbox.xmax * plotid_object.qr_position[0] - plotid_object.qr_size,
fig.bbox.ymax * plotid_object.qr_position[1],
cmap="bone",
)
fig.tight_layout()
figs_and_ids = PlotIDTransfer(plotid_object.figs, plotid_object.figure_ids)
......
......
......@@ -48,10 +48,11 @@ class TestTagplot(unittest.TestCase):
)
self.assertEqual(
str(plot_obj),
"<class 'plotid.plotoptions.PlotOptions'>: {'figs': "
"'FIG', 'figure_ids': [], 'rotation': 270, 'position'"
": (100, 200), 'prefix': 'xyz', 'id_method': "
"'random', 'qrcode': False, 'id_on_plot': False}",
"<class 'plotid.plotoptions.PlotOptions'>: {'figs': 'FIG', 'figure_ids': "
"[], 'rotation': 270, 'position': (100, 200), 'prefix': 'xyz', 'id_method':"
" 'random', 'qrcode': False, 'qr_position': (1, 0), 'qr_size': 100, "
"'id_on_plot': False, 'font': False, 'fontsize': 12, 'fontcolor': "
"(0, 0, 0)}",
)
def test_str_plotidtransfer(self) -> None:
......
......
......@@ -9,6 +9,8 @@ import os
import sys
import platform
import shutil
from collections import Counter
from importlib.metadata import version
from subprocess import run, CalledProcessError
from unittest.mock import patch
import matplotlib.pyplot as plt
......@@ -341,6 +343,42 @@ class TestPublish(unittest.TestCase):
str(publish_obj),
)
def test_export_imports(self) -> None:
"""
Test if imports of the calling script are correctly written to file.
This test only works if called from the parent directory, since the path to the
file to test the behaviour has to be specified correctly.
"""
mpl_version = version("matplotlib")
expected_modules = [
"shutil\n",
"unittest\n",
"subprocess\n",
"platform\n",
f"matplotlib=={mpl_version}\n",
"os\n",
"sys\n",
"plotid\n",
"collections\n",
"importlib\n",
]
folder = os.path.join("test_parent", "test_dst_folder")
os.mkdir(folder)
publish_obj = PublishOptions(FIGS_AND_IDS, SRC_DIR, DST_PATH)
publish_obj.export_imports(os.path.join("tests", "test_publish.py"), folder)
file_path = os.path.join(folder, "required_imports.txt")
assert os.path.isfile(file_path)
with open(file_path, "r", encoding="utf-8") as file:
modules = file.readlines()
print(modules, expected_modules)
self.assertEqual(
Counter(modules),
Counter(expected_modules),
msg=f"{modules}, {expected_modules}",
)
def tearDown(self) -> None:
"""Delete all files created in setUp."""
shutil.rmtree(SRC_DIR)
......
......
......@@ -36,8 +36,23 @@ class TestTagplot(unittest.TestCase):
Test if tagplot runs successful.
"""
tagplot(FIGS_AS_LIST, PLOT_ENGINE, prefix=PROJECT_ID, id_method=METHOD)
tagplot(FIGS_AS_LIST, PLOT_ENGINE, rotation=42, position=(0.3, 0.14))
tagplot(IMGS_AS_LIST, "image", location="north")
def test_rotation(self) -> None:
"""Test if Error is raised if rotation is not a number."""
with self.assertRaises(TypeError):
tagplot(FIGS_AS_LIST, PLOT_ENGINE, rotation="42")
def test_position(self) -> None:
"""Test if Error is raised if position is not a tuple containing two numbers."""
with self.assertRaises(ValueError):
tagplot(FIGS_AS_LIST, PLOT_ENGINE, position=(0.3, 0.14, 5))
with self.assertRaises(TypeError):
tagplot(FIGS_AS_LIST, PLOT_ENGINE, position=0.3)
with self.assertRaises(TypeError):
tagplot(FIGS_AS_LIST, PLOT_ENGINE, position=(0.3, True))
def test_prefix(self) -> None:
"""Test if Error is raised if prefix is not a string."""
with self.assertRaises(TypeError):
......
......
......@@ -16,7 +16,6 @@ FIG1 = plt.figure()
IMG1 = "image1.png"
FIG2 = plt.figure()
IMG2 = "image2.jpg"
IMGS_AS_LIST = [IMG1, IMG2]
# Constants for tests
PROJECT_ID = "MR01"
......@@ -40,12 +39,16 @@ class TestTagplotImage(unittest.TestCase):
respectively.
"""
options = PlotOptions(
IMGS_AS_LIST,
[IMG1, IMG2],
ROTATION,
POSITION,
figure_ids=["test123456", "654321tset"],
prefix=PROJECT_ID,
id_method=METHOD,
qrcode=True,
fontsize=10,
font="plotid/resources/OpenSans/OpenSans-Bold.ttf",
fontcolor=(0, 1, 0),
)
options.validate_input()
figs_and_ids = tagplot_image(options)
......@@ -85,6 +88,13 @@ class TestTagplotImage(unittest.TestCase):
with self.assertRaises(TypeError):
tagplot_image("wrong_object")
def test_font_file_not_defined(self) -> None:
"""Test if a Warning is raised if an invalid font file was specified."""
options = PlotOptions(IMG1, ROTATION, POSITION, font="font")
options.validate_input()
with self.assertWarns(Warning):
tagplot_image(options)
def tearDown(self) -> None:
os.remove(IMG1)
os.remove(IMG2)
......
......
......@@ -33,9 +33,13 @@ class TestTagplotMatplotlib(unittest.TestCase):
FIGS_AS_LIST,
ROTATION,
POSITION,
figure_ids=["test123456", "654321tset"],
prefix=PROJECT_ID,
id_method=METHOD,
qrcode=True,
fontsize=10,
font="plotid/resources/OpenSans/OpenSans-Bold.ttf",
fontcolor=(0, 0, 1),
)
options.validate_input()
figs_and_ids = tagplot_matplotlib(options)
......
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment