Exemplo n.º 1
0
    def post(self) -> ({str: str}, HTTPStatus):
        """
        Delete an existing Theme.
        :param  name:   name of Theme to delete.
        :param id:      id of Theme to delete.
        :type  name:    str
        :type  id:      str
        :returns: A no content with a http status code of 204, otherwise a JSON of the error details
                  and the appropriate http status code
        """
        if not get_jwt_claims()['admin']:
            return {"error": "administration privileges required"}, HTTPStatus.FORBIDDEN

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

        # does the theme exist?
        theme = Theme.get_by_name(args["name"]) if "name" in args else Theme.get_by_id(args["id"])
        if not theme:
            # cannot delete a theme that does not exist.
            return {'error': 'Theme does not exists.', 'id': " ", 'name': args["name"]}, HTTPStatus.BAD_REQUEST

        sub_themes = SubTheme.get_by_theme_id(theme.id)
        for sub_theme in sub_themes:
            sub_theme.delete()
            sub_theme.commit()

        # delete the theme
        theme.delete()
        theme.commit()

        return "", HTTPStatus.NO_CONTENT
Exemplo n.º 2
0
    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()
Exemplo n.º 3
0
    def tearDown(self):
        """ Handle the cleanup after the tests"""
        for theme_id in self.dummy_ids:
            theme = Theme.get_by_id(theme_id)
            if theme:
                theme.delete()
                theme.commit()

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

        if self.user:
            self.user.delete()
            self.user.commit()

        self.app_context.pop()
    def args_db_checker(self, args) -> None:
        """
        Check parsed Arguments and dependencies and Create appropriate RFC-7807 JSON Error Response
        :param args: Parsed Arguments in GET request
        """
        invalid_params = []
        if "user_id" in args:
            # Create JSON Error message if User does not exist
            if not Users.find_by_id(args["user_id"]) and args["user_id"] >= 0:
                invalid_params.append({
                    "name":
                    "user_id",
                    "value":
                    args["user_id"],
                    "reason":
                    "User Not Found",
                    "code":
                    404,
                    "rollback":
                    "Theme Tree will not contain  Attribute Aliases"
                })

        if "theme_id" in args:
            # Create JSON Error message if Theme does not exist
            if not Theme.get_by_id(args["theme_id"]):
                invalid_params.append({
                    "name":
                    "theme_id",
                    "value":
                    args["theme_id"],
                    "reason":
                    "Theme Not Found",
                    "code":
                    404,
                    "rollback":
                    "A Themes will be return in the Theme Tree"
                })

        if invalid_params:
            # Put Error message in response
            self.response = [{
                "error":
                dict(type='Request entries not found',
                     title="Unable to fetch dB entries for parsed arguments",
                     invalid_params=invalid_params)
            }]
    def get(self) -> ([Theme], HTTPStatus):
        """
        Fetch Themes
        Parameters can be passed using a POST request that contains a JSON with the following fields:
        :param limit:   the maximum number of entries to return
        :param name:    themes name
        :param id:      the themes identification number
        :type limit:    int
        :type name:     str
        :type id:       str

        :return: a list of Theme/s and an HTTPStatus code of 200 on success otherwise an JSON with an error message
                 and appropriate http status
        """
        # Get arguments passed in POST request
        args = self.reqparser.parse_args()

        # fetch themes using arguments passed in post request
        themes = []
        if "id" in args:
            theme = Theme.get_by_id(args["id"])
            if theme:
                themes.append(theme.json())
        elif "name" in args:
            theme = Theme.get_by_name(args["name"])
            if theme:
                themes.append(theme.json())
        else:
            [themes.append(theme.json()) for theme in Theme.get_all()]

        # were any themes found in the database?
        if len(themes) < 1:
            # no themes were found
            return [], HTTPStatus.OK

        if "limit" in args:
            try:
                themes = themes[:int(args["limit"])]
            except ValueError:
                return {"error": "Limit parsed is not an int"}, HTTPStatus.BAD_REQUEST

        # themes were found
        return themes, HTTPStatus.OK
    def create_theme_tree(self, theme_id: int, user_id: int) -> None:
        """
        Create Theme Tree
        :param theme_id: Theme Id
        :param user_id: User Id
        """
        theme = Theme.get_by_id(theme_id)
        if not theme:
            # Theme does not exist
            self.get_all_themes(user_id)
            return
        # Create Theme Trunk
        theme_tree = theme.serializable

        sub_themes = SubTheme.get_by_theme_id(theme_id)
        if not sub_themes:
            # No SubThemes in Theme return Trunk
            return theme_tree

        sub_theme_ids = {sub.id for sub in sub_themes}

        sub_list = []
        for sub in sub_themes:
            sub_list.append(sub.serializable)

        attribute_by_sub_id = self.get_attributes(user_id, sub_theme_ids,
                                                  theme_id)

        for sub in sub_list:
            # Add Attribute branches
            attr = attribute_by_sub_id.get(sub["id"])
            if attr:
                sub["attributes"] = attr
        # Add SubTheme branches
        theme_tree["sub_themes"] = sub_list

        self.response.append(theme_tree)
    def post(self) -> ({str: str}, HTTPStatus):
        """
        Create new SubTheme
        :param  theme:      the name of the parent theme
        :param theme_id:    the identification number of the parent theme
        :param  subtheme:   the name of the sub theme
        :type  theme:       str
        :type  theme_id:    str
        :type  subtheme:    str
        :returns: A JSON of the new SubTheme with a http status code of 200, otherwise a JSON of the error details
                  and the appropriate http status code
        """
        if not get_jwt_claims()['admin']:
            return {
                "error": "administration privileges required"
            }, HTTPStatus.FORBIDDEN

        args = self.reqparser.parse_args()

        if "theme" not in args and "theme_id" not in args:
            return {
                "error": "theme or theme_id required"
            }, HTTPStatus.BAD_REQUEST

        theme = None
        if "theme_id" in args:
            theme = Theme.get_by_id(args["theme_id"])

        elif "theme" in args:
            theme = Theme.get_by_theme(args["theme"])

        if not theme:
            return ({
                "error":
                "Theme not found",
                "Theme":
                args["theme_id"] if args["theme_id"] else args["theme"]
            }, HTTPStatus.NOT_FOUND)

        sub_theme = SubTheme.get_by(name=args["subtheme"], t_id=theme.id)

        # Avoid duplicating sub themes
        if sub_theme:
            return {
                "error": "sub theme already exists",
                "theme_id": theme.id,
                "sub_theme_id": sub_theme.id,
                "Theme": theme.name,
                "subtheme": sub_theme.name
            }, HTTPStatus.BAD_REQUEST

        sub_theme = SubTheme(theme.id, args["subtheme"])
        sub_theme.save()
        sub_theme.commit()
        return {
            "message": "sub theme created",
            "theme_id": theme.id,
            "sub_theme_id": sub_theme.id,
            "Theme": theme.name,
            "subtheme": sub_theme.name
        }, HTTPStatus.OK