"""Tests for django comment client views."""
from contextlib import contextmanager
import logging
import json
import ddt
from django.conf import settings
from django.core.cache import get_cache
from django.test.client import Client, RequestFactory
from django.contrib.auth.models import User
from django.core.management import call_command
from django.core.urlresolvers import reverse
from request_cache.middleware import RequestCache
from mock import patch, ANY, Mock
from nose.tools import assert_true, assert_equal  # pylint: disable=no-name-in-module
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from lms.lib.comment_client import Thread
from common.test.utils import MockSignalHandlerMixin, disable_signal
from django_comment_client.base import views
from django_comment_client.tests.group_id import CohortedTopicGroupIdTestMixin, NonCohortedTopicGroupIdTestMixin, GroupIdAssertionMixin
from django_comment_client.tests.utils import CohortedTestCase
from django_comment_client.tests.unicode import UnicodeTestMixin
from django_comment_common.models import Role
from django_comment_common.utils import seed_permissions_roles, ThreadContext
from student.tests.factories import CourseEnrollmentFactory, UserFactory, CourseAccessRoleFactory
from util.testing import UrlResetMixin
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import check_mongo_calls
from xmodule.modulestore.django import modulestore
from xmodule.modulestore import ModuleStoreEnum
from teams.tests.factories import CourseTeamFactory
log = logging.getLogger(__name__)
CS_PREFIX = "http://localhost:4567/api/v1"
# pylint: disable=missing-docstring
class MockRequestSetupMixin(object):
    def _create_response_mock(self, data):
        return Mock(text=json.dumps(data), json=Mock(return_value=data))
    def _set_mock_request_data(self, mock_request, data):
        mock_request.return_value = self._create_response_mock(data)
@patch('lms.lib.comment_client.utils.requests.request')
class CreateThreadGroupIdTestCase(
        MockRequestSetupMixin,
        CohortedTestCase,
        CohortedTopicGroupIdTestMixin,
        NonCohortedTopicGroupIdTestMixin
):
    cs_endpoint = "/threads"
    def call_view(self, mock_request, commentable_id, user, group_id, pass_group_id=True):
        self._set_mock_request_data(mock_request, {})
        mock_request.return_value.status_code = 200
        request_data = {"body": "body", "title": "title", "thread_type": "discussion"}
        if pass_group_id:
            request_data["group_id"] = group_id
        request = RequestFactory().post("dummy_url", request_data)
        request.user = user
        request.view_name = "create_thread"
        return views.create_thread(
            request,
            course_id=unicode(self.course.id),
            commentable_id=commentable_id
        )
    def test_group_info_in_response(self, mock_request):
        response = self.call_view(
            mock_request,
            "cohorted_topic",
            self.student,
            None
        )
        self._assert_json_response_contains_group_info(response)
@patch('lms.lib.comment_client.utils.requests.request')
@disable_signal(views, 'thread_edited')
@disable_signal(views, 'thread_voted')
@disable_signal(views, 'thread_deleted')
class ThreadActionGroupIdTestCase(
        MockRequestSetupMixin,
        CohortedTestCase,
        GroupIdAssertionMixin
):
    def call_view(
            self,
            view_name,
            mock_request,
            user=None,
            post_params=None,
            view_args=None
    ):
        self._set_mock_request_data(
            mock_request,
            {
                "user_id": str(self.student.id),
                "group_id": self.student_cohort.id,
                "closed": False,
                "type": "thread",
                "commentable_id": "non_team_dummy_id"
            }
        )
        mock_request.return_value.status_code = 200
        request = RequestFactory().post("dummy_url", post_params or {})
        request.user = user or self.student
        request.view_name = view_name
        return getattr(views, view_name)(
            request,
            course_id=unicode(self.course.id),
            thread_id="dummy",
            **(view_args or {})
        )
    def test_update(self, mock_request):
        response = self.call_view(
            "update_thread",
            mock_request,
            post_params={"body": "body", "title": "title"}
        )
        self._assert_json_response_contains_group_info(response)
    def test_delete(self, mock_request):
        response = self.call_view("delete_thread", mock_request)
        self._assert_json_response_contains_group_info(response)
    def test_vote(self, mock_request):
        response = self.call_view(
            "vote_for_thread",
            mock_request,
            view_args={"value": "up"}
        )
        self._assert_json_response_contains_group_info(response)
        response = self.call_view("undo_vote_for_thread", mock_request)
        self._assert_json_response_contains_group_info(response)
    def test_flag(self, mock_request):
        response = self.call_view("flag_abuse_for_thread", mock_request)
        self._assert_json_response_contains_group_info(response)
        response = self.call_view("un_flag_abuse_for_thread", mock_request)
        self._assert_json_response_contains_group_info(response)
    def test_pin(self, mock_request):
        response = self.call_view(
            "pin_thread",
            mock_request,
            user=self.moderator
        )
        self._assert_json_response_contains_group_info(response)
        response = self.call_view(
            "un_pin_thread",
            mock_request,
            user=self.moderator
        )
        self._assert_json_response_contains_group_info(response)
    def test_openclose(self, mock_request):
        response = self.call_view(
            "openclose_thread",
            mock_request,
            user=self.moderator
        )
        self._assert_json_response_contains_group_info(
            response,
            lambda d: d['content']
        )
class ViewsTestCaseMixin(object):
    """
    This class is used by both ViewsQueryCountTestCase and ViewsTestCase. By
    breaking out set_up_course into its own method, ViewsQueryCountTestCase
    can build a course in a particular modulestore, while ViewsTestCase can
    just run it in setUp for all tests.
    """
    def set_up_course(self, module_count=0):
        """
        Creates a course, optionally with module_count discussion modules, and
        a user with appropriate permissions.
        """
        # create a course
        self.course = CourseFactory.create(
            org='MITx', course='999',
            discussion_topics={"Some Topic": {"id": "some_topic"}},
            display_name='Robot Super Course',
        )
        self.course_id = self.course.id
        # add some discussion modules
        for i in range(module_count):
            ItemFactory.create(
                parent_location=self.course.location,
                category='discussion',
                discussion_id='id_module_{}'.format(i),
                discussion_category='Category {}'.format(i),
                discussion_target='Discussion {}'.format(i)
            )
        # seed the forums permissions and roles
        call_command('seed_permissions_roles', unicode(self.course_id))
        # Patch the comment client user save method so it does not try
        # to create a new cc user when creating a django user
        with patch('student.models.cc.User.save'):
            uname = 'student'
            email = 'student@edx.org'
            self.password = 'test'  # pylint: disable=attribute-defined-outside-init
            # Create the user and make them active so we can log them in.
            self.student = User.objects.create_user(uname, email, self.password)  # pylint: disable=attribute-defined-outside-init
            self.student.is_active = True
            self.student.save()
            # Add a discussion moderator
            self.moderator = UserFactory.create(password=self.password)  # pylint: disable=attribute-defined-outside-init
            # Enroll the student in the course
            CourseEnrollmentFactory(user=self.student,
                                    course_id=self.course_id)
            # Enroll the moderator and give them the appropriate roles
            CourseEnrollmentFactory(user=self.moderator, course_id=self.course.id)
            self.moderator.roles.add(Role.objects.get(name="Moderator", course_id=self.course.id))
            self.client = Client()
            assert_true(self.client.login(username='student', password=self.password))
    def _setup_mock_request(self, mock_request, include_depth=False):
        """
        Ensure that mock_request returns the data necessary to make views
        function correctly
        """
        mock_request.return_value.status_code = 200
        data = {
            "user_id": str(self.student.id),
            "closed": False,
            "commentable_id": "non_team_dummy_id"
        }
        if include_depth:
            data["depth"] = 0
        self._set_mock_request_data(mock_request, data)
    def create_thread_helper(self, mock_request, extra_request_data=None, extra_response_data=None):
        """
        Issues a request to create a thread and verifies the result.
        """
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(mock_request, {
            "thread_type": "discussion",
            "title": "Hello",
            "body": "this is a post",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
            "closed": False,
            "id": "518d4237b023791dca00000d",
            "user_id": "1",
            "username": "robot",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [],
            "type": "thread",
            "group_id": None,
            "pinned": False,
            "endorsed": False,
            "unread_comments_count": 0,
            "read": False,
            "comments_count": 0,
        })
        thread = {
            "thread_type": "discussion",
            "body": ["this is a post"],
            "anonymous_to_peers": ["false"],
            "auto_subscribe": ["false"],
            "anonymous": ["false"],
            "title": ["Hello"],
        }
        if extra_request_data:
            thread.update(extra_request_data)
        url = reverse('create_thread', kwargs={'commentable_id': 'i4x-MITx-999-course-Robot_Super_Course',
                                               'course_id': unicode(self.course_id)})
        response = self.client.post(url, data=thread)
        assert_true(mock_request.called)
        expected_data = {
            'thread_type': 'discussion',
            'body': u'this is a post',
            'context': ThreadContext.COURSE,
            'anonymous_to_peers': False, 'user_id': 1,
            'title': u'Hello',
            'commentable_id': u'i4x-MITx-999-course-Robot_Super_Course',
            'anonymous': False,
            'course_id': unicode(self.course_id),
        }
        if extra_response_data:
            expected_data.update(extra_response_data)
        mock_request.assert_called_with(
            'post',
            '{prefix}/i4x-MITx-999-course-Robot_Super_Course/threads'.format(prefix=CS_PREFIX),
            data=expected_data,
            params={'request_id': ANY},
            headers=ANY,
            timeout=5
        )
        assert_equal(response.status_code, 200)
    def update_thread_helper(self, mock_request):
        """
        Issues a request to update a thread and verifies the result.
        """
        self._setup_mock_request(mock_request)
        # Mock out saving in order to test that content is correctly
        # updated. Otherwise, the call to thread.save() receives the
        # same mocked request data that the original call to retrieve
        # the thread did, overwriting any changes.
        with patch.object(Thread, 'save'):
            response = self.client.post(
                reverse("update_thread", kwargs={
                    "thread_id": "dummy",
                    "course_id": unicode(self.course_id)
                }),
                data={"body": "foo", "title": "foo", "commentable_id": "some_topic"}
            )
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content)
        self.assertEqual(data['body'], 'foo')
        self.assertEqual(data['title'], 'foo')
        self.assertEqual(data['commentable_id'], 'some_topic')
@ddt.ddt
@patch('lms.lib.comment_client.utils.requests.request')
@disable_signal(views, 'thread_created')
@disable_signal(views, 'thread_edited')
class ViewsQueryCountTestCase(UrlResetMixin, ModuleStoreTestCase, MockRequestSetupMixin, ViewsTestCaseMixin):
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        super(ViewsQueryCountTestCase, self).setUp(create_user=False)
    def clear_caches(self):
        """Clears caches so that query count numbers are accurate."""
        for cache in settings.CACHES:
            get_cache(cache).clear()
        RequestCache.clear_request_cache()
    def count_queries(func):  # pylint: disable=no-self-argument
        """
        Decorates test methods to count mongo and SQL calls for a
        particular modulestore.
        """
        def inner(self, default_store, module_count, mongo_calls, sql_queries, *args, **kwargs):
            with modulestore().default_store(default_store):
                self.set_up_course(module_count=module_count)
                self.clear_caches()
                with self.assertNumQueries(sql_queries):
                    with check_mongo_calls(mongo_calls):
                        func(self, *args, **kwargs)
        return inner
    @ddt.data(
        (ModuleStoreEnum.Type.mongo, 3, 4, 22),
        (ModuleStoreEnum.Type.mongo, 20, 4, 22),
        (ModuleStoreEnum.Type.split, 3, 13, 22),
        (ModuleStoreEnum.Type.split, 20, 13, 22),
    )
    @ddt.unpack
    @count_queries
    def test_create_thread(self, mock_request):
        self.create_thread_helper(mock_request)
    @ddt.data(
        (ModuleStoreEnum.Type.mongo, 3, 3, 16),
        (ModuleStoreEnum.Type.mongo, 20, 3, 16),
        (ModuleStoreEnum.Type.split, 3, 10, 16),
        (ModuleStoreEnum.Type.split, 20, 10, 16),
    )
    @ddt.unpack
    @count_queries
    def test_update_thread(self, mock_request):
        self.update_thread_helper(mock_request)
@ddt.ddt
@patch('lms.lib.comment_client.utils.requests.request')
class ViewsTestCase(
        UrlResetMixin,
        ModuleStoreTestCase,
        MockRequestSetupMixin,
        ViewsTestCaseMixin,
        MockSignalHandlerMixin
):
    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):
        # Patching the ENABLE_DISCUSSION_SERVICE value affects the contents of urls.py,
        # so we need to call super.setUp() which reloads urls.py (because
        # of the UrlResetMixin)
        super(ViewsTestCase, self).setUp(create_user=False)
        self.set_up_course()
    @contextmanager
    def assert_discussion_signals(self, signal, user=None):
        if user is None:
            user = self.student
        with self.assert_signal_sent(views, signal, sender=None, user=user, exclude_args=('post',)):
            yield
    def test_create_thread(self, mock_request):
        with self.assert_discussion_signals('thread_created'):
            self.create_thread_helper(mock_request)
    def test_create_thread_standalone(self, mock_request):
        team = CourseTeamFactory.create(
            name="A Team",
            course_id=self.course_id,
            topic_id='topic_id',
            discussion_topic_id="i4x-MITx-999-course-Robot_Super_Course"
        )
        # Add the student to the team so they can post to the commentable.
        team.add_user(self.student)
        # create_thread_helper verifies that extra data are passed through to the comments service
        self.create_thread_helper(mock_request, extra_response_data={'context': ThreadContext.STANDALONE})
    def test_delete_thread(self, mock_request):
        self._set_mock_request_data(mock_request, {
            "user_id": str(self.student.id),
            "closed": False,
        })
        test_thread_id = "test_thread_id"
        request = RequestFactory().post("dummy_url", {"id": test_thread_id})
        request.user = self.student
        request.view_name = "delete_thread"
        with self.assert_discussion_signals('thread_deleted'):
            response = views.delete_thread(
                request,
                course_id=unicode(self.course.id),
                thread_id=test_thread_id
            )
        self.assertEqual(response.status_code, 200)
        self.assertTrue(mock_request.called)
    def test_delete_comment(self, mock_request):
        self._set_mock_request_data(mock_request, {
            "user_id": str(self.student.id),
            "closed": False,
        })
        test_comment_id = "test_comment_id"
        request = RequestFactory().post("dummy_url", {"id": test_comment_id})
        request.user = self.student
        request.view_name = "delete_comment"
        with self.assert_discussion_signals('comment_deleted'):
            response = views.delete_comment(
                request,
                course_id=unicode(self.course.id),
                comment_id=test_comment_id
            )
        self.assertEqual(response.status_code, 200)
        self.assertTrue(mock_request.called)
        args = mock_request.call_args[0]
        self.assertEqual(args[0], "delete")
        self.assertTrue(args[1].endswith("/{}".format(test_comment_id)))
    def _test_request_error(self, view_name, view_kwargs, data, mock_request):
        """
        Submit a request against the given view with the given data and ensure
        that the result is a 400 error and that no data was posted using
        mock_request
        """
        self._setup_mock_request(mock_request, include_depth=(view_name == "create_sub_comment"))
        response = self.client.post(reverse(view_name, kwargs=view_kwargs), data=data)
        self.assertEqual(response.status_code, 400)
        for call in mock_request.call_args_list:
            self.assertEqual(call[0][0].lower(), "get")
    def test_create_thread_no_title(self, mock_request):
        self._test_request_error(
            "create_thread",
            {"commentable_id": "dummy", "course_id": unicode(self.course_id)},
            {"body": "foo"},
            mock_request
        )
    def test_create_thread_empty_title(self, mock_request):
        self._test_request_error(
            "create_thread",
            {"commentable_id": "dummy", "course_id": unicode(self.course_id)},
            {"body": "foo", "title": " "},
            mock_request
        )
    def test_create_thread_no_body(self, mock_request):
        self._test_request_error(
            "create_thread",
            {"commentable_id": "dummy", "course_id": unicode(self.course_id)},
            {"title": "foo"},
            mock_request
        )
    def test_create_thread_empty_body(self, mock_request):
        self._test_request_error(
            "create_thread",
            {"commentable_id": "dummy", "course_id": unicode(self.course_id)},
            {"body": " ", "title": "foo"},
            mock_request
        )
    def test_update_thread_no_title(self, mock_request):
        self._test_request_error(
            "update_thread",


Answer:             {"thread_id": "dummy", "course_id": unicode(self.course_id)},