<commit_before># -*- coding: utf-8 -*-
"""
Tests for the teams API at the HTTP request level.
"""


import itertools
from contextlib import contextmanager
from datetime import datetime

import ddt
import pytz
import six
from mock import Mock, patch
from opaque_keys.edx.keys import CourseKey

from course_modes.models import CourseMode
from lms.djangoapps.teams import TEAM_DISCUSSION_CONTEXT
from lms.djangoapps.teams.errors import AddToIncompatibleTeamError
from lms.djangoapps.teams.models import CourseTeam, CourseTeamMembership
from lms.djangoapps.teams.tests.factories import CourseTeamFactory, CourseTeamMembershipFactory
from openedx.core.djangoapps.django_comment_common.signals import (
    comment_created,
    comment_deleted,
    comment_edited,
    comment_endorsed,
    comment_voted,
    thread_created,
    thread_deleted,
    thread_edited,
    thread_voted
)
from student.tests.factories import CourseEnrollmentFactory, UserFactory
from util.testing import EventTestMixin
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase

COURSE_KEY1 = CourseKey.from_string('edx/history/1')
COURSE_KEY2 = CourseKey.from_string('edx/history/2')
TEAMSET_1_ID = "the-teamset"
TEAMSET_2_ID = "the-teamset-2"


class TestModelStrings(SharedModuleStoreTestCase):
    """
    Test `__repr__` and `__str__` methods of this app's models.
    """
    @classmethod
    def setUpClass(cls):
        super(TestModelStrings, cls).setUpClass()
        cls.user = UserFactory.create(username="the-user")
        CourseEnrollmentFactory.create(user=cls.user, course_id="edx/the-course/1")
        cls.team = CourseTeamFactory(
            course_id="edx/the-course/1",
            team_id="the-team",
            topic_id=TEAMSET_1_ID,
            name="The Team"
        )
        cls.team_membership = cls.team.add_user(cls.user)

    def test_team_repr(self):
        assert repr(self.team) == (
            "<CourseTeam"
            " id=1"
            " team_id=the-team"
            " team_size=1"
            " topic_id=the-teamset"
            " course_id=edx/the-course/1"
            ">"
        )

    def test_team_text(self):
        assert six.text_type(self.team) == (
            "The Team in edx/the-course/1"
        )

    def test_team_membership_repr(self):
        assert repr(self.team_membership) == (
            "<CourseTeamMembership id=1 user_id=1 team_id=1>"
        )

    def test_team_membership_text_type(self):
        assert six.text_type(self.team_membership) == (
            "the-user is member of The Team in edx/the-course/1"
        )


class CourseTeamTest(SharedModuleStoreTestCase):
    """Tests for the CourseTeam model."""

    @classmethod
    def setUpClass(cls):
        super(CourseTeamTest, cls).setUpClass()

        cls.audit_learner = UserFactory.create(username="audit")
        CourseEnrollmentFactory.create(user=cls.audit_learner, course_id="edx/the-course/1", mode=CourseMode.AUDIT)
        cls.audit_team = CourseTeamFactory(
            course_id="edx/the-course/1",
            team_id="audit-team",
            topic_id=TEAMSET_1_ID,
            name="The Team"
        )

        cls.masters_learner = UserFactory.create(username="masters")
        CourseEnrollmentFactory.create(user=cls.masters_learner, course_id="edx/the-course/1", mode=CourseMode.MASTERS)
        cls.masters_team = CourseTeamFactory(
            course_id="edx/the-course/1",
            team_id="masters-team",
            topic_id=TEAMSET_1_ID,
            name="The Team",
            organization_protected=True
        )

    def test_add_user(self):
        """Test that we can add users with correct protection status to a team"""
        self.assertIsNotNone(self.masters_team.add_user(self.masters_learner))
        self.assertIsNotNone(self.audit_team.add_user(self.audit_learner))

    def test_add_user_bad_team_access(self):
        """Test that we are blocked from adding a user to a team of mixed enrollment types"""

        with self.assertRaises(AddToIncompatibleTeamError):
            self.audit_team.add_user(self.masters_learner)

        with self.assertRaises(AddToIncompatibleTeamError):
            self.masters_team.add_user(self.audit_learner)

    def test_defaults_with_create(self):
        field = CourseTeam._meta.get_field('last_activity_at')
        default_date = datetime(1978, 1, 1)
        mock_now = lambda: default_date
        with patch.object(field, 'default', new=mock_now):
            team = CourseTeam.create(
                name='foo',
                course_id='sedx/the-course/1',
                description='Import from csv',
                topic_id=TEAMSET_1_ID,
                organization_protected=True
            )
        self.assert_team_default_values(default_date, team)

    def test_defaults_with_constructor(self):
        field = CourseTeam._meta.get_field('last_activity_at')
        default_date = datetime(1978, 1, 1)
        mock_now = lambda: default_date
        with patch.object(field, 'default', new=mock_now):
            team = CourseTeam(
                name='foo',
                course_id='sedx/the-course/1',
                description='Import from csv',
                topic_id=TEAMSET_1_ID,
                organization_protected=True
            )
        self.assert_team_default_values(default_date, team)

    def assert_team_default_values(self, default_date, team):
        self.assertEqual(default_date, team.last_activity_at)
        self.assertEqual('', team.language)
        self.assertEqual('', team.country)


@ddt.ddt
class TeamMembershipTest(SharedModuleStoreTestCase):
    """Tests for the TeamMembership model."""

    def setUp(self):
        """
        Set up tests.
        """
        super(TeamMembershipTest, self).setUp()

        self.user1 = UserFactory.create(username='user1')
        self.user2 = UserFactory.create(username='user2')
        self.user3 = UserFactory.create(username='user3')

        for user in (self.user1, self.user2, self.user3):
            CourseEnrollmentFactory.create(user=user, course_id=COURSE_KEY1)
        CourseEnrollmentFactory.create(user=self.user1, course_id=COURSE_KEY2)

        self.team1 = CourseTeamFactory(
            course_id=COURSE_KEY1,
            team_id='team1',
            topic_id=TEAMSET_1_ID,
        )
        self.team2 = CourseTeamFactory(<commit_msg>remove some potentially problematic tests<commit_after># -*- coding: utf-8 -*-
"""
Tests for the teams API at the HTTP request level.
"""


import itertools
from contextlib import contextmanager
from datetime import datetime

import ddt
import pytz
import six
from mock import Mock, patch
from opaque_keys.edx.keys import CourseKey

from course_modes.models import CourseMode
from lms.djangoapps.teams import TEAM_DISCUSSION_CONTEXT
from lms.djangoapps.teams.errors import AddToIncompatibleTeamError
from lms.djangoapps.teams.models import CourseTeam, CourseTeamMembership
from lms.djangoapps.teams.tests.factories import CourseTeamFactory, CourseTeamMembershipFactory
from openedx.core.djangoapps.django_comment_common.signals import (
    comment_created,
    comment_deleted,
    comment_edited,
    comment_endorsed,
    comment_voted,
    thread_created,
    thread_deleted,
    thread_edited,
    thread_voted
)
from student.tests.factories import CourseEnrollmentFactory, UserFactory
from util.testing import EventTestMixin
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase

COURSE_KEY1 = CourseKey.from_string('edx/history/1')
COURSE_KEY2 = CourseKey.from_string('edx/history/2')
TEAMSET_1_ID = "the-teamset"
TEAMSET_2_ID = "the-teamset-2"


class TestModelStrings(SharedModuleStoreTestCase):
    """
    Test `__repr__` and `__str__` methods of this app's models.
    """
    @classmethod
    def setUpClass(cls):
        super(TestModelStrings, cls).setUpClass()
        cls.user = UserFactory.create(username="the-user")
        CourseEnrollmentFactory.create(user=cls.user, course_id="edx/the-course/1")
        cls.team = CourseTeamFactory(
            course_id="edx/the-course/1",
            team_id="the-team",
            topic_id=TEAMSET_1_ID,
            name="The Team"
        )
        cls.team_membership = cls.team.add_user(cls.user)

    def test_team_repr(self):
        assert repr(self.team) == (
            "<CourseTeam"
            " id=1"
            " team_id=the-team"
            " team_size=1"
            " topic_id=the-teamset"
            " course_id=edx/the-course/1"
            ">"
        )

    def test_team_text(self):
        assert six.text_type(self.team) == (
            "The Team in edx/the-course/1"
        )

    def test_team_membership_repr(self):
        assert repr(self.team_membership) == (
            "<CourseTeamMembership id=1 user_id=1 team_id=1>"
        )

    def test_team_membership_text_type(self):
        assert six.text_type(self.team_membership) == (
            "the-user is member of The Team in edx/the-course/1"
        )


class CourseTeamTest(SharedModuleStoreTestCase):
    """Tests for the CourseTeam model."""

    @classmethod
    def setUpClass(cls):
        super(CourseTeamTest, cls).setUpClass()

        cls.audit_learner = UserFactory.create(username="audit")
        CourseEnrollmentFactory.create(user=cls.audit_learner, course_id="edx/the-course/1", mode=CourseMode.AUDIT)
        cls.audit_team = CourseTeamFactory(
            course_id="edx/the-course/1",
            team_id="audit-team",
            topic_id=TEAMSET_1_ID,
            name="The Team"
        )

        cls.masters_learner = UserFactory.create(username="masters")
        CourseEnrollmentFactory.create(user=cls.masters_learner, course_id="edx/the-course/1", mode=CourseMode.MASTERS)
        cls.masters_team = CourseTeamFactory(
            course_id="edx/the-course/1",
            team_id="masters-team",
            topic_id=TEAMSET_1_ID,
            name="The Team",
            organization_protected=True
        )

    def test_add_user(self):
        """Test that we can add users with correct protection status to a team"""
        self.assertIsNotNone(self.masters_team.add_user(self.masters_learner))
        self.assertIsNotNone(self.audit_team.add_user(self.audit_learner))

    def test_add_user_bad_team_access(self):
        """Test that we are blocked from adding a user to a team of mixed enrollment types"""

        with self.assertRaises(AddToIncompatibleTeamError):
            self.audit_team.add_user(self.masters_learner)

        with self.assertRaises(AddToIncompatibleTeamError):
            self.masters_team.add_user(self.audit_learner)


@ddt.ddt
class TeamMembershipTest(SharedModuleStoreTestCase):
    """Tests for the TeamMembership model."""

    def setUp(self):
        """
        Set up tests.
        """
        super(TeamMembershipTest, self).setUp()

        self.user1 = UserFactory.create(username='user1')
        self.user2 = UserFactory.create(username='user2')
        self.user3 = UserFactory.create(username='user3')

        for user in (self.user1, self.user2, self.user3):
            CourseEnrollmentFactory.create(user=user, course_id=COURSE_KEY1)
        CourseEnrollmentFactory.create(user=self.user1, course_id=COURSE_KEY2)

        self.team1 = CourseTeamFactory(
            course_id=COURSE_KEY1,
            team_id='team1',
            topic_id=TEAMSET_1_ID,
        )
        self.team2 = CourseTeamFactory(
{'fraction_non_alphanumeric': 0.09722222222222222, 'fraction_numerical': 0.008735150244584208, 'mean_word_length': 2.8770741618692854, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5888183', 'n_tokens_mistral': 3596, 'n_tokens_neox': 3522, 'n_words': 617}