Exemple #1
0
def overview(request):
    """Returns the overview for a daterange.

    GET paramaters:
    * daterange - 7d, 1m, 3m, 6m or 1y (default: 1y)

    Returns an overview dict with a count for all action types.
    """
    form = OverviewAPIForm(request.GET)
    if not form.is_valid():
        return {'success': False, 'errors': form.errors}

    daterange = form.cleaned_data.get('daterange') or '1y'

    mgr = KarmaManager()
    overview = {}
    for t in KarmaManager.action_types.keys():
        overview[t] = mgr.count(daterange, type=t)

    # TODO: Maybe have a karma action not assigned to a user for this?
    num_days = KarmaManager.date_ranges[daterange]
    start_day = date.today() - timedelta(days=num_days)
    overview['question'] = Question.objects.filter(
        created__gt=start_day).count()

    return {
        'success': True,
        'overview': overview}
Exemple #2
0
def overview(request):
    """Returns the overview for a daterange.

    GET paramaters:
    * daterange - 7d, 1m, 3m, 6m or 1y (default: 1y)

    Returns an overview dict with a count for all action types.
    """
    form = OverviewAPIForm(request.GET)
    if not form.is_valid():
        return {'success': False, 'errors': form.errors}

    daterange = form.cleaned_data.get('daterange') or '1y'

    mgr = KarmaManager()
    overview = {}
    for t in KarmaManager.action_types.keys():
        overview[t] = mgr.count(daterange, type=t)

    # TODO: Maybe have a karma action not assigned to a user for this?
    num_days = KarmaManager.date_ranges[daterange]
    start_day = date.today() - timedelta(days=num_days)
    overview['question'] = Question.objects.filter(
        created__gt=start_day).count()

    return {'success': True, 'overview': overview}
Exemple #3
0
def users(request):
    """Returns list of user karma information.

    GET paramaters:
    * daterange - 7d, 1m, 3m, 6m or 1y (default: 1y)
    * sort - field to sort on (default: points). Order is always descending.
    * page - starts at 1 (default: 1)
    * pagesize - (default: 100)

    Returns list of objects with the following fields:
        userid, username, points, <action_types>
    """
    form = UserAPIForm(request.GET)
    if not form.is_valid():
        return {'success': False, 'errors': form.errors}

    daterange = form.cleaned_data.get('daterange') or '1y'
    sort = form.cleaned_data.get('sort') or 'points'
    page = form.cleaned_data.get('page') or 1
    pagesize = form.cleaned_data.get('pagesize') or 100

    mgr = KarmaManager()
    users = mgr.top_users(daterange, type=sort, count=pagesize,
                          offset=(page - 1) * pagesize) or []

    now = datetime.now()
    action_types = KarmaManager.action_types.keys()
    schema = ['id', 'username', 'lastactivity', 'points'] + action_types
    user_list = []
    for u in users:
        user = [u.id, u.username]
        last_activity = Answer.last_activity_for(u)
        user.append((now - last_activity).days if last_activity else None)
        user.append(mgr.count(daterange, u, type='points'))
        for t in action_types:
            user.append(mgr.count(daterange, u, type=t))
        user_list.append(user)

    return {
        'success': True,
        'results': user_list,
        'schema': schema}
Exemple #4
0
def users(request):
    """Returns list of user karma information.

    GET paramaters:
    * daterange - 7d, 1m, 3m, 6m or 1y (default: 1y)
    * sort - field to sort on (default: points). Order is always descending.
    * page - starts at 1 (default: 1)
    * pagesize - (default: 100)

    Returns list of objects with the following fields:
        userid, username, points, <action_types>
    """
    form = UserAPIForm(request.GET)
    if not form.is_valid():
        return {'success': False, 'errors': form.errors}

    daterange = form.cleaned_data.get('daterange') or '1y'
    sort = form.cleaned_data.get('sort') or 'points'
    page = form.cleaned_data.get('page') or 1
    pagesize = form.cleaned_data.get('pagesize') or 100

    mgr = KarmaManager()
    users = mgr.top_users(
        daterange, type=sort, count=pagesize,
        offset=(page - 1) * pagesize) or []

    now = datetime.now()
    action_types = KarmaManager.action_types.keys()
    schema = ['id', 'username', 'lastactivity', 'points'] + action_types
    user_list = []
    for u in users:
        user = [u.id, u.username]
        last_activity = Answer.last_activity_for(u)
        user.append((now - last_activity).days if last_activity else None)
        user.append(mgr.count(daterange, u, type='points'))
        for t in action_types:
            user.append(mgr.count(daterange, u, type=t))
        user_list.append(user)

    return {'success': True, 'results': user_list, 'schema': schema}
Exemple #5
0
def user_num_answers(user):
    """Count the number of answers a user has.

    If karma is enabled, and redis is working, this will query that (much
    faster), otherwise it will just count objects in the database.
    """
    if waffle.switch_is_active('karma'):
        try:
            km = KarmaManager()
            count = km.count(user=user, type=AnswerAction.action_type)
            if count is not None:
                return count
        except RedisError as e:
            statsd.incr('redis.errror')
            log.error('Redis connection error: %s' % e)

    return Answer.objects.filter(creator=user).count()
Exemple #6
0
def user_num_answers(user):
    """Count the number of answers a user has.

    If karma is enabled, and redis is working, this will query that (much
    faster), otherwise it will just count objects in the database.
    """
    if waffle.switch_is_active('karma'):
        try:
            km = KarmaManager()
            count = km.count(user=user, type=AnswerAction.action_type)
            if count is not None:
                return count
        except RedisError as e:
            statsd.incr('redis.errror')
            log.error('Redis connection error: %s' % e)

    return Answer.objects.filter(creator=user).count()
Exemple #7
0
def user_num_solutions(user):
    """Count the number of solutions a user has.

    This means the number of answers the user has submitted that are then
    marked as the solution to the question they belong to.

    If karma is enabled, and redis is working, this will query that (much
    faster), otherwise it will just count objects in the database.
    """
    if waffle.switch_is_active("karma"):
        try:
            km = KarmaManager()
            count = km.count(user=user, type=SolutionAction.action_type)
            if count is not None:
                return count
        except RedisError as e:
            statsd.incr("redis.errror")
            log.error("Redis connection error: %s" % e)

    return Question.objects.filter(solution__in=Answer.objects.filter(creator=user)).count()
Exemple #8
0
def user_num_solutions(user):
    """Count the number of solutions a user has.

    This means the number of answers the user has submitted that are then
    marked as the solution to the question they belong to.

    If karma is enabled, and redis is working, this will query that (much
    faster), otherwise it will just count objects in the database.
    """
    if waffle.switch_is_active('karma'):
        try:
            km = KarmaManager()
            count = km.count(user=user, type=SolutionAction.action_type)
            if count is not None:
                return count
        except RedisError as e:
            statsd.incr('redis.errror')
            log.error('Redis connection error: %s' % e)

    return Question.objects.filter(solution__in=Answer.objects.filter(
        creator=user)).count()
Exemple #9
0
class KarmaActionTests(TestCase):
    def setUp(self):
        super(KarmaActionTests, self).setUp()
        self.user = user(save=True)
        try:
            self.mgr = KarmaManager()
            redis_client('karma').flushdb()
        except RedisError:
            raise SkipTest

    @mock.patch.object(waffle, 'switch_is_active')
    def test_action(self, switch_is_active):
        """Save an action and verify."""
        switch_is_active.return_value = True
        TestAction1(user=self.user).save()
        eq_(3, self.mgr.count('all', self.user, type='points'))
        eq_(1, self.mgr.count('all', self.user, type=TestAction1.action_type))
        today = date.today()
        eq_(1, self.mgr.day_count(self.user, today, TestAction1.action_type))
        eq_(
            1,
            self.mgr.month_count(self.user, today.year, today.month,
                                 TestAction1.action_type))
        eq_(
            1,
            self.mgr.year_count(self.user, today.year,
                                TestAction1.action_type))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_two_actions(self, switch_is_active):
        """Save two actions, one twice, and verify."""
        switch_is_active.return_value = True
        TestAction1(user=self.user).save()
        TestAction2(user=self.user).save()
        TestAction2(user=self.user).save()
        eq_(17, self.mgr.count('all', self.user, type='points'))
        eq_(1, self.mgr.count('all', self.user, type=TestAction1.action_type))
        eq_(2, self.mgr.count('all', self.user, type=TestAction2.action_type))
        today = date.today()
        eq_(1, self.mgr.day_count(self.user, today, TestAction1.action_type))
        eq_(
            1,
            self.mgr.month_count(self.user, today.year, today.month,
                                 TestAction1.action_type))
        eq_(
            1,
            self.mgr.year_count(self.user, today.year,
                                TestAction1.action_type))
        eq_(2, self.mgr.day_count(self.user, today, TestAction2.action_type))
        eq_(
            2,
            self.mgr.month_count(self.user, today.year, today.month,
                                 TestAction2.action_type))
        eq_(
            2,
            self.mgr.year_count(self.user, today.year,
                                TestAction2.action_type))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_delete_action(self, switch_is_active):
        """Save two actions, one twice, and verify."""
        switch_is_active.return_value = True
        today = date.today()

        # Create two TestAction1s and verify counts.
        TestAction1(user=self.user).save()
        TestAction1(user=self.user).save()
        eq_(6, self.mgr.count('all', self.user, type='points'))
        eq_(2, self.mgr.count('all', self.user, type=TestAction1.action_type))
        today = date.today()
        eq_(2, self.mgr.day_count(self.user, today, TestAction1.action_type))
        eq_(
            2,
            self.mgr.month_count(self.user, today.year, today.month,
                                 TestAction1.action_type))
        eq_(
            2,
            self.mgr.year_count(self.user, today.year,
                                TestAction1.action_type))

        # Delete one and verify new counts
        TestAction1(user=self.user).delete()
        eq_(3, self.mgr.count('all', self.user, type='points'))
        eq_(1, self.mgr.count('all', self.user, type=TestAction1.action_type))
        today = date.today()
        eq_(1, self.mgr.day_count(self.user, today, TestAction1.action_type))
        eq_(
            1,
            self.mgr.month_count(self.user, today.year, today.month,
                                 TestAction1.action_type))
        eq_(
            1,
            self.mgr.year_count(self.user, today.year,
                                TestAction1.action_type))

        # Delete the other and verify all zeroes
        TestAction1(user=self.user).delete()
        eq_(0, self.mgr.count('all', self.user, type='points'))
        eq_(0, self.mgr.count('all', self.user, type=TestAction1.action_type))
        today = date.today()
        eq_(0, self.mgr.day_count(self.user, today, TestAction1.action_type))
        eq_(
            0,
            self.mgr.month_count(self.user, today.year, today.month,
                                 TestAction1.action_type))
        eq_(
            0,
            self.mgr.year_count(self.user, today.year,
                                TestAction1.action_type))
Exemple #10
0
class KarmaManagerTests(TestCase):
    @mock.patch.object(waffle, 'switch_is_active')
    def setUp(self, switch_is_active):
        switch_is_active.return_value = True

        super(KarmaManagerTests, self).setUp()

        try:
            self.mgr = KarmaManager()
            redis_client('karma').flushdb()
        except RedisError:
            raise SkipTest

        self.user1 = user(save=True)
        self.user2 = user(save=True)
        self.user3 = user(save=True)

        today = date.today()

        # user1 actions (3 + 3 + 7):
        TestAction1(user=self.user1, day=today).save()
        TestAction1(user=self.user1, day=today).save()
        TestAction2(user=self.user1, day=today).save()

        # user2 actions (3 + 7 + 7):
        TestAction1(user=self.user2, day=today - timedelta(days=8)).save()
        TestAction2(user=self.user2, day=today - timedelta(days=32)).save()
        TestAction2(user=self.user2, day=today - timedelta(days=360)).save()

        # user3 actions (3 + 3 + 3 + 7):
        TestAction1(user=self.user3, day=today - timedelta(days=10)).save()
        TestAction1(user=self.user3, day=today - timedelta(days=40)).save()
        TestAction1(user=self.user3, day=today - timedelta(days=190)).save()
        TestAction2(user=self.user3, day=today - timedelta(days=3)).save()

    @mock.patch.object(waffle, 'switch_is_active')
    def test_count(self, switch_is_active):
        """Test count method."""
        switch_is_active.return_value = True
        self.mgr.update_top()
        eq_(13, self.mgr.count('all', self.user1, type='points'))
        eq_(2, self.mgr.count('all', self.user1, type=TestAction1.action_type))
        eq_(1, self.mgr.count('all', self.user1, type=TestAction2.action_type))
        eq_(0, self.mgr.count('1w', self.user2, type='points'))
        eq_(3, self.mgr.count('1m', self.user2, type='points'))
        eq_(2, self.mgr.count('1y', self.user2, type=TestAction2.action_type))
        eq_(2, self.mgr.count('6m', self.user3, type=TestAction1.action_type))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_top_users(self, switch_is_active):
        """Test top_users method."""
        switch_is_active.return_value = True
        self.mgr.update_top()
        u1, u2, u3 = self.user1, self.user2, self.user3
        eq_([u3, u1, u2], self.mgr.top_users('3m'))
        eq_([u3, u1, u2], self.mgr.top_users('all',
                                             type=TestAction1.action_type))
        eq_([u3, u1, u2], self.mgr.top_users('all',
                                             type=TestAction1.action_type))
        eq_([u1], self.mgr.top_users('1w', type=TestAction1.action_type))
        eq_([u1, u3], self.mgr.top_users(daterange='1w'))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_ranking(self, switch_is_active):
        """Test ranking method."""
        switch_is_active.return_value = True
        self.mgr.update_top()
        eq_(1, self.mgr.ranking('all', self.user2))
        eq_(3, self.mgr.ranking('all', self.user1))
        eq_(1, self.mgr.ranking('1w', self.user1))
        eq_(1, self.mgr.ranking('all', self.user3,
                                type=TestAction1.action_type))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_recalculate_points(self, switch_is_active):
        """Test the recalculate_points method."""
        switch_is_active.return_value = True

        # Create Points with new point values.
        p1 = Points.objects.create(action='test-action-1', points=15)
        Points.objects.create(action='test-action-2', points=12)

        self.mgr.recalculate_points(self.user1)
        eq_(42, self.mgr.count('all', self.user1, type='points'))

        # Update one of the Point values.
        p1.points = 30
        p1.save()

        self.mgr.recalculate_points(self.user1)
        eq_(72, self.mgr.count('all', self.user1, type='points'))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_overview_counts(self, switch_is_active):
        """Verify the overview counts are correct."""
        switch_is_active.return_value = True
        self.mgr.update_top()
        eq_(46, self.mgr.count('all', type='points'))
        eq_(6, self.mgr.count('all', type=TestAction1.action_type))
        eq_(4, self.mgr.count('all', type=TestAction2.action_type))
        eq_(2, self.mgr.count('1w', type=TestAction1.action_type))
        eq_(2, self.mgr.count('1m', type=TestAction2.action_type))
        eq_(3, self.mgr.count('6m', type=TestAction2.action_type))
        eq_(2, self.mgr.day_count(type=TestAction1.action_type))
        eq_(1, self.mgr.day_count(type=TestAction2.action_type))
Exemple #11
0
class KarmaManagerTests(TestCase):
    @mock.patch.object(waffle, 'switch_is_active')
    def setUp(self, switch_is_active):
        switch_is_active.return_value = True

        super(KarmaManagerTests, self).setUp()

        try:
            self.mgr = KarmaManager()
            redis_client('karma').flushdb()
        except RedisError:
            raise SkipTest

        self.user1 = user(save=True)
        self.user2 = user(save=True)
        self.user3 = user(save=True)

        today = date.today()

        # user1 actions (3 + 3 + 7):
        TestAction1(user=self.user1, day=today).save()
        TestAction1(user=self.user1, day=today).save()
        TestAction2(user=self.user1, day=today).save()

        # user2 actions (3 + 7 + 7):
        TestAction1(user=self.user2, day=today - timedelta(days=8)).save()
        TestAction2(user=self.user2, day=today - timedelta(days=32)).save()
        TestAction2(user=self.user2, day=today - timedelta(days=360)).save()

        # user3 actions (3 + 3 + 3 + 7):
        TestAction1(user=self.user3, day=today - timedelta(days=10)).save()
        TestAction1(user=self.user3, day=today - timedelta(days=40)).save()
        TestAction1(user=self.user3, day=today - timedelta(days=190)).save()
        TestAction2(user=self.user3, day=today - timedelta(days=3)).save()

    @mock.patch.object(waffle, 'switch_is_active')
    def test_count(self, switch_is_active):
        """Test count method."""
        switch_is_active.return_value = True
        self.mgr.update_top()
        eq_(13, self.mgr.count('all', self.user1, type='points'))
        eq_(2, self.mgr.count('all', self.user1, type=TestAction1.action_type))
        eq_(1, self.mgr.count('all', self.user1, type=TestAction2.action_type))
        eq_(0, self.mgr.count('1w', self.user2, type='points'))
        eq_(3, self.mgr.count('1m', self.user2, type='points'))
        eq_(2, self.mgr.count('1y', self.user2, type=TestAction2.action_type))
        eq_(2, self.mgr.count('6m', self.user3, type=TestAction1.action_type))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_top_users(self, switch_is_active):
        """Test top_users method."""
        switch_is_active.return_value = True
        self.mgr.update_top()
        u1, u2, u3 = self.user1, self.user2, self.user3
        eq_([u3, u1, u2], self.mgr.top_users('3m'))
        eq_([u3, u1, u2],
            self.mgr.top_users('all', type=TestAction1.action_type))
        eq_([u3, u1, u2],
            self.mgr.top_users('all', type=TestAction1.action_type))
        eq_([u1], self.mgr.top_users('1w', type=TestAction1.action_type))
        eq_([u1, u3], self.mgr.top_users(daterange='1w'))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_ranking(self, switch_is_active):
        """Test ranking method."""
        switch_is_active.return_value = True
        self.mgr.update_top()
        eq_(1, self.mgr.ranking('all', self.user2))
        eq_(3, self.mgr.ranking('all', self.user1))
        eq_(1, self.mgr.ranking('1w', self.user1))
        eq_(1, self.mgr.ranking('all',
                                self.user3,
                                type=TestAction1.action_type))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_recalculate_points(self, switch_is_active):
        """Test the recalculate_points method."""
        switch_is_active.return_value = True

        # Create Points with new point values.
        p1 = Points.objects.create(action='test-action-1', points=15)
        Points.objects.create(action='test-action-2', points=12)

        self.mgr.recalculate_points(self.user1)
        eq_(42, self.mgr.count('all', self.user1, type='points'))

        # Update one of the Point values.
        p1.points = 30
        p1.save()

        self.mgr.recalculate_points(self.user1)
        eq_(72, self.mgr.count('all', self.user1, type='points'))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_overview_counts(self, switch_is_active):
        """Verify the overview counts are correct."""
        switch_is_active.return_value = True
        self.mgr.update_top()
        eq_(46, self.mgr.count('all', type='points'))
        eq_(6, self.mgr.count('all', type=TestAction1.action_type))
        eq_(4, self.mgr.count('all', type=TestAction2.action_type))
        eq_(2, self.mgr.count('1w', type=TestAction1.action_type))
        eq_(2, self.mgr.count('1m', type=TestAction2.action_type))
        eq_(3, self.mgr.count('6m', type=TestAction2.action_type))
        eq_(2, self.mgr.day_count(type=TestAction1.action_type))
        eq_(1, self.mgr.day_count(type=TestAction2.action_type))
Exemple #12
0
class KarmaActionTests(TestCase):
    def setUp(self):
        super(KarmaActionTests, self).setUp()
        self.user = user(save=True)
        try:
            self.mgr = KarmaManager()
            redis_client('karma').flushdb()
        except RedisError:
            raise SkipTest

    @mock.patch.object(waffle, 'switch_is_active')
    def test_action(self, switch_is_active):
        """Save an action and verify."""
        switch_is_active.return_value = True
        TestAction1(user=self.user).save()
        eq_(3, self.mgr.count('all', self.user, type='points'))
        eq_(1, self.mgr.count('all', self.user, type=TestAction1.action_type))
        today = date.today()
        eq_(1, self.mgr.day_count(self.user, today, TestAction1.action_type))
        eq_(1, self.mgr.month_count(self.user, today.year,
                                    today.month, TestAction1.action_type))
        eq_(1, self.mgr.year_count(self.user, today.year,
                                   TestAction1.action_type))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_two_actions(self, switch_is_active):
        """Save two actions, one twice, and verify."""
        switch_is_active.return_value = True
        TestAction1(user=self.user).save()
        TestAction2(user=self.user).save()
        TestAction2(user=self.user).save()
        eq_(17, self.mgr.count('all', self.user, type='points'))
        eq_(1, self.mgr.count('all', self.user, type=TestAction1.action_type))
        eq_(2, self.mgr.count('all', self.user, type=TestAction2.action_type))
        today = date.today()
        eq_(1, self.mgr.day_count(self.user, today, TestAction1.action_type))
        eq_(1, self.mgr.month_count(self.user, today.year, today.month,
                                    TestAction1.action_type))
        eq_(1, self.mgr.year_count(self.user, today.year,
                                   TestAction1.action_type))
        eq_(2, self.mgr.day_count(self.user, today, TestAction2.action_type))
        eq_(2, self.mgr.month_count(self.user, today.year, today.month,
                                    TestAction2.action_type))
        eq_(2, self.mgr.year_count(self.user, today.year,
                                   TestAction2.action_type))

    @mock.patch.object(waffle, 'switch_is_active')
    def test_delete_action(self, switch_is_active):
        """Save two actions, one twice, and verify."""
        switch_is_active.return_value = True
        today = date.today()

        # Create two TestAction1s and verify counts.
        TestAction1(user=self.user).save()
        TestAction1(user=self.user).save()
        eq_(6, self.mgr.count('all', self.user, type='points'))
        eq_(2, self.mgr.count('all', self.user, type=TestAction1.action_type))
        today = date.today()
        eq_(2, self.mgr.day_count(self.user, today, TestAction1.action_type))
        eq_(2, self.mgr.month_count(self.user, today.year,
                                    today.month, TestAction1.action_type))
        eq_(2, self.mgr.year_count(self.user, today.year,
                                   TestAction1.action_type))

        # Delete one and verify new counts
        TestAction1(user=self.user).delete()
        eq_(3, self.mgr.count('all', self.user, type='points'))
        eq_(1, self.mgr.count('all', self.user, type=TestAction1.action_type))
        today = date.today()
        eq_(1, self.mgr.day_count(self.user, today, TestAction1.action_type))
        eq_(1, self.mgr.month_count(self.user, today.year,
                                    today.month, TestAction1.action_type))
        eq_(1, self.mgr.year_count(self.user, today.year,
                                   TestAction1.action_type))

        # Delete the other and verify all zeroes
        TestAction1(user=self.user).delete()
        eq_(0, self.mgr.count('all', self.user, type='points'))
        eq_(0, self.mgr.count('all', self.user, type=TestAction1.action_type))
        today = date.today()
        eq_(0, self.mgr.day_count(self.user, today, TestAction1.action_type))
        eq_(0, self.mgr.month_count(self.user, today.year,
                                    today.month, TestAction1.action_type))
        eq_(0, self.mgr.year_count(self.user, today.year,
                                   TestAction1.action_type))