Skip to content

Commit

Permalink
fixed tests; merged open/import
Browse files Browse the repository at this point in the history
  • Loading branch information
aravindm711 committed Jul 17, 2021
1 parent 8c0f788 commit 7050cd9
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 257 deletions.
39 changes: 23 additions & 16 deletions mslib/msui/_tests/test_mscolab.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import fs
import fs.errors
import fs.opener.errors
import requests.exceptions
# import requests.exceptions
import mock
import pytest

Expand Down Expand Up @@ -88,6 +88,13 @@ def test_login(self):
assert self.main_window.listProjectsMSC.model().rowCount() == 0
assert self.main_window.mscolab.conn is None

# ToDo for new connect window
# for exc in [requests.exceptions.ConnectionError, requests.exceptions.InvalidSchema,
# requests.exceptions.InvalidURL, requests.exceptions.SSLError, Exception("")]:
# with mock.patch("requests.get", new=ExceptionMock(exc).raise_exc):
# self.window.connect_handler()
# assert mockbox.critical.call_count == 5

def test_add_user(self):
self._connect_to_mscolab()
self._create_user("something", "something@something.org", "something")
Expand Down Expand Up @@ -136,8 +143,6 @@ class Test_Mscolab(object):
}
export_plugins = {
"Text": ["txt", "mslib.plugins.io.text", "save_to_txt"],
# "KML": ["kml", "mslib.plugins.io.kml", "save_to_kml"],
# "GPX": ["gpx", "mslib.plugins.io.gpx", "save_to_gpx"]
}

def setup(self):
Expand Down Expand Up @@ -213,12 +218,13 @@ def test_handle_export(self, mockbox):
for i in range(wp_count):
assert exported_waypoints.waypoint_data(i).lat == self.window.mscolab.waypoints_model.waypoint_data(i).lat

@pytest.mark.parametrize("ext", [".ftml", ".csv", ".txt"])
@pytest.mark.parametrize("ext", [".ftml", ".csv"])
@mock.patch("PyQt5.QtWidgets.QMessageBox")
def test_import_file(self, mockbox, ext):
with mock.patch("mslib.msui.mscolab.config_loader", return_value=self.import_plugins):
# ToDo for .txt extension
with mock.patch("mslib.msui.mss_pyui.config_loader", return_value=self.import_plugins):
self.window.add_import_plugins("qt")
with mock.patch("mslib.msui.mscolab.config_loader", return_value=self.export_plugins):
with mock.patch("mslib.msui.mss_pyui.config_loader", return_value=self.export_plugins):
self.window.add_export_plugins("qt")
with mock.patch("PyQt5.QtWidgets.QFileDialog.getSaveFileName", return_value=(fs.path.join(
mscolab_settings.MSCOLAB_DATA_DIR, f'test_import{ext}'), None)):
Expand All @@ -233,6 +239,7 @@ def test_import_file(self, mockbox, ext):
if action.objectName() == full_name:
action.trigger()
break
assert os.path.exists(fs.path.join(mscolab_settings.MSCOLAB_DATA_DIR, f'test_import{ext}'))
QtWidgets.QApplication.processEvents()
self.window.mscolab.waypoints_model.invert_direction()
QtWidgets.QApplication.processEvents()
Expand Down Expand Up @@ -297,20 +304,20 @@ def test_add_project(self, mockbox):
assert self.window.usernameLabel.text() == 'something'
assert self.window.connectBtn.isVisible() is False
self._create_project("Alpha", "Description Alpha")
assert mockbox.return_value.showMessage.call_count == 2
assert mockbox.return_value.showMessage.call_count == 1
with mock.patch("PyQt5.QtWidgets.QLineEdit.text", return_value=None):
self._create_project("Alpha2", "Description Alpha")
with mock.patch("PyQt5.QtWidgets.QTextEdit.toPlainText", return_value=None):
self._create_project("Alpha3", "Description Alpha")
self._create_project("/", "Description Alpha")
assert mockbox.return_value.showMessage.call_count == 5
assert self.window.listProjects.model().rowCount() == 1
assert mockbox.return_value.showMessage.call_count == 4
assert self.window.listProjectsMSC.model().rowCount() == 1
self._create_project("reproduce-test", "Description Test")
assert self.window.listProjects.model().rowCount() == 2
assert self.window.listProjectsMSC.model().rowCount() == 2
self._activate_project_at_index(0)
assert self.window.active_project_name == "Alpha"
assert self.window.mscolab.active_project_name == "Alpha"
self._activate_project_at_index(1)
assert self.window.active_project_name == "reproduce-test"
assert self.window.mscolab.active_project_name == "reproduce-test"

@mock.patch("mslib.msui.mscolab.QtWidgets.QInputDialog.getText", return_value=("flight7", True))
def test_handle_delete_project(self, mocktext):
Expand Down Expand Up @@ -405,14 +412,14 @@ def test_close_help_dialog(self):
@mock.patch("sys.exit")
def test_create_dir_exceptions(self, mockexit, mockbox):
with mock.patch("fs.open_fs", new=ExceptionMock(fs.errors.CreateFailed).raise_exc):
self.window.data_dir = "://"
self.window.create_dir()
self.window.mscolab.data_dir = "://"
self.window.mscolab.create_dir()
assert mockbox.critical.call_count == 1
assert mockexit.call_count == 1

with mock.patch("fs.open_fs", new=ExceptionMock(fs.opener.errors.UnsupportedProtocol).raise_exc):
self.window.data_dir = "://"
self.window.create_dir()
self.window.mscolab.data_dir = "://"
self.window.mscolab.create_dir()
assert mockbox.critical.call_count == 2
assert mockexit.call_count == 2

Expand Down
82 changes: 13 additions & 69 deletions mslib/msui/_tests/test_mss_pyui.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@
from mslib._tests.constants import ROOT_DIR
import mslib.msui.mss_pyui as mss_pyui
from mslib._tests.utils import ExceptionMock
from mslib.plugins.io.text import load_from_txt
from mslib.plugins.io.flitestar import load_from_flitestar


class Test_MSS_AboutDialog():
Expand Down Expand Up @@ -186,20 +184,8 @@ def test_open_shortcut(self, mockbox):
QtWidgets.QApplication.processEvents()
assert mockbox.critical.call_count == 0

@pytest.mark.parametrize("save_file", [save_ftml, save_csv])
def test_default_plugins_saveas(self, save_file):
with mock.patch("mslib.msui.mss_pyui.get_save_filename", return_value=save_file) as mocksave:
assert self.window.listFlightTracks.count() == 1
assert mocksave.call_count == 0
self.window.last_save_directory = ROOT_DIR
self.window.actionSaveActiveFlightTrackAs.trigger()
QtWidgets.QApplication.processEvents()
assert mocksave.call_count == 1
assert os.path.exists(save_file)
os.remove(save_file)

@pytest.mark.parametrize("save_file", [save_txt])
def test_external_plugins_saveas(self, save_file):
@pytest.mark.parametrize("save_file", [save_ftml, save_csv, save_txt])
def test_plugin_saveas(self, save_file):
with mock.patch("mslib.msui.mss_pyui.config_loader", return_value=self.export_plugins):
self.window.add_export_plugins("qt")
with mock.patch("mslib.msui.mss_pyui.get_save_filename", return_value=save_file) as mocksave:
Expand All @@ -212,26 +198,21 @@ def test_external_plugins_saveas(self, save_file):
assert os.path.exists(save_file)
os.remove(save_file)

@pytest.mark.parametrize("open_file", [open_ftml, open_csv])
def test_default_plugins_open(self, open_file):
with mock.patch("mslib.msui.mss_pyui.get_open_filename", return_value=open_file) as mockopen:
assert self.window.listFlightTracks.count() == 1
assert mockopen.call_count == 0
self.window.last_save_directory = ROOT_DIR
self.window.actionOpenFlightTrack.trigger()
QtWidgets.QApplication.processEvents()
assert mockopen.call_count == 1
assert self.window.listFlightTracks.count() == 2

@pytest.mark.parametrize("open_file", [open_txt])
def test_external_plugins_open(self, open_file):
@pytest.mark.parametrize(
"open_file", [(open_ftml, "ftml"), (open_csv, "csv"), (open_txt, "txt"), (open_fls, "fls")])
def test_plugin_import(self, open_file):
with mock.patch("mslib.msui.mss_pyui.config_loader", return_value=self.import_plugins):
self.window.add_import_plugins("qt")
with mock.patch("mslib.msui.mss_pyui.get_open_filename", return_value=open_file) as mockopen:
with mock.patch("mslib.msui.mss_pyui.get_open_filename", return_value=open_file[0]) as mockopen:
assert self.window.listFlightTracks.count() == 1
assert mockopen.call_count == 0
self.window.last_save_directory = ROOT_DIR
self.window.actionOpenFlightTrack.trigger()
ext = open_file[1]
full_name = f"actionImportFlightTrack{ext}"
for action in self.window.menuImportFlightTrack.actions():
if action.objectName() == full_name:
action.trigger()
break
QtWidgets.QApplication.processEvents()
assert mockopen.call_count == 1
assert self.window.listFlightTracks.count() == 2
Expand All @@ -255,43 +236,6 @@ def test_plugin_export(self, save_file):
assert os.path.exists(save_file)
os.remove(save_file)

@mock.patch("mslib.msui.mss_pyui.get_open_filename", return_value=os.path.join(sample_path, u"example.csv"))
def test_plugin_csv_read(self, mockopen):
pytest.skip("To be done")
assert self.window.listFlightTracks.count() == 1
assert mockopen.call_count == 0
self.window.last_save_directory = self.sample_path
self.window.actionImportFlightTrackcsv.trigger()
QtWidgets.QApplication.processEvents()
assert self.window.listFlightTracks.count() == 2
assert mockopen.call_count == 1

@mock.patch("mslib.msui.mss_pyui.get_open_filename", return_value=os.path.join(sample_path, u"example.txt"))
def test_plugin_txt_read(self, mockopen):
pytest.skip("To be done")
self.window.add_plugin_submenu("Text", "txt", "qt", plugin_type="Import")
self.window.import_plugins['txt'] = load_from_txt
assert self.window.listFlightTracks.count() == 1
assert mockopen.call_count == 0
self.window.last_save_directory = self.sample_path
self.window.actionImportFlightTracktxt.trigger()
assert mockopen.call_count == 1
QtWidgets.QApplication.processEvents()
assert self.window.listFlightTracks.count() == 2

@mock.patch("mslib.msui.mss_pyui.get_open_filename",
return_value=os.path.join(sample_path, u"flitestar.txt"))
def test_plugin_flitestar(self, mockopen):
pytest.skip("To be done")
self.window.last_save_directory = self.sample_path
self.window.add_plugin_submenu("FliteStar", "fls", "qt", plugin_type="Import")
self.window.import_plugins['fls'] = load_from_flitestar
assert self.window.listFlightTracks.count() == 1
self.window.actionImportFlightTrackfls.trigger()
QtWidgets.QApplication.processEvents()
assert self.window.listFlightTracks.count() == 2
assert mockopen.call_count == 1

@mock.patch("PyQt5.QtWidgets.QMessageBox")
@mock.patch("mslib.msui.mss_pyui.config_loader", return_value=export_plugins)
def test_add_plugins(self, mockopen, mockbox):
Expand Down Expand Up @@ -350,7 +294,7 @@ def test_flight_track_io(self, mockload, mocksave, mockq, mocki, mockw, mockbox)
self.window.active_flight_track = tmp_ft
self.window.actionCloseSelectedFlightTrack.trigger()
assert self.window.listFlightTracks.count() == 1
self.window.actionOpenFlightTrack.trigger()
self.window.actionImportFlightTrackftml.trigger()
assert self.window.listFlightTracks.count() == 2
assert os.path.exists(self.save_ftml)
os.remove(self.save_ftml)
5 changes: 1 addition & 4 deletions mslib/msui/flighttrack.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,7 @@ def __init__(self, name="", filename=None, waypoints=None, mscolab_mode=False, d

# If a filename is passed to the constructor, load data from this file.
if filename is not None:
if filename.endswith(".ftml"):
self.load_from_ftml(filename)
else:
logging.debug("No known file extension! '%s'", filename)
self.load_from_ftml(filename)

# If xml string is passed to constructor, load data from that
elif xml_content is not None:
Expand Down
39 changes: 14 additions & 25 deletions mslib/msui/mscolab.py
Original file line number Diff line number Diff line change
Expand Up @@ -1176,44 +1176,35 @@ def reload_view_windows(self):
except AttributeError as err:
logging.error("%s" % err)

def handle_import_msc(self, extension, pickertype):
def handle_import_msc(self, file_path, extension, function, pickertype):
if self.verify_user_token():
if self.active_pid is None:
return

if self.ui.workLocallyCheckbox.isChecked() and extension != "ftml":
self.ui.statusBar().showMessage("Work Locally only supports FTML filetypes for import")
return
file_path = get_open_filename(
self.ui, "Import to Server", "", f"Flight track (*.{extension})", pickertype=pickertype
)
if file_path is None:
return
dir_path, file_name = fs.path.split(file_path)
file_name = fs.path.basename(file_path)
name, file_ext = fs.path.splitext(file_name)
if file_ext[1:] == "ftml":
if function is None:
with open_fs(dir_path) as file_dir:
xml_content = file_dir.readtext(file_name)
try:
model = ft.WaypointsTableModel(xml_content=xml_content)
except SyntaxError:
show_popup(self.ui, "Import Failed", f"The file - {file_name}, does not contain valid XML")
return
self.waypoints_model = model
if self.ui.workLocallyCheckbox.isChecked():
self.waypoints_model.save_to_ftml(self.local_ftml_file)
self.waypoints_model.dataChanged.connect(self.handle_waypoints_changed)
else:
self.conn.save_file(self.token, self.active_pid, xml_content, comment=None)
self.waypoints_model.dataChanged.connect(self.handle_waypoints_changed)
else:
_function = self.ui.import_plugins[file_ext[1:]]
_, new_waypoints = _function(file_path)
# _function = self.ui.import_plugins[file_ext[1:]]
_, new_waypoints = function(file_path)
model = ft.WaypointsTableModel(waypoints=new_waypoints)
self.waypoints_model = model
xml_doc = self.waypoints_model.get_xml_doc()
xml_content = xml_doc.toprettyxml(indent=" ", newl="\n")
self.waypoints_model.dataChanged.connect(self.handle_waypoints_changed)
self.waypoints_model = model
if self.ui.workLocallyCheckbox.isChecked():
self.waypoints_model.save_to_ftml(self.local_ftml_file)
self.waypoints_model.dataChanged.connect(self.handle_waypoints_changed)
else:
self.conn.save_file(self.token, self.active_pid, xml_content, comment=None)
self.waypoints_model.dataChanged.connect(self.handle_waypoints_changed)
self.reload_view_windows()
Expand All @@ -1222,7 +1213,7 @@ def handle_import_msc(self, extension, pickertype):
show_popup(self.ui, "Error", "Your Connection is expired. New Login required!")
self.logout()

def handle_export_msc(self, extension, pickertype):
def handle_export_msc(self, extension, function, pickertype):
if self.verify_user_token():
if self.active_pid is None:
return
Expand All @@ -1235,15 +1226,14 @@ def handle_export_msc(self, extension, pickertype):
pickertype=pickertype)
if file_name is None:
return
if file_name.endswith('.ftml'):
if function is None:
xml_doc = self.waypoints_model.get_xml_doc()
dir_path, file_name = fs.path.split(file_name)
with open_fs(dir_path).open(file_name, 'w') as file:
xml_doc.writexml(file, indent=" ", addindent=" ", newl="\n", encoding="utf-8")
else:
file_path = fs.path.basename(file_name)
_function = self.ui.export_plugins[extension]
_function(file_name, file_path, self.waypoints_model.waypoints)
name = fs.path.basename(file_name)
function(file_name, name, self.waypoints_model.waypoints)
show_popup(self.ui, "Export Success", f"The file - {file_name}, was exported successfully!", 1)
else:
show_popup(self.ui, "Error", "Your Connection is expired. New Login required!")
Expand Down Expand Up @@ -1330,7 +1320,6 @@ def logout(self):
self.ui.usernameLabel.hide()
self.ui.userOptionsTb.hide()
self.ui.connectBtn.show()
# self.ui.addProjectBtn.hide()
self.ui.actionAddProject.setEnabled(False)
# disconnect socket
if self.conn is not None:
Expand Down
Loading

0 comments on commit 7050cd9

Please sign in to comment.