Example #1
0
def client():
    """ This function initialize a new DB for every test and creates the app. This function returns a tuple,
    the first element is a test client and the second is the app itself. Test client must be used for sending
    request and the app should be used for getting a context when, for example, we need to query the DB.
    I haven't found a more elegant way to do this."""
    app = create_app()
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db_fd, app.config['DATABASE'] = tempfile.mkstemp()
    print(app.config['DATABASE'])
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE']
    app.config['TESTING'] = True
    app.config[
        'WTF_CSRF_ENABLED'] = False  # disable CSRF validation -> DO THIS ONLY DURING TESTS!
    client = app.test_client()

    db.create_all(app=app)
    db.init_app(app=app)
    #with app.app_context():
    #db.engine.execute(_data_sql)
    with app.app_context():
        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.email = '*****@*****.**'
            example.is_admin = True
            example.set_password('admin')
            db.session.add(example)
            db.session.commit()

    yield client, app

    os.close(db_fd)
    os.unlink(app.config['DATABASE'])
Example #2
0
def send_all_mail():  # pragma: no cover
    print('sending')
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP
    mail = Mail(app)
    mail.init_app(app=app)
    with app.app_context():
        users = db.session.query(User).filter()
        for user in users:
            report = db.session.query(Report).filter(
                Report.runner_id == user.id).first()
            if report is not None and time(
            ) - report.timestamp >= report.choice_time:
                body = prepare_body(user, app)

                if body:
                    msg = Message('Your BeepBeep Report',
                                  sender=app.config['MAIL_USERNAME'],
                                  recipients=[user.email])
                    msg.body = body
                    mail.send(msg)
                    report.set_timestamp()
                    db.session.merge(report)
                    db.session.commit()
Example #3
0
    def test_invalid_post_short_story(self):

        global _app
        if _app is None:
            tested_app = create_app(debug=True)
            _app = tested_app
        else:
            tested_app = _app
        restart_db_tables(db, tested_app)

        with tested_app.test_client() as client:

            # login
            reply = login(client, '*****@*****.**', 'admin')
            assert b'Hi Admin!' in reply.data
            reply = client.get('/stories')
            assert b'Trial story of example admin user' in reply.data

            # post a new story
            roll = json.dumps(
                ["bird", "whale", "coffee", "bananas", "ladder", "glasses"])

            reply = client.post('/stories',
                                data=dict(text="short story", roll=roll),
                                follow_redirects=True)

            self.assertEqual(reply.status_code, 200)

            assert b'The number of words of the story must greater or equal of the number of resulted faces.' in reply.data

            # check database entry
            q = db.session.query(Story).order_by(Story.id.desc()).first()
            self.assertNotEqual(q.text, "short story")
    def test1(self):
        global _app
        if _app is None:
            tested_app = create_app(debug=True)
            _app = tested_app
        else:
            tested_app = _app
        restart_db_tables(db, tested_app)

        with tested_app.test_client() as client:

            # login
            reply = login(client, '*****@*****.**', 'admin')
            assert b'Hi Admin!' in reply.data

            reply = client.get('/stories/filter')
            self.assertIn(b'Filter Stories', reply.data)

            # Filter correctly a time interval
            reply = client.post('/stories/filter', data=dict(
                init_date='2019-01-01',
                end_date='2019-12-01'
            ), follow_redirects=True)
            self.assertIn(b'Trial story of example', reply.data)

            # Filter wrongly a time interval (init_date > end_date)
            reply = client.post('/stories/filter', data=dict(
                init_date='2019-12-01',
                end_date='2019-01-01'
            ), follow_redirects=True)
            self.assertIn(b'Cant travel back in time', reply.data)
Example #5
0
    def test_roll(self):

        global _app
        if _app is None:
            tested_app = create_app(debug=True)
            _app = tested_app
        else:
            tested_app = _app
        restart_db_tables(db, tested_app)

        with tested_app.test_client() as client:

            # login
            reply = login(client, '*****@*****.**', 'admin')
            self.assertEqual(reply.status_code, 200)

            # wrong dice number
            reply = client.get('/rolldice/12/basic')
            assert b'Error!' in reply.data

            # non-existing dice set
            reply = client.get('/rolldice/6/pippo')
            self.assertEqual(reply.status_code, 404)

            # correct roll
            reply = client.get('/rolldice/5/basic')

            self.assertEqual(reply.status_code, 200)
Example #6
0
 def test_story_retrieval(self):
     tested_app = create_app(debug=True)
     with tested_app.test_client() as client:
         reply = client.get('/stories/random',
                            content_type='html/text',
                            follow_redirects=True)
         self.assertIn('<div class="card text-center">', str(reply.data))
Example #7
0
    def test_getuser(self):
        global _app
        if _app is None:
            tested_app = create_app(debug=True)
            _app = tested_app
        else:
            tested_app = _app
        restart_db_tables(db, tested_app)

        with tested_app.test_client() as client:
            with client.session_transaction() as session:
                user_base = User.query.first()
                # push in the users_table 3 users
                user_a = User()
                user_a.email = '*****@*****.**'
                user_a.set_password('test')

                user_b = User()
                user_b.email = '*****@*****.**'
                user_b.set_password('test')

                user_c = User()
                user_c.email = '*****@*****.**'
                user_c.set_password('test')

                db.session.add(user_a)
                db.session.add(user_b)
                db.session.add(user_c)
                db.session.commit()
                res = get_users()
        correct = [user_base, user_a, user_b, user_c]
        print(res)
        print(correct)
        self.assertEqual(res, correct)
Example #8
0
def send_report():
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP

    with app.app_context():
        mail = Mail(app)
        q = db.session.query(User)
        # Check all users if they requested report
        for user in q:
            if user.email_frequency is None:
                continue
            # check report freq against the current time - in case worker dies the report would be send with proper freq
            # Opposed to when some counter would be used(the state of counyter would die with it)
            if int(time.time()) % user.email_frequency == 0:
                msg = Message('BeepBeep Email report',
                              sender=os.environ['EMAIL_ID'],
                              recipients=[user.email])
                msg.body = "Report from strava"
                mail.send(msg)
Example #9
0
    def test_get_followed_list(self):
        global _app
        if _app is None:
            tested_app = create_app(debug=True)
            _app = tested_app
        else:
            tested_app = _app
        restart_db_tables(db, tested_app)

        with tested_app.test_client() as client:
            with client.session_transaction() as session:
                # push in the users_table 3 users
                user_a = User()
                user_a.email = '*****@*****.**'
                user_a.set_password('test')

                user_b = User()
                user_b.email = '*****@*****.**'
                user_b.set_password('test')

                user_c = User()
                user_c.email = '*****@*****.**'
                user_c.set_password('test')

                user_d = User()
                user_d.email = '*****@*****.**'
                user_d.set_password('test')

                db.session.add(user_a)
                db.session.add(user_b)
                db.session.add(user_c)
                db.session.add(user_d)
                db.session.commit()

                # Get users ID
                user_a_id = User.query.filter_by(
                    email=user_a.email).first().get_id()
                user_b_id = User.query.filter_by(
                    email=user_b.email).first().get_id()
                user_c_id = User.query.filter_by(
                    email=user_c.email).first().get_id()
                user_d_id = User.query.filter_by(
                    email=user_d.email).first().get_id()

            with client.session_transaction() as session:
                follow_ab = _create_follow(user_a_id, user_b_id)
                follow_ac = _create_follow(user_a_id, user_c_id)
                follow_ad = _create_follow(user_a_id, user_d_id)
                follow_bc = _create_follow(user_b_id, user_c_id)

                db.session.add(follow_ab)
                db.session.add(follow_ac)
                db.session.add(follow_ad)
                db.session.add(follow_bc)
                db.session.commit()

                res = get_followed_list(user_a_id)
                correct = [user_b_id, user_c_id, user_d_id]
                self.assertEqual(res, correct)
Example #10
0
 def test_send_email(self):
     global _app
     if _app is None:
         tested_app = create_app(debug=True)
         _app = tested_app
     else:
         tested_app = _app
     restart_db_tables(db, tested_app)
Example #11
0
def client():
    app = create_app(tests=True)
    app.config["TESTING"] = True
    app.config["WTF_CSRF_ENABLED"] = False
    app.config["DEBUG"] = True
    ctx = app.app_context()
    ctx.push()

    with app.test_client() as client:
        yield client
Example #12
0
def fetch_all_runs():
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP

    return runs_fetched
Example #13
0
def do_task():
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP

    return []
Example #14
0
def app():
    db_fd, db_path = tempfile.mkstemp()
    db_url = 'sqlite:///' + db_path
    app = create_app(test=True, database=db_url, test_telegram=True)

    yield app

    app.config['TELEGRAM_UPDATER'].stop()

    os.close(db_fd)
    os.unlink(db_path)
Example #15
0
def create_context():
    global _APP
    # lazy init
    print(_APP)  #for testing shows what kind of app we use
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
        _APP = app
    else:
        app = _APP
    return app
Example #16
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()

        with tested_app.test_client() as client:
            # Create user
            resp = client.post('/signup',
                       data=dict(firstname="admin_firstname",
                        lastname="admin_lastname",
                        email="*****@*****.**",
                        dateofbirth=1994,
                        password="******"),
                       follow_redirects=True)
            assert b'Index Page' in resp.data

            # login
            reply = login(client, '*****@*****.**', 'admin')
            assert b'Hi admin_firstname!' in reply.data

            # post a new story
            roll = json.dumps(["bike", "tulip", "happy", "cat", "ladder", "rain"])
            reply = client.post('/stories', data=dict(text="bike tulip happy cat ladder rain", roll=roll), follow_redirects=True)
            assert b'bike tulip happy cat ladder rain' in reply.data

            reply = client.get('/stories')
            assert b'bike tulip happy cat ladder rain' in reply.data

            # add reaction to a story
            reply = client.get('/stories/reaction/1/1')
            print(reply.data)
            assert b'Reaction created' in reply.data

            # add same reaction to a story - delete that reaction
            reply = client.get('/stories/reaction/1/1')
            assert b'Reaction removed!' in reply.data

            # add different reaction to a story
            reply = client.get('/stories/reaction/1/2')
            assert b'Reaction created' in reply.data

            # change the reaction to a story
            reply = client.get('/stories/reaction/1/1')
            assert b'Reaction changed!' in reply.data

            # add reaction to non-existing story
            reply = client.get('/stories/reaction/3/1')
            assert b'Story not exists!' in reply.data
 def test2(self):
     global _app
     if _app is None:
         tested_app = create_app(debug=True)
         _app = tested_app
     else:
         tested_app = _app
     # create 100 Stories
     restart_db_tables(db, tested_app)
     with tested_app.test_client() as client:
         # login
         reply = login(client, '*****@*****.**', 'admin')
         assert b'Hi Admin!' in reply.data
Example #18
0
    def test_delete_story_negative(self):

        global _app
        if _app is None:
            tested_app = create_app(debug=True)
            _app = tested_app
        else:
            tested_app = _app
        restart_db_tables(db, tested_app)

        with tested_app.test_client() as client:

            # login
            reply = login(client, '*****@*****.**', 'admin')
            self.assertEqual(reply.status_code, 200)

            users = User.query.all()
            self.assertEqual(len(users), 1)

            # add reaction to a story
            reply = client.get('/stories/reaction/1/1')
            self.assertEqual(reply.status_code, 200)

            reply = client.post('stories/2/remove/stories',
                                follow_redirects=True)
            self.assertEqual(reply.status_code, 404)

            story = db.session.query(Story).filter_by(id=1).first()
            self.assertNotEqual(story, None)

            reactions = Reaction.query.filter_by(story_id=1).all()
            self.assertEqual(len(reactions), 1)

            stories = Story.query.filter_by(id=1).all()
            self.assertEqual(len(stories), 1)

            users = User.query.all()
            self.assertEqual(len(users), 1)

            reply = client.post('stories/1/remove/stories',
                                follow_redirects=True)
            self.assertEqual(reply.status_code, 200)

            assert b'The story has been canceled.' in reply.data

            reactions = Reaction.query.filter_by(story_id=1).all()
            self.assertEqual(len(reactions), 0)

            # logout
            reply = logout(client)
            self.assertEqual(reply.status_code, 200)
Example #19
0
def test_app():
    app = create_app()

    app.config[
        'WTF_CSRF_ENABLED'] = False  #this has been disabled to allows testing of forms
    temp_db, app.config['DATABASE'] = tempfile.mkstemp()
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE']

    db.create_all(app=app)
    db.init_app(app=app)

    yield app, app.test_client()

    os.close(temp_db)
Example #20
0
def like_task():
    global _APP
    # lazy init
    if _APP is None:
        print("App not yet initialized")
        _APP = create_app()
        db.init_app(_APP)

    with _APP.app_context():
        q = db.engine.execute(
            "SELECT story_id, reaction_type_id, reaction_caption, COUNT(*) AS count, marked "
            "FROM reaction r "
            "JOIN reaction_catalogue rc on r.reaction_type_id = rc.reaction_id "
            "JOIN story s on r.story_id = s.id "
            "WHERE marked=0 OR marked=2 "
            "GROUP BY story_id, reaction_type_id, marked "
            "ORDER BY story_id, reaction_type_id, marked").fetchall()

        print("Analyzing {} reactions: \n".format(len(q)))

        for r in q:
            print("Story {}: {} {}(s) marked to {}".format(
                r.story_id, r.count, r.reaction_caption, r.marked))
            counter_row = Counter.query.filter(
                and_(Counter.reaction_type_id == r.reaction_type_id,
                     Counter.story_id == r['story_id'])).first()
            if r.marked == 0:  # INCREASE COUNTER

                if counter_row is None:  # non-existing counter
                    # Create counter and set it
                    new_counter = Counter()
                    new_counter.reaction_type_id = r.reaction_type_id
                    new_counter.story_id = r.story_id
                    new_counter.counter = r.count
                    db.session.add(new_counter)
                else:  # existing counter
                    counter_row.counter = counter_row.counter + r.count

            else:  # DECREASE COUNTER
                counter_row.counter = counter_row.counter - r.count

            # Delete all the rows with marked = 2
            Reaction.query.filter(Reaction.marked == 2).delete()

            # Update all the rows with marked = 1
            Reaction.query.filter(Reaction.marked == 0).update(
                {Reaction.marked: 1})
        db.session.commit()
Example #21
0
    def test_reduce_list(self):
        tested_app = create_app(debug=True)
        with tested_app.test_client() as client:
            with client.session_transaction():
                user_stories = db.session.query(User, Story) \
                    .join(Story) \
                    .order_by(desc(Story.id))

                user_stories = reduce_list(user_stories)

                users = db.session.query(User)

                for user in users:
                    filtered = list(
                        filter(lambda x: x[0].id == user.id, user_stories))
                    print(user, filtered)
                    self.assertTrue(len(filtered) in [0, 1])
Example #22
0
def app():
    '''
    Builds and configures a new app instance for each test, using the test
    flag and a temporary fresh database. 
    
    Automatically manages the temporary files. 
    
    Can be overridden locally to pass different flags to the app instance, 
    see test_unitStories for reference.
    '''

    db_fd, db_path = tempfile.mkstemp()
    db_url = 'sqlite:///' + db_path
    app = create_app(test=True, database=db_url)

    yield app

    os.close(db_fd)
    os.unlink(db_path)
Example #23
0
def update_reactions(story_id):
    global _APP
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        # db.init_app(app)
    else:
        app = _APP
    with app.app_context():
        q = Story.query.filter_by(id=story_id).first()
        # count the likes, dislikes
        # use the first column for efficiency
        # [https://stackoverflow.com/questions/14754994/why-is-sqlalchemy-count-much-slower-than-the-raw-query]
        num_likes = db.session.query(Reaction.story_id).filter_by(
            story_id=story_id, type=1).count()
        num_dislikes = db.session.query(Reaction.story_id).filter_by(
            story_id=story_id, type=2).count()
        # update likes and dislikes counters
        q.likes = num_likes
        q.dislikes = num_dislikes
        db.session.commit()
Example #24
0
def fetch_all_runs():
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP

    runs_fetched = {}

    with app.app_context():
        q = db.session.query(User)
        for user in q:
            if user.strava_token is None:
                continue
            print('Fetching Strava for %s' % user.email)
            runs_fetched[user.id] = fetch_runs(user)

    return runs_fetched
Example #25
0
def fetch_all_groups():
    global _APP
    # lazy init
    if _APP is None:
        from monolith.app import create_app
        app = create_app()
        db.init_app(app)
    else:
        app = _APP

    groups_fetched = {}

    with app.app_context():
        q = db.session.query(User)
        for user in q:
            if user.gitlab_token is None:
                continue
            print('Fetching Gitlab Groups for %s' % user.email)
            groups_fetched[user.id] = fetch_groups(user)

    return groups_fetched
Example #26
0
    def test_invalid_post_too_long_story(self):

        global _app
        if _app is None:
            tested_app = create_app(debug=True)
            _app = tested_app
        else:
            tested_app = _app
        restart_db_tables(db, tested_app)

        with tested_app.test_client() as client:

            # login
            reply = login(client, '*****@*****.**', 'admin')
            assert b'Hi Admin!' in reply.data
            reply = client.get('/stories')
            assert b'Trial story of example admin user' in reply.data

            # post a new story
            roll = json.dumps(
                ["bird", "whale", "coffee", "bananas", "ladder", "glasses"])

            text = ""
            for i in range(0, 2000):
                text = text + " a"

            print('ERROR 2', file=sys.stderr)

            reply = client.post('/stories',
                                data=dict(text=text, roll=roll),
                                follow_redirects=True)

            self.assertEqual(reply.status_code, 200)

            assert b'The story is too long' in reply.data

            # check database entry
            q = db.session.query(Story).order_by(Story.id.desc()).first()
            self.assertNotEqual(q.text, text)
Example #27
0
    def test_email_sender(self):
        global _app
        if _app is None:
            tested_app = create_app(debug=True)
            _app = tested_app
        else:
            tested_app = _app
        restart_db_tables(db, tested_app)

        with tested_app.test_client() as client:
            with client.session_transaction() as session:
                example2 = User()
                example2.firstname = 'Daniele'
                example2.lastname = 'Arioli'
                example2.email = '*****@*****.**'
                example2.dateofbirth = datetime(2020, 10, 5)
                example2.is_admin = True
                example2.set_password('admin')
                db.session.add(example2)
                db.session.commit()

                self.assertTrue(send_emails())
Example #28
0
import datetime
import random
import unittest
import json
from flask import request, jsonify
from monolith.app import create_app
from monolith.classes.Wall import Wall
from monolith.database import db, User, Story
from monolith.tests.test_stories_reactions import login

test_app = create_app(debug=True)
test_app.app_context().push()


class WallTestCase(unittest.TestCase):
    def test_json_wall(self):
        app = test_app.test_client()

        with app.session_transaction() as sess:
            db.drop_all()
            db.create_all()

        q = db.session.query(User).filter(User.email == '*****@*****.**')
        user = q.first()
        if user is None:
            example = User()
            example.firstname = 'userwall'
            example.lastname = 'theWall'
            example.email = '*****@*****.**'
            example.dateofbirth = datetime.datetime(2020, 10, 5)
            example.is_admin = True
Example #29
0
 def getTester(self):
     application = app.create_app()
     tester = application.test_client(self)
     return tester
Example #30
0
 def setUpClass(self):
     self.app = create_app()
     self.app.test_client_class = FlaskClient