<commit_before>import json
from contextlib import contextmanager

from django.contrib import admin
from django.contrib.admin.tests import AdminSeleniumTestCase
from django.contrib.admin.views.autocomplete import AutocompleteJsonView
from django.contrib.auth.models import Permission, User
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import RequestFactory, override_settings
from django.urls import reverse, reverse_lazy

from .admin import AnswerAdmin, QuestionAdmin
from .models import Answer, Author, Authorship, Book, Question
from .tests import AdminViewBasicTestCase

PAGINATOR_SIZE = AutocompleteJsonView.paginate_by


class AuthorAdmin(admin.ModelAdmin):
    ordering = ['id']
    search_fields = ['id']


class AuthorshipInline(admin.TabularInline):
    model = Authorship
    autocomplete_fields = ['author']


class BookAdmin(admin.ModelAdmin):
    inlines = [AuthorshipInline]


site = admin.AdminSite(name='autocomplete_admin')
site.register(Question, QuestionAdmin)
site.register(Answer, AnswerAdmin)
site.register(Author, AuthorAdmin)
site.register(Book, BookAdmin)


@contextmanager
def model_admin(model, model_admin, admin_site=site):
    org_admin = admin_site._registry.get(model)
    if org_admin:
        admin_site.unregister(model)
    admin_site.register(model, model_admin)
    try:
        yield
    finally:
        if org_admin:
            admin_site._registry[model] = org_admin


class AutocompleteJsonViewTests(AdminViewBasicTestCase):
    as_view_args = {'admin_site': site}
    opts = {
        'app_label': Answer._meta.app_label,
        'model_name': Answer._meta.model_name,
        'field_name': 'question'
    }
    factory = RequestFactory()
    url = reverse_lazy('autocomplete_admin:autocomplete')

    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user(
            username='user', password='<PASSWORD>',
            email='<EMAIL>', is_staff=True,
        )
        super().setUpTestData()

    def test_success(self):
        q = Question.objects.create(question='Is this a question?')
        request = self.factory.get(self.url, {'term': 'is', **self.opts})
        request.user = self.superuser
        response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(data, {
            'results': [{'id': str(q.pk), 'text': q.question}],
            'pagination': {'more': False},
        })

    def test_custom_to_field(self):
        q = Question.objects.create(question='Is this a question?')
        request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'question_with_to_field'})
        request.user = self.superuser
        response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(data, {
            'results': [{'id': str(q.uuid), 'text': q.question}],
            'pagination': {'more': False},
        })

    def test_field_does_not_exist(self):
        request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'does_not_exist'})
        request.user = self.superuser
        with self.assertRaises(PermissionDenied):
            AutocompleteJsonView.as_view(**self.as_view_args)(request)

    def test_field_no_related_field(self):
        request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'answer'})
        request.user = self.superuser
        with self.assertRaises(PermissionDenied):
            AutocompleteJsonView.as_view(**self.as_view_args)(request)

    def test_field_does_not_allowed(self):
        request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'related_questions'})
        request.user = self.superuser
        with self.assertRaises(PermissionDenied):
            AutocompleteJsonView.as_view(**self.as_view_args)(request)

    def test_limit_choices_to(self):
        # Answer.question_with_to_field defines limit_choices_to to "those not
        # starting with 'not'".
        q = Question.objects.create(question='Is this a question?')
        Question.objects.create(question='Not a question.')
        request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'question_with_to_field'})
        request.user = self.superuser
        response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(data, {
            'results': [{'id': str(q.uuid), 'text': q.question}],
            'pagination': {'more': False},
        })

    def test_must_be_logged_in(self):
        response = self.client.get(self.url, {'term': '', **self.opts})
        self.assertEqual(response.status_code, 200)
        self.client.logout()
        response = self.client.get(self.url, {'term': '', **self.opts})
        self.assertEqual(response.status_code, 302)

    def test_has_view_or_change_permission_required(self):
        """
        Users require the change permission for the related model to the
        autocomplete view for it.
        """
        request = self.factory.get(self.url, {'term': 'is', **self.opts})
        self.user.is_staff = True
        self.user.save()
        request.user = self.user
        with self.assertRaises(PermissionDenied):
            AutocompleteJsonView.as_view(**self.as_view_args)(request)
        for permission in ('view', 'change'):
            with self.subTest(permission=permission):<commit_msg>Removed unnecessary lines in test_has_view_or_change_permission_required().<commit_after>import json
from contextlib import contextmanager

from django.contrib import admin
from django.contrib.admin.tests import AdminSeleniumTestCase
from django.contrib.admin.views.autocomplete import AutocompleteJsonView
from django.contrib.auth.models import Permission, User
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import RequestFactory, override_settings
from django.urls import reverse, reverse_lazy

from .admin import AnswerAdmin, QuestionAdmin
from .models import Answer, Author, Authorship, Book, Question
from .tests import AdminViewBasicTestCase

PAGINATOR_SIZE = AutocompleteJsonView.paginate_by


class AuthorAdmin(admin.ModelAdmin):
    ordering = ['id']
    search_fields = ['id']


class AuthorshipInline(admin.TabularInline):
    model = Authorship
    autocomplete_fields = ['author']


class BookAdmin(admin.ModelAdmin):
    inlines = [AuthorshipInline]


site = admin.AdminSite(name='autocomplete_admin')
site.register(Question, QuestionAdmin)
site.register(Answer, AnswerAdmin)
site.register(Author, AuthorAdmin)
site.register(Book, BookAdmin)


@contextmanager
def model_admin(model, model_admin, admin_site=site):
    org_admin = admin_site._registry.get(model)
    if org_admin:
        admin_site.unregister(model)
    admin_site.register(model, model_admin)
    try:
        yield
    finally:
        if org_admin:
            admin_site._registry[model] = org_admin


class AutocompleteJsonViewTests(AdminViewBasicTestCase):
    as_view_args = {'admin_site': site}
    opts = {
        'app_label': Answer._meta.app_label,
        'model_name': Answer._meta.model_name,
        'field_name': 'question'
    }
    factory = RequestFactory()
    url = reverse_lazy('autocomplete_admin:autocomplete')

    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user(
            username='user', password='<PASSWORD>',
            email='<EMAIL>', is_staff=True,
        )
        super().setUpTestData()

    def test_success(self):
        q = Question.objects.create(question='Is this a question?')
        request = self.factory.get(self.url, {'term': 'is', **self.opts})
        request.user = self.superuser
        response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(data, {
            'results': [{'id': str(q.pk), 'text': q.question}],
            'pagination': {'more': False},
        })

    def test_custom_to_field(self):
        q = Question.objects.create(question='Is this a question?')
        request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'question_with_to_field'})
        request.user = self.superuser
        response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(data, {
            'results': [{'id': str(q.uuid), 'text': q.question}],
            'pagination': {'more': False},
        })

    def test_field_does_not_exist(self):
        request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'does_not_exist'})
        request.user = self.superuser
        with self.assertRaises(PermissionDenied):
            AutocompleteJsonView.as_view(**self.as_view_args)(request)

    def test_field_no_related_field(self):
        request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'answer'})
        request.user = self.superuser
        with self.assertRaises(PermissionDenied):
            AutocompleteJsonView.as_view(**self.as_view_args)(request)

    def test_field_does_not_allowed(self):
        request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'related_questions'})
        request.user = self.superuser
        with self.assertRaises(PermissionDenied):
            AutocompleteJsonView.as_view(**self.as_view_args)(request)

    def test_limit_choices_to(self):
        # Answer.question_with_to_field defines limit_choices_to to "those not
        # starting with 'not'".
        q = Question.objects.create(question='Is this a question?')
        Question.objects.create(question='Not a question.')
        request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'question_with_to_field'})
        request.user = self.superuser
        response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(data, {
            'results': [{'id': str(q.uuid), 'text': q.question}],
            'pagination': {'more': False},
        })

    def test_must_be_logged_in(self):
        response = self.client.get(self.url, {'term': '', **self.opts})
        self.assertEqual(response.status_code, 200)
        self.client.logout()
        response = self.client.get(self.url, {'term': '', **self.opts})
        self.assertEqual(response.status_code, 302)

    def test_has_view_or_change_permission_required(self):
        """
        Users require the change permission for the related model to the
        autocomplete view for it.
        """
        request = self.factory.get(self.url, {'term': 'is', **self.opts})
        request.user = self.user
        with self.assertRaises(PermissionDenied):
            AutocompleteJsonView.as_view(**self.as_view_args)(request)
        for permission in ('view', 'change'):
            with self.subTest(permission=permission):
{'fraction_non_alphanumeric': 0.12528922786871197, 'fraction_numerical': 0.003599280143971206, 'mean_word_length': 3.4508009153318078, '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': '3943944', 'n_tokens_mistral': 3516, 'n_tokens_neox': 3423, 'n_words': 664}