Skip to content
Snippets Groups Projects
Commit ec68696e authored by Anders H. Rebner's avatar Anders H. Rebner
Browse files

#38 #39 Laget tester

parent 4b968b3c
No related branches found
No related tags found
1 merge request!40#38 #39 Eksporter og importer SOI til/fra fil
Pipeline #76114 failed
...@@ -235,15 +235,15 @@ class MainWindow(QMainWindow): ...@@ -235,15 +235,15 @@ class MainWindow(QMainWindow):
in a new tab, which is selected. in a new tab, which is selected.
""" """
# Get file-name from dialog # Get file-name from dialog
file_name = QFileDialog().getOpenFileName( file_path = QFileDialog().getOpenFileName(
self, self,
"Åpne SOI", "Åpne SOI",
os.getcwd(), os.getcwd(),
"Text/JSON-filer (SOI_*.txt SOI_*.json)", "Text/JSON-filer (SOI_*.txt SOI_*.json)",
)[0] )[0]
if len(file_name) > 0: if len(file_path) > 0:
soi = import_soi(file_name) soi = import_soi(file_path)
# Create and select tab # Create and select tab
tab = SOIWorkspaceWidget(soi) tab = SOIWorkspaceWidget(soi)
......
...@@ -22,13 +22,13 @@ def serialize_soi(soi): ...@@ -22,13 +22,13 @@ def serialize_soi(soi):
Raises Raises
------ ------
ValueError TypeError
Raises error if parameter 'soi' is not a SOI. Raises error if parameter 'soi' is not a SOI.
""" """
# If parameter 'soi' is not a SOI # If parameter 'soi' is not a SOI
if not isinstance(soi, SOI): if not isinstance(soi, SOI):
raise ValueError( raise TypeError(
"Invalid value for parameter 'soi': " + "'{}'.".format(soi) "Invalid type for parameter 'soi': " + "'{}'.".format(soi)
) )
# Create dict with relevant module-information # Create dict with relevant module-information
...@@ -58,6 +58,7 @@ def serialize_soi(soi): ...@@ -58,6 +58,7 @@ def serialize_soi(soi):
"title": soi.title, "title": soi.title,
"description": soi.description, "description": soi.description,
"date": soi.date, "date": soi.date,
"version": soi.version,
"valid": {"from": soi.valid_from, "to": soi.valid_to}, "valid": {"from": soi.valid_from, "to": soi.valid_to},
"icon": soi.icon, "icon": soi.icon,
"classification": soi.classification, "classification": soi.classification,
...@@ -107,14 +108,29 @@ def export_soi(soi, compressed=True): ...@@ -107,14 +108,29 @@ def export_soi(soi, compressed=True):
file.close() file.close()
def import_soi(file_name): def import_soi(file_path):
"""Import compressed or uncompressed serialized SOI. """Import compressed or uncompressed serialized SOI.
Reads content of file and decompresses it for .txt-files. Reads content of file and decompresses it for .txt-files.
Creates an SOI-object based on the file content. Creates an SOI-object based on the file content.
Parameters
----------
file_path : string
full path to file containing serialized SOI
Returns
-------
soitool.soi.SOI
SOI-object
Raises
------
TypeError
If 'type' of module or attachment is not implemented.
""" """
with open(file_name, "r") as file: with open(file_path, "r") as file:
if file_name[-4::] == ".txt": if file_path[-4::] == ".txt":
serialized = literal_eval(decompress(file.read())) serialized = literal_eval(decompress(file.read()))
else: else:
serialized = literal_eval(file.read()) serialized = literal_eval(file.read())
...@@ -131,7 +147,7 @@ def import_soi(file_name): ...@@ -131,7 +147,7 @@ def import_soi(file_name):
{"widget": TableModule(size, content), "meta": module["meta"]} {"widget": TableModule(size, content), "meta": module["meta"]}
) )
else: else:
raise ValueError( raise TypeError(
"Module-type '{}' is not recognized.".format(module_type) "Module-type '{}' is not recognized.".format(module_type)
) )
...@@ -150,15 +166,15 @@ def import_soi(file_name): ...@@ -150,15 +166,15 @@ def import_soi(file_name):
} }
) )
else: else:
raise ValueError( raise TypeError(
"Module-type '{}' is not recognized.".format(module_type) "Module-type '{}' is not recognized.".format(module_type)
) )
# Create SOI # Create SOI
soi = SOI( soi = SOI(
serialized["title"], serialized["title"],
serialized["description"], serialized["description"],
"1", # version serialized["version"],
None, # date serialized["date"],
serialized["valid"]["from"], serialized["valid"]["from"],
serialized["valid"]["to"], serialized["valid"]["to"],
serialized["icon"], serialized["icon"],
......
...@@ -378,6 +378,8 @@ class SOI: ...@@ -378,6 +378,8 @@ class SOI:
""" """
if self.placement_strategy == "auto": if self.placement_strategy == "auto":
self.reorganize_rectpack() self.reorganize_rectpack()
elif self.placement_strategy == "manual":
return
else: else:
raise Exception( raise Exception(
"Unknown placement strategy: {}".format( "Unknown placement strategy: {}".format(
......
...@@ -43,14 +43,6 @@ class ExportTest(unittest.TestCase): ...@@ -43,14 +43,6 @@ class ExportTest(unittest.TestCase):
# Assert file exists # Assert file exists
self.assertTrue(os.path.exists(file_path_small)) self.assertTrue(os.path.exists(file_path_small))
self.addCleanup( # Delete files
partial(delete_generated_files, file_path_full, file_path_small) os.remove(file_path_full)
) os.remove(file_path_small)
def delete_generated_files(file_path1, file_path2):
"""Delete generated PDF-files."""
if os.path.exists(file_path1):
os.remove(file_path1)
if os.path.exists(file_path2):
os.remove(file_path2)
"""Test serializing, exporting and importing of SOI."""
import os
import unittest
import json
from pathlib import Path
from datetime import datetime
from schema import Schema, And, Or
from PySide2.QtWidgets import QApplication
from PySide2 import QtGui
from soitool.soi import SOI
from soitool.modules.module_table import TableModule
from soitool.serialize_export_import_soi import (
serialize_soi,
export_soi,
import_soi,
)
if isinstance(QtGui.qApp, type(None)):
app = QApplication([])
else:
app = QtGui.qApp
SOITOOL_ROOT_PATH = Path(__file__).parent.parent
# SOI content
TITLE = "testSOI"
DESCRIPTION = "This is a description"
VERSION = "1"
DATE = "01.01.2020"
VALID_FROM = "01.01.2020"
VALID_TO = "02.01.2020"
ICON = "soitool/media/HVlogo.png"
CLASSIFICATION = "Ugradert"
ORIENTATION = "portrait"
PLACEMENT_STRATEGY = "manual"
ALGORITHM_BIN = "BFF"
ALGORITHM_PACK = "MaxRectsBl"
ALGORITHM_SORT = "area"
MODULES = [
{
"widget": TableModule(
size={"width": 50, "height": 75},
content=[["H1"], ["Row1"], ["Row2"]],
),
"meta": {"x": 0, "y": 0, "page": 1, "name": "Table1"},
},
{
"widget": TableModule(
size={"width": 100, "height": 75},
content=[["H1", "H2"], ["Row1Col1", "Row1Col2"]],
),
"meta": {"x": 200, "y": 150, "page": 1, "name": "Table1"},
},
]
# Valid schema for serialized SOI
SCHEMA = Schema(
{
"title": And(str, len),
"description": str,
"date": Or(str, None),
"version": And(str, len),
"valid": {"from": Or(str, None), "to": Or(str, None)},
"icon": Or(str, None),
"classification": And(str, len),
"orientation": And(str, len, Or("portrait", "landscape")),
"placement_strategy": And(str, len, Or("manual", "auto")),
"algorithm_bin": And(str, len, Or("BFF", "BBF")),
"algorithm_pack": And(
str, len, Or("MaxRectsBl", "SkylineBl", "GuillotineBssfSas")
),
"algorithm_sort": And(str, len, Or("none", "area", "width", "height")),
"modules": [
{
"type": And(str, len),
"data": {
"size": {
"width": And(Or(int, float), lambda w: w > 0),
"height": And(Or(int, float), lambda h: h > 0),
},
"content": object,
},
"meta": {
"x": And(Or(int, float), lambda x: x >= 0),
"y": And(Or(int, float), lambda y: y >= 0),
"page": And(int, lambda page: page >= 0),
"name": And(str, len),
},
}
],
"attachments": [
{
"type": And(str, len),
"data": {
"size": {
"width": And(Or(int, float), lambda w: w > 0),
"height": And(Or(int, float), lambda h: h > 0),
},
"content": object,
},
"meta": {
"x": And(Or(int, float), lambda x: x >= 0),
"y": And(Or(int, float), lambda y: y >= 0),
"page": And(int, lambda page: page >= 0),
"name": And(str, len),
},
}
],
}
)
class SerializeTest(unittest.TestCase):
"""Testcase for functions in module 'serialize_export_import.py'."""
def setUp(self):
"""Create SOI-object and generate filepath for exported SOI."""
self.soi = SOI(
title=TITLE,
description=DESCRIPTION,
version=VERSION,
date=DATE,
valid_from=VALID_FROM,
valid_to=VALID_TO,
icon=ICON,
classification=CLASSIFICATION,
orientation=ORIENTATION,
placement_strategy=PLACEMENT_STRATEGY,
algorithm_bin=ALGORITHM_BIN,
algorithm_pack=ALGORITHM_PACK,
algorithm_sort=ALGORITHM_SORT,
modules=MODULES,
attachments=MODULES,
)
date = datetime.now().strftime("%Y_%m_%d")
file_name = f"SOI_{TITLE}_{date}.json"
self.file_path = os.path.join(SOITOOL_ROOT_PATH, file_name)
def test_export_soi(self):
"""Export SOI and check if file was created."""
# Export SOI
export_soi(self.soi, compressed=False)
# Assert file exists
self.assertTrue(os.path.exists(self.file_path))
def test_serialize_soi(self):
"""Serialize SOI and check its validity against schema."""
# Serialize SOI and load as dict
serialized = serialize_soi(self.soi)
json_data = json.loads(serialized)
# Assert serialized SOI format matches schema
self.assertTrue(SCHEMA.is_valid(json_data))
def test_import_soi(self):
"""Import serialized SOI, check SOI content and delete SOI-file."""
# Import SOI
soi = import_soi(self.file_path)
# Assert SOI content is correct
self.assertEqual(TITLE, soi.title)
self.assertEqual(DESCRIPTION, soi.description)
self.assertEqual(VERSION, soi.version)
self.assertEqual(DATE, soi.date)
self.assertEqual(VALID_FROM, soi.valid_from)
self.assertEqual(VALID_TO, soi.valid_to)
self.assertEqual(ICON, soi.icon)
self.assertEqual(CLASSIFICATION, soi.classification)
self.assertEqual(ORIENTATION, soi.orientation)
self.assertEqual(PLACEMENT_STRATEGY, soi.placement_strategy)
self.assertEqual(ALGORITHM_BIN, soi.algorithm_bin)
self.assertEqual(ALGORITHM_PACK, soi.algorithm_pack)
self.assertEqual(ALGORITHM_SORT, soi.algorithm_sort)
self.assertEqual(type(MODULES[0]["widget"]), TableModule)
self.assertEqual(type(MODULES[1]["widget"]), TableModule)
self.assertEqual(MODULES[0]["meta"], soi.modules[0]["meta"])
self.assertEqual(MODULES[1]["meta"], soi.modules[1]["meta"])
# Delete exported SOI-file
os.remove(self.file_path)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment