Esempio n. 1
0
    def test_ui(self):
        if os.environ.get('CI'):
            pass
        else:
            u1 = User(username="******")
            u2 = User(username="******")
            u3 = User(username="******")
            u4 = User(username="******")

            db.session.add(u1)
            db.session.add(u2)
            db.session.add(u3)
            db.session.add(u4)

            s1 = Subreddit(name='nfl')
            s2 = Subreddit(name='askreddit')
            s3 = Subreddit(name='pics')
            s4 = Subreddit(name='funny')

            u1.favorite(s1)
            u2.favorite(s1)
            u4.favorite(s1)

            db.session.commit()

            success = execute_js('./register-accept-chat.js')
            assert success
Esempio n. 2
0
    def test_favorite(self):
        u1 = User(username='******',email='*****@*****.**')
        u2 = User(username='******')

        s1 = Subreddit(name='trees')
        s2 = Subreddit(name='nsfw')

        db.session.add(u1)
        db.session.add(u2)
        db.session.add(s1)
        db.session.add(s2)

        db.session.commit()

        assert not u1.has_favorite(s1)
        assert u1.favorited_subs().count() == 0

        s = u1.favorite(s1)

        db.session.add(s)
        db.session.commit()

        assert u1.has_favorite(s1)
        assert u1.favorited_subs().count() == 1

        s = u1.favorite(s1)

        assert u1.has_favorite(s1)
        assert u1.favorited_subs().count() == 1
Esempio n. 3
0
    def test_can_save_subreddit_instance(self):
        sbr = {
            'name': 'random',
            'desc': 'This is a testing and random subreddit'
        }

        new_subreddit = Subreddit(name=sbr['name'], description=sbr['desc'])
        new_subreddit.save()

        self.assertEqual(Subreddit.query.count(), 4)
Esempio n. 4
0
def search():
    if not g.search_form.validate():
        return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    target_index = request.args.get('index', 'thread')
    if target_index == 'thread':
        results, total = Thread.search(g.search_form.q.data, page,
                                       app.config['POSTS_PER_PAGE'])
    elif target_index == 'user':
        results, total = User.search(g.search_form.q.data, page,
                                     app.config['POSTS_PER_PAGE'])
    elif target_index == 'subreddit':
        results, total = Subreddit.search(g.search_form.q.data, page,
                                          app.config['POSTS_PER_PAGE'])
    else:
        return render_template('404.html')

    results = results.all()
    next_url = url_for(
        'search', index=target_index, q=g.search_form.q.data, page=page +
        1) if total > page * app.config['POSTS_PER_PAGE'] else None
    prev_url = url_for(
        'search', index=target_index, q=g.search_form.q.data, page=page -
        1) if page > 1 else None
    return render_template('search.html',
                           title=_('Search'),
                           results=results,
                           next_url=next_url,
                           prev_url=prev_url,
                           query=g.search_form.q.data,
                           query_language=guess_language(g.search_form.q.data),
                           index=target_index)
Esempio n. 5
0
    def test_can_create_subreddit_instance(self):
        sbr = {
            'name': 'random',
            'desc': 'This is a testing and random subreddit'
        }

        new_subreddit = Subreddit(name=sbr['name'], description=sbr['desc'])

        self.assertEqual(new_subreddit.name, sbr['name'])
        self.assertEqual(new_subreddit.description, sbr['desc'])
Esempio n. 6
0
def create_subreddit():
    """
    Creates a new subreddit
    """
    form = SubredditForm()
    print(request.get_json())
    form['csrf_token'].data = request.cookies['csrf_token']
    print(current_user.id)
    if form.validate_on_submit():
        try:
            subreddit = Subreddit(name=form.data['name'],
                                  about=form.data['about'],
                                  rules=form.data['rules'],
                                  owner=current_user.id)
            db.session.add(subreddit)
            db.session.commit()
            return subreddit.to_dict()
        except IntegrityError:
            return {"errors": "Subreddit already exists."}
    return {'errors': validation_errors_to_error_messages(form.errors)}, 401
    def archive_subreddit(self, sub):
        queried_sub = self.db_session.query(Subreddit).filter(Subreddit.id == sub.id).first()

        # if sub not in table, add it
        if not queried_sub:
            new_sub = Subreddit(id = sub.id, 
                                name = sub.display_name)
            self.db_session.add(new_sub)
            self.db_session.commit()
            return True

        # else don't add it to subreddit table
        return False
Esempio n. 8
0
def create_subreddit():
    form = CreateSubredditForm()
    if form.validate_on_submit():
        subreddit_language = guess_language(form.description.data)
        if subreddit_language == 'UNKNOWN' or len(subreddit_language) > 5:
            subreddit_language = ''
        new_subreddit = Subreddit(name=form.name.data,
                                  description=form.description.data,
                                  language=subreddit_language)
        db.session.add(new_subreddit)
        db.session.commit()
        return redirect(session['prior_thread_create_page'])
    return render_template('create_subreddit.html',
                           form=form,
                           page_title=_('Reddit - Create Subreddit'))
Esempio n. 9
0
def index():
    form = IndexForm()
    if form.tag_form.submit_tag.data and form.tag_form.validate(form):
        tag_input = form.tag_form.tag.data
        query_user_tag = current_user.tags.filter(
            Tag.text == tag_input).first()
        if query_user_tag is not None:
            flash('You have already added this tag')
        else:
            tag = Tag.query.filter_by(text=tag_input).first()
            if tag is None:
                tag = Tag(text=tag_input)
                db.session.add(tag)
            current_user.tags.append(tag)
            db.session.commit()
            flash('Your tag has been saved')
        return redirect(url_for('main.index'))
    if (form.subreddit_form.submit_subreddit.data
            and form.subreddit_form.validate(form)):
        subreddit_input = form.subreddit_form.subreddit.data
        if not sub_exists(subreddit_input):
            flash(f'There aren\'t any subreddit with name: {subreddit_input}')
        else:
            query_user_subreddit = current_user.subreddits \
                .filter(Subreddit.sub == subreddit_input).first()
            if query_user_subreddit is not None:
                flash('You have already added this subreddit')
            else:
                subreddit = Subreddit.query.filter_by(
                    sub=subreddit_input).first()
                if subreddit is None:
                    subreddit = Subreddit(sub=subreddit_input)
                    db.session.add(subreddit)
                current_user.subreddits.append(subreddit)
                db.session.commit()
                flash('Subreddit saved')
            return redirect(url_for('main.index'))
    tags = [tag.text for tag in current_user.tags.all()]
    subreddits = current_user.subreddits.all()
    submissions = get_tagged_submissions()
    return render_template('index.html',
                           title='Home',
                           form=form,
                           tags=tags,
                           subreddits=subreddits,
                           submissions=submissions,
                           data=json.dumps(tags))
Esempio n. 10
0
 def test_subreddits(self):
     with self.app.test_request_context():
         sub = Subreddit(subreddit_id='123',
                         display_name='display',
                         subscribers=10,
                         accounts_active=4,
                         title='test',
                         created_utc=datetime(2012, 4, 2),
                         icon_img='icon_url',
                         banner_img='banner_url')
         self.assertIsNotNone(sub)
         subreddit_query = self.session.query(
             Subreddit).filter_by(display_name="politics").first()
         self.assertEqual(subreddit_query.title, "Politics")
         self.assertEqual(subreddit_query.subscribers, 3343705)
         self.assertEqual(subreddit_query.accounts_active, 16918)
         self.assertEqual(subreddit_query.subreddit_id, "2cneq")
         self.assertEqual(str(subreddit_query.created_utc),
                          "2007-08-06 00:16:39")
Esempio n. 11
0
    def test_subreddit(self):
        u1 = User(username='******', email='*****@*****.**')
        db.session.add(u1)
        db.session.commit()
        self.assertEqual(u1.subreddits.all(), [])

        # Add Subreddit
        subreddit = Subreddit(sub='popular')
        db.session.add(subreddit)
        u1.subreddits.append(subreddit)
        db.session.commit()

        self.assertTrue(u1.subreddits.all() == [subreddit])
        self.assertEqual(u1.subreddits.count(), 1)
        self.assertEqual(u1.subreddits.first().sub, 'popular')

        # Delete Subreddit
        u1.subreddits.remove(subreddit)
        db.session.commit()
        self.assertEqual(u1.subreddits.all(), [])
Esempio n. 12
0
def test_archive_last_thousand_comments(mock_reddit):
    r = mock_reddit.return_value
    log = app.cs_logger.get_logger(ENV, BASE_DIR)

    subreddit_name = "science"
    subreddit_id = "mouw"

    comment_fixtures = []
    for filename in glob.glob(
            "{script_dir}/fixture_data/comments*".format(script_dir=TEST_DIR)):
        f = open(filename, "r")
        comment_fixtures.append(json.loads(f.read()))
        f.close()

    m = Mock()
    m.side_effect = [
        comment_fixtures[0][0:100], comment_fixtures[0][100:200],
        comment_fixtures[0][200:300], comment_fixtures[0][300:400],
        comment_fixtures[0][400:500], comment_fixtures[0][500:600],
        comment_fixtures[0][600:700], comment_fixtures[0][700:800],
        comment_fixtures[0][800:900], comment_fixtures[0][900:], []
    ]

    r.get_comments = m
    patch('praw.')

    ## add science subreddit
    db_session.add(Subreddit(id=subreddit_id, name=subreddit_name))
    db_session.commit()

    cc = app.controllers.comment_controller.CommentController(
        db_session, r, log)

    assert db_session.query(Comment).count() == 0
    cc.archive_last_thousand_comments(subreddit_name)
    assert db_session.query(Comment).count() == 1000

    db_comment = db_session.query(Comment).order_by(
        app.models.Comment.created_utc.asc()).first()
    assert db_comment.subreddit_id == subreddit_id
    assert db_comment.post_id == comment_fixtures[0][-1]['link_id'].replace(
        "t3_", "")
    assert db_comment.user_id == comment_fixtures[0][-1]['author']
    assert len(db_comment.comment_data) > 0

    ## NOW TEST THAT NO OVERLAPPING IDS ARE ADDED
    first_ids = [x['id'] for x in comment_fixtures[0]]
    second_ids = [
        x['id'] for x in comment_fixtures[1] if (x['id'] in first_ids) != True
    ]

    m = Mock()
    m.side_effect = [
        comment_fixtures[1][0:100], comment_fixtures[1][100:200],
        comment_fixtures[1][200:300], comment_fixtures[1][300:400],
        comment_fixtures[1][400:500], comment_fixtures[1][500:600],
        comment_fixtures[1][600:700], comment_fixtures[1][700:800],
        comment_fixtures[1][800:900], comment_fixtures[1][900:], []
    ]
    r.get_comments = m
    patch('praw.')
    cc.archive_last_thousand_comments(subreddit_name)
    db_session.commit()
    assert db_session.query(
        Comment).count() == len(first_ids) + len(second_ids)
Esempio n. 13
0
def seed_subreddits(user_list):
    subreddit_list = [
        Subreddit(
            name='AskReddit',
            about='Ask the community your deepest curiosities',
            rules='No profanity#Open ended questions only#No loaded questions#',
            owner=user_list[0].id
        ),
        Subreddit(
            name='FunTimes',
            about='Fun times for great minds',
            rules='No profanity#Optimism only#Stay happy#Stay friendly#',
            owner=user_list[1].id
        ),
        Subreddit(
            name='DoggoTown',
            about='The best place to show off your best friend',
            rules='No profanity#No cats allowed#Bark Bark#',
            owner=user_list[2].id
        ),
        Subreddit(
            name='DecoratingTips',
            about='Display your chic house decor',
            rules='No profanity#Pictures only#Office space only#Keep comments constructive#',
            owner=user_list[3].id
        ),
        Subreddit(
            name='HoldMyCatnip',
            about='Cats on the herb are totally preferred',
            rules='No profanity#No dogs#Pictures only#',
            owner=user_list[4].id
        ),
        Subreddit(
            name='ScaryStories',
            about='Dive into the depths of the unknown',
            rules='No profanity#No graphic images#',
            owner=user_list[5].id
        ),
        Subreddit(
            name='NatureIsLit',
            about='Prove the beauty of mother nature',
            rules='No profanity#Images only#No Nudity#',
            owner=user_list[6].id
        ),
        Subreddit(
            name='CodingLife',
            about='Everything coding related from fails to first try success',
            rules='No profanity#No Jinja#',
            owner=user_list[7].id
        ),
        Subreddit(
            name='WholesomeMemes',
            about='Kappa',
            rules='#No pepe#wut#',
            owner=user_list[8].id
        ),
        Subreddit(
            name='Covid19',
            about='The one thing keeping you out of bars',
            rules='Face mask required#No coughing#Are you running a fever#',
            owner=user_list[9].id
        ),
        Subreddit(
            name='TravelPack',
            about='Share stories, pictures, and tips of your travels',
            rules='No profanity#Constructive criticism only#Clean images#',
            owner=user_list[10].id
        ),
        Subreddit(
            name='GamersGazebo',
            about='Everything Gaming',
            rules='No profanity#Pc is master race#Minecraft OGs are royalty#',
            owner=user_list[11].id
        ),
        Subreddit(
            name='NewsCorner',
            about='Share news stories and your opinions',
            rules='No profanity#Keep conversations civil and constructive#Creditable sources only#',
            owner=user_list[12].id
        ),
        Subreddit(
            name='TechLab',
            about='Share cool inventions, upcomming tech advancements, and other tech news',
            rules='No profanity#Creditable sources only#',
            owner=user_list[13].id
        ),
        Subreddit(
            name='CollectorsShowcase',
            about='Show off what you are collecting and maybe tell a story as to why',
            rules='No profanity#Keep things clean#',
            owner=user_list[14].id
        ),
    ]

    db.session.add_all(subreddit_list)
    db.session.commit()
    return subreddit_list
Esempio n. 14
0
    def test_get_favorited_users(self):
        u1 = User(username="******")
        u2 = User(username="******")
        u3 = User(username="******")
        u4 = User(username="******")

        db.session.add(u1)
        db.session.add(u2)
        db.session.add(u3)
        db.session.add(u4)

        db.session.commit()

        s1 = Subreddit(name='nfl')
        s2 = Subreddit(name='askreddit')
        s3 = Subreddit(name='pics')
        s4 = Subreddit(name='funny')

        u1.favorite(s1)
        u2.favorite(s1)
        u4.favorite(s1)

        assert s1.favorited_users().count() == 3
        assert s2.favorited_users().count() == 0

        assert u1 and u2 and u4 in s1.favorited_users().all()

        u1.unfavorite_all()

        assert s1.favorited_users().count() == 2
        assert u1 not in s1.favorited_users().all()
        assert u2 and u4 in s1.favorited_users().all()