Exemplo n.º 1
0
def test_get_random_story(client, database, templates, story_actions):
    example = Story()
    example.text = 'very not recent story (months/years ago)'
    example.likes = 0
    example.author_id = 1
    example.date = dt.datetime(2019, 9, 5)
    example.is_draft = False
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)

    example = Story()
    example.text = 'not recent story (yesterday)'
    example.date = dt.datetime.now() - dt.timedelta(days=1)
    example.likes = 0
    example.author_id = 2
    example.is_draft = False
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)

    example = Story()
    example.text = 'drafted story'
    example.date = dt.datetime.now() - dt.timedelta(days=1)
    example.likes = 0
    example.author_id = 1
    example.is_draft = True
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)

    example = Story()
    example.text = 'deleted story'
    example.date = dt.datetime.now() - dt.timedelta(days=1)
    example.likes = 0
    example.author_id = 1
    example.is_draft = False
    example.deleted = True
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)

    database.session.commit()

    # story found
    reply = story_actions.get_random_recent_story()
    assert reply.status_code == 200

    template_context = templates[-1]
    id = template_context['story'].id
    message = template_context['message']
    assert id == 1 or id == 2
    assert message == 'no stories today. Here is a random one:'
Exemplo n.º 2
0
    def setUp(self) -> None:
        with app.app_context():
            # user for login
            example = User()
            example.firstname = 'Admin'
            example.lastname = 'Admin'
            example.email = '*****@*****.**'
            example.dateofbirth = datetime.datetime(2020, 10, 5)
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)

            # dummy user
            dummy_user = User()
            dummy_user.firstname = 'Dummy'
            dummy_user.lastname = 'Dummy'
            dummy_user.email = '*****@*****.**'
            dummy_user.dateofbirth = datetime.datetime(2020, 10, 5)
            dummy_user.is_admin = True
            dummy_user.set_password('admin')
            db.session.add(dummy_user)
            db.session.commit()

            dummy_id = User.query.filter(
                User.email == '*****@*****.**').first().id

            test_story = Story()
            test_story.text = "Test story from admin user"
            test_story.author_id = 1
            test_story.is_draft = 0
            test_story.figures = "#Test#admin#"

            dummy_story = Story()
            dummy_story.text = "Test story from dummy user"
            dummy_story.author_id = dummy_id
            dummy_story.is_draft = 0
            dummy_story.figures = "#Test#dummy#"

            db.session.add(test_story)
            db.session.add(dummy_story)
            db.session.commit()

            payload = {'email': '*****@*****.**', 'password': '******'}

            form = LoginForm(data=payload)

            self.client.post('/users/login',
                             data=form.data,
                             follow_redirects=True)
Exemplo n.º 3
0
def make_story(userid, text="test text", likes=0, dislikes=0):
    example = Story()
    example.text = text
    example.likes = likes
    example.dislikes = dislikes
    example.author_id = userid
    return example
Exemplo n.º 4
0
def test_get_story(client, auth, database, templates, story_actions):
    example = Story()
    example.text = 'Trial story of example admin user :)'
    example.likes = 42
    example.author_id = 1
    example.dice_set = ['dice1', 'dice2']

    database.session.add(example)
    database.session.commit()

    auth.login()

    # story found
    reply = story_actions.get_story(1)
    template_capture = templates[-1]
    assert reply.status_code == 200
    assert template_capture['story'].id == 1
    # assert template_capture['message'] == ''

    # story not found
    reply = story_actions.get_story(0)
    assert reply.status_code == 404

    # invalid input
    reply = story_actions.get_story('ciao')
    assert reply.status_code == 404

    # deleted story
    reply = story_actions.delete_story(1)
    assert reply.status_code == 200
    reply = story_actions.get_story(1)
    assert reply.status_code == 410
Exemplo n.º 5
0
    def test_random_recent_story(self):

        # Random recent story as anonymous user
        self.client.get('/stories/random', follow_redirects=True)
        self.assert_template_used('story.html')
        self.assertEqual(self.get_context_variable('story').text, 'Just another story')

        # Login as Admin
        payload = {'email': '*****@*****.**', 'password': '******'}
        form = LoginForm(data=payload)
        self.client.post('/users/login', data=form.data, follow_redirects=True)

        # No recent stories
        self.client.get('/stories/random', follow_redirects=True)
        self.assert_template_used('stories.html')
        self.assert_message_flashed('Oops, there are no recent stories by other users!')

        # Create a new recent story by Admin2
        example = Story()
        example.text = 'This is a valid recent story'
        example.date = datetime.datetime.now()
        example.author_id = 2
        example.figures = 'story#recent'
        example.is_draft = False
        db.session.add(example)
        db.session.commit()

        # Get the only recent story not written by Admin
        response = self.client.get('/stories/random', follow_redirects=True)
        self.assert_template_used('story.html')
        self.assertEqual(self.get_context_variable('story').text, 'This is a valid recent story')
Exemplo n.º 6
0
def test_getuser(client, auth, database, templates):
    reply = auth.login()
    assert reply.status_code == 302

    reply = client.get('/users/2')
    assert reply.status_code == 200

    user = templates[-1]['user']
    stories = templates[-1]['stories']
    assert user == 'test1'
    assert stories == []

    example = Story()
    example.text = 'First story of test1 user :)'
    example.author_id = 2
    example.is_draft = False
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)
    database.session.commit()

    reply = client.get('/users/2')
    assert reply.status_code == 200

    user = templates[-1]['user']
    stories = templates[-1]['stories']
    assert user == 'test1'
    assert len(stories) == 1
    assert stories[0].id == example.id
Exemplo n.º 7
0
def test_story_with_unmarked_dislike(client, auth, database, templates,
                                     story_actions):
    # example story and unmarked reaction
    s = Story()
    s.text = 'Trial story of example admin user :)'
    s.likes = 42
    s.dislikes = 0
    s.author_id = 1
    s.dice_set = ['dice1', 'dice2']
    s.is_draft = False
    s.deleted = False

    database.session.add(s)

    r = Reaction()
    r.reactor_id = 1
    r.author = s
    r.reaction_val = -1
    r.marked = False

    database.session.add(r)

    database.session.commit()

    # get the story
    auth.login()
    reply = story_actions.get_story(1)
    template_capture = templates[-1]
    assert reply.status_code == 200
    assert template_capture['story'].likes == 42
    # check that the unmarked dislike is counted
    assert template_capture['story'].dislikes == 1

    database.session.commit()
Exemplo n.º 8
0
    def setUp(self) -> None:
        with app.app_context():
            # user for login
            example = User()
            example.firstname = 'Admin'
            example.lastname = 'Admin'
            example.email = '*****@*****.**'
            example.dateofbirth = datetime.datetime(2020, 10, 5)
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()

            # reacted story
            test_story = Story()
            test_story.text = "Test story from admin user"
            test_story.author_id = 1
            test_story.is_draft = 0
            test_story.figures = "#Test#admin#"
            db.session.add(test_story)
            db.session.commit()

            # login
            payload = {'email': '*****@*****.**', 'password': '******'}

            form = LoginForm(data=payload)

            self.client.post('/users/login',
                             data=form.data,
                             follow_redirects=True)
Exemplo n.º 9
0
def test_check_mywall(client, auth, database, templates):
    reply = client.get('/')
    assert reply.status_code == 302

    auth.login()

    reply = client.get('/')
    stories = templates[-1]['stories']
    assert reply.status_code == 200
    assert stories == []

    example = Story()
    # gets story_id=1 as user_id or as the first?
    example.text = 'Trial story of example admin user :)'
    example.likes = 42
    example.dislikes = 0
    example.author_id = 1
    example.dice_set = 'face1?face2?face3?face4'
    database.session.add(example)
    database.session.commit()

    reply = client.get('/')
    stories = templates[-1]['stories']
    assert reply.status_code == 200
    assert len(stories) == 1
    assert stories[0].id == example.id

    example2 = Story()
    # gets story_id=1 as user_id or as the first?
    example2.text = 'New story of example admin user :)'
    example2.likes = 42
    example2.dislikes = 0
    example2.author_id = 1
    example2.dice_set = 'face1?face2?face3?face4'
    database.session.add(example2)
    database.session.commit()

    reply = client.get('/')
    stories = templates[-1]['stories']

    assert reply.status_code == 200
    assert len(stories) == 2
    for story in stories:
        assert story.id == example.id or story.id == example2.id
Exemplo n.º 10
0
def init_database(database):
    example = Story()
    example.text = 'lorem ipsum dolor sit amet'
    example.likes = 42
    example.author_id = 1
    example.date = dt.datetime(year=2018, month=12, day=1)
    example.is_draft = False
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)

    example = Story()
    example.text = 'bird drink coffee baloon'
    example.likes = 42
    example.author_id = 1
    example.date = dt.datetime(year=2019, month=1, day=1)
    example.is_draft = False
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)

    example = Story()
    example.text = 'lorem Coffee dolor sit amet'
    example.likes = 42
    example.author_id = 1
    example.date = dt.datetime(year=2019, month=3, day=12)
    example.is_draft = False
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)

    example = Story()
    example.text = 'bird cofFee baloon amet'
    example.likes = 42
    example.author_id = 1
    example.date = dt.datetime(year=2017, month=10, day=1)
    example.is_draft = False
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)

    database.session.commit()
Exemplo n.º 11
0
def test_get_by_interest(client, auth, database, templates, story_actions):
    auth.login()

    example1 = Story()
    example1.theme = 'halloween'
    example1.text = 'Halloween story of test1 user :)'
    example1.author_id = 2
    example1.is_draft = False
    example1.deleted = False
    example1.dice_set = ['a', 'b', 'c']
    database.session.add(example1)
    database.session.commit()

    example2 = Story()
    example2.theme = 'xmas'
    example2.text = 'Xmas story of test2 user :)'
    example2.author_id = 3
    example2.is_draft = False
    example2.deleted = False
    example2.dice_set = ['a', 'b', 'c']
    database.session.add(example2)
    database.session.commit()

    example3 = Story()
    example3.theme = 'xmas'
    example3.theme = 'Old xmas story of test3 user :)'
    example3.date = dt.datetime.now() - dt.timedelta(days=6)
    example3.author_id = 4
    example3.is_draft = False
    example3.deleted = False
    example3.dice_set = ['a', 'b', 'c']
    database.session.add(example3)
    database.session.commit()

    reply = story_actions.get_all_stories(theme='xmas')
    assert reply.status_code == 200
    assert templates[-1]['stories'].all() == [example2]
Exemplo n.º 12
0
    def setUp(self) -> None:
        with app.app_context():
            # user for login
            example = User()
            example.firstname = 'Admin'
            example.lastname = 'Admin'
            example.email = '*****@*****.**'
            example.dateofbirth = datetime.datetime(2020, 10, 5)
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()

            # reacted story
            test_story = Story()
            test_story.text = "Test story from admin user"
            test_story.author_id = 1
            test_story.is_draft = 0
            test_story.figures = "#admin#cat#"
            db.session.add(test_story)
            db.session.commit()
Exemplo n.º 13
0
def new_stories():
    if request.method == 'GET':
        dice_themes = retrieve_themes()
        return render_template("new_story.html", themes=dice_themes)
    else:
        stry = Story.query.filter(Story.author_id == current_user.id).filter(
            Story.published == 0).filter(
                Story.theme == request.form["theme"]).first()
        if stry != None:
            return redirect("/write_story/" + str(stry.id), code=302)

        dice_set = retrieve_dice_set(request.form["theme"])
        face_set = dice_set.throw()[:int(request.form["dice_number"])]
        new_story = Story()
        new_story.author_id = current_user.id
        new_story.theme = request.form["theme"]
        new_story.rolls_outcome = json.dumps(face_set)
        db.session.add(new_story)
        db.session.flush()
        db.session.commit()
        db.session.refresh(new_story)
        return redirect('/write_story/' + str(new_story.id), code=302)
Exemplo n.º 14
0
def test_statistics(client, auth, database, templates):
    auth.login()

    reply = client.get('/')

    assert reply.status_code == 200
    # As soon as I create a new user I shouldn't have stats
    # since I have no stories
    stats = templates[-1]['stats']
    assert stats == {}

    example = Story()
    example.text = 'Lorem ipsum dolor sit amet'
    example.likes = 0
    example.dislikes = 0
    example.author_id = 1
    example.dice_set = ["face1", "face2", "face3", "face4"]
    database.session.add(example)
    database.session.commit()

    reply = client.get('/')
    stats = templates[-1]['stats']
    assert reply.status_code == 200
    # List index 0 refers to number of stories,
    # index 1 refers to the number of likes,
    # index 2 to the number of dislikes
    assert stats['stories'][0] == 1 \
        and stats['stories'][1] == 0 \
        and stats['stories'][2] == 0

    # I threw one set of four dice only once
    assert stats['avg_dice'] == 4

    # Published only only one story
    assert stats['stories_frequency'] == 1

    # Active user, it has been published at least one story in the last 7 days
    assert stats['active']
Exemplo n.º 15
0
def _rollDice():
    '''
    Rolls the dice and enables the user to start writing a story.

    The story is created as a draft, so that it can be edited.

    Raises:
        Exception: due to eventual failures during the commit of the
            created story into the database.

    Returns:
        302 -> the user is redirected to the page in which he/she can
                start writing the story on the faces which came out.
    '''

    diceset = request.args.get('diceset', 'standard')
    dicenum = request.args.get('dicenum', 6, type=int)

    try:
        dice = DiceSet(diceset, dicenum)
        roll = dice.throw_dice()
        story = Story()
        story.text = ''
        story.theme = diceset
        story.likes = 0
        story.dislikes = 0
        story.dice_set = roll
        story.author_id = current_user.id
        db.session.add(story)
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        abort(400)

    return redirect(url_for('stories._story_edit', storyid=story.id))
Exemplo n.º 16
0
def _write_story(id_story=None, message='', status=200):
    form = StoryForm()

    # Setting session to modify draft
    if 'GET' == request.method and id_story is not None:
        story = Story.query.filter(Story.id == id_story).first()
        if story is not None and story.author_id == current_user.id and story.is_draft:
            form.text.data = story.text
            session['figures'] = story.figures.split('#')
            session['figures'] = session['figures'][1:-1]
            session['id_story'] = story.id
        else:
            flash(
                'Request is invalid, check if you are the author of the story and it is still a draft',
                'error')
            return redirect(
                url_for('users._user_drafts', id_user=current_user.id))

    # Check if there are the words to write the story
    if 'figures' not in session:
        flash('Request is invalid, you need to set a story before', 'error')
        return redirect(url_for('home.index'))

    elif 'POST' == request.method:
        if form.validate_on_submit():
            draft = bool(int(form.as_draft.data))
            if draft:
                if 'id_story' in session:
                    # Update a draft
                    db.session.query(Story).filter_by(
                        id=session['id_story']).update({
                            'text':
                            form.text.data,
                            'date':
                            datetime.datetime.now()
                        })
                    db.session.commit()
                    session.pop('id_story')
                else:
                    # Save new story as draft
                    new_story = Story()
                    new_story.author_id = current_user.id
                    new_story.figures = '#' + '#'.join(
                        session['figures']) + '#'
                    new_story.is_draft = True
                    form.populate_obj(new_story)
                    db.session.add(new_story)
                    db.session.commit()
                session.pop('figures')
                return redirect(
                    url_for('users._user_drafts', id_user=current_user.id))
            else:
                # Check validity
                dice_figures = session['figures'].copy()
                trans = str.maketrans(string.punctuation,
                                      ' ' * len(string.punctuation))
                new_s = form['text'].data.translate(trans).lower()
                story_words = new_s.split()
                for w in story_words:
                    if w in dice_figures:
                        dice_figures.remove(w)
                        if not dice_figures:
                            break
                if len(dice_figures) > 0:
                    status = 400
                    message = 'Your story doesn\'t contain all the words. Missing: '
                    for w in dice_figures:
                        message += w + ' '
                else:
                    if 'id_story' in session:
                        # Publish a draft
                        date_format = "%Y %m %d %H:%M"
                        date = datetime.datetime.strptime(
                            datetime.datetime.now().strftime(date_format),
                            date_format)
                        db.session.query(Story).filter_by(
                            id=session['id_story']).update({
                                'text': form.text.data,
                                'date': date,
                                'is_draft': False
                            })
                        db.session.commit()
                        session.pop('id_story')
                    else:
                        # Publish a new story
                        new_story = Story()
                        new_story.author_id = current_user.id
                        new_story.figures = '#' + '#'.join(
                            session['figures']) + '#'
                        new_story.is_draft = False
                        form.populate_obj(new_story)
                        db.session.add(new_story)
                        db.session.commit()
                    session.pop('figures')
                    flash('Your story is a valid one! It has been published')
                    return redirect(
                        url_for('users._user_stories',
                                id_user=current_user.id,
                                _external=True))
    return make_response(
        render_template("write_story.html",
                        home_url=HOME_URL,
                        form=form,
                        words=session['figures'],
                        message=message), status)
Exemplo n.º 17
0
    def test1(self):
        global _app
        tested_app = create_app(debug=True)
        _app = tested_app
        with tested_app.test_client() as client:
            with client.session_transaction() as sess:
                db.drop_all()
                db.create_all()

                # create user
                user_a = User()
                user_a.email = '*****@*****.**'
                user_a.set_password('test')
                db.session.add(user_a)
                db.session.commit()

                user_b = User()
                user_b.email = '*****@*****.**'
                user_b.set_password('test')
                db.session.add(user_b)
                db.session.commit()

                # create story
                story = Story()
                story.text = 'Text a'
                story.likes = 0
                story.dislikes = 0
                story.author_id = user_a.get_id()
                story.roll = {
                    'dice':
                    ['bike', 'tulip', 'happy', 'cat', 'ladder', 'rain']
                }
                db.session.add(story)
                db.session.commit()

                # add like
                like = Reaction()
                like.marked = 0
                like.story_id = story.id
                like.user_id = user_b.id
                like.type = 1
                db.session.add(story)
                db.session.commit()

                # create 1000 user and like the story
                users = []
                for i in range(10):
                    user = User()
                    user.email = 'user' + str(i) + '@test.com'
                    user.set_password('test')
                    db.session.add(user)
                    users.append(user)
                    db.session.add(story)

                db.session.commit()
                for u in users:
                    add_reaction(u.id, 1, 1)
                #
                # reaction = Reaction.query.count()
                # print(str(reaction)))
                res = update_reactions.apply_async(args=[1], time_limit=3)
                res.get()
                q = Story.query.filter_by(author_id=1).first()
                self.assertEqual(int(q.likes), 10)
Exemplo n.º 18
0
def test_getusers(client, database, auth, templates):
    reply = auth.login('Admin', 'admin')
    assert reply.status_code == 302

    reply = client.get('/users')
    template_capture = templates[-1]['result']
    users = [(r[0], r[1]) for r in template_capture]
    assert users == [('Admin', None),
                     ('test1', None),
                     ('test2', None),
                     ('test3', None)]

    example = Story()
    example.text = 'First story of admin user :)'
    example.author_id = 1
    example.is_draft = False
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)
    database.session.commit()

    reply = client.get('/users')
    template_capture = templates[-1]['result']
    users = [(r[0], r[1]) for r in template_capture]
    assert users == [('Admin', 'First story of admin user :)'),
                     ('test1', None),
                     ('test2', None),
                     ('test3', None)]

    client.get('/logout')

    client.post('/signup', data={'email': '*****@*****.**',
                                 'username': '******',
                                 'password': '******'})
    reply = client.get('/users')
    template_capture = templates[-1]['result']
    users = [(r[0], r[1]) for r in template_capture]
    assert users == [('Admin', 'First story of admin user :)'),
                     ('test1', None),
                     ('test2', None),
                     ('test3', None),
                     ('prova', None)]

    example = Story()
    example.text = 'First story of prova user :)'
    example.author_id = 5
    example.is_draft = False
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)
    database.session.commit()

    reply = client.get('/users')
    template_capture = templates[-1]['result']
    users = [(r[0], r[1]) for r in template_capture]
    assert users == [('Admin', 'First story of admin user :)'),
                     ('test1', None),
                     ('test2', None),
                     ('test3', None),
                     ('prova', 'First story of prova user :)')]

    example = Story()
    example.text = 'Second story of admin user :)'
    example.author_id = 1
    example.is_draft = False
    example.deleted = False
    example.dice_set = ['a', 'b', 'c']
    database.session.add(example)
    database.session.commit()

    reply = client.get('/users')
    template_capture = templates[-1]['result']
    users = [(r[0], r[1]) for r in template_capture]
    assert users == [('Admin', 'Second story of admin user :)'),
                     ('test1', None),
                     ('test2', None),
                     ('test3', None),
                     ('prova', 'First story of prova user :)')]
Exemplo n.º 19
0
def _stories(message='', error=False, res_msg='', info_bar=False):
    form = SelectDiceSetForm()
    if 'POST' == request.method:
        # Create a new story
        new_story = Story()
        new_story.author_id = current_user.id
        new_story.likes = 0
        new_story.dislikes = 0

        if form.validate_on_submit():
            text = request.form.get('text')
            roll = request.form.get('roll')
            # for the tests
            if re.search('"', roll):
                roll = json.loads(request.form.get('roll'))

        if (type(roll) is str):
            roll = roll.replace("[", "")
            roll = roll.replace("]", "")
            roll = roll.replace("'", "")
            roll = roll.replace(" ", "")
            aux = roll.split(",")
            roll = aux

        dicenumber = len(roll)
        try:
            check_storyV2(text, roll)
            new_story.text = text
            new_story.roll = {'dice': roll}
            new_story.dicenumber = dicenumber
            db.session.add(new_story)
            db.session.commit()
        except WrongFormatStoryError:
            # print('ERROR 1', file=sys.stderr)
            message = "There was an error. Try again."

        except WrongFormatDiceError:
            # print('ERROR 2', file=sys.stderr)
            message = "There was an error. Try again."

        except TooLongStoryError:
            # print('ERROR 3', file=sys.stderr)
            message = "The story is too long. The length is > 1000 characters."

        except TooSmallStoryError:
            # print('ERROR 4', file=sys.stderr)
            message = "The number of words of the story must greater or equal of the number of resulted faces."

        except WrongFormatSingleDiceError:
            # print('ERROR 5', file=sys.stderr)
            message = "There was an error. Try again."

        except InvalidStory:
            # print('ERROR 6', file=sys.stderr)
            message = "Invalid story. Try again!"

        allstories = db.session.query(Story, User).join(User).all()
        allstories = list(
            map(
                lambda x:
                (x[0], x[1], "hidden"
                 if x[1].id == current_user.id else "", "unfollow"
                 if _is_follower(current_user.id, x[1].id) else "follow",
                 reacted(current_user.id, x[0].id)), allstories))
        return render_template("stories.html",
                               message=message,
                               form=form,
                               stories=allstories,
                               active_button="stories",
                               like_it_url="/stories/reaction",
                               details_url="/stories",
                               error=error,
                               info_bar=info_bar,
                               res_msg=str(res_msg))
    elif 'GET' == request.method:
        allstories = db.session.query(Story, User).join(User).all()
        allstories = list(
            map(
                lambda x:
                (x[0], x[1], "hidden"
                 if x[1].id == current_user.id else "", "unfollow"
                 if _is_follower(current_user.id, x[1].id) else "follow",
                 reacted(current_user.id, x[0].id)), allstories))

        return render_template("stories.html",
                               message=message,
                               form=form,
                               stories=allstories,
                               active_button="stories",
                               like_it_url="/stories/reaction",
                               details_url="/stories",
                               error=error,
                               info_bar=info_bar,
                               res_msg=str(res_msg))