示例#1
0
    def test_insertion(self):
        # type: () -> None
        """
        Test the insert functions of class Well

        :return: Nothing
        :raises AssertionError: Raises AssertionError if a test fails
        """
        wells = Well.load_all_from_db(self.session)
        marker_1 = WellMarker(301.43, StratigraphicObject.init_stratigraphy(self.session, "ku"), self.session,
                              "Comment 1")
        marker_2 = WellMarker(351.65, StratigraphicObject.init_stratigraphy(self.session, "mo"), self.session)
        marker_3 = WellMarker(934.23, StratigraphicObject.init_stratigraphy(self.session, "mm"), self.session,
                              "Comment 3")

        wells[0].insert_marker(marker_1)
        self.assertEqual(len(wells[0].marker), 6)
        self.assertEqual(wells[0].marker[5], marker_1)
        self.assertRaises(ValueError, wells[1].insert_marker, marker_3)

        wells[2].insert_multiple_marker([marker_1, marker_2])
        self.assertEqual(len(wells[2].marker), 6)
        self.assertEqual(wells[2].marker[2], marker_1)
        self.assertEqual(wells[2].marker[4], marker_2)
        del wells

        wells = Well.load_all_from_db(self.session)
        self.assertEqual(wells[2].marker[2], marker_1)
        self.assertEqual(wells[2].marker[4], marker_2)
        del wells

        wells = Well.load_all_from_db(self.session)
        self.assertRaises(ValueError, wells[1].insert_multiple_marker, [marker_1, marker_2, marker_3])
示例#2
0
    def test_setter_and_getter(self):
        # type: () -> None
        """
        Test setter and getters of class StratigraphicObject

        :return: Nothing

        :raises AssertionError: Raises AssertionError if a test fails
        """
        result = StratigraphicObject.load_by_stratigraphic_name_from_db(
            'mo', self.session)
        result.age = 10
        result.save_to_db()
        del result

        result = StratigraphicObject.load_by_stratigraphic_name_from_db(
            'mo', self.session)
        self.assertEqual(
            result.age, 10,
            "Wrong age for horizon 'mo' ({}). Should be {}.".format(
                result.age, 10))

        result.statigraphic_name = 'Blubb'
        result.save_to_db()
        del result

        result = StratigraphicObject.load_by_age_from_db(10, 10, self.session)
        self.assertEqual(
            len(result), 1,
            "Wrong number of query results ({}). Should be {}.".format(
                len(result), 1))
        self.assertEqual(
            result[0].statigraphic_name, 'Blubb',
            "Wrong statigraphic_name of stratigraphic unit ({}). Should be {}".
            format(result[0].statigraphic_name, 'Blubb'))
示例#3
0
    def test_WellMarker_setter_and_getter(self):
        # type: () -> None
        """
        Test setter and getter functionality

        :return: Nothing
        :raises AssertionError: Raises Assertion Error if a test fails
        """
        marker = WellMarker.load_all_from_db(self.session)
        self.assertEqual(len(marker), 13)
        test_string = "abcdefghijklmnopqrstuvwxyz1234567890"

        # first part: test setter functionality
        marker[0].comment = "This is a new comment"
        marker[1].comment = 4 * test_string
        marker[2].depth = 123.43
        marker[3].depth = "2345.54"
        with (self.assertRaises(ValueError)):
            marker[4].depth = "Test"
        marker[4].horizon = StratigraphicObject.init_stratigraphy(self.session, "z", 50, False)
        with (self.assertRaises(TypeError)):
            marker[5].horizon = "test"

        # second part: getter functionality
        marker = WellMarker.load_all_from_db(self.session)
        self.assertEqual(marker[0].comment, "This is a new comment")
        self.assertEqual(len(marker[1].comment), 100)
        self.assertEqual(marker[3].comment, "Comment 2")
        self.assertEqual(marker[2].depth, 123.43)
        self.assertEqual(marker[1].depth, 15)
        self.assertEqual(marker[4].horizon.statigraphic_name, "z")
        self.assertEqual(marker[5].horizon.statigraphic_name, "mo")
示例#4
0
    def test_setter_and_getter(self):
        # type: () -> None
        """
        Test the setter and getter functions of class GeoPoint

        :return: Nothing
        :raises AssertionError: Raises AssertionError if a test fails
        """
        # points = GeoPoint.load_all_from_db(self.session)
        points = GeoPoint.load_all_without_lines_from_db(self.session)
        self.assertEqual(
            len(points), len(self.points),
            "Wrong point length ({}). Should be {}.".format(
                len(points), len(self.points)))
        points[0].easting = 1
        points[1].northing = 2
        points[2].altitude = 3
        points[2].use_z()
        points[3].horizon = StratigraphicObject.init_stratigraphy(
            self.session, "so", 10, False)
        points[0].name = "point set name"
        points[1].del_z()

        for point in points:
            point.save_to_db()

        del points
        points = GeoPoint.load_all_without_lines_from_db(self.session)
        self.assertEqual(
            len(points), len(self.points),
            "Wrong point length ({}). Should be {}.".format(
                len(points), len(self.points)))
        self.assertEqual(
            points[0].easting, 1,
            "Wrong easting value ({}). Should be {}.".format(
                points[0].easting, 1))
        self.assertEqual(
            points[1].northing, 2,
            "Wrong northing value ({}). Should be {}.".format(
                points[1].northing, 2))
        self.assertEqual(
            points[2].altitude, 3,
            "Wrong altitude value ({}). Should be {}.".format(
                points[2].altitude, 3))
        self.assertTrue(
            points[2].has_z,
            "Third point has no z-value...")  # Third point got z-value
        self.assertEqual(
            points[3].horizon.statigraphic_name, "so",
            "Wrong horizon ({}). Should be {}.".format(
                points[3].horizon.statigraphic_name, "so"))
        self.assertEqual(
            points[0].name, "point set name",
            "Wrong point name ({}). Should be {}.".format(
                points[0].name, "point set name"))
        self.assertFalse(points[1].has_z, "Second point has a z-value...")
        self.assertEqual(
            points[1].altitude, 0,
            "Wrong altitude value ({}). Should be {}.".format(
                points[1].altitude, 0))
    def setUp(self):
        # type: () -> None
        """
        Initialise a temporary database connection for all test cases and fill the database with test data

        :return: None
        """
        # initialise a in-memory sqlite database
        self.handler = DBHandler(connection="sqlite://", echo=False)
        self.session = self.handler.get_session()

        # add test data to the database
        point = GeoPoint(StratigraphicObject.init_stratigraphy(self.session, "mu", 1), True, "", 1, 2, 3, self.session,
                         "test", "")
        point.save_to_db()

        point.add_property(Property(0, PropertyTypes.INT, "test prop", "test unit", self.session))
        point.add_property(Property(0, PropertyTypes.FLOAT, "test prop 2", "test unit 2", self.session))
        point.add_property(Property(0, PropertyTypes.STRING, "test prop 3", "test unit 3", self.session))
示例#6
0
    def setUp(self):
        # type: () -> None
        """
        Initialise a temporary database connection for all test cases and fill the database with test data

        :return: None
        """
        # initialise a in-memory sqlite database
        self.handler = DBHandler(connection='sqlite://', echo=False)
        self.session = self.handler.get_session()

        units = [{
            'statigraphic_name': 'mo',
            'age': 1,
            'update': False
        }, {
            'statigraphic_name': 'mm',
            'age': 2,
            'update': True
        }, {
            'statigraphic_name': 'mu',
            'age': 25,
            'update': False
        }, {
            'statigraphic_name': 'so',
            'age': 4,
            'update': False
        }, {
            'statigraphic_name': 'mu',
            'age': 3,
            'update': True
        }, {
            'statigraphic_name': 'so',
            'age': 5,
            'update': False
        }]

        for unit in units:
            new_unit = StratigraphicObject.init_stratigraphy(
                self.session, unit['statigraphic_name'], unit['age'],
                unit['update'])
            new_unit.save_to_db()
示例#7
0
    def test_delete_marker(self):
        # type: () -> None
        """
        Test the Well.get_marker_by_depth function

        :return: Nothing
        :raises AssertionError: Raises AssertionError if a test fails
        """
        well = Well.load_by_wellname_from_db("Well_1", self.session)
        marker = well.get_marker_by_depth(16)
        self.assertEqual(marker.horizon.statigraphic_name, "sm")
        self.assertRaises(ValueError, well.get_marker_by_depth, 100)
        well.delete_marker(marker)
        well.save_to_db()
        self.assertEqual(len(well.marker), 4)
        del well

        well = Well.load_by_wellname_from_db("Well_1", self.session)
        self.assertEqual(len(well.marker), 4)

        new_marker = WellMarker(23423, StratigraphicObject.init_stratigraphy(self.session, "so"), self.session,
                                "Nothing")
        self.assertRaises(ValueError, well.delete_marker, new_marker)
        self.assertRaises(TypeError, well.delete_marker, "test")
示例#8
0
    def test_setter_and_getter(self):
        # type: () -> None
        """
        Test the setter and getter functions of class Line

        :return: Nothing
        :raises AssertionError: Raises AssertionError if a test fails
        """
        lines = Line.load_all_from_db(self.session)
        lines[0].is_closed = True
        lines[1].horizon = StratigraphicObject.init_stratigraphy(
            self.session, "mu")
        lines[2].name = "Line_2"
        session_2 = lines[3].session
        lines[3].session = session_2

        for line in lines:
            line.save_to_db()

        del lines

        lines = Line.load_all_from_db(self.session)
        line_with_name = Line.load_by_name_from_db("Line_2", self.session)
        self.assertTrue(lines[0].is_closed,
                        "First line should be changed to closed.")
        self.assertEqual(
            lines[1].horizon.statigraphic_name, "mu",
            "Second line has wrong horizon ({}). Should have {}.".format(
                lines[1].horizon.statigraphic_name, "mu"))
        self.assertEqual(
            lines[2].name, "Line_2",
            "Third line has wrong line name ({}). Should have {}".format(
                lines[2].name, "Line_2"))
        self.assertEqual(len(line_with_name), 3,
                         "Wrong Number of lines with line name 'Line_2' ({}). Should be {}". \
                         format(len(line_with_name), 3))
示例#9
0
    def run(self) -> bool:
        """
        Save the Well Object(s) to the database
        :return: True if function executed successfully, else False
        """

        self._mutex.lock()
        service = DatabaseService.get_instance()
        service.close_session()
        service.connect()
        session = DatabaseService.get_instance().get_session()

        try:
            onekey = self._data[next(iter(self._data.keys()))]["values"]
            count = len(onekey)

            name = self._selection["name"]
            short_name = self._selection["short_name"]
            east = self._selection["easting"]
            north = self._selection["northing"]
            alt = self._selection["altitude"]
            total_depth = self._selection["total_depth"]
            strat = self._selection["strat"]
            depth_to = self._selection["depth_to"]
            comment = self._selection["comment"]

            reference = ImportService.get_instance().get_crs()
            if reference is None:
                reference = ""
            else:
                reference = reference.toWkt()

            self._logger.debug("Saving with reference system\n{}".format(reference))

            wells = dict()

            maximum = count
            for i in range(count):
                if (self._data[east]["values"][i] == "") and (self._data[north]["values"][i] == ""):
                    continue

                na = self._data[name]["values"][i]
                sn = "" if short_name == "" else self._data[short_name]["values"][i]
                e = float(self._data[east]["values"][i])
                n = float(self._data[north]["values"][i])
                kb = None if alt == "" else float(self._data[alt]["values"][i])
                td = -1 if total_depth == "" else float(self._data[total_depth]["values"][i])
                s = "" if strat == "" else self._data[strat]["values"][i]
                dt = -1 if depth_to == "" else float(self._data[depth_to]["values"][i])
                c = "" if comment == "" else self._data[comment]["values"][i]

                strat_obj = StratigraphicObject.init_stratigraphy(session, s, -1)
                strat_obj.save_to_db()

                marker = WellMarker(dt, strat_obj, session=session, comment=c)
                # marker.save_to_db()
                # point = GeoPoint(None, False if (h is None) else True, reference,
                #                e, n, 0 if (h is None) else h, session, sn, c)

                if na in wells:
                    wells[na]["marker"].append(marker)
                else:
                    wells[na] = {
                        "short_name": sn,
                        "easting": e,
                        "northing": n,
                        "altitude": kb,
                        "total_depth": td,
                        "marker": [marker]
                    }

                    maximum += 1

                if self._cancel:
                    self._logger.debug("Import canceled")
                    self.import_failed.emit(self._message)
                    break

                self.update_progress.emit(100 * i / maximum)

            i = count
            if not self._cancel:
                for well_name in wells:
                    i += 1
                    well = wells[well_name]

                    new_well = Well.load_by_wellname_from_db(well_name, session)
                    if new_well is not None:
                        try:
                            self._logger.debug("Updating existing well: {}".format(new_well))
                            for marker in new_well.marker:
                                WellMarker.delete_from_db(marker, session)

                            new_well.save_to_db()
                            new_well.marker = well["marker"]
                            new_well.short_name = well["short_name"]
                            new_well.easting = well["easting"]
                            new_well.northing = well["northing"]
                            new_well.depth = well["total_depth"]
                        except WellMarkerDepthException as e:
                            self._logger.error("WellMarkerDepthException", "{}\n{}".format(new_well, str(e)))
                            return False
                    else:
                        self._logger.debug("Creating new well with name [{}]".format(well_name))
                        new_well = Well(well_name, well["short_name"], well["total_depth"], reference_system=reference,
                                        easting=well["easting"], northing=well["northing"], altitude=well["altitude"],
                                        session=session)

                        new_well.marker = well["marker"]

                    new_well.save_to_db()

                    self._logger.debug("Saved well:\n{}".format(new_well))

                    self.update_progress.emit(100 * i / maximum)

                    if self._cancel:
                        self._logger.debug("Import canceled")
                        self.import_failed.emit(self._message)
                        break

            if not self._cancel:
                self.update_progress.emit(100)
                self._logger.debug("Lines successfully imported")
                self.import_finished.emit()

        except Exception as e:
            msg = str(ExceptionHandler(e))
            self.import_failed.emit(msg)
            self._logger.error("Error", msg)

        finally:
            service.close_session()

        self._mutex.unlock()
        self.quit()
示例#10
0
    def run(self):
        """
        Save the Point Object(s) to the database
        :return: True if function executed successfully, else False
        """
        self._mutex.lock()
        service = DatabaseService.get_instance()
        service.close_session()
        service.connect()
        session = DatabaseService.get_instance().get_session()

        try:
            onekey = self._data[next(iter(self._data.keys()))]["values"]
            # import json
            # self._logger.info(json.dumps(onekey, indent=2))
            count = len(onekey)

            east = self._selection["easting"]
            north = self._selection["northing"]
            alt = self._selection["altitude"]
            strat = self._selection["strat"]
            age = self._selection["strat_age"]
            set_name = self._selection["set_name"]
            comment = self._selection["comment"]

            reference = ImportService.get_instance().get_crs()
            if reference is None:
                reference = ""
            else:
                reference = reference.toWkt()

            self._logger.debug("Saving with reference system\n{}".format(reference))

            lines = dict()

            line = 0

            maximum = count
            for i in range(count):
                _id = None
                if "gln_id" in self._data:
                    try:
                        _id = int(self._data["gln_id"]["values"][i])
                    except ValueError:
                        pass

                if (self._data[east]["values"][i] == "") and (self._data[north]["values"][i] == ""):
                    line += 1
                    continue

                e = float(self._data[east]["values"][i])
                n = float(self._data[north]["values"][i])
                h = None if alt == "" else float(self._data[alt]["values"][i])
                s = "" if strat == "" else self._data[strat]["values"][i]
                a = -1 if age == "" else float(self._data[age]["values"][i])
                sn = "" if set_name == "" else self._data[set_name]["values"][i]
                c = "" if comment == "" else self._data[comment]["values"][i]

                strat_obj = StratigraphicObject.init_stratigraphy(session, s, a)
                point = GeoPoint(None, False if (h is None) else True, reference,
                                 e, n, 0 if (h is None) else h, session, sn, c)

                # add / update properties
                for item in self._properties:
                    self._logger.debug("Property: {}".format(item))
                    if point.has_property(item.name):
                        p = point.get_property(item.name)
                        p.property_unit = item.unit
                        p.value = self._data[item.name]["values"][i]
                        p.property_type = item.property_type
                    else:
                        p = Property(value=self._data[item.name]["values"][i], property_name=item.name,
                                     _type=item.property_type, property_unit=item.unit,
                                     session=session)
                        point.add_property(p)

                if _id is not None:
                    point.line_id = _id

                self._logger.debug("line point: {}".format(point))

                if line in lines:
                    lines[line]["points"].append(point)
                else:
                    lines[line] = {
                        "id": _id,
                        "strat": strat_obj,
                        "points": [point],
                        "name": sn,
                        "comment": c
                    }
                    maximum += 1

                i += 1
                self.update_progress.emit(100 * i / maximum)

                if self._cancel:
                    self._logger.debug("Import canceled")
                    self.import_failed.emit(self._message)
                    break

            i = count
            if not self._cancel:
                for l in lines:
                    i += 1

                    line = lines[l]
                    closed = False
                    if (len(line["points"]) > 1) and (line["points"][0] == line["points"][-1]):
                        closed = True
                        line["points"].pop()

                    new_line = None
                    if line["id"] is not None:
                        new_line = Line.load_by_id_from_db(line["id"], session)
                        if new_line is not None:
                            for point in new_line.points:
                                AbstractDBObject.delete_from_db(point, session)
                                del point

                            new_line.closed = closed
                            new_line.points = line["points"]
                            new_line.horizon = line["strat"]
                            new_line.name = line["name"]
                            new_line.comment = line["comment"]

                            self._logger.debug("Updated existing line")

                    if line["id"] is None or new_line is None:  # new_line is None ? not in database -> create a new one
                        new_line = Line(closed, line["strat"], line["points"], session, line["name"], line["comment"])
                        self._logger.debug("Created new line")

                    new_line.save_to_db()
                    self._logger.debug("Line: {}".format(str(new_line)))

                    self.update_progress.emit(100 * i / maximum)

                    if self._cancel:
                        self._logger.debug("Import canceled")
                        self.import_failed.emit(self._message)
                        break

            if not self._cancel:
                self.update_progress.emit(100)
                self._logger.debug("Lines successfully imported")
                self.import_finished.emit()

        except Exception as e:
            msg = str(ExceptionHandler(e))
            self.import_failed.emit(msg)
            self._logger.error("Error", msg)

        finally:
            service.close_session()

        self._mutex.unlock()
        self.quit()
示例#11
0
    def run(self):
        """
        Save the Point Object(s) to the database
        :return: True if function executed successfully, else False
        """

        self._mutex.lock()
        service = DatabaseService.get_instance()
        service.close_session()
        service.connect()
        session = service.get_session()

        try:
            onekey = self._data[next(iter(self._data.keys()))]["values"]
            # import json
            # self._logger.info(json.dumps(onekey, indent=2))
            count = len(onekey)

            east = self._selection["easting"]
            north = self._selection["northing"]
            alt = self._selection["altitude"]
            strat = self._selection["strat"]
            age = self._selection["strat_age"]
            set_name = self._selection["set_name"]
            comment = self._selection["comment"]

            reference = ImportService.get_instance().get_crs()
            if reference is None:
                reference = ""
            else:
                reference = reference.toWkt()

            self._logger.debug("Saving with reference system\n{}".format(reference))

            for i in range(count):
                self.update_progress.emit(100 * i / count)

                if (self._data[east]["values"][i] == "") and (self._data[north]["values"][i] == ""):
                    continue

                _id = None
                if "gpt_id" in self._data:
                    try:
                        _id = int(self._data["gpt_id"]["values"][i])
                    except ValueError:
                        pass

                e = float(self._data[east]["values"][i])
                n = float(self._data[north]["values"][i])
                h = None if alt == "" else float(self._data[alt]["values"][i])
                s = "" if strat == "" else self._data[strat]["values"][i]
                a = -1 if age == "" else float(self._data[age]["values"][i])
                sn = "" if set_name == "" else self._data[set_name]["values"][i]
                c = "" if comment == "" else self._data[comment]["values"][i]

                strat_obj = StratigraphicObject.init_stratigraphy(session, s, a)

                if (_id is not None) and (_id > -1):
                    point = GeoPoint.load_by_id_from_db(_id, session)
                    point.easting = e
                    point.northing = n
                    point.altitude = h
                    point.del_z() if h is None else point.use_z()
                    point.reference_system = reference
                    point.horizon = strat_obj
                    point.name = sn
                    point.comment = c
                    self._logger.debug("point update")

                else:
                    point = GeoPoint(strat_obj, False if (h is None) else True, reference,
                                     e, n, 0 if (h is None) else h, session, sn, c)
                    self._logger.debug("new point")

                # add / update properties
                for item in self._properties:
                    self._logger.debug("Property: {}".format(item))
                    if point.has_property(item.name):
                        p = point.get_property(item.name)
                        p.property_unit = item.unit
                        p.value = self._data[item.name]["values"][i]
                        p.property_type = item.property_type
                    else:
                        p = Property(value=self._data[item.name]["values"][i], property_name=item.name,
                                     _type=item.property_type, property_unit=item.unit,
                                     session=session)
                        point.add_property(p)

                self._logger.debug("point: {}".format(point))
                point.save_to_db()

                if self._cancel:
                    self._logger.debug("Import canceled")
                    self.import_failed.emit(self._message)
                    break

            if not self._cancel:
                self.update_progress.emit(100)
                self._logger.debug("Points successfully imported")
                self.import_finished.emit()

        except Exception as e:
            msg = str(ExceptionHandler(e))
            self.import_failed.emit(msg)
            self._logger.error("Error", msg)

        finally:
            service.close_session()

        self._mutex.unlock()
        self.quit()
示例#12
0
    def setUp(self):
        # type: () -> None
        """
        Initialise a temporary database connection for all test cases and fill the database with test data

        :return: None
        """
        # initialise a in-memory sqlite database
        self.handler = DBHandler(connection="sqlite://", echo=False)
        self.session = self.handler.get_session()

        # add test data to the database
        self.wells = [
            {
                "name": "Well_1",
                "short_name": "W1",
                "comment": "A drilled well",
                "east": 1234.56,
                "north": 123.45,
                "altitude": 10.5,
                "depth": 555,
                "marker": ((10, "mu", 4, ""),
                           (15, "so", 3, "Comment 1"),
                           (16, "sm", 2, ""),
                           (17, "su", 1, "Comment 2"),
                           (5, "mm", 5, "Comment 3"))
            }, {
                "name": "Well_2",
                "short_name": "W2",
                "comment": "",
                "east": 1000.23,
                "north": 2300.34,
                "altitude": 342.23,
                "depth": 341,
                "marker": ((12, "mo", 6, ""),
                           (120, "mm", 5, "Comment 1"),
                           (300, "Fault", 0, "Comment 2"),
                           (320, "mo", 6, ""))
            }, {
                "name": "Well_3",
                "short_name": "W3",
                "comment": "A third well",
                "east": 3454.34,
                "north": 2340.22,
                "altitude": 342.20,
                "depth": 645.21,
                "marker": ((34, "mu", 4, ""),
                           (234, "so", 3, "Comment 1"),
                           (345, "Fault", 0, "Comment 2"),
                           (635, "mu", 4, "Comment 3"))
            }
        ]

        for well in self.wells:
            new_well = Well(well["name"], well["short_name"], well["depth"], "spatial_reference_unknown", well["east"],
                            well["north"], well["altitude"], self.session, "well_set", well["comment"])
            new_well.save_to_db()

            for mark in well["marker"]:
                new_well.marker.append(
                    WellMarker(mark[0], StratigraphicObject.init_stratigraphy(self.session, mark[1], mark[2], False),
                               self.session, well["name"], mark[3]))
                new_well.marker[-1].save_to_db()
示例#13
0
    def test_insert_multiple(self):
        # type: () -> None
        """
        Test the insertion of multiple points. Although test remove of doubled values in a line.

        :return: Nothing
        :raises AssertionError: Raises AssertionError if a test fails
        """
        insert_point_1 = GeoPoint(
            StratigraphicObject.init_stratigraphy(self.session, "mu"), False,
            "", 1204200, 620800, 0, self.session)
        insert_point_2 = GeoPoint(
            StratigraphicObject.init_stratigraphy(self.session, "mu"), False,
            "", 1204500, 621200, 0, self.session)
        insert_point_3 = GeoPoint(
            StratigraphicObject.init_stratigraphy(self.session, "mu"), False,
            "", 1204700, 621000, 0, self.session)
        insert_point_4 = GeoPoint(
            StratigraphicObject.init_stratigraphy(self.session, "mu"), False,
            "", 1204700, 621000, 0, self.session)

        points = [
            insert_point_1, insert_point_2, insert_point_3, insert_point_4
        ]
        line_query = self.session.query(Line).filter_by(id=1)
        count = line_query.count()
        self.assertEqual(
            count, 1,
            "Get more than one expected result for line-id-request ({})".
            format(count))
        line = line_query.one()
        line.session = self.session
        line.insert_points(points, 1)
        line.save_to_db()

        # point is inserted, now delete insert details
        del count
        del insert_point_1, insert_point_2, insert_point_3
        del line
        del line_query

        # test the insertion-process
        line_query = self.session.query(Line).filter_by(id=1)
        count = line_query.count()
        self.assertEqual(
            count, 1,
            "Get more than one expected result for line-id-request ({})".
            format(count))
        line = line_query.one()

        # 20 Point initially, 2 removed, new point are Nr 19-21 -> id=19 to 21
        # !!!ATTENTION!!! counting starts with 1 not 0 in sqlite-DB!
        # line-pos should be 1, 2 and 3
        self.assertEqual(
            line.points[1].id, 19,
            "Wrong id ({}) for new point (should be {})".format(
                line.points[1].id, 19))
        self.assertEqual(
            line.points[2].id, 20,
            "Wrong id ({}) for new point (should be {})".format(
                line.points[2].id, 20))
        self.assertEqual(
            line.points[3].id, 21,
            "Wrong id ({}) for new point (should be {})".format(
                line.points[3].id, 21))
        self.assertEqual(
            line.points[4].id, 2,
            "Wrong id ({}) for point after insert (should be {})".format(
                line.points[4].id, 2))
        self.assertEqual(
            line.points[1].line_pos, 1,
            "Wrong position of the new point ({}) in the line (should be {})".
            format(line.points[1].line_pos, 1))
        self.assertEqual(
            line.points[2].line_pos, 2,
            "Wrong position of the new point ({}) in the line (should be {})".
            format(line.points[2].line_pos, 2))
        self.assertEqual(
            line.points[3].line_pos, 3,
            "Wrong position of the new point ({}) in the line (should be {})".
            format(line.points[3].line_pos, 3))
        self.assertEqual(
            line.points[1].easting, 1204200,
            "Wrong easting ({} / should be {})".format(line.points[1].easting,
                                                       1204200))
        self.assertEqual(
            line.points[1].northing, 620800,
            "Wrong northing ({} / should be {})".format(
                line.points[1].northing, 620800))
        self.assertEqual(
            line.points[1].altitude, 0,
            "Wrong altitude ({} / should be {})".format(
                line.points[1].altitude, 0))
        self.assertEqual(
            line.points[1].has_z, False,
            "Wrong has_z ({} / should be {})".format(line.points[1].has_z,
                                                     False))

        # test Exception handling
        self.assertRaises(ValueError, line.insert_points, points, "abc")
        points.append("cde")
        self.assertRaises(TypeError, line.insert_points, points, 2)
示例#14
0
    def test_insert_one(self):
        # type: () -> None
        """
        Test the insertion of one point. Additionally test get_point_index(point) function

        :return: Nothing
        :raises AssertionError: Raises AssertionError if a test fails
        """
        insert_point = GeoPoint(
            StratigraphicObject.init_stratigraphy(self.session, "mu"), False,
            "", 1204200, 620800, 0, self.session)
        line_query = self.session.query(Line).filter_by(id=1)
        count = line_query.count()
        self.assertEqual(
            count, 1,
            "Get more than one expected result for line-id-request ({})".
            format(count))
        line = line_query.one()
        line.session = self.session
        line.insert_point(insert_point, 1)

        self.assertEqual(line.points[1].line_pos, 1)

        # point is inserted, now delete insert details
        del count
        del line
        del line_query

        # test the insertion-process
        line_query = self.session.query(Line).filter_by(id=1)
        count = line_query.count()
        self.assertEqual(
            count, 1,
            "Get more than one expected result for line-id-request ({})".
            format(count))
        line = line_query.one()
        # 20 Point initially, 2 removed, new point is Nr 19 -> id=19
        # !!!ATTENTION!!! counting starts with 1 not 0 in sqlite-DB!
        # line-pos and get_point_index should be 1

        self.assertEqual(
            line.points[1].id, 19,
            "Wrong id ({}) for new point (should be {})".format(
                line.points[1].id, 19))
        self.assertEqual(
            line.points[1].line_pos, 1,
            "Wrong position of the new point ({}) in the line (should be {})".
            format(line.points[1].line_pos, 1))
        self.assertEqual(
            line.get_point_index(insert_point), 1,
            "Wrong get_point_index(...) value ({}) in the line (should be {})".
            format(line.get_point_index(insert_point), 1))
        self.assertEqual(
            line.points[1].easting, 1204200,
            "Wrong easting ({} / should be {})".format(line.points[1].easting,
                                                       1204200))
        self.assertEqual(
            line.points[1].northing, 620800,
            "Wrong northing ({} / should be {})".format(
                line.points[1].northing, 620800))
        self.assertEqual(
            line.points[1].altitude, 0,
            "Wrong altitude ({} / should be {})".format(
                line.points[1].altitude, 0))
        self.assertEqual(
            line.points[1].has_z, False,
            "Wrong has_z ({} / should be {})".format(line.points[1].has_z,
                                                     False))

        # test Exception handling
        self.assertRaises(TypeError, line.insert_point, "string", 1)
        self.assertRaises(ValueError, line.insert_points, insert_point, "abc")
示例#15
0
    def setUp(self):
        # type: () -> None
        """
        Initialise a temporary database connection for all test cases and fill the database with test data

        :return: None
        """
        # initialise a in-memory sqlite database
        self.handler = DBHandler(connection="sqlite://", echo=False)
        self.session = self.handler.get_session()

        # handler = DBHandler(
        # 		connection="sqlite:////Users/stephan/Documents/data.db",
        # 		debug=False)
        # handler = DBHandler(connection="sqlite:///D:\\data.db", debug=False)

        # add test data to the database
        self.lines = [{
            "closed":
            False,
            "horizon":
            "mu",
            "age":
            3,
            "update":
            False,
            "points":
            ((1204067.0548148106, 634617.5980860253),
             (1204067.0548148106, 620742.1035724243), (1215167.4504256917,
                                                       620742.1035724243),
             (1215167.4504256917, 634617.5980860253), (1204067.0548148106,
                                                       634617.5980860253)),
            "name":
            "Line_1"
        }, {
            "closed":
            True,
            "horizon":
            "so",
            "age":
            2,
            "update":
            True,
            "points":
            ((1179553.6811741155, 647105.5431482664), (1179553.6811741155,
                                                       626292.3013778647),
             (1194354.20865529, 626292.3013778647), (1194354.20865529,
                                                     647105.5431482664)),
            "name":
            "Line_2"
        }, {
            "closed":
            False,
            "horizon":
            "mm",
            "age":
            4,
            "update":
            True,
            "points":
            ((1179091.1646903288, 712782.8838459781),
             (1161053.0218226474, 667456.2684348812), (1214704.933941905,
                                                       641092.8288590391),
             (1228580.428455506, 682719.3123998424), (1218405.0658121984,
                                                      721108.1805541387)),
            "name":
            "Line_3"
        }, {
            "closed":
            False,
            "horizon":
            "mo",
            "age":
            5,
            "update":
            True,
            "points":
            ((1149490.1097279799, 691044.6091080031), (1149490.1097279799,
                                                       648030.5761158396),
             (1191579.1097525698, 648030.5761158396), (1149490.1097279799,
                                                       648030.5761158396),
             (1191579.1097525698, 691044.6091080031), (1149490.1097279799,
                                                       691044.6091080031)),
            "name":
            "Line_2"
        }]

        for line in self.lines:
            points = list()
            for point in line["points"]:
                points.append(
                    GeoPoint(None, False, "", point[0], point[1], 0,
                             self.session, line["name"], ""))
            new_line = Line(
                line["closed"],
                StratigraphicObject.init_stratigraphy(self.session,
                                                      line["horizon"],
                                                      line["age"],
                                                      line["update"]), points,
                self.session, line["name"], "")
            new_line.save_to_db()
示例#16
0
    def test_loading(self):
        # type: () -> None
        """
        Test the loading functions of the stratigraphy class

        /1/ load all from database
        /2/ load by statigraphic_name from database
        /3/ load in age range from database

        :return: Nothing

        :raises AssertionError: Raises AssertionError if a test fails
        """

        # /1/ load all from database
        # additionally update value is tested for mu / so unit
        result = {
            unit.statigraphic_name: unit
            for unit in StratigraphicObject.load_all_from_db(self.session)
        }
        self.assertEqual(
            len(result), 4,
            "Wrong number of entries ({}). Should be {}.".format(
                len(result), 4))
        self.assertEqual(
            result['mu'].age, 3,
            "Wrong age for mu ({}). Should be {}".format(result['mu'].age, 3))
        self.assertEqual(
            result['so'].age, 4,
            "Wrong age for so ({}). Should be {}".format(result['so'].age, 4))

        del result

        # /2/ load by statigraphic_name from database
        result = StratigraphicObject.load_by_stratigraphic_name_from_db(
            'mo', self.session)
        self.assertEqual(
            result.age, 1,
            "Wrong age for mo ({}). Should be {}".format(result.age, 3))
        del result

        result = StratigraphicObject.load_by_stratigraphic_name_from_db(
            'sm', self.session)
        self.assertIsNone(
            result,
            'Result for sm is not None, but should be: {}'.format(str(result)))
        del result

        # /3/ load in age range from database
        result = StratigraphicObject.load_by_age_from_db(2, 3, self.session)
        self.assertEqual(
            len(result), 2,
            "Wrong number of query results ({}). Should be {}.".format(
                len(result), 2))
        self.assertEqual(
            result[0].statigraphic_name, 'mm',
            "Wrong statigraphic_name of first horizon ({}). Should be {}.".
            format(result[0], 'mm'))
        self.assertEqual(
            result[1].statigraphic_name, 'mu',
            "Wrong statigraphic_name of second horizon ({}). Should be {}.".
            format(result[1], 'mu'))
        self.assertEqual(
            result[1].age, 3,
            "Wrong age for second horizon ({}). Should be {}.".format(
                result[1].age, 3))
        del result

        result = StratigraphicObject.load_by_age_from_db(4, 4, self.session)
        self.assertEqual(
            len(result), 1,
            "Wrong number of query results ({}). Should be {}.".format(
                len(result), 1))
        self.assertEqual(
            result[0].statigraphic_name, 'so',
            "Wrong statigraphic_name of first horizon ({}). Should be {}.".
            format(result[0], 'so'))
        del result

        result = StratigraphicObject.load_by_age_from_db(5, 10, self.session)
        self.assertEqual(
            len(result), 0,
            "Wrong number of query results ({}). Should be {}.".format(
                len(result), 0))