<commit_before># -*- coding: utf-8 -*-
from django.test import TestCase, override_settings
from django.contrib.auth.models import User
from django.test.client import Client
from django.core.urlresolvers import reverse
from datetime import date
from collections import OrderedDict
from molo.core.tests.base import MoloTestCaseMixin
from molo.core.models import Main, Languages, SiteLanguageRelation
from molo.profiles.admin import ProfileUserAdmin, download_as_csv
from molo.profiles.models import UserProfile, SecurityQuestion, SecurityAnswer
from molo.profiles.admin import MultiSiteUserResource


class ModelsTestCase(TestCase, MoloTestCaseMixin):
    def setUp(self):
        self.mk_main()
        self.user = User.objects.create_user(
            username='tester',
            email='<EMAIL>',
            password='<PASSWORD>')
        self.main = Main.objects.all().first()
        self.language_setting = Languages.objects.create(
            site_id=self.main.get_site().pk)
        self.english = SiteLanguageRelation.objects.create(
            language_setting=self.language_setting,
            locale='en',
            is_active=True)
        self.mk_main2()

    def test_download_csv(self):
        profile = self.user.profile
        profile.alias = 'The Alias'
        profile.mobile_number = '+27784667723'
        profile.save()

        response = download_as_csv(ProfileUserAdmin(UserProfile, self.site),
                                   None,
                                   User.objects.all())
        date = str(self.user.date_joined.strftime("%Y-%m-%d %H:%M"))
        expected_output = ('Content-Type: text/csv\r\nContent-Disposition: '
                           'attachment;filename=export.csv\r\n\r\nusername,'
                           'email,first_name,last_name,is_staff,date_joined,'
                           'alias,mobile_number\r\ntester,<EMAIL>,'
                           ',,False,' + date + ',The Alias,+27784667723\r\n')
        self.assertEquals(str(response), expected_output)

    def test_download_csv_with_an_alias_contains_ascii_code(self):
        profile = self.user.profile
        profile.alias = 'The Alias 😁'
        profile.mobile_number = '+27784667723'
        profile.save()

        response = download_as_csv(ProfileUserAdmin(UserProfile, self.site),
                                   None,
                                   User.objects.all())
        date = str(self.user.date_joined.strftime("%Y-%m-%d %H:%M"))
        expected_output = ('Content-Type: text/csv\r\nContent-Disposition: '
                           'attachment;filename=export.csv\r\n\r\nusername,'
                           'email,first_name,last_name,is_staff,date_joined,'
                           'alias,mobile_number\r\ntester,<EMAIL>,'
                           ',,False,' + date + ',The Alias \xf0\x9f\x98\x81,'
                           '+27784667723\r\n')
        self.assertEquals(str(response), expected_output)

    def test_download_csv_with_an_username_contains_ascii_code(self):
        self.user.username = '사이네'
        self.user.save()

        response = download_as_csv(ProfileUserAdmin(UserProfile, self.site),
                                   None,
                                   User.objects.all())
        date = str(self.user.date_joined.strftime("%Y-%m-%d %H:%M"))
        expected_output = ('Content-Type: text/csv\r\nContent-Disposition: '
                           'attachment;filename=export.csv\r\n\r\nusername,'
                           'email,first_name,last_name,is_staff,date_joined,'
                           'alias,mobile_number\r\n\xec\x82\xac\xec\x9d\xb4'
                           '\xeb\x84\xa4,<EMAIL>,'
                           ',,False,' + date + ',,\r\n')
        self.assertEquals(str(response), expected_output)

    def test_successful_login_for_migrated_users(self):
        user = User.objects.create_user(
            username='1_newuser',
            email='<EMAIL>',
            password='<PASSWORD>')
        user.profile.migrated_username = 'newuser'
        user.profile.save()

        response = self.client.post('/profiles/login/?next=/', {
            'username': 'newuser',
            'password': '<PASSWORD>',
        })
        self.assertRedirects(response, '/')

        client = Client(HTTP_HOST=self.site2.hostname)

        response = client.post('/profiles/login/?next=/', {
            'username': 'newuser',
            'password': '<PASSWORD>',
        })
        self.assertContains(
            response,
            'Your username and password do not match. Please try again.')

    def test_successful_login_for_migrated_users_in_site_2(self):
        user = User.objects.create_user(
            username='2_newuser',
            email='<EMAIL>',
            password='<PASSWORD>')
        user.profile.migrated_username = 'newuser'
        user.profile.site = self.site2
        user.profile.save()

        response = self.client.post('/profiles/login/?next=/', {
            'username': 'newuser',
            'password': '<PASSWORD>',
        })
        self.assertContains(
            response,
            'Your username and password do not match. Please try again.')

        client = Client(HTTP_HOST=self.site2.hostname)

        response = client.post('/profiles/login/?next=/', {
            'username': 'newuser',
            'password': '<PASSWORD>',
        })
        self.assertRedirects(response, '/')

    def test_importing_does_not_override_existing_data(self):
        user = User.objects.create_user(
            username='2_newuser',
            email='<EMAIL>',
            password='<PASSWORD>')
        user.profile.migrated_username = 'newuser'
        user.profile.site = self.site2
        user.profile.save()
        self.assertEquals(User.objects.count(), 2)
        data = OrderedDict(
            [('security_question_answers',
              []),
             ('username', user.username),
             ('first_name', ''),
             ('last_name', ''),
             ('migrated_username', user.profile.migrated_username),
             ('gender', ''),
             ('is_active', '1'),
             ('site', '1'),<commit_msg>add tests<commit_after># -*- coding: utf-8 -*-
from django.test import TestCase, override_settings
from django.contrib.auth.models import User
from django.test.client import Client
from django.core.urlresolvers import reverse
from datetime import date
from collections import OrderedDict
from molo.core.tests.base import MoloTestCaseMixin
from molo.core.models import Main, Languages, SiteLanguageRelation
from molo.profiles.admin import ProfileUserAdmin, download_as_csv
from molo.profiles.models import (
    UserProfile, SecurityQuestion, SecurityAnswer, SecurityQuestionIndexPage)
from molo.profiles.admin import MultiSiteUserResource


class ModelsTestCase(TestCase, MoloTestCaseMixin):
    def setUp(self):
        self.mk_main()
        self.user = User.objects.create_user(
            username='tester',
            email='<EMAIL>',
            password='<PASSWORD>')
        self.main = Main.objects.all().first()
        self.language_setting = Languages.objects.create(
            site_id=self.main.get_site().pk)
        self.english = SiteLanguageRelation.objects.create(
            language_setting=self.language_setting,
            locale='en',
            is_active=True)
        self.mk_main2()

    def test_download_csv(self):
        profile = self.user.profile
        profile.alias = 'The Alias'
        profile.mobile_number = '+27784667723'
        profile.save()

        response = download_as_csv(ProfileUserAdmin(UserProfile, self.site),
                                   None,
                                   User.objects.all())
        date = str(self.user.date_joined.strftime("%Y-%m-%d %H:%M"))
        expected_output = ('Content-Type: text/csv\r\nContent-Disposition: '
                           'attachment;filename=export.csv\r\n\r\nusername,'
                           'email,first_name,last_name,is_staff,date_joined,'
                           'alias,mobile_number\r\ntester,<EMAIL>,'
                           ',,False,' + date + ',The Alias,+27784667723\r\n')
        self.assertEquals(str(response), expected_output)

    def test_download_csv_with_an_alias_contains_ascii_code(self):
        profile = self.user.profile
        profile.alias = 'The Alias 😁'
        profile.mobile_number = '+27784667723'
        profile.save()

        response = download_as_csv(ProfileUserAdmin(UserProfile, self.site),
                                   None,
                                   User.objects.all())
        date = str(self.user.date_joined.strftime("%Y-%m-%d %H:%M"))
        expected_output = ('Content-Type: text/csv\r\nContent-Disposition: '
                           'attachment;filename=export.csv\r\n\r\nusername,'
                           'email,first_name,last_name,is_staff,date_joined,'
                           'alias,mobile_number\r\ntester,<EMAIL>,'
                           ',,False,' + date + ',The Alias \xf0\x9f\x98\x81,'
                           '+27784667723\r\n')
        self.assertEquals(str(response), expected_output)

    def test_download_csv_with_an_username_contains_ascii_code(self):
        self.user.username = '사이네'
        self.user.save()

        response = download_as_csv(ProfileUserAdmin(UserProfile, self.site),
                                   None,
                                   User.objects.all())
        date = str(self.user.date_joined.strftime("%Y-%m-%d %H:%M"))
        expected_output = ('Content-Type: text/csv\r\nContent-Disposition: '
                           'attachment;filename=export.csv\r\n\r\nusername,'
                           'email,first_name,last_name,is_staff,date_joined,'
                           'alias,mobile_number\r\n\xec\x82\xac\xec\x9d\xb4'
                           '\xeb\x84\xa4,<EMAIL>,'
                           ',,False,' + date + ',,\r\n')
        self.assertEquals(str(response), expected_output)

    def test_successful_login_for_migrated_users(self):
        user = User.objects.create_user(
            username='1_newuser',
            email='<EMAIL>',
            password='<PASSWORD>')
        user.profile.migrated_username = 'newuser'
        user.profile.save()

        response = self.client.post('/profiles/login/?next=/', {
            'username': 'newuser',
            'password': '<PASSWORD>',
        })
        self.assertRedirects(response, '/')

        client = Client(HTTP_HOST=self.site2.hostname)

        response = client.post('/profiles/login/?next=/', {
            'username': 'newuser',
            'password': '<PASSWORD>',
        })
        self.assertContains(
            response,
            'Your username and password do not match. Please try again.')

    def test_successful_login_for_migrated_users_in_site_2(self):
        user = User.objects.create_user(
            username='2_newuser',
            email='<EMAIL>',
            password='<PASSWORD>')
        user.profile.migrated_username = 'newuser'
        user.profile.site = self.site2
        user.profile.save()

        response = self.client.post('/profiles/login/?next=/', {
            'username': 'newuser',
            'password': '<PASSWORD>',
        })
        self.assertContains(
            response,
            'Your username and password do not match. Please try again.')

        client = Client(HTTP_HOST=self.site2.hostname)

        response = client.post('/profiles/login/?next=/', {
            'username': 'newuser',
            'password': '<PASSWORD>',
        })
        self.assertRedirects(response, '/')

    def test_security_question_dehydrate_method(self):
        user = User.objects.create_user(
            username='2_newuser',
            email='<EMAIL>',
            password='<PASSWORD>')
        user.profile.migrated_username = 'newuser'
        user.profile.site = self.site2
        user.profile.save()

        self.security_index = SecurityQuestionIndexPage(
            title='Security Questions',
            slug='security_questions',
        )
        self.main.add_child(instance=self.security_index)
        self.security_index.save()
        self.question = SecurityQuestion(
            title="How old are you?",
            slug="how-old-are-you",
        )
        self.security_index.add_child(instance=self.question)
        self.question.save()

        # create answers for this user
        self.a1 = SecurityAnswer.objects.create(
            user=user.profile, question=self.question, answer="20"
        )
        resource = MultiSiteUserResource()
        result = resource.dehydrate_security_question_answers(user)

        # it should return a tuple of the question title and answer hash
        expected_result = [(self.question.title, self.a1.answer)]
        self.assertEquals(result, expected_result)

    def test_importing_does_not_override_existing_data(self):
        user = User.objects.create_user(
            username='2_newuser',
            email='<EMAIL>',
            password='<PASSWORD>')
        user.profile.migrated_username = 'newuser'
        user.profile.site = self.site2
        user.profile.save()
        self.assertEquals(User.objects.count(), 2)
        data = OrderedDict(
            [('security_question_answers',
              []),
             ('username', user.username),
             ('first_name', ''),
             ('last_name', ''),
             ('migrated_username', user.profile.migrated_username),
             ('gender', ''),
             ('is_active', '1'),
             ('site', '1'),
{'fraction_non_alphanumeric': 0.12283914444769997, 'fraction_numerical': 0.010694403750366246, 'mean_word_length': 2.0380507343124163, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '502152', 'n_tokens_mistral': 3963, 'n_tokens_neox': 3846, 'n_words': 594}