def test_deletes_tip(self):
     tags = [Tag("kirjat"), Tag("maksulliset")]
     self.repository.create_tip(
         ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", self.user, tags))
     tip = self.repository.get_tips(self.user, "all")[0]
     self.repository.delete_tip(tip)
     self.assertEqual(self.repository.get_tips(self.user, "all"), [])
Ejemplo n.º 2
0
    def parse(self):
        results = []
        for x, tag in enumerate(self.html.descendants):

            if str(type(tag)) == "<class 'bs4.element.Tag'>":

                if tag.name == 'script':
                    continue

                # Find tags with no children (base tags)
                if tag.contents:
                    if sum(1 for _ in tag.descendants) == 1:
                        t = Tag(tag.name.lower())

                        # Because it might be None (<i class="fa fa-icon"></i>)
                        if tag.string:
                            t.add_content(tag.string)

                        if tag.attrs:
                            for a in tag.attrs:
                                t.add_attribute(a, tag[a])

                        results.append(t.get_data())

                # Self enclosed tags (hr, meta, img, etc...)
                else:
                    t = Tag(tag.name.lower())

                    if tag.attrs:
                        for a in tag.attrs:
                            t.add_attribute(a, tag[a])

                    results.append(t.get_data())

        return results
 def test_create_tip(self):
     tags = [Tag("kirjat"), Tag("maksulliset")]
     self.repository.create_tip(
         ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", self.user, tags))
     tips = self.repository.get_tips(self.user, "all")
     self.assertEqual(tips[0].title, "Hyvä kirja")
     self.assertEqual(tips[0].tags[0].name, "kirjat")
     self.assertEqual(tips[0].tags[1].name, "maksulliset")
    def test_cannot_see_others_tip(self):
        tags = [Tag("kirjat"), Tag("maksulliset")]
        second_user = self.user_repository.register("mikko", "oko7Aeko")
        self.repository.create_tip(
            ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", second_user, tags))

        assert not self.repository.contains_title(self.user, "Hyvä kirja")
        self.assertEqual(self.repository.get_tips(self.user, "all"), [])
Ejemplo n.º 5
0
    def setUp(self):
        self.company_1 = Company("RailScot")
        self.tag_1 = Tag("travel")
        self.company_2 = Company("Pilot Beer")
        self.tag_2 = Tag("food")

        self.transaction_1 = Transaction(10.00, self.company_1, self.tag_1)
        self.transaction_2 = Transaction(6.50, self.company_2, self.tag_2)
Ejemplo n.º 6
0
 def test_constructor_sets_fields_correctly(self):
     tags = [Tag("kirjat"), Tag("maksulliset")]
     readingtip = ReadingTip("Hyvä kirja", "https://kirjakauppa.fi/123",
                             self.user, tags)
     self.assertEqual(readingtip.title, "Hyvä kirja")
     self.assertEqual(readingtip.link, "https://kirjakauppa.fi/123")
     self.assertEqual(readingtip.tags[0].name, "kirjat")
     self.assertEqual(readingtip.tags[1].name, "maksulliset")
 def test_marks_tip_as_read(self):
     tags = [Tag("kirjat"), Tag("maksulliset")]
     self.repository.create_tip(
         ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", self.user, tags))
     assert self.repository.get_tips(self.user)[0].read is None
     self.repository.read_tip(
         self.repository.get_tips(self.user)[0], "2021")
     assert self.repository.get_tips(self.user)[0].read is not None
 def test_can_get_tips_based_on_tags(self):
     tags = [Tag("Hyvä")]
     self.repository.create_tip(
         ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", self.user, tags))
     second_tags = [Tag("Huono")]
     self.repository.create_tip(
         ReadingTip("Huono kirja", "kirjakauppa.fi/123", self.user,
                    second_tags))
     self.assertEqual(len(self.repository.get_tips(self.user, "all")), 2)
     self.assertEqual(len(self.repository.get_tips(self.user, "Hyvä")), 1)
 def test_update_tip(self):
     tags = [Tag("kirjat"), Tag("maksulliset")]
     self.repository.create_tip(
         ReadingTip("Hyvä kirja", "kirjakauppa.fi/123", self.user, tags))
     tags.append(Tag("uusi"))
     self.repository.update_tip(1, "Muutettu kirja", "kirjakauppa.fi/123",
                                tags)
     self.assertEqual(
         self.repository.get_tips(self.user)[0].title, "Muutettu kirja")
     self.assertEqual(
         self.repository.get_tips(self.user)[0].tags[2].name, "uusi")
Ejemplo n.º 10
0
    def parse(self):
        results = []
        for x, tag in enumerate(self.html.descendants):

            if str(type(tag)) == "<class 'bs4.element.Tag'>":

                #look for global.document.metadata
                if tag.name == 'script':
                    if tag.string:
                        position = tag.string.find('global.document.metadata=')
                        if position == -1:
                            continue
                        else:
                            a = 'global.document.metadata='
                            t = Tag('global.document.metadata')

                            s = tag.string[position + len(a):]
                            s = s[:s.find('\n') - 1]

                            t.add_content(s)

                            results.append(t.get_data())

                # Find tags with no children (base tags)
                if tag.contents:
                    if sum(1 for _ in tag.descendants) == 1:
                        t = Tag(tag.name.lower())

                        # Because it might be None (<i class="fa fa-icon"></i>)
                        if tag.string:
                            t.add_content(tag.string)

                        if tag.attrs:
                            for a in tag.attrs:
                                t.add_attribute(a, tag[a])

                        results.append(t.get_data())

                # Self enclosed tags (hr, meta, img, etc...)
                else:
                    t = Tag(tag.name.lower())

                    if tag.attrs:
                        for a in tag.attrs:
                            t.add_attribute(a, tag[a])

                    results.append(t.get_data())

        return results
Ejemplo n.º 11
0
 def setUp(self):
     db.create_all()
     author1 = Author('Matt')
     author2 = Author('Elie')
     tag1 = Tag('Sci Fi')
     tag2 = Tag('Horror')
     tag3 = Tag('Biography')
     db.session.add_all([author1, author2, tag1, tag2, tag3])
     db.session.commit()
     book1 = Book('Night of the Living Decorator', author2.id)
     book1.tags = [tag2]
     book2 = Book("Matt's Scary Sci Fi book", author1.id)
     book2.tags = [tag1, tag2]
     db.session.add_all([book1, book2])
     db.session.commit()
Ejemplo n.º 12
0
    def test_get_most_reactions_per_article_tag(self):
        most_popular_tag = Tag("tagname1")
        most_popular_tag.register_article(
            Article('t', 0, 6, 0, None, ["tagname1"]))
        most_popular_tag.register_article(
            Article('t', 0, 8, 0, None, ["tagname1"]))

        other_tag = Tag("tagname2")
        other_tag.register_article(Article('t', 0, 2, 0, None, ["tagname2"]))
        other_tag.register_article(Article('t', 0, 8, 0, None, ["tagname2"]))

        self.assertEqual(
            most_popular_tag,
            tag_analytics.get_most_reactions_per_article_tag(
                [most_popular_tag, other_tag]))
Ejemplo n.º 13
0
    def test_get_most_comments_per_article_tag(self):
        most_popular_tag = Tag("tagname1")
        most_popular_tag.register_article(
            Article('t', 0, 0, 3, None, ["tagname1"]))
        most_popular_tag.register_article(
            Article('t', 0, 0, 3, None, ["tagname1"]))

        other_tag = Tag("tagname2")
        other_tag.register_article(Article('t', 0, 0, 3, None, ["tagname2"]))
        other_tag.register_article(Article('t', 0, 0, 1, None, ["tagname2"]))

        self.assertEqual(
            most_popular_tag,
            tag_analytics.get_most_comments_per_article_tag(
                [most_popular_tag, other_tag]))
Ejemplo n.º 14
0
    def test_put_create_a_pet(self):
        category = Category(2, "Dogs")
        tag = Tag(5, "Red")
        pet = Pet(888888, "avaliable", "Rose", category.__dict__, ["string"],
                  [tag.__dict__])
        body = json.dumps(pet.__dict__)  # .replace('"', '\"')
        headers = {'Content-Type': 'application/json'}

        response = requests.put(self.base_url + "/pet",
                                headers=headers,
                                data=body)

        assert response.status_code == 200
        json_response = json.loads(response.text)
        pet_name = json_response["name"]
        pet_id = json_response["id"]

        assert pet_name == "Rose"
        assert pet_id == 888888

        response = requests.request("GET", self.get_url(888888))
        assert response.status_code == 200

        json_response = json.loads(response.text)

        pet_name = json_response["name"]
        pet_id = json_response["id"]

        assert pet_name == "Rose"
        assert pet_id == 888888
Ejemplo n.º 15
0
def tag_view(tag_name):
    tag = Tag(tag_name)
    posts = True
    # existance of the attributes _ORIGINAL_ATTR denotes the model instance
    # is not new and interfaces an entry in table
    if not hasattr(tag, '_ORIGINAL_ATTR'):
        error_context = {
            'error_name':
            "404 Not Found",
            'error_info':
            "The tag you tried to access does not exist, but you can create this tag."
        }
        return render_template('error.html', **error_context)

    # TODO: Implement tag page and pagination

    page_index = int(request.args.get('page') or 1)
    if not isinstance(page_index, int):
        page_index = 1
    if page_index <= 0:
        page_index = 1

    context = {
        'tag_info': {
            'title': tag.title,
            'rules': tag.rules,
            'description': tag.description
        }
    }
    context['pagination'] = tag.paginate(page_index)
    return render_template('tag.html', **context)
Ejemplo n.º 16
0
def tag_moderate_edit_info(tag_name):
    try:
        tag = Tag(tag_name)
    except:
        error_context = {
            'error_name':
            "404 Not Found",
            'error_info':
            "The tag you tried to access does not exist, but you can create this tag."
        }
        return render_template('error.html', **error_context)

    if not check.logged_in():
        error_context = {
            'error_name': "Forbidden",
            'error_info': "You may not access this page without logging in"
        }
        return render_template('error.html', **error_context)

    if not TagModerator.is_mod(session['user_id'], tag.id):
        error_context = {
            'error_name': "Access Denied",
            'error_info': "You are not a moderator of this tag"
        }
        return render_template('error.html', **error_context)

    form = TagEditForm(csrf_enabled=False)
    if form.validate_on_submit():
        tag.description = form.description.data
        tag.rules = form.rules.data
        tag.save()
        flash('Tag info saved')

    return redirect(url_for('tag_pages.tag_moderate', tag_name=tag_name))
Ejemplo n.º 17
0
def tag_moderate_remove_mod(tag_name):
    """Form processor for removing existing moderators
    """
    try:
        tag = Tag(tag_name)
    except:
        error_context = {
            'error_name':
            "404 Not Found",
            'error_info':
            "The tag you tried to access does not exist, but you can create this tag."
        }
        return render_template('error.html', **error_context)

    if not check.logged_in():
        error_context = {
            'error_name': "Forbidden",
            'error_info': "You may not access this page without logging in"
        }
        return render_template('error.html', **error_context)

    if not TagModerator.is_mod(session['user_id'], tag.id):
        error_context = {
            'error_name': "Access Denied",
            'error_info': "You are not a moderator of this tag"
        }
        return render_template('error.html', **error_context)

    form = TagModForm(csrf_enabled=False)
    if form.validate_on_submit():
        username_to_remove = form.user.data
        if username_to_remove:
            try:
                user = User.get_from_username(username_to_remove)
            except:
                flash('User does not exist')
                return redirect(
                    url_for('tag_pages.tag_moderate', tag_name=tag_name))
            if not user:
                flash('User does not exist')
                return redirect(
                    url_for('tag_pages.tag_moderate', tag_name=tag_name))
            if not TagModerator.is_mod(user.id, tag.id):
                flash('Specified user is not a mod')
                return redirect(
                    url_for('tag_pages.tag_moderate', tag_name=tag_name))
            if user.id == session['user_id']:
                flash('You may not delete yourself as a mod')
                return redirect(
                    url_for('tag_pages.tag_moderate', tag_name=tag_name))
            tag.mod_remove_user(user.id)
            flash('User removed as mod successfully')
            return redirect(
                url_for('tag_pages.tag_moderate', tag_name=tag_name))
        else:
            flash('Invalid Input')
            return redirect(
                url_for('tag_pages.tag_moderate', tag_name=tag_name))

    return redirect(url_for('tag_pages.tag_moderate', tag_name=tag_name))
Ejemplo n.º 18
0
def create_new_tag():
    category = request.form['category']

    tag = Tag(category)
    tag_repository.save(tag)

    return redirect("/tags")
Ejemplo n.º 19
0
    async def create(
        self,
        ctx,
        name: clean_content,
        tag_type: TagTypeConverter,
        *content: clean_content,
    ):
        """create tag content"""
        with self.bot.session_scope() as session:
            if Tag.exists(name, ctx.guild.id, session):
                raise NerpyException("tag already exists!")

        async with ctx.typing():
            with self.bot.session_scope() as session:
                self.bot.log.info(
                    f"creating tag {ctx.guild.name}/{name} started")
                _tag = Tag(
                    Name=name,
                    Author=str(ctx.author),
                    Type=tag_type,
                    CreateDate=datetime.utcnow(),
                    Count=0,
                    Volume=100,
                    GuildId=ctx.guild.id,
                )

                Tag.add(_tag, session)
                session.flush()

                self._add_tag_entries(session, _tag, content)

            self.bot.log.info(f"creating tag {ctx.guild.name}/{name} finished")
        await self.bot.sendc(ctx, f"tag {name} created!")
Ejemplo n.º 20
0
 def setUp(self):
     self.mostViewedTag = Tag("tagname1",
                              views=700,
                              reactions=70,
                              comments=7)
     self.mostCommentedTag = Tag("tagname2",
                                 views=500,
                                 reactions=50,
                                 comments=10)
     self.mostReactedTag = Tag("tagname3",
                               views=600,
                               reactions=100,
                               comments=6)
     self.tags = [
         self.mostViewedTag, self.mostCommentedTag, self.mostReactedTag
     ]
Ejemplo n.º 21
0
    def parse(self) -> List[dict]:
        """
        :return: list of dictionaries with all the tags
        """
        results: List[dict] = []
        for tag in self.html.descendants:

            if isinstance(tag, bs4.element.Tag):

                # look for global.document.metadata
                if tag.name == 'script' and tag.string:
                    position = tag.string.find('global.document.metadata=')
                    if position == -1:
                        continue
                    else:
                        a = 'global.document.metadata='
                        t = Tag('global.document.metadata')

                        s = tag.string[position + len(a):]
                        s = s[:s.find('\n') - 1]

                        t.add_content(s)
                        results.append(t.get_data())

                t = Tag(tag.name.lower())

                # Find tags with no children (base tags)
                if tag.contents and ilen(tag.descendants) == 1:
                    # Because it might be None (<i class="fa fa-icon"></i>)
                    if tag.string:
                        t.add_content(tag.string)

                    if tag.attrs:
                        for a in tag.attrs:
                            t.add_attribute(a, tag[a])

                    results.append(t.get_data())

                else:
                    # Self enclosed tags (hr, meta, img, etc...)
                    if tag.attrs:
                        for a in tag.attrs:
                            t.add_attribute(a, tag[a])

                    results.append(t.get_data())

        return results
def select_all():
    tags = []
    sql = "SELECT * FROM tags"
    results = run_sql(sql)
    for row in results:
        tag = Tag(row["tag_type"], row["id"])
        tags.append(tag)
    return tags
Ejemplo n.º 23
0
def select_all():
    tags = []
    sql = "SELECT * FROM tags"
    results = run_sql(sql)
    for result in results:
        tag = Tag(result["category"], result["id"])
        tags.append(tag)
    return tags
Ejemplo n.º 24
0
    def test_get_comments_per_tag(self):
        tag = Tag("tagname1")
        tag.register_article(Article('t', 0, 0, 0, None, ["tagname1"]))
        tag.register_article(Article('t', 0, 0, 2, None, ["tagname1"]))

        self.assertEqual({tag: 1},
                         tag_analytics.get_comments_per_article_for_each_tag(
                             [tag]))
Ejemplo n.º 25
0
    def test_get_reactions_per_tag(self):
        tag = Tag("tagname1")
        tag.register_article(Article('t', 0, 6, 0, None, ["tagname1"]))
        tag.register_article(Article('t', 0, 8, 0, None, ["tagname1"]))

        self.assertEqual({tag: 7},
                         tag_analytics.get_reactions_per_article_for_each_tag(
                             [tag]))
Ejemplo n.º 26
0
    def test_get_views_per_tag(self):
        tag = Tag("tagname1")
        tag.register_article(Article('t', 300, 0, 0, None, ["tagname1"]))
        tag.register_article(Article('t', 500, 0, 0, None, ["tagname1"]))

        self.assertEqual({tag: 400},
                         tag_analytics.get_views_per_article_for_each_tag(
                             [tag]))
Ejemplo n.º 27
0
def select_all_tag():
    tag_selected = []
    sql = 'SELECT * FROM tags'
    results = run_sql(sql)
    for result in results:
        tag = Tag(result['name'], result["id"])
        tag_selected.append(tag)
    return tag_selected
Ejemplo n.º 28
0
def select_all():
    tags = []
    sql = "SELECT * FROM tags ORDER BY name ASC"
    results = run_sql(sql)
    for row in results:
        tag = Tag(row["name"], row["description"], row["id"])
        tags.append(tag)
    return tags
def select(id):
    tag = None
    sql = "SELECT * FROM tags WHERE id = %s"
    values = [id]
    result = run_sql(sql, values)[0]
    if result is not None:
        tag = Tag(result["tag_type"], result["id"])
    return tag
Ejemplo n.º 30
0
def select(id):
    tag = None
    sql = "SELECT * FROM tags WHERE id = %s"
    values = [id]
    result = run_sql(sql, values)[0]

    if result is not None:
        tag = Tag(result['name'], result['id'])
    return tag