Beispiel #1
0
    def test_return_attribute_of_subtheme(self):
        """
        Adding a theme and subtheme to the database and then testing to see if it's data is
        retrieved correctly
        """

        theme = Theme("Test_Theme")
        theme.save()
        theme.commit()

        sub_theme = SubTheme(theme.id, "Test_Sub_Theme")
        sub_theme.save()
        sub_theme.commit()

        attributes = Attributes("1234567890-123456789-123456789",
                                "_test_attribute_", "_table_name_",
                                sub_theme.id, 1)
        attributes.save()
        attributes.commit()

        response = self.testing_client.get('/data',
                                           data=dict(subtheme=theme.id))

        self.assertEqual(theme.json(), response.get_json())

        attributes.delete()
        attributes.commit()

        sub_theme.delete()
        sub_theme.commit()

        theme.delete()
        theme.commit()
 def create_dummy_theme(self) -> Theme:
     """
     Create a Theme
     :return: a Theme
     """
     theme = Theme.get_by_name("_test_add_theme_")
     if not theme:
         theme = Theme("_test_add_theme_")
         theme.save()
         theme.commit()
         return theme
     return theme
Beispiel #3
0
 def create_dummy_theme(self) -> Theme:
     """
     Create a Theme
     :return: a Theme instance
     """
     theme = Theme.get_by_name("_test_add_theme_")
     if not theme:
         theme = Theme("_test_add_theme_")
         theme.save()
         theme.commit()
         self.dummy_ids.append(theme.id)
         return theme
     return theme
def create_theme(name: str = 'Environment') -> Theme:
    """
    Create a Theme
    :param name: Themes name
    :raises ValueError: If the new Theme is not persisted to the dB
    :return: A new Theme
    """
    theme = Theme.get_by_name(name)
    if not theme:
        theme = Theme(name)
        theme.save()
        theme.commit()
    if not theme:
        logger.critical('ValueError raised while creating Theme')
        raise ValueError
    return theme
    def post(self) -> ({str: str}, HTTPStatus):
        """
        Creates a new theme
        :post_argument  name: the name of the new theme
        :post_type  name: str
        :returns: A JSON with a message, theme id, and new themes name with a http status of 200 (OK) otherwise,
                  A JSON with an appropriate error message and http status applicable to the error
        """
        if not get_jwt_claims()['admin']:
            return {
                "error": "administration privileges required"
            }, HTTPStatus.FORBIDDEN

        # Get arguments
        args = self.reqparser.parse_args()

        # Check the theme name is not empty, abort if it is empty
        if not args["name"]:
            return {
                'error': 'Theme cannot be empty',
                'name': "''"
            }, HTTPStatus.BAD_REQUEST

        # Check theme does not exist (avoid duplicates)
        if Theme.get_by_name(args["name"]):
            return {
                'error': 'Theme already exists.',
                'id': " ",
                'name': args["name"]
            }, HTTPStatus.BAD_REQUEST

        # Create the new theme
        theme = Theme(args["name"])
        theme.save()
        theme.commit()

        return {
            "message": "New theme created",
            "id": theme.id,
            "name": theme.name
        }, HTTPStatus.OK
Beispiel #6
0
    def test_return_subthemes_of_theme(self):
        """
        Adding a theme and subtheme (linked to to that theme) to the database and then
        testing to see if it is retrieved correctly
        """
        theme = Theme(name='Test_Theme')
        theme.save()
        theme.commit()

        sub_theme = SubTheme(theme.id, "Test_Sub_Theme")
        sub_theme.save()
        sub_theme.commit()

        response = self.testing_client.get('/data', data=dict(theme=theme.id))

        self.assertEqual(sub_theme.json(), response.get_json())

        sub_theme.delete()
        sub_theme.commit()

        theme.delete()
        theme.commit()
Beispiel #7
0
    def post(self) -> (dict, HTTPStatus):
        """
        Get dummy data from CSV. Store dummy data in database
        :param file_name: File name to extract data from.
        :return: A Status Report detailing the dB Entries created and an HTTP
        Status code 200 on success otherwise, a JSON error message is returned
        with the appropriate HTTPStatus code
        """
        args = self.reqparser.parse_args()
        # Get size of tables before import
        self.loc_stats["before"] = db.session.query(func.count(
            LocationData.id)).scalar()
        self.tracker_stats["before"] = db.session.query(func.count(
            Tracker.id)).scalar()

        # Fetch Data from CSV
        try:
            df = pd.read_csv(args['file_name'])
        except IOError as ioe:
            logger.error("Unable to parse CSV data to dataframe",
                         ioe.with_traceback(ioe.__traceback__))
            return dict(error="Unable to parse CSV data to dataframe",
                        trackback=ioe.with_traceback(
                            ioe.__traceback__)), HTTPStatus.BAD_REQUEST

        moving_theme = Theme.get_by_name("Moving_Sensors")
        if moving_theme:
            moving_sensor_theme_id = moving_theme.id
        else:
            moving_sensor_theme = Theme("Moving_Sensors")
            moving_sensor_theme.save()
            moving_sensor_theme.commit()
            moving_sensor_theme_id = moving_sensor_theme.id

        moving_subtheme = SubTheme.get_by_name("Moving_Airquality")
        if moving_subtheme:
            moving_sensor_subtheme_id = moving_subtheme.id
        else:
            moving_sensor_subtheme = SubTheme(moving_sensor_theme_id,
                                              "Moving_Airquality")
            moving_sensor_subtheme.save()
            moving_sensor_subtheme.commit()
            moving_sensor_subtheme_id = moving_sensor_subtheme.id

        # Trackers must be unique, Fetch trackers and make dB entries for
        # each unique tracker
        unique_tracker_ids = df["tracker"].unique()

        for tracker_id in unique_tracker_ids:
            self.t_ids[self.create_trackers(str(tracker_id),
                                            moving_sensor_subtheme_id)] = 0

        # Define Location data Pandas DataFrame Column names
        loc_df = df[[
            'tracker', 'datetime', 'latitude', 'longitude', 'speed', 'heading',
            'elevation', 'charger', 'battery', 'signalquality', 'satcnt'
        ]]

        # Drop all entries that are incomplete have NaN or None/ Null values
        loc_df = loc_df.dropna()

        # Store Location Data in the dB
        for index, row in loc_df.iterrows():
            self.add_location_data(row['tracker'], row['datetime'],
                                   row['latitude'], row['longitude'],
                                   row['speed'], row['heading'],
                                   row['elevation'], row['charger'],
                                   row['battery'], row['signalquality'],
                                   row['satcnt'])

        self.loc_stats["after"] = db.session.query(func.count(
            LocationData.id)).scalar()
        self.tracker_stats["after"] = db.session.query(func.count(
            Tracker.id)).scalar()

        return self.status_report(), 200
Beispiel #8
0
class TestGetThemeTree(TestCase):
    def setUp(self):
        """
        Setup FlaskClient for tests, create an admin user and create the authorization header for requests to
        the FlaskClient
        """
        self.client, self.app_context = self.create_client()
        self.user = self.create_admin_user()
        self.auth_header = self.get_auth_header()
        self.units = []
        self.theme = None
        self.create_theme()
        self.sub_themes = []
        self.create_sub_themes(3)
        self.attributes = []
        self.create_attributes(4)
        self.aliases = []
        self.create_attribute_alias()

    @staticmethod
    def create_client() -> (FlaskClient, AppContext):
        """
        Create a FlaskClient
        :returns: A FlaskClient and a AppContext
        """
        test_app = create_app(DATABASE_NAME='test_analysis', TESTING=True)
        testing_client = test_app.test_client()
        test_app_context = test_app.app_context()
        test_app_context.push()
        return testing_client, test_app_context

    def create_theme(self) -> None:
        """
        Create a Theme
        """
        self.theme = Theme.get_by_name("_test_theme_")
        if self.theme:
            return

        self.theme = Theme("_test_theme_")
        self.theme.save()
        try:
            self.theme.commit()

        except Exception as exp:
            logger.error(exp)
            self.tearDown()

        if not self.theme:
            self.fail()

    def create_sub_themes(self, count: int) -> None:
        """
        Create SubThemes
        :param count: The number of SubThemes to create.
        """
        if self.theme:
            theme_id = self.theme.id
            for num in range(0, count):
                sub_theme = SubTheme(theme_id,
                                     "_test_sub_theme_{}".format(num))
                if sub_theme:

                    try:
                        sub_theme.save()
                        sub_theme.commit()
                        self.sub_themes.append(sub_theme)
                    except Exception as exp:
                        logger.error(exp)
                        self.tearDown()

    def create_unit(self, number: int) -> Unit:
        """
        Create unit/s
        :param number: a number to make the unit type unique
        """
        unit = Unit.get_by_symbol("Unit_type_{}".format(number))
        if unit:
            self.units.append(unit)
            return unit

        unit = Unit("Unit_type_{}".format(number),
                    "Description_{}".format(number))
        unit.save()
        unit.commit()
        self.units.append(unit)
        return unit

    def create_attributes(self, count: int) -> None:
        """
        Create Attributes for SubThemes
        :param count: Number of Attributes per SubTheme
        """
        number_attributes = len(self.sub_themes) * count

        try:
            index = 0
            sub_theme = self.sub_themes[index]
            for num in range(0, number_attributes):

                unit = self.create_unit(num)
                attr = Attributes(
                    "attribute_id_{}".format(num),
                    "attribute_name_{}".format(num),
                    "b3_heat_value_bffc4e56_20e2_41a5_84d8_de725a3f875b",
                    sub_theme.id, unit.id, "_test_description_{}".format(num),
                    "1")
                attr.save()
                attr.commit()
                self.attributes.append(attr)

                if num % count:
                    index += 1
                    if index >= len(self.sub_themes):
                        return
                    sub_theme = self.sub_themes[index]

        except Exception as exp:
            logger.error(exp)
            self.fail()

    def create_attribute_alias(self) -> None:
        """
        Create Attributes Aliases for Attributes
        :param count: The number of attributes to create per SubTheme
        """
        try:
            for attr in self.attributes:
                alias = AttrAlias(attr.id,
                                  user_id=self.user.id,
                                  name="_alias_name {}".format(
                                      len(self.aliases)),
                                  table_name="_alias_table_name_{}".format(
                                      len(self.aliases)))

                alias.save()
                alias.commit()
                self.aliases.append(alias)

        except Exception as exp:
            logger.error(exp)
            self.tearDown()

    @staticmethod
    def create_admin_user() -> Users:
        """
        Create an Admin user
        :return: an Admin user
        """
        password_hash = bcrypt.hashpw("@p@22M0rd#@!".encode("utf-8"),
                                      bcrypt.gensalt())
        user = Users.find_by_email("test_admin_user@no_an_email.cr")
        if not user:
            user = Users("test_admin_user", "test_admin_user@no_an_email.cr",
                         password_hash.decode("utf8"), True, True)
            try:
                user.save()
                user.commit()
            except Exception as e:
                pass
        return user

    def get_auth_header(self) -> {str: str}:
        """
        # Create an Authorization header
        :return: An Authorization header
        """
        response_login = self.client.post('/login',
                                          data=dict(email=self.user.email,
                                                    password="******",
                                                    remember=True),
                                          follow_redirects=True)
        response_login_json = response_login.get_json()
        return {
            'Authorization':
            'Bearer {}'.format(response_login_json["access_token"])
        }

    def test_get(self) -> None:
        """
        Test Create Theme Tree endpoint
        """
        resp = self.client.get('/admin/themes/get_tree',
                               data=dict(user_id=self.user.id,
                                         theme_id=self.theme.id),
                               headers=self.auth_header)
        data = resp.get_json()

        self.assertEqual(resp.status_code, HTTPStatus.OK)
        self.assertTrue('id' in data)
        self.assertTrue(data['id'] == self.theme.id)
        self.assertTrue(data['Name'] == self.theme.name)
        self.assertTrue('sub_themes' in data)
        self.assertTrue(len(data['sub_themes']) == len(self.sub_themes))
        for sub in data['sub_themes']:
            self.assertTrue("attributes" in sub)
            for attr in sub["attributes"]:
                self.assertTrue("alias" in attr)

    def tearDown(self) -> None:
        """ Clean up all dependencies after tests"""

        for alias in self.aliases:
            try:
                if AttrAlias.get_by_user_id(self.user.id):
                    alias.delete()
                    alias.commit()
            except Exception:
                pass

        for attr in self.attributes:
            try:
                if Attributes.get_by_id(attr.id):
                    attr.delete()
                    attr.commit()
            except Exception:
                pass

        for sub_theme in self.sub_themes:
            try:
                if SubTheme.get_by_id(sub_theme.id):
                    sub_theme.delete()
                    sub_theme.commit()
            except Exception:
                pass

        for unit in self.units:
            try:
                if Unit.get_by_id(unit.id):
                    unit.delete()
                    unit.commit()
            except Exception:
                pass

        try:
            if Theme.get_by_id(self.theme.id):
                self.theme.delete()
                self.theme.commit()
        except Exception:
            pass

        self.client.post('/logout', headers=self.auth_header)

        if self.user:
            if Users.find_by_id(self.user.id):
                try:
                    self.user.delete()
                    self.user.commit()
                except Exception:
                    pass

        self.app_context.pop()