<commit_before>"""Tests for root config views and urls."""
from __future__ import unicode_literals
from django.core import mail
from django.test import Client, TestCase
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.auth.forms import AuthenticationForm
from registration.forms import RegistrationForm
import re

DEFAULT_IMG = 'media/django-magic.jpg'
HOME = '/'
REG = '/accounts/register/'
LOGIN = '/accounts/login/'
LOGOUT = '/accounts/logout/'

BAD_LOGIN_PARAMS = {'username': 'NotRealUser', 'password': '<PASSWORD>'}
BAD_REG_PARAMS = {'username': 'NotRealUser',
                  'email': 'b<EMAIL>',
                  'password1': '<PASSWORD>',
                  'password2': '<PASSWORD>'}

GOOD_REG_PARAMS = {'username': 'CoolPerson',
                   'email': '<EMAIL>',
                   'password1': '<PASSWORD>',
                   'password2': '<PASSWORD>'}

LINK_PATTERN = r'/accounts/activate/.*/'


def user_from_response(response):
    """Helper function to dig the user from the HTTPresponse."""
    for dic in response.context[0]:
        user = dic.get('user')
        if user:
            break
    return user


class UnauthenticatedCase(TestCase):
    """Testing when user is not logged in."""

    def setUp(self):
        """Set up for unauthenticated case with no users."""
        client = Client()
        self.home_response = client.get(HOME)
        self.reg_response = client.get(REG)
        self.reg_post_bad = client.post(REG, BAD_REG_PARAMS)
        self.login_get_response = client.get(LOGIN)
        self.login_post_bad = client.post(LOGIN, BAD_LOGIN_PARAMS)
        self.logout_response = client.get(LOGOUT)

    def test_no_users_in_db(self):
        """Make sure test session starts with empty database."""
        self.assertFalse(User.objects.count())

    def test_homepage_ok(self):
        """Check that homepage can be visited."""
        self.assertEqual(self.home_response.status_code, 200)

    def test_login_ok(self):
        """Check that login page can be visited."""
        self.assertEqual(self.login_get_response.status_code, 200)

    def test_logout_ok(self):
        """Check that logout page can be visited."""
        self.assertEqual(self.logout_response.status_code, 200)

    def test_register_ok(self):
        """Check that register page can be visited."""
        self.assertEqual(self.reg_response.status_code, 200)

    def test_no_authenticated_user(self):
        """Test that there is no authenticated user."""
        user = user_from_response(self.home_response)
        self.assertFalse(user.is_authenticated())

    def test_no_username_display(self):
        """Test that message displaying username does not appear."""
        self.assertNotIn(b'Log out', self.home_response.content)

    def test_default_img(self):
        """Check that the default image is displayed, not a user's image."""
        img_url = self.home_response.context_data.get('img_url')
        self.assertEqual(img_url, DEFAULT_IMG)

    def test_correct_reg_form(self):
        """Check that the registration page delivers the registration form."""
        self.assertIsInstance(self.reg_response.context_data.get('form'),
                              RegistrationForm)

    def test_correct_login_form(self):
        """Check that the login page delivers the registration form."""
        self.assertIsInstance(self.login_get_response.context_data.get('form'),
                              AuthenticationForm)

    def test_login_failure_ok(self):
        """Test that login failure returns to login page."""
        self.assertEqual(self.login_post_bad.status_code, 200)

    def test_login_failure_message(self):
        """Test that login fails since there are no registered users."""
        expected_msg = b'Please enter a correct username and password.'
        self.assertIn(expected_msg, self.login_post_bad.content)

    def test_reg_failure_ok(self):
        """Test that bad registration information returns a 200 response."""
        self.assertEqual(self.reg_post_bad.status_code, 200)

    def test_reg_failure_message_email(self):
        """Test that bad registration gives a bad email message."""
        expected_msg = b'Enter a valid email address.'
        self.assertIn(expected_msg, self.reg_post_bad.content)

    def test_reg_failure_message_password_match(self):
        """Test bad registration gives message when passwords don't match."""
        expected_msg = b'The two password fields didn&#39;t match.'
        self.assertIn(expected_msg, self.reg_post_bad.content)


class RegistrationCase(TestCase):
    """Tests with one registraton post attempt in setup."""

    def setUp(self):
        """Set up for unauthenticated case with no users."""
        self.client = Client()
        self.reg_post_good = self.client.post(REG, GOOD_REG_PARAMS,
                                              follow=True)
        try:
            self.email = mail.outbox[0]
        except IndexError:
            self.email = None

    def tearDown(self):
        """Delete all users to re-use good params."""<commit_msg>Added tests to ensure login_required redirect from accounts/profile and images/library when not authenticated.<commit_after>"""Tests for root config views and urls."""
from __future__ import unicode_literals
from django.core import mail
from django.test import Client, TestCase
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.auth.forms import AuthenticationForm
from registration.forms import RegistrationForm
import re

DEFAULT_IMG = 'media/django-magic.jpg'
HOME = '/'
REG = '/accounts/register/'
LOGIN = '/accounts/login/'
LOGOUT = '/accounts/logout/'
PROFILE = '/accounts/profile/'
LIBRARY = '/images/library/'

BAD_LOGIN_PARAMS = {'username': 'NotRealUser', 'password': '<PASSWORD>'}
BAD_REG_PARAMS = {'username': 'NotRealUser',
                  'email': 'bademail@badd<EMAIL>',
                  'password1': '<PASSWORD>',
                  'password2': '<PASSWORD>'}

GOOD_REG_PARAMS = {'username': 'CoolPerson',
                   'email': '<EMAIL>',
                   'password1': '<PASSWORD>',
                   'password2': '<PASSWORD>'}

LINK_PATTERN = r'/accounts/activate/.*/'


def user_from_response(response):
    """Helper function to dig the user from the HTTPresponse."""
    for dic in response.context[0]:
        user = dic.get('user')
        if user:
            break
    return user


class UnauthenticatedCase(TestCase):
    """Testing when user is not logged in."""

    def setUp(self):
        """Set up for unauthenticated case with no users."""
        client = Client()
        self.home_response = client.get(HOME)
        self.reg_response = client.get(REG)
        self.reg_post_bad = client.post(REG, BAD_REG_PARAMS)
        self.login_get_response = client.get(LOGIN)
        self.login_post_bad = client.post(LOGIN, BAD_LOGIN_PARAMS)
        self.logout_response = client.get(LOGOUT)
        self.profile_response = client.get(PROFILE)
        self.library_response = client.get(LIBRARY)

    def test_no_users_in_db(self):
        """Make sure test session starts with empty database."""
        self.assertFalse(User.objects.count())

    def test_homepage_ok(self):
        """Check that homepage can be visited."""
        self.assertEqual(self.home_response.status_code, 200)

    def test_login_ok(self):
        """Check that login page can be visited."""
        self.assertEqual(self.login_get_response.status_code, 200)

    def test_logout_ok(self):
        """Check that logout page can be visited."""
        self.assertEqual(self.logout_response.status_code, 200)

    def test_register_ok(self):
        """Check that register page can be visited."""
        self.assertEqual(self.reg_response.status_code, 200)

    def test_no_authenticated_user(self):
        """Test that there is no authenticated user."""
        user = user_from_response(self.home_response)
        self.assertFalse(user.is_authenticated())

    def test_no_username_display(self):
        """Test that message displaying username does not appear."""
        self.assertNotIn(b'Log out', self.home_response.content)

    def test_default_img(self):
        """Check that the default image is displayed, not a user's image."""
        img_url = self.home_response.context_data.get('img_url')
        self.assertEqual(img_url, DEFAULT_IMG)

    def test_correct_reg_form(self):
        """Check that the registration page delivers the registration form."""
        self.assertIsInstance(self.reg_response.context_data.get('form'),
                              RegistrationForm)

    def test_correct_login_form(self):
        """Check that the login page delivers the registration form."""
        self.assertIsInstance(self.login_get_response.context_data.get('form'),
                              AuthenticationForm)

    def test_login_failure_ok(self):
        """Test that login failure returns to login page."""
        self.assertEqual(self.login_post_bad.status_code, 200)

    def test_login_failure_message(self):
        """Test that login fails since there are no registered users."""
        expected_msg = b'Please enter a correct username and password.'
        self.assertIn(expected_msg, self.login_post_bad.content)

    def test_reg_failure_ok(self):
        """Test that bad registration information returns a 200 response."""
        self.assertEqual(self.reg_post_bad.status_code, 200)

    def test_reg_failure_message_email(self):
        """Test that bad registration gives a bad email message."""
        expected_msg = b'Enter a valid email address.'
        self.assertIn(expected_msg, self.reg_post_bad.content)

    def test_reg_failure_message_password_match(self):
        """Test bad registration gives message when passwords don't match."""
        expected_msg = b'The two password fields didn&#39;t match.'
        self.assertIn(expected_msg, self.reg_post_bad.content)

    def test_profile_login_required(self):
        """Test that getting /accounts/profile/ redirects to login."""
        self.assertEqual(self.profile_response.status_code, 302)
        self.assertTrue(self.profile_response.url.startswith(LOGIN))

    def test_library_login_required(self):
        """Test that getting /images/library/ redirects to login."""
        self.assertEqual(self.profile_response.status_code, 302)
        self.assertTrue(self.profile_response.url.startswith(LOGIN))


class RegistrationCase(TestCase):
    """Tests with one registraton post attempt in setup."""

    def setUp(self):
        """Set up for unauthenticated case with no users."""
        self.client = Client()
        self.reg_post_good = self.client.post(REG, GOOD_REG_PARAMS,
                                              follow=True)
        try:
            self.email = mail.outbox[0]
        except IndexError:
            self.email = None

    def tearDown(self):
        """Delete all users to re-use good params."""
{'fraction_non_alphanumeric': 0.10678289294470171, 'fraction_numerical': 0.005811313901752474, 'mean_word_length': 2.9790462427745665, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4493129', 'n_tokens_mistral': 3152, 'n_tokens_neox': 3006, 'n_words': 795}