language
stringclasses
2 values
source_code
stringlengths
0
963k
test_code
stringlengths
300
420k
source_path
stringlengths
29
179
test_path
stringlengths
36
183
repo_name
stringclasses
58 values
instruction
stringlengths
380
1.3k
meta_class
stringlengths
2
57
python
import contextlib import os @contextlib.contextmanager def override_environ(**kwargs): save_env = dict(os.environ) for key, value in kwargs.items(): if value is None: del os.environ[key] else: os.environ[key] = value try: yield finally: os.enviro...
import copy import filecmp import os import tarfile import zipfile from collections import deque from io import BytesIO from unittest import mock import pytest from requests import compat from requests._internal_utils import unicode_is_ascii from requests.cookies import RequestsCookieJar from requests.structures impo...
./temp_repos/requests/tests/utils.py
./temp_repos/requests/tests/test_utils.py
requests
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: os, contextlib Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the ex...
Unknown
python
""" requests.hooks ~~~~~~~~~~~~~~ This module provides the capabilities for the Requests hooks system. Available hooks: ``response``: The response generated from a Request. """ HOOKS = ["response"] def default_hooks(): return {event: [] for event in HOOKS} # TODO: response is the only one def dispatch_...
import pytest from requests import hooks def hook(value): return value[1:] @pytest.mark.parametrize( "hooks_list, result", ( (hook, "ata"), ([hook, lambda x: None, hook], "ta"), ), ) def test_hooks(hooks_list, result): assert hooks.dispatch_hook("response", {"response": hooks_li...
./temp_repos/requests/src/requests/hooks.py
./temp_repos/requests/tests/test_hooks.py
requests
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external depende...
Unknown
python
"""Module containing bug report helper(s).""" import json import platform import ssl import sys import idna import urllib3 from . import __version__ as requests_version try: import charset_normalizer except ImportError: charset_normalizer = None try: import chardet except ImportError: chardet = Non...
from unittest import mock from requests.help import info def test_system_ssl(): """Verify we're actually setting system_ssl when it should be available.""" assert info()["system_ssl"]["version"] != "" class VersionedPackage: def __init__(self, version): self.__version__ = version def test_idn...
./temp_repos/requests/src/requests/help.py
./temp_repos/requests/tests/test_help.py
requests
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: OpenSSL, platform, urllib3.contrib, idna, ssl, urllib3, chardet, json, charset_normalizer, cryp...
Unknown
python
""" Built-in, globally-available admin actions. """ from django.contrib import messages from django.contrib.admin import helpers from django.contrib.admin.decorators import action from django.contrib.admin.utils import model_ngettext from django.core.exceptions import PermissionDenied from django.template.response imp...
from django.contrib import admin from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import TestCase from .models import Band class AdminActionsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.ob...
./temp_repos/django/django/contrib/admin/actions.py
./temp_repos/django/tests/modeladmin/test_actions.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.contrib.admin.decorators, django.contrib.admin, django.core.exceptions, django.contrib.a...
Unknown
python
from ctypes import c_void_p class CPointerBase: """ Base class for objects that have a pointer access property that controls access to the underlying C pointer. """ _ptr = None # Initially the pointer is NULL. ptr_type = c_void_p destructor = None null_ptr_exception_class = Attribute...
import ctypes from unittest import mock from django.contrib.gis.ptr import CPointerBase from django.test import SimpleTestCase class CPointerBaseTests(SimpleTestCase): def test(self): destructor_mock = mock.Mock() class NullPointerException(Exception): pass class FakeGeom1(C...
./temp_repos/django/django/contrib/gis/ptr.py
./temp_repos/django/tests/gis_tests/test_ptr.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'CPointerBase'. Context: - Class Name: CPointerBase - Dependencies to Mock: None detected - Key Imports: ctypes Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the ...
CPointerBase
python
""" This module houses the GeoIP2 object, a wrapper for the MaxMind GeoIP2(R) Python API (https://geoip2.readthedocs.io/). This is an alternative to the Python GeoIP2 interface provided by MaxMind. GeoIP(R) is a registered trademark of MaxMind, Inc. For IP-based geolocation, this module requires the GeoLite2 Country ...
import ipaddress import itertools import pathlib from unittest import mock, skipUnless from django.conf import settings from django.contrib.gis.geoip2 import HAS_GEOIP2 from django.contrib.gis.geos import GEOSGeometry from django.test import SimpleTestCase, override_settings if HAS_GEOIP2: import geoip2 from...
./temp_repos/django/django/contrib/gis/geoip2.py
./temp_repos/django/tests/gis_tests/test_geoip2.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'GeoIP2Exception'. Context: - Class Name: GeoIP2Exception - Dependencies to Mock: cache, path, country, city - Key Imports: django.utils.functional, django.conf, django.contrib.gis.geos, dja...
GeoIP2Exception
python
""" ******** Models for test_data.py *********** The following classes are for testing basic data marshalling, including NULL values, where allowed. The basic idea is to have a model for each Django data type. """ import uuid from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from djang...
""" This module has the mock object definitions used to hold reference geometry for the GEOS and GDAL tests. """ import json import os from django.utils.functional import cached_property # Path where reference test data is located. TEST_DATA = os.path.join(os.path.dirname(__file__), "data") def tuplize(seq): "...
./temp_repos/django/tests/serializers/models/data.py
./temp_repos/django/tests/gis_tests/test_data.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'BinaryData'. Context: - Class Name: BinaryData - Dependencies to Mock: None detected - Key Imports: base, django.contrib.contenttypes.fields, django.db, django.contrib.contenttypes.models, ...
BinaryData
python
from ctypes import c_void_p from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.libgdal import GDAL_VERSION from django.contrib.gis.gdal.prototypes import ds as capi from django.utils.encoding import force_bytes, force_str class Drive...
import unittest from unittest import mock from django.contrib.gis.gdal import GDAL_VERSION, Driver, GDALException valid_drivers = ( # vector "ESRI Shapefile", "MapInfo File", "S57", "DGN", "Memory", "CSV", "GML", "KML", # raster "GTiff", "JPEG", "MEM", "PNG", ) ...
./temp_repos/django/django/contrib/gis/gdal/driver.py
./temp_repos/django/tests/gis_tests/gdal_tests/test_driver.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Driver'. Context: - Class Name: Driver - Dependencies to Mock: dr_input - Key Imports: django.contrib.gis.gdal.libgdal, django.contrib.gis.gdal.prototypes, django.contrib.gis.gdal.error, dj...
Driver
python
""" This module houses the ctypes function prototypes for GDAL DataSource (raster) related data structures. """ from ctypes import POINTER, c_bool, c_char_p, c_double, c_int, c_void_p from functools import partial from django.contrib.gis.gdal.libgdal import std_call from django.contrib.gis.gdal.prototypes.generation ...
import os import shutil import struct import tempfile import zipfile from pathlib import Path from unittest import mock from django.contrib.gis.gdal import GDAL_VERSION, GDALRaster, SpatialReference from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.raster.band import GDALBand from dj...
./temp_repos/django/django/contrib/gis/gdal/prototypes/raster.py
./temp_repos/django/tests/gis_tests/gdal_tests/test_raster.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.contrib.gis.gdal.libgdal, django.contrib.gis.gdal.prototypes.generation, functools, ctyp...
Unknown
python
""" Creates the default Site object. """ from django.apps import apps as global_apps from django.conf import settings from django.core.management.color import no_style from django.db import DEFAULT_DB_ALIAS, connections, router def create_default_site( app_config, verbosity=2, interactive=True, using...
import datetime import os import shutil import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from admin_scripts.tests import AdminScriptTestCase from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import storage from django....
./temp_repos/django/django/contrib/sites/management.py
./temp_repos/django/tests/staticfiles_tests/test_management.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.db, django.conf, django.apps, django.core.management.color Requirements: 1. Use 'unitte...
Unknown
python
import collections from itertools import chain from django.apps import apps from django.conf import settings from django.contrib.admin.exceptions import NotRegistered from django.contrib.admin.utils import NotRelationField, flatten, get_fields_from_path from django.core import checks from django.core.exceptions import...
from pathlib import Path from unittest import mock from django.conf import DEFAULT_STORAGE_ALIAS, STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles.checks import E005, check_finders, check_storages from django.contrib.staticfiles.finders import BaseFinder, get_finder from django.core.checks import Er...
./temp_repos/django/django/contrib/admin/checks.py
./temp_repos/django/tests/staticfiles_tests/test_checks.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'BaseModelAdminChecks'. Context: - Class Name: BaseModelAdminChecks - Dependencies to Mock: None detected - Key Imports: collections, django.utils.module_loading, itertools, django.conf, dja...
BaseModelAdminChecks
python
from django.core.files.storage.filesystem import FileSystemStorage class NoReadFileSystemStorage(FileSystemStorage): def open(self, *args, **kwargs): raise AssertionError("This storage class does not support reading.")
import json import os import shutil import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.management.comman...
./temp_repos/django/tests/model_fields/storage.py
./temp_repos/django/tests/staticfiles_tests/test_storage.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'NoReadFileSystemStorage'. Context: - Class Name: NoReadFileSystemStorage - Dependencies to Mock: None detected - Key Imports: django.core.files.storage.filesystem Requirements: 1. Use 'uni...
NoReadFileSystemStorage
python
from urllib.parse import urlparse from urllib.request import url2pathname from asgiref.sync import sync_to_async from django.conf import settings from django.contrib.staticfiles import utils from django.contrib.staticfiles.views import serve from django.core.handlers.asgi import ASGIHandler from django.core.handlers....
from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler from django.core.handlers.asgi import ASGIHandler from django.test import AsyncRequestFactory from .cases import StaticFilesTestCase class MockApplication: """ASGI application that returns a string indicating that it was called.""" async...
./temp_repos/django/django/contrib/staticfiles/handlers.py
./temp_repos/django/tests/staticfiles_tests/test_handlers.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'StaticFilesHandlerMixin'. Context: - Class Name: StaticFilesHandlerMixin - Dependencies to Mock: application - Key Imports: django.conf, django.http, django.core.handlers.asgi, urllib.parse...
StaticFilesHandlerMixin
python
""" This module contains helper functions for controlling caching. It does so by managing the "Vary" header of responses. It includes functions to patch the header of response objects directly and decorators that change functions to do that header-patching themselves. For information on the Vary header, see RFC 9110 S...
from unittest import mock from asgiref.sync import iscoroutinefunction from django.http import HttpRequest, HttpResponse from django.test import SimpleTestCase from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_control, cache_page, never_cache class HttpRequestProxy...
./temp_repos/django/django/utils/cache.py
./temp_repos/django/tests/decorators/test_cache.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: collections, time, django.conf, django.http, django.utils.timezone, django.core.cache, django.u...
Unknown
python
from django.http import HttpResponse def empty_view(request, *args, **kwargs): return HttpResponse()
import datetime from unittest import mock from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.views import shortcut from django.contrib.sites.models import Site from django.contrib.sites.shortcuts import get_current_site from django.http import Http404, HttpRequest from django.t...
./temp_repos/django/tests/urlpatterns/views.py
./temp_repos/django/tests/contenttypes_tests/test_views.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.http Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the exter...
Unknown
python
""" Creates the default Site object. """ from django.apps import apps as global_apps from django.conf import settings from django.core.management.color import no_style from django.db import DEFAULT_DB_ALIAS, connections, router def create_default_site( app_config, verbosity=2, interactive=True, using...
from unittest import mock from django.apps.registry import Apps, apps from django.contrib.contenttypes import management as contenttypes_management from django.contrib.contenttypes.models import ContentType from django.core.management import call_command from django.test import TestCase, modify_settings from django.te...
./temp_repos/django/django/contrib/sites/management.py
./temp_repos/django/tests/contenttypes_tests/test_management.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.db, django.conf, django.apps, django.core.management.color Requirements: 1. Use 'unitte...
Unknown
python
import collections from itertools import chain from django.apps import apps from django.conf import settings from django.contrib.admin.exceptions import NotRegistered from django.contrib.admin.utils import NotRelationField, flatten, get_fields_from_path from django.core import checks from django.core.exceptions import...
from unittest import mock from django.contrib.contenttypes.checks import check_model_name_lengths from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core import checks from django.db import models from django.test imp...
./temp_repos/django/django/contrib/admin/checks.py
./temp_repos/django/tests/contenttypes_tests/test_checks.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'BaseModelAdminChecks'. Context: - Class Name: BaseModelAdminChecks - Dependencies to Mock: None detected - Key Imports: collections, django.utils.module_loading, itertools, django.conf, dja...
BaseModelAdminChecks
python
from django.apps import apps from django.contrib.sites.models import Site from django.core.cache import cache from django.test import TestCase, modify_settings, override_settings from .models import I18nTestModel, TestModel @modify_settings(INSTALLED_APPS={"append": "django.contrib.sitemaps"}) @override_settings(ROO...
import os from unittest import mock from django.core.exceptions import SuspiciousFileOperation from django.core.files.storage import Storage from django.test import SimpleTestCase class CustomStorage(Storage): """Simple Storage subclass implementing the bare minimum for testing.""" def exists(self, name): ...
./temp_repos/django/tests/sitemaps_tests/base.py
./temp_repos/django/tests/file_storage/test_base.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'SitemapTestsBase'. Context: - Class Name: SitemapTestsBase - Dependencies to Mock: None detected - Key Imports: django.test, django.contrib.sites.models, django.core.cache, models, django.a...
SitemapTestsBase
python
from django.contrib.gis.db.models.fields import BaseSpatialField from django.contrib.gis.measure import Distance from django.db import NotSupportedError from django.db.models import Expression, Lookup, Transform from django.db.models.sql.query import Query from django.utils.regex_helper import _lazy_re_compile class ...
from datetime import datetime from unittest import mock from django.db.models import DateTimeField, Value from django.db.models.lookups import Lookup, YearLookup from django.test import SimpleTestCase class CustomLookup(Lookup): pass class LookupTests(SimpleTestCase): def test_equality(self): looku...
./temp_repos/django/django/contrib/gis/db/models/lookups.py
./temp_repos/django/tests/lookup/test_lookups.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'RasterBandTransform'. Context: - Class Name: RasterBandTransform - Dependencies to Mock: lhs, rhs - Key Imports: django.db.models.sql.query, django.db, django.contrib.gis.db.models.fields, ...
RasterBandTransform
python
from contextlib import contextmanager from copy import copy # Hard-coded processor for easier use of CSRF protection. _builtin_context_processors = ("django.template.context_processors.csrf",) class ContextPopException(Exception): "pop() has been called more times than push()" pass class ContextDict(dict)...
from copy import copy from unittest import mock from django.http import HttpRequest from django.template import ( Context, Engine, RequestContext, Template, Variable, VariableDoesNotExist, ) from django.template.context import RenderContext from django.test import RequestFactory, SimpleTestCase...
./temp_repos/django/django/template/context.py
./temp_repos/django/tests/template_tests/test_context.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'ContextPopException'. Context: - Class Name: ContextPopException - Dependencies to Mock: dict_, processors, use_l10n, autoescape, context, use_tz, request - Key Imports: contextlib, copy R...
ContextPopException
python
""" Cross Site Request Forgery Middleware. This module provides a middleware that implements protection against request forgeries from other sites. """ import logging import string from collections import defaultdict from urllib.parse import urlsplit from django.conf import settings from django.core.exceptions impor...
from unittest import mock from django.template import TemplateDoesNotExist from django.test import Client, RequestFactory, SimpleTestCase, override_settings from django.utils.translation import override from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure @override_settings(ROOT_URLCONF="view_tests...
./temp_repos/django/django/middleware/csrf.py
./temp_repos/django/tests/view_tests/tests/test_csrf.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'InvalidTokenFormat'. Context: - Class Name: InvalidTokenFormat - Dependencies to Mock: reason - Key Imports: collections, string, django.conf, django.http, django.utils.log, django.utils.cr...
InvalidTokenFormat
python
import functools import inspect import itertools import re import sys import types import warnings from pathlib import Path from django.conf import settings from django.http import Http404, HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.default...
import importlib import inspect import os import re import sys import tempfile import threading from io import StringIO from pathlib import Path from unittest import mock, skipIf from asgiref.sync import async_to_sync, iscoroutinefunction from django.core import mail from django.core.files.uploadedfile import SimpleU...
./temp_repos/django/django/views/debug.py
./temp_repos/django/tests/view_tests/tests/test_debug.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'ExceptionCycleWarning'. Context: - Class Name: ExceptionCycleWarning - Dependencies to Mock: tb, callable_setting, exc_type, is_email, exc_value, request - Key Imports: django.utils.module_...
ExceptionCycleWarning
python
import json import os import re from pathlib import Path from django.apps import apps from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.template import Context, Engine from django.urls import translate_url from django.utils.formats import get_format f...
import gettext import json from os import path from unittest import mock from django.conf import settings from django.test import ( RequestFactory, SimpleTestCase, TestCase, modify_settings, override_settings, ) from django.test.selenium import SeleniumTestCase from django.urls import reverse from ...
./temp_repos/django/django/views/i18n.py
./temp_repos/django/tests/view_tests/tests/test_i18n.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'JavaScriptCatalog'. Context: - Class Name: JavaScriptCatalog - Dependencies to Mock: None detected - Key Imports: django.conf, django.http, django.urls, django.utils.translation.trans_real,...
JavaScriptCatalog
python
""" Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ import mimetypes import posixpath from pathlib import Path from django.http import FileResponse, Http404, HttpResponse, HttpResponseNotModified from django.template impor...
import mimetypes import unittest from os import path from unittest import mock from urllib.parse import quote from django.conf.urls.static import static from django.core.exceptions import ImproperlyConfigured from django.http import FileResponse, HttpResponseNotModified from django.test import SimpleTestCase, override...
./temp_repos/django/django/views/static.py
./temp_repos/django/tests/view_tests/tests/test_static.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.utils._os, django.http, mimetypes, pathlib, django.utils.http, django.utils.translation,...
Unknown
python
from django.core.exceptions import ValidationError from django.forms.fields import BooleanField, IntegerField from django.forms.forms import Form from django.forms.renderers import get_default_renderer from django.forms.utils import ErrorList, RenderableFormMixin from django.forms.widgets import CheckboxInput, HiddenIn...
import datetime from collections import Counter from unittest import mock from django.core.exceptions import ValidationError from django.forms import ( BaseForm, CharField, DateField, FileField, Form, IntegerField, SplitDateTimeField, formsets, ) from django.forms.formsets import ( ...
./temp_repos/django/django/forms/formsets.py
./temp_repos/django/tests/forms_tests/tests/test_formsets.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'ManagementForm'. Context: - Class Name: ManagementForm - Dependencies to Mock: data, error_messages, auto_id, files, error_class, form_kwargs, initial, prefix - Key Imports: django.forms.fi...
ManagementForm
python
from django.contrib.admin.forms import AdminAuthenticationForm, AdminPasswordChangeForm from django.contrib.admin.helpers import ActionForm from django.core.exceptions import ValidationError class CustomAdminAuthenticationForm(AdminAuthenticationForm): class Media: css = {"all": ("path/to/media.css",)} ...
import datetime import re import sys import urllib.parse from unittest import mock from django import forms from django.contrib.auth.forms import ( AdminPasswordChangeForm, AdminUserCreationForm, AuthenticationForm, BaseUserCreationForm, PasswordChangeForm, PasswordResetForm, ReadOnlyPasswo...
./temp_repos/django/tests/admin_views/forms.py
./temp_repos/django/tests/auth_tests/test_forms.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'CustomAdminAuthenticationForm'. Context: - Class Name: CustomAdminAuthenticationForm - Dependencies to Mock: None detected - Key Imports: django.core.exceptions, django.contrib.admin.forms,...
CustomAdminAuthenticationForm
python
from datetime import datetime from django.conf import settings from django.utils.crypto import constant_time_compare, salted_hmac from django.utils.http import base36_to_int, int_to_base36 class PasswordResetTokenGenerator: """ Strategy object used to generate and check tokens for the password reset mech...
from datetime import datetime, timedelta from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from django.test.utils import override_settin...
./temp_repos/django/django/contrib/auth/tokens.py
./temp_repos/django/tests/auth_tests/test_tokens.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'PasswordResetTokenGenerator'. Context: - Class Name: PasswordResetTokenGenerator - Dependencies to Mock: None detected - Key Imports: datetime, django.conf, django.utils.http, django.utils....
PasswordResetTokenGenerator
python
from django.contrib.auth.backends import ModelBackend from .models import CustomUser class CustomUserBackend(ModelBackend): def authenticate(self, request, username=None, password=None): try: user = CustomUser.custom_objects.get_by_natural_key(username) if user.check_password(pass...
import sys from datetime import date from unittest import mock from unittest.mock import patch from asgiref.sync import sync_to_async from django.contrib.auth import ( BACKEND_SESSION_KEY, SESSION_KEY, _clean_credentials, aauthenticate, authenticate, get_user, signals, ) from django.contri...
./temp_repos/django/tests/test_client_regress/auth_backends.py
./temp_repos/django/tests/auth_tests/test_auth_backends.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'CustomUserBackend'. Context: - Class Name: CustomUserBackend - Dependencies to Mock: None detected - Key Imports: models, django.contrib.auth.backends Requirements: 1. Use 'unittest.mock' ...
CustomUserBackend
python
class StorageSettingsMixin: def _clear_cached_properties(self, setting, **kwargs): """Reset setting based property values.""" if setting == "MEDIA_ROOT": self.__dict__.pop("base_location", None) self.__dict__.pop("location", None) elif setting == "MEDIA_URL": ...
from unittest import mock from django.contrib.auth import models from django.contrib.auth.mixins import ( LoginRequiredMixin, PermissionRequiredMixin, UserPassesTestMixin, ) from django.contrib.auth.models import AnonymousUser from django.core.exceptions import PermissionDenied from django.http import Http...
./temp_repos/django/django/core/files/storage/mixins.py
./temp_repos/django/tests/auth_tests/test_mixins.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'StorageSettingsMixin'. Context: - Class Name: StorageSettingsMixin - Dependencies to Mock: None detected - Key Imports: Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2....
StorageSettingsMixin
python
import ipaddress import math import re from pathlib import Path from urllib.parse import urlsplit from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from django.utils.http import MAX_URL_LENGTH from django.utils.ipv6 import is_valid_ipv6_address from django.utils.re...
import os from unittest import mock from django.contrib.auth import validators from django.contrib.auth.models import User from django.contrib.auth.password_validation import ( CommonPasswordValidator, MinimumLengthValidator, NumericPasswordValidator, UserAttributeSimilarityValidator, get_default_p...
./temp_repos/django/django/core/validators.py
./temp_repos/django/tests/auth_tests/test_validators.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'RegexValidator'. Context: - Class Name: RegexValidator - Dependencies to Mock: flags, inverse_match, message, allowed_extensions, decimal_places, schemes, limit_value, allowlist, code, rege...
RegexValidator
python
def special(request): return {"path": request.special_path}
from django.contrib.auth import authenticate from django.contrib.auth.context_processors import PermLookupDict, PermWrapper from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.db.models import Q from django.test import SimpleTestCase, TestCase, ...
./temp_repos/django/tests/test_client_regress/context_processors.py
./temp_repos/django/tests/auth_tests/test_context_processors.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external depende...
Unknown
python
""" Reverse lookups This demonstrates the reverse lookup features of the database API. """ from django.db import models class User(models.Model): name = models.CharField(max_length=200) class Poll(models.Model): question = models.CharField(max_length=200) creator = models.ForeignKey(User, models.CASCA...
from unittest import mock from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.hashers import get_hasher from django.contrib.auth....
./temp_repos/django/tests/reverse_lookup/models.py
./temp_repos/django/tests/auth_tests/test_models.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'User'. Context: - Class Name: User - Dependencies to Mock: None detected - Key Imports: django.db Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external depe...
User
python
from django.http import HttpResponse def empty_view(request, *args, **kwargs): return HttpResponse()
import datetime import itertools import re from importlib import import_module from unittest import mock from urllib.parse import quote, urljoin from django.apps import apps from django.conf import settings from django.contrib.admin.models import LogEntry from django.contrib.auth import BACKEND_SESSION_KEY, REDIRECT_F...
./temp_repos/django/tests/urlpatterns/views.py
./temp_repos/django/tests/auth_tests/test_views.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.http Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the exter...
Unknown
python
""" Creates the default Site object. """ from django.apps import apps as global_apps from django.conf import settings from django.core.management.color import no_style from django.db import DEFAULT_DB_ALIAS, connections, router def create_default_site( app_config, verbosity=2, interactive=True, using...
import builtins import getpass import os import sys from datetime import date from io import StringIO from unittest import mock from django.apps import apps from django.conf import settings from django.contrib.auth import get_permission_codename, management from django.contrib.auth.management import ( RenamePermis...
./temp_repos/django/django/contrib/sites/management.py
./temp_repos/django/tests/auth_tests/test_management.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.db, django.conf, django.apps, django.core.management.color Requirements: 1. Use 'unitte...
Unknown
python
import base64 import binascii import functools import hashlib import importlib import math import warnings from asgiref.sync import sync_to_async from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.dispatch import receive...
from contextlib import contextmanager from unittest import mock, skipUnless from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth.hashers import ( UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH, Argon2PasswordHasher, BasePasswordHasher, BCryptPasswordHasher, ...
./temp_repos/django/django/contrib/auth/hashers.py
./temp_repos/django/tests/auth_tests/test_hashers.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'BasePasswordHasher'. Context: - Class Name: BasePasswordHasher - Dependencies to Mock: None detected - Key Imports: django.dispatch, django.utils.module_loading, django.conf, django.utils.c...
BasePasswordHasher
python
from types import NoneType from django.core.exceptions import ValidationError from django.db import DEFAULT_DB_ALIAS from django.db.backends.ddl_references import Expressions, Statement, Table from django.db.models import BaseConstraint, Deferrable, F, Q from django.db.models.expressions import Exists, ExpressionList ...
import datetime from unittest import mock from django.contrib.postgres.indexes import OpClass from django.core.checks import Error from django.core.exceptions import ValidationError from django.db import IntegrityError, connection, transaction from django.db.models import ( CASCADE, CharField, CheckConstra...
./temp_repos/django/django/contrib/postgres/constraints.py
./temp_repos/django/tests/postgres_tests/test_constraints.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'ExclusionConstraintExpression'. Context: - Class Name: ExclusionConstraintExpression - Dependencies to Mock: None detected - Key Imports: django.db, django.db.models.expressions, django.cor...
ExclusionConstraintExpression
python
from pathlib import Path import jinja2 from django.conf import settings from django.template import TemplateDoesNotExist, TemplateSyntaxError from django.utils.functional import cached_property from django.utils.module_loading import import_string from .base import BaseEngine from .utils import csrf_input_lazy, csrf...
from pathlib import Path from unittest import mock, skipIf from django.contrib.auth.models import User from django.template import TemplateSyntaxError from django.test import RequestFactory, TestCase from .test_dummy import TemplateStringsTests try: import jinja2 except ImportError: jinja2 = None Jinja2 ...
./temp_repos/django/django/template/backends/jinja2.py
./temp_repos/django/tests/template_backends/test_jinja2.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Jinja2'. Context: - Class Name: Jinja2 - Dependencies to Mock: template, template_name, name, params, backend - Key Imports: django.utils.module_loading, django.conf, base, pathlib, utils, ...
Jinja2
python
"Commonly-used date structures" from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy WEEKDAYS = { 0: _("Monday"), 1: _("Tuesday"), 2: _("Wednesday"), 3: _("Thursday"), 4: _("Friday"), 5: _("Saturday"), 6: _("Sunday"), } WEEKDAYS_ABBR = {...
import datetime from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, override_settings, skipUnlessDBFeature from django.test.utils import requires_tz_support from .models import Artist, Author, Book, BookSigning, Page def _make_books(n, base_date): ...
./temp_repos/django/django/utils/dates.py
./temp_repos/django/tests/generic_views/test_dates.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.utils.translation Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. M...
Unknown
python
from django.apps import apps from django.contrib.sites.models import Site from django.core.cache import cache from django.test import TestCase, modify_settings, override_settings from .models import I18nTestModel, TestModel @modify_settings(INSTALLED_APPS={"append": "django.contrib.sitemaps"}) @override_settings(ROO...
import logging import time from logging_tests.tests import LoggingAssertionMixin from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponse from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import require_jinja2 from django.urls import r...
./temp_repos/django/tests/sitemaps_tests/base.py
./temp_repos/django/tests/generic_views/test_base.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'SitemapTestsBase'. Context: - Class Name: SitemapTestsBase - Dependencies to Mock: None detected - Key Imports: django.test, django.contrib.sites.models, django.core.cache, models, django.a...
SitemapTestsBase
python
""" Timezone-related classes and functions. """ import functools import zoneinfo from contextlib import ContextDecorator from datetime import UTC, datetime, timedelta, timezone, tzinfo from asgiref.local import Local from django.conf import settings __all__ = [ "get_fixed_timezone", "get_default_timezone", ...
import datetime import zoneinfo from unittest import mock from django.test import SimpleTestCase, override_settings from django.utils import timezone PARIS_ZI = zoneinfo.ZoneInfo("Europe/Paris") EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok UTC = datet...
./temp_repos/django/django/utils/timezone.py
./temp_repos/django/tests/utils_tests/test_timezone.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'override'. Context: - Class Name: override - Dependencies to Mock: timezone - Key Imports: contextlib, zoneinfo, django.conf, asgiref.local, functools, datetime Requirements: 1. Use 'unitt...
override
python
"""HTML utilities suitable for global use.""" import html import json import re import warnings from collections import deque from collections.abc import Mapping from html.parser import HTMLParser from itertools import chain from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit from djan...
import os import sys from datetime import datetime from django.core.exceptions import SuspiciousOperation from django.core.serializers.json import DjangoJSONEncoder from django.test import SimpleTestCase from django.test.utils import override_settings from django.utils.deprecation import RemovedInDjango70Warning from ...
./temp_repos/django/django/utils/html.py
./temp_repos/django/tests/utils_tests/test_html.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'MLStripper'. Context: - Class Name: MLStripper - Dependencies to Mock: None detected - Key Imports: collections, html, django.utils.functional, django.utils.safestring, html.parser, django....
MLStripper
python
""" Utility functions for generating "lorem ipsum" Latin text. """ import random COMMON_P = ( "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod " "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim " "veniam, quis nostrud exercitation ullamco laboris nisi ut aliqu...
import unittest from unittest import mock from django.utils.lorem_ipsum import paragraph, paragraphs, sentence, words class LoremIpsumTests(unittest.TestCase): def test_negative_words(self): """words(n) returns n + 19 words, even if n is negative.""" self.assertEqual( words(-5), ...
./temp_repos/django/django/utils/lorem_ipsum.py
./temp_repos/django/tests/utils_tests/test_lorem_ipsum.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: random Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external d...
Unknown
python
from datetime import date, datetime from django.conf.urls.i18n import i18n_patterns from django.contrib.sitemaps import GenericSitemap, Sitemap, views from django.http import HttpResponse from django.urls import path from django.utils import timezone from django.views.decorators.cache import cache_page from ..models ...
import platform import unittest from datetime import UTC, datetime from unittest import mock from django.test import SimpleTestCase from django.utils.datastructures import MultiValueDict from django.utils.http import ( MAX_HEADER_LENGTH, MAX_URL_LENGTH, base36_to_int, content_disposition_header, es...
./temp_repos/django/tests/sitemaps_tests/urls/http.py
./temp_repos/django/tests/utils_tests/test_http.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'SimpleSitemap'. Context: - Class Name: SimpleSitemap - Dependencies to Mock: None detected - Key Imports: django.http, django.contrib.sitemaps, django.urls, django.utils, django.views.decor...
SimpleSitemap
python
import itertools import logging import os import signal import subprocess import sys import threading import time import traceback import weakref from collections import defaultdict from functools import lru_cache, wraps from pathlib import Path from types import ModuleType from zipimport import zipimporter import dja...
import contextlib import os import py_compile import shutil import sys import tempfile import threading import time import types import weakref import zipfile import zoneinfo from importlib import import_module from pathlib import Path from subprocess import CompletedProcess from unittest import mock, skip, skipIf imp...
./temp_repos/django/django/utils/autoreload.py
./temp_repos/django/tests/utils_tests/test_autoreload.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'BaseReloader'. Context: - Class Name: BaseReloader - Dependencies to Mock: None detected - Key Imports: collections, django.dispatch, django, pathlib, django.utils.version, django.utils.fun...
BaseReloader
python
import secrets from enum import StrEnum from django.utils.functional import SimpleLazyObject, empty class CSP(StrEnum): """ Content Security Policy constants for directive values and special tokens. These constants represent: 1. Standard quoted string values from the CSP spec (e.g., 'self', '...
from secrets import token_urlsafe from unittest.mock import patch from django.test import SimpleTestCase from django.utils.csp import CSP, LazyNonce, build_policy from django.utils.functional import empty basic_config = { "default-src": [CSP.SELF], } alt_config = { "default-src": [CSP.SELF, CSP.UNSAFE_INLINE]...
./temp_repos/django/django/utils/csp.py
./temp_repos/django/tests/utils_tests/test_csp.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'CSP'. Context: - Class Name: CSP - Dependencies to Mock: None detected - Key Imports: django.utils.functional, secrets, enum Requirements: 1. Use 'unittest.mock' library (MagicMock, patch)...
CSP
python
""" Syndication feed generation library -- used for generating RSS, etc. Sample usage: >>> from django.utils import feedgenerator >>> feed = feedgenerator.Rss201rev2Feed( ... title="Poynter E-Media Tidbits", ... link="http://www.poynter.org/column.asp?id=31", ... description="A group blog by the sharpest ...
import datetime from unittest import mock from django.test import SimpleTestCase from django.utils import feedgenerator from django.utils.functional import SimpleLazyObject from django.utils.timezone import get_fixed_timezone class FeedgeneratorTests(SimpleTestCase): """ Tests for the low-level syndication f...
./temp_repos/django/django/utils/feedgenerator.py
./temp_repos/django/tests/utils_tests/test_feedgenerator.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Stylesheet'. Context: - Class Name: Stylesheet - Dependencies to Mock: stylesheets, mime_type, link, author_link, feed_copyright, author_email, description, url, ttl, media, subtitle, autho...
Stylesheet
python
import codecs import datetime import locale from decimal import Decimal from types import NoneType from urllib.parse import quote from django.utils.functional import Promise class DjangoUnicodeDecodeError(UnicodeDecodeError): def __str__(self): return "%s. You passed in %r (%s)" % ( super()._...
import datetime import inspect import sys import unittest from pathlib import Path from unittest import mock from urllib.parse import quote, quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, ...
./temp_repos/django/django/utils/encoding.py
./temp_repos/django/tests/utils_tests/test_encoding.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DjangoUnicodeDecodeError'. Context: - Class Name: DjangoUnicodeDecodeError - Dependencies to Mock: None detected - Key Imports: decimal, codecs, locale, urllib.parse, django.utils.functiona...
DjangoUnicodeDecodeError
python
from collections.abc import Callable, Iterable, Iterator, Mapping from itertools import islice, tee, zip_longest from django.utils.functional import Promise __all__ = [ "BaseChoiceIterator", "BlankChoiceIterator", "CallableChoiceIterator", "flatten_choices", "normalize_choices", ] class BaseChoi...
import collections.abc from unittest import mock from django.db.models import TextChoices from django.test import SimpleTestCase from django.utils.choices import ( BaseChoiceIterator, CallableChoiceIterator, flatten_choices, normalize_choices, ) from django.utils.translation import gettext_lazy as _ ...
./temp_repos/django/django/utils/choices.py
./temp_repos/django/tests/utils_tests/test_choices.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'BaseChoiceIterator'. Context: - Class Name: BaseChoiceIterator - Dependencies to Mock: func, blank_choice, choices - Key Imports: django.utils.functional, collections.abc, itertools, django...
BaseChoiceIterator
python
import gzip import re import secrets import textwrap import unicodedata from collections import deque from gzip import GzipFile from gzip import compress as gzip_compress from html import escape from html.parser import HTMLParser from io import BytesIO from django.core.exceptions import SuspiciousFileOperation from dj...
import json import sys from unittest.mock import patch from django.core.exceptions import SuspiciousFileOperation from django.test import SimpleTestCase from django.utils import text from django.utils.functional import lazystr from django.utils.text import format_lazy from django.utils.translation import gettext_lazy,...
./temp_repos/django/django/utils/text.py
./temp_repos/django/tests/utils_tests/test_text.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'TruncateHTMLParser'. Context: - Class Name: TruncateHTMLParser - Dependencies to Mock: text - Key Imports: secrets, textwrap, collections, html.parser, io, django.core.exceptions, html, dja...
TruncateHTMLParser
python
import functools import re from collections import defaultdict, namedtuple from enum import Enum from graphlib import TopologicalSorter from itertools import chain from django.conf import settings from django.db import models from django.db.migrations import operations from django.db.migrations.migration import Migrat...
import copy import functools import re from unittest import mock from django.apps import apps from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core.validators import RegexValidator, validate_slug from django.db import connection, migrations, models from django.db.mig...
./temp_repos/django/django/db/migrations/autodetector.py
./temp_repos/django/tests/migrations/test_autodetector.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'OperationDependency'. Context: - Class Name: OperationDependency - Dependencies to Mock: to_state, questioner, from_state - Key Imports: collections, django.db.migrations.questioner, iterto...
OperationDependency
python
import datetime import importlib import os import sys from django.apps import apps from django.core.management.base import OutputWrapper from django.db.models import NOT_PROVIDED from django.utils import timezone from django.utils.version import get_docs_version from .loader import MigrationLoader class MigrationQu...
import datetime from io import StringIO from unittest import mock from django.core.management.base import OutputWrapper from django.db.migrations.questioner import ( InteractiveMigrationQuestioner, MigrationQuestioner, ) from django.db.models import NOT_PROVIDED from django.test import SimpleTestCase from djan...
./temp_repos/django/django/db/migrations/questioner.py
./temp_repos/django/tests/migrations/test_questioner.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'MigrationQuestioner'. Context: - Class Name: MigrationQuestioner - Dependencies to Mock: log, prompt_output, specified_apps, defaults, dry_run, verbosity - Key Imports: importlib, django.co...
MigrationQuestioner
python
import os import re from importlib import import_module from django import get_version from django.apps import apps # SettingsReference imported for backwards compatibility in Django 2.2. from django.conf import SettingsReference # NOQA from django.db import migrations from django.db.migrations.loader import Migrati...
import datetime import decimal import enum import functools import math import os import pathlib import re import sys import time import uuid import zoneinfo from types import NoneType from unittest import mock import custom_migration_operations.more_operations import custom_migration_operations.operations from djang...
./temp_repos/django/django/db/migrations/writer.py
./temp_repos/django/tests/migrations/test_writer.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'OperationWriter'. Context: - Class Name: OperationWriter - Dependencies to Mock: indentation, migration, include_header, operation - Key Imports: django.db.migrations.serializer, django.uti...
OperationWriter
python
from django.core.checks import Error, Tags, register @register(Tags.commands) def migrate_and_makemigrations_autodetector(**kwargs): from django.core.management import get_commands, load_command_class commands = get_commands() make_migrations = load_command_class(commands["makemigrations"], "makemigrati...
import datetime import importlib import io import os import re import shutil import sys from pathlib import Path from unittest import mock from django.apps import apps from django.core.checks import Error, Tags, register from django.core.checks.registry import registry from django.core.management import CommandError, ...
./temp_repos/django/django/core/checks/commands.py
./temp_repos/django/tests/migrations/test_commands.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.core.checks, django.core.management Requirements: 1. Use 'unittest.mock' library (Magic...
Unknown
python
from django.apps.registry import apps as global_apps from django.db import migrations, router from .exceptions import InvalidMigrationPlan from .loader import MigrationLoader from .recorder import MigrationRecorder from .state import ProjectState class MigrationExecutor: """ End-to-end migration execution - ...
from unittest import mock from django.apps.registry import apps as global_apps from django.db import DatabaseError, connection, migrations, models from django.db.migrations.exceptions import InvalidMigrationPlan from django.db.migrations.executor import MigrationExecutor from django.db.migrations.graph import Migratio...
./temp_repos/django/django/db/migrations/executor.py
./temp_repos/django/tests/migrations/test_executor.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'MigrationExecutor'. Context: - Class Name: MigrationExecutor - Dependencies to Mock: progress_callback, connection - Key Imports: recorder, state, django.db, exceptions, django.apps.registr...
MigrationExecutor
python
""" Helpers to manipulate deferred DDL statements that might need to be adjusted or discarded within when executing a migration. """ from copy import deepcopy class Reference: """Base class that defines the reference interface.""" def references_table(self, table): """ Return whether or not ...
from django.db import connection from django.db.backends.ddl_references import ( Columns, Expressions, ForeignKeyName, IndexName, Statement, Table, ) from django.db.models import ExpressionList, F from django.db.models.functions import Upper from django.db.models.indexes import IndexExpression f...
./temp_repos/django/django/db/backends/ddl_references.py
./temp_repos/django/tests/backends/test_ddl_references.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Reference'. Context: - Class Name: Reference - Dependencies to Mock: template, col_suffixes, expressions, suffix, table, create_index_name, from_table, quote_value, opclasses, to_columns, t...
Reference
python
import os import subprocess import sys from django.db.backends.base.creation import BaseDatabaseCreation from .client import DatabaseClient class DatabaseCreation(BaseDatabaseCreation): def sql_table_creation_suffix(self): suffix = [] test_settings = self.connection.settings_dict["TEST"] ...
import subprocess import unittest from io import BytesIO, StringIO from unittest import mock from django.db import DatabaseError, connection from django.db.backends.base.creation import BaseDatabaseCreation from django.db.backends.mysql.creation import DatabaseCreation from django.test import SimpleTestCase from djang...
./temp_repos/django/django/db/backends/mysql/creation.py
./temp_repos/django/tests/backends/mysql/test_creation.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DatabaseCreation'. Context: - Class Name: DatabaseCreation - Dependencies to Mock: None detected - Key Imports: client, subprocess, django.db.backends.base.creation, os, sys Requirements: ...
DatabaseCreation
python
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures from django.db.backends.mysql.features import DatabaseFeatures as MySQLDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseSpatialFeatures, MySQLDatabaseFeatures): empty_intersection_returns_no...
from unittest import mock, skipUnless from django.db import connection from django.db.backends.mysql.features import DatabaseFeatures from django.test import TestCase @skipUnless(connection.vendor == "mysql", "MySQL tests") class TestFeatures(TestCase): def test_supports_transactions(self): """ A...
./temp_repos/django/django/contrib/gis/db/backends/mysql/features.py
./temp_repos/django/tests/backends/mysql/test_features.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DatabaseFeatures'. Context: - Class Name: DatabaseFeatures - Dependencies to Mock: None detected - Key Imports: django.utils.functional, django.contrib.gis.db.backends.base.features, django...
DatabaseFeatures
python
import os import subprocess import sys from django.db.backends.base.creation import BaseDatabaseCreation from .client import DatabaseClient class DatabaseCreation(BaseDatabaseCreation): def sql_table_creation_suffix(self): suffix = [] test_settings = self.connection.settings_dict["TEST"] ...
import unittest from contextlib import contextmanager from io import StringIO from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import DatabaseError, connection from django.db.backends.base.creation import BaseDatabaseCreation from django.test import SimpleTestCase try: ...
./temp_repos/django/django/db/backends/mysql/creation.py
./temp_repos/django/tests/backends/postgresql/test_creation.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DatabaseCreation'. Context: - Class Name: DatabaseCreation - Dependencies to Mock: None detected - Key Imports: client, subprocess, django.db.backends.base.creation, os, sys Requirements: ...
DatabaseCreation
python
import re from django.contrib.auth.views import ( INTERNAL_RESET_SESSION_TOKEN, PasswordResetConfirmView, ) from django.test import Client def extract_token_from_url(url): token_search = re.search(r"/reset/.*/(.+?)/", url) if token_search: return token_search[1] class PasswordResetConfirmCl...
from unittest import mock from django.db import connection from django.db.backends.base.client import BaseDatabaseClient from django.test import SimpleTestCase class SimpleDatabaseClientTests(SimpleTestCase): def setUp(self): self.client = BaseDatabaseClient(connection=connection) def test_settings_...
./temp_repos/django/tests/auth_tests/client.py
./temp_repos/django/tests/backends/base/test_client.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'PasswordResetConfirmClient'. Context: - Class Name: PasswordResetConfirmClient - Dependencies to Mock: None detected - Key Imports: django.contrib.auth.views, django.test, re Requirements:...
PasswordResetConfirmClient
python
import os import subprocess import sys from django.db.backends.base.creation import BaseDatabaseCreation from .client import DatabaseClient class DatabaseCreation(BaseDatabaseCreation): def sql_table_creation_suffix(self): suffix = [] test_settings = self.connection.settings_dict["TEST"] ...
import copy import datetime import os from unittest import mock from django.db import DEFAULT_DB_ALIAS, connection, connections from django.db.backends.base.creation import TEST_DATABASE_PREFIX, BaseDatabaseCreation from django.test import SimpleTestCase, TransactionTestCase from django.test.utils import override_sett...
./temp_repos/django/django/db/backends/mysql/creation.py
./temp_repos/django/tests/backends/base/test_creation.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DatabaseCreation'. Context: - Class Name: DatabaseCreation - Dependencies to Mock: None detected - Key Imports: client, subprocess, django.db.backends.base.creation, os, sys Requirements: ...
DatabaseCreation
python
from django.apps import apps from django.contrib.sites.models import Site from django.core.cache import cache from django.test import TestCase, modify_settings, override_settings from .models import I18nTestModel, TestModel @modify_settings(INSTALLED_APPS={"append": "django.contrib.sitemaps"}) @override_settings(ROO...
import gc from unittest.mock import MagicMock, patch from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction from django.db.backends.base.base import BaseDatabaseWrapper from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, skipUnlessDBFeature, ) from django.test...
./temp_repos/django/tests/sitemaps_tests/base.py
./temp_repos/django/tests/backends/base/test_base.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'SitemapTestsBase'. Context: - Class Name: SitemapTestsBase - Dependencies to Mock: None detected - Key Imports: django.test, django.contrib.sites.models, django.core.cache, models, django.a...
SitemapTestsBase
python
import os import subprocess import sys from django.db.backends.base.creation import BaseDatabaseCreation from .client import DatabaseClient class DatabaseCreation(BaseDatabaseCreation): def sql_table_creation_suffix(self): suffix = [] test_settings = self.connection.settings_dict["TEST"] ...
import unittest from io import StringIO from unittest import mock from django.db import DatabaseError, connection from django.db.backends.oracle.creation import DatabaseCreation from django.test import TestCase @unittest.skipUnless(connection.vendor == "oracle", "Oracle tests") @mock.patch.object(DatabaseCreation, "...
./temp_repos/django/django/db/backends/mysql/creation.py
./temp_repos/django/tests/backends/oracle/test_creation.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DatabaseCreation'. Context: - Class Name: DatabaseCreation - Dependencies to Mock: None detected - Key Imports: client, subprocess, django.db.backends.base.creation, os, sys Requirements: ...
DatabaseCreation
python
import os import subprocess import sys from django.db.backends.base.creation import BaseDatabaseCreation from .client import DatabaseClient class DatabaseCreation(BaseDatabaseCreation): def sql_table_creation_suffix(self): suffix = [] test_settings = self.connection.settings_dict["TEST"] ...
import copy import multiprocessing import unittest from unittest import mock from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connection, connections from django.test import SimpleTestCase @unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests") class TestDbSignatureTests(SimpleTestCase): de...
./temp_repos/django/django/db/backends/mysql/creation.py
./temp_repos/django/tests/backends/sqlite/test_creation.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DatabaseCreation'. Context: - Class Name: DatabaseCreation - Dependencies to Mock: None detected - Key Imports: client, subprocess, django.db.backends.base.creation, os, sys Requirements: ...
DatabaseCreation
python
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures from django.db.backends.mysql.features import DatabaseFeatures as MySQLDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseSpatialFeatures, MySQLDatabaseFeatures): empty_intersection_returns_no...
import sqlite3 from unittest import mock, skipUnless from django.db import OperationalError, connection from django.test import TestCase @skipUnless(connection.vendor == "sqlite", "SQLite tests.") class FeaturesTests(TestCase): def test_supports_json_field_operational_error(self): if hasattr(connection.f...
./temp_repos/django/django/contrib/gis/db/backends/mysql/features.py
./temp_repos/django/tests/backends/sqlite/test_features.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DatabaseFeatures'. Context: - Class Name: DatabaseFeatures - Dependencies to Mock: None detected - Key Imports: django.utils.functional, django.contrib.gis.db.backends.base.features, django...
DatabaseFeatures
python
import os from . import Error, Tags, register E001 = Error( "You should not set the DJANGO_ALLOW_ASYNC_UNSAFE environment variable in " "deployment. This disables async safety protection.", id="async.E001", ) @register(Tags.async_support, deploy=True) def check_async_unsafe(app_configs, **kwargs): i...
import os from unittest import mock from django.core.checks.async_checks import E001, check_async_unsafe from django.test import SimpleTestCase class AsyncCheckTests(SimpleTestCase): @mock.patch.dict(os.environ, {"DJANGO_ALLOW_ASYNC_UNSAFE": ""}) def test_no_allowed_async_unsafe(self): self.assertEqu...
./temp_repos/django/django/core/checks/async_checks.py
./temp_repos/django/tests/check_framework/test_async_checks.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: os Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external depen...
Unknown
python
from django.db import connections from . import Tags, register @register(Tags.database) def check_database_backends(databases=None, **kwargs): if databases is None: return [] issues = [] for alias in databases: conn = connections[alias] issues.extend(conn.validation.check(**kwargs...
import unittest from unittest import mock from django.core.checks.database import check_database_backends from django.db import connection, connections from django.test import TestCase class DatabaseCheckTests(TestCase): databases = {"default", "other"} @mock.patch("django.db.backends.base.validation.BaseDa...
./temp_repos/django/django/core/checks/database.py
./temp_repos/django/tests/check_framework/test_database.py
django
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: django.db Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the externa...
Unknown
python
from os import path from random import randrange from random import sample from urllib.parse import urlsplit from jinja2 import Environment from jinja2 import FileSystemLoader from werkzeug.local import Local from werkzeug.local import LocalManager from werkzeug.routing import Map from werkzeug.routing import Rule fro...
from __future__ import annotations import inspect from datetime import datetime import pytest from werkzeug import Request from werkzeug import utils from werkzeug.datastructures import Headers from werkzeug.http import http_date from werkzeug.http import parse_date from werkzeug.test import Client from werkzeug.tes...
./temp_repos/werkzeug/examples/couchy/utils.py
./temp_repos/werkzeug/tests/test_utils.py
werkzeug
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Pagination'. Context: - Class Name: Pagination - Dependencies to Mock: page, per_page, results, endpoint - Key Imports: werkzeug.utils, werkzeug.routing, random, werkzeug.wrappers, urllib.p...
Pagination
python
from __future__ import annotations import hashlib import hmac import os import posixpath import secrets SALT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" DEFAULT_PBKDF2_ITERATIONS = 1_000_000 _os_alt_seps: list[str] = list( sep for sep in [os.sep, os.path.altsep] if sep is not None an...
import os import sys import pytest from werkzeug.security import check_password_hash from werkzeug.security import generate_password_hash from werkzeug.security import safe_join def test_default_password_method(): value = generate_password_hash("secret") assert value.startswith("scrypt:") @pytest.mark.xfa...
./temp_repos/werkzeug/src/werkzeug/security.py
./temp_repos/werkzeug/tests/test_security.py
werkzeug
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: secrets, hmac, hashlib, os, __future__, posixpath Requirements: 1. Use 'unittest.mock' library...
Unknown
python
"""A WSGI and HTTP server for use **during development only**. This server is convenient to use, but is not designed to be particularly stable, secure, or efficient. Use a dedicate WSGI server and HTTP server when deploying to production. It provides features like interactive debugging and code reloading. Use ``run_si...
from __future__ import annotations import collections.abc as cabc import http.client import importlib.metadata import json import os import shutil import socket import ssl import sys import typing as t from importlib.metadata import PackageNotFoundError from io import BytesIO from pathlib import Path from unittest.moc...
./temp_repos/werkzeug/src/werkzeug/serving.py
./temp_repos/werkzeug/tests/test_serving.py
werkzeug
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DechunkedInput'. Context: - Class Name: DechunkedInput - Dependencies to Mock: rfile, app, host, handler, fd, ssl_context, processes, passthrough_errors, port - Key Imports: socketserver, d...
DechunkedInput
python
from __future__ import annotations import typing as t from io import BytesIO from urllib.parse import parse_qsl from ._internal import _plain_int from .datastructures import FileStorage from .datastructures import Headers from .datastructures import MultiDict from .exceptions import RequestEntityTooLarge from .http i...
import csv import io from os.path import dirname from os.path import join import pytest from werkzeug import formparser from werkzeug.datastructures import MultiDict from werkzeug.exceptions import RequestEntityTooLarge from werkzeug.formparser import FormDataParser from werkzeug.formparser import parse_form_data fro...
./temp_repos/werkzeug/src/werkzeug/formparser.py
./temp_repos/werkzeug/tests/test_formparser.py
werkzeug
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'FormDataParser'. Context: - Class Name: FormDataParser - Dependencies to Mock: max_content_length, silent, cls, stream_factory, max_form_parts, max_form_memory_size, buffer_size - Key Impor...
FormDataParser
python
""" X-Forwarded-For Proxy Fix ========================= This module provides a middleware that adjusts the WSGI environ based on ``X-Forwarded-`` headers that proxies in front of an application may set. When an application is running behind a proxy server, WSGI may see the request as coming from that server rather th...
import pytest from werkzeug.middleware.proxy_fix import ProxyFix from werkzeug.routing import Map from werkzeug.routing import Rule from werkzeug.test import Client from werkzeug.test import create_environ from werkzeug.utils import redirect from werkzeug.wrappers import Request from werkzeug.wrappers import Response ...
./temp_repos/werkzeug/src/werkzeug/middleware/proxy_fix.py
./temp_repos/werkzeug/tests/middleware/test_proxy_fix.py
werkzeug
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'ProxyFix'. Context: - Class Name: ProxyFix - Dependencies to Mock: app, x_proto, x_prefix, x_port, x_host, x_for - Key Imports: typing, http, __future__, _typeshed.wsgi Requirements: 1. Us...
ProxyFix
python
""" Application Profiler ==================== This module provides a middleware that profiles each request with the :mod:`cProfile` module. This can help identify bottlenecks in your code that may be slowing down your application. .. autoclass:: ProfilerMiddleware :copyright: 2007 Pallets :license: BSD-3-Clause """ ...
import datetime import os from unittest.mock import ANY from unittest.mock import MagicMock from unittest.mock import patch from werkzeug.middleware.profiler import Profile from werkzeug.middleware.profiler import ProfilerMiddleware from werkzeug.test import Client def dummy_application(environ, start_response): ...
./temp_repos/werkzeug/src/werkzeug/middleware/profiler.py
./temp_repos/werkzeug/tests/middleware/test_profiler.py
werkzeug
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'ProfilerMiddleware'. Context: - Class Name: ProfilerMiddleware - Dependencies to Mock: app, stream, profile_dir, sort_by, restrictions, filename_format - Key Imports: time, profile, cProfil...
ProfilerMiddleware
python
""" Application Dispatcher ====================== This middleware creates a single WSGI application that dispatches to multiple other WSGI applications mounted at different URL paths. A common example is writing a Single Page Application, where you have a backend API and a frontend written in JavaScript that does the...
from werkzeug.middleware.dispatcher import DispatcherMiddleware from werkzeug.test import create_environ from werkzeug.test import run_wsgi_app def test_dispatcher(): def null_application(environ, start_response): start_response("404 NOT FOUND", [("Content-Type", "text/plain")]) yield b"NOT FOUND"...
./temp_repos/werkzeug/src/werkzeug/middleware/dispatcher.py
./temp_repos/werkzeug/tests/middleware/test_dispatcher.py
werkzeug
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DispatcherMiddleware'. Context: - Class Name: DispatcherMiddleware - Dependencies to Mock: app, mounts - Key Imports: typing, __future__, _typeshed.wsgi Requirements: 1. Use 'unittest.mock...
DispatcherMiddleware
python
from fastapi import FastAPI, File, Form, UploadFile app = FastAPI() @app.post("/files/") async def create_file( file: bytes = File(), fileb: UploadFile = File(), token: str = Form() ): return { "file_size": len(file), "token": token, "fileb_content_type": fileb.content_type, }
import importlib from fastapi.testclient import TestClient from ...utils import needs_pydanticv2 def get_client() -> TestClient: from docs_src.conditional_openapi import tutorial001 importlib.reload(tutorial001) client = TestClient(tutorial001.app) return client @needs_pydanticv2 def test_disabl...
./temp_repos/fastapi/docs_src/request_forms_and_files/tutorial001.py
./temp_repos/fastapi/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py
fastapi
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: fastapi Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external ...
Unknown
python
from typing import Union from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: Union[str, None] = None price: float tax: Union[float, None] = None app = FastAPI() @app.post("/items/") async def create_item(item: Item): item_dict = item.dict()...
import importlib import warnings import pytest from dirty_equals import IsDict, IsInt from fastapi.testclient import TestClient from inline_snapshot import Is, snapshot from sqlalchemy import StaticPool from sqlmodel import SQLModel, create_engine from sqlmodel.main import default_registry from tests.utils import nee...
./temp_repos/fastapi/docs_src/body/tutorial002.py
./temp_repos/fastapi/tests/test_tutorial/test_sql_databases/test_tutorial002.py
fastapi
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Item'. Context: - Class Name: Item - Dependencies to Mock: None detected - Key Imports: typing, pydantic, fastapi Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock t...
Item
python
from fastapi import FastAPI, File, Form, UploadFile app = FastAPI() @app.post("/files/") async def create_file( file: bytes = File(), fileb: UploadFile = File(), token: str = Form() ): return { "file_size": len(file), "token": token, "fileb_content_type": fileb.content_type, }
import importlib from unittest.mock import patch import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ "tutorial001", pytest.param("tutorial001_py310", marks=needs_py310), ], ) def...
./temp_repos/fastapi/docs_src/request_forms_and_files/tutorial001.py
./temp_repos/fastapi/tests/test_tutorial/test_body/test_tutorial001.py
fastapi
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: fastapi Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external ...
Unknown
python
from fastapi import FastAPI, File, Form, UploadFile app = FastAPI() @app.post("/files/") async def create_file( file: bytes = File(), fileb: UploadFile = File(), token: str = Form() ): return { "file_size": len(file), "token": token, "fileb_content_type": fileb.content_type, }
import importlib import pytest from fastapi.testclient import TestClient from pytest import MonkeyPatch from ...utils import needs_pydanticv1, needs_pydanticv2 @pytest.fixture( name="app", params=[ pytest.param("tutorial001", marks=needs_pydanticv2), pytest.param("tutorial001_pv1", marks=nee...
./temp_repos/fastapi/docs_src/request_forms_and_files/tutorial001.py
./temp_repos/fastapi/tests/test_tutorial/test_settings/test_tutorial001.py
fastapi
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Unknown'. Context: - Class Name: Unknown - Dependencies to Mock: None detected - Key Imports: fastapi Requirements: 1. Use 'unittest.mock' library (MagicMock, patch). 2. Mock the external ...
Unknown
python
from __future__ import annotations import errno import importlib.util import os import stat from email.utils import parsedate from typing import Union import anyio import anyio.to_thread from starlette._utils import get_route_path from starlette.datastructures import URL, Headers from starlette.exceptions import HTT...
import os import stat import tempfile import time from pathlib import Path from typing import Any import anyio import pytest from starlette.applications import Starlette from starlette.exceptions import HTTPException from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware,...
./temp_repos/starlette/starlette/staticfiles.py
./temp_repos/starlette/tests/test_staticfiles.py
starlette
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'NotModifiedResponse'. Context: - Class Name: NotModifiedResponse - Dependencies to Mock: headers - Key Imports: anyio.to_thread, starlette._utils, starlette.datastructures, starlette.respon...
NotModifiedResponse
python
from __future__ import annotations import contextlib import inspect import io import json import math import sys import warnings from collections.abc import Awaitable, Callable, Generator, Iterable, Mapping, MutableMapping, Sequence from concurrent.futures import Future from contextlib import AbstractContextManager fr...
from __future__ import annotations import itertools import sys from asyncio import Task, current_task as asyncio_current_task from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from typing import Any import anyio import anyio.lowlevel import pytest import sniffio import trio.lowleve...
./temp_repos/starlette/starlette/testclient.py
./temp_repos/starlette/tests/test_testclient.py
starlette
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class '_WrapASGI2'. Context: - Class Name: _WrapASGI2 - Dependencies to Mock: app, follow_redirects, headers, backend_options, client, raise_server_exceptions, base_url, session, scope, root_path,...
_WrapASGI2
python
from __future__ import annotations import enum import json from collections.abc import AsyncIterator, Iterable from typing import Any, cast from starlette.requests import HTTPConnection from starlette.responses import Response from starlette.types import Message, Receive, Scope, Send class WebSocketState(enum.Enum)...
import sys from collections.abc import MutableMapping from typing import Any import anyio import pytest from anyio.abc import ObjectReceiveStream, ObjectSendStream from starlette import status from starlette.responses import Response from starlette.testclient import WebSocketDenialResponse from starlette.types import...
./temp_repos/starlette/starlette/websockets.py
./temp_repos/starlette/tests/test_websockets.py
starlette
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'WebSocketState'. Context: - Class Name: WebSocketState - Dependencies to Mock: send, receive, scope, code, reason - Key Imports: starlette.responses, enum, typing, collections.abc, starlett...
WebSocketState
python
from __future__ import annotations import hashlib import http.cookies import json import os import stat import sys import warnings from collections.abc import AsyncIterable, Awaitable, Callable, Iterable, Mapping, Sequence from datetime import datetime from email.utils import format_datetime, formatdate from functools...
from __future__ import annotations import datetime as dt import sys import time from collections.abc import AsyncGenerator, AsyncIterator, Iterator from http.cookies import SimpleCookie from pathlib import Path from typing import Any import anyio import pytest from starlette import status from starlette.background i...
./temp_repos/starlette/starlette/responses.py
./temp_repos/starlette/tests/test_responses.py
starlette
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Response'. Context: - Class Name: Response - Dependencies to Mock: status_code, path, headers, content_disposition_type, background, stat_result, url, filename, max_size, content, method, m...
Response
python
from __future__ import annotations import os import warnings from collections.abc import Callable, Iterator, Mapping, MutableMapping from pathlib import Path from typing import Any, TypeVar, overload class undefined: pass class EnvironError(Exception): pass class Environ(MutableMapping[str, str]): de...
import os from pathlib import Path from typing import Any import pytest from typing_extensions import assert_type from starlette.config import Config, Environ, EnvironError from starlette.datastructures import URL, Secret def test_config_types() -> None: """ We use `assert_type` to test the types returned b...
./temp_repos/starlette/starlette/config.py
./temp_repos/starlette/tests/test_config.py
starlette
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'undefined'. Context: - Class Name: undefined - Dependencies to Mock: encoding, env_prefix, env_file, environ - Key Imports: warnings, pathlib, typing, collections.abc, os, __future__ Requi...
undefined
python
from __future__ import annotations import http from collections.abc import Mapping class HTTPException(Exception): def __init__(self, status_code: int, detail: str | None = None, headers: Mapping[str, str] | None = None) -> None: if detail is None: detail = http.HTTPStatus(status_code).phrase...
from collections.abc import Generator from typing import Any import pytest from pytest import MonkeyPatch from starlette.exceptions import HTTPException, WebSocketException from starlette.middleware.exceptions import ExceptionMiddleware from starlette.requests import Request from starlette.responses import JSONRespon...
./temp_repos/starlette/starlette/exceptions.py
./temp_repos/starlette/tests/test_exceptions.py
starlette
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'HTTPException'. Context: - Class Name: HTTPException - Dependencies to Mock: status_code, headers, code, detail, reason - Key Imports: http, __future__, collections.abc Requirements: 1. Us...
HTTPException
python
from __future__ import annotations from collections.abc import AsyncGenerator from dataclasses import dataclass, field from enum import Enum from tempfile import SpooledTemporaryFile from typing import TYPE_CHECKING from urllib.parse import unquote_plus from starlette.datastructures import FormData, Headers, UploadFi...
from __future__ import annotations import os import threading from collections.abc import Generator from contextlib import AbstractContextManager, nullcontext as does_not_raise from io import BytesIO from pathlib import Path from tempfile import SpooledTemporaryFile from typing import Any, ClassVar from unittest impor...
./temp_repos/starlette/starlette/formparsers.py
./temp_repos/starlette/tests/test_formparsers.py
starlette
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'FormMessage'. Context: - Class Name: FormMessage - Dependencies to Mock: stream, message, headers - Key Imports: multipart, starlette.datastructures, enum, typing, multipart.multipart, coll...
FormMessage
python
from __future__ import annotations import functools import sys from collections.abc import Awaitable, Callable, Generator from contextlib import AbstractAsyncContextManager, contextmanager from typing import Any, Generic, Protocol, TypeVar, overload from starlette.types import Scope if sys.version_info >= (3, 13): ...
import functools from typing import Any from unittest.mock import create_autospec import pytest from starlette._utils import get_route_path, is_async_callable from starlette.types import Scope def test_async_func() -> None: async def async_func() -> None: ... # pragma: no cover def func() -> None: ... # ...
./temp_repos/starlette/starlette/_utils.py
./temp_repos/starlette/tests/test__utils.py
starlette
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'AwaitableOrContextManager'. Context: - Class Name: AwaitableOrContextManager - Dependencies to Mock: aw - Key Imports: contextlib, inspect, exceptiongroup, functools, typing_extensions, typ...
AwaitableOrContextManager
python
from __future__ import annotations import functools import re from collections.abc import Sequence from starlette.datastructures import Headers, MutableHeaders from starlette.responses import PlainTextResponse, Response from starlette.types import ASGIApp, Message, Receive, Scope, Send ALL_METHODS = ("DELETE", "GET"...
from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.middleware.cors import CORSMiddleware from starlette.requests import Request from starlette.responses import PlainTextResponse from starlette.routing import Route from tests.types import TestClientFactory def test_...
./temp_repos/starlette/starlette/middleware/cors.py
./temp_repos/starlette/tests/middleware/test_cors.py
starlette
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'CORSMiddleware'. Context: - Class Name: CORSMiddleware - Dependencies to Mock: app, allow_headers, max_age, allow_methods, allow_origin_regex, allow_private_network, expose_headers, allow_o...
CORSMiddleware
python
from __future__ import annotations from collections.abc import AsyncGenerator, AsyncIterable, Awaitable, Callable, Mapping, MutableMapping from typing import Any, TypeVar import anyio from starlette._utils import collapse_excgroups from starlette.requests import ClientDisconnect, Request from starlette.responses imp...
from __future__ import annotations import contextvars from collections.abc import AsyncGenerator, AsyncIterator, Generator from contextlib import AsyncExitStack from pathlib import Path from typing import Any import anyio import pytest from anyio.abc import TaskStatus from starlette.applications import Starlette fro...
./temp_repos/starlette/starlette/middleware/base.py
./temp_repos/starlette/tests/middleware/test_base.py
starlette
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class '_CachedRequest'. Context: - Class Name: _CachedRequest - Dependencies to Mock: status_code, app, headers, receive, dispatch, scope, content, info, media_type - Key Imports: starlette._utils...
_CachedRequest
python
import abc import asyncio import base64 import functools import hashlib import html import inspect import keyword import os import re import sys from collections.abc import ( Awaitable, Callable, Container, Generator, Iterable, Iterator, Mapping, Sized, ) from pathlib import Path from re...
import asyncio import functools import os import pathlib import socket import sys from collections.abc import Generator from stat import S_IFIFO, S_IMODE from typing import Any, NoReturn import pytest import yarl from aiohttp import web from aiohttp.pytest_plugin import AiohttpClient from aiohttp.web_urldispatcher im...
./temp_repos/aiohttp/aiohttp/web_urldispatcher.py
./temp_repos/aiohttp/tests/test_web_urldispatcher.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class '_InfoDict'. Context: - Class Name: _InfoDict - Dependencies to Mock: match_dict, path, app, handler, directory, resources, http_exception, resource, route, domain, method, rule, prefix - Ke...
_InfoDict
python
"""Various helper functions""" import asyncio import base64 import binascii import contextlib import dataclasses import datetime import enum import functools import inspect import netrc import os import platform import re import sys import time import warnings import weakref from collections import namedtuple from col...
import asyncio import base64 import datetime import gc import sys import weakref from collections.abc import Iterator from math import ceil, modf from pathlib import Path from types import MappingProxyType from unittest import mock from urllib.request import getproxies_environment import pytest from multidict import C...
./temp_repos/aiohttp/aiohttp/helpers.py
./temp_repos/aiohttp/tests/test_helpers.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'BasicAuth'. Context: - Class Name: BasicAuth - Dependencies to Mock: t, ceil_threshold, loop, name, timeout, maps - Key Imports: yarl, collections, email.policy, pathlib, binascii, dataclas...
BasicAuth
python
import asyncio import datetime import enum import json import math import time import warnings from collections.abc import Iterator, MutableMapping from concurrent.futures import Executor from http import HTTPStatus from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union, cast, overload from multidict import C...
import collections.abc import datetime import gzip import io import json import re import sys import weakref from collections.abc import AsyncIterator, Iterator from concurrent.futures import ThreadPoolExecutor from unittest import mock import aiosignal import pytest from multidict import CIMultiDict, CIMultiDictProxy...
./temp_repos/aiohttp/aiohttp/web_response.py
./temp_repos/aiohttp/tests/test_web_response.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'ContentCoding'. Context: - Class Name: ContentCoding - Dependencies to Mock: None detected - Key Imports: time, web_request, helpers, enum, math, warnings, payload, typedefs, typing, asynci...
ContentCoding
python
import asyncio import socket import weakref from typing import Any, Optional from .abc import AbstractResolver, ResolveResult __all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver") try: import aiodns aiodns_default = hasattr(aiodns.DNSResolver, "getaddrinfo") except ImportError: aiodns = No...
import asyncio import gc import ipaddress import socket from collections.abc import Awaitable, Callable, Collection, Generator, Iterable from ipaddress import ip_address from typing import Any, NamedTuple from unittest.mock import Mock, create_autospec, patch import pytest from aiohttp.resolver import ( _NAME_SOC...
./temp_repos/aiohttp/aiohttp/resolver.py
./temp_repos/aiohttp/tests/test_resolver.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'ThreadedResolver'. Context: - Class Name: ThreadedResolver - Dependencies to Mock: None detected - Key Imports: aiodns, typing, weakref, asyncio, abc, socket Requirements: 1. Use 'unittest...
ThreadedResolver
python
import asyncio import datetime import io import re import socket import string import sys import tempfile import types from collections.abc import Iterator, Mapping, MutableMapping from re import Pattern from types import MappingProxyType from typing import TYPE_CHECKING, Any, Final, Optional, TypeVar, cast, overload f...
import asyncio import datetime import socket import ssl import sys import weakref from collections.abc import Iterator, MutableMapping from typing import NoReturn from unittest import mock import pytest from multidict import CIMultiDict, CIMultiDictProxy, MultiDict from yarl import URL from aiohttp import ETag, HttpV...
./temp_repos/aiohttp/aiohttp/web_request.py
./temp_repos/aiohttp/tests/test_web_request.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'FileField'. Context: - Class Name: FileField - Dependencies to Mock: payload_writer, message, task, loop, protocol, payload - Key Imports: yarl, web_response, web_app, web_urldispatcher, we...
FileField
python
import asyncio import enum import io import json import mimetypes import os import sys import warnings from abc import ABC, abstractmethod from collections.abc import AsyncIterable, AsyncIterator, Iterable from itertools import chain from typing import IO, Any, Final, TextIO from multidict import CIMultiDict from . i...
import array import asyncio import io import json import unittest.mock from collections.abc import AsyncIterator, Iterator from io import StringIO from pathlib import Path from typing import TextIO, Union import pytest from multidict import CIMultiDict from aiohttp import payload from aiohttp.abc import AbstractStrea...
./temp_repos/aiohttp/aiohttp/payload.py
./temp_repos/aiohttp/tests/test_payload.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'LookupError'. Context: - Class Name: LookupError - Dependencies to Mock: encoding, headers, type, content_type, disposition, value, filename, dumps - Key Imports: itertools, mimetypes, io, ...
LookupError
python
import asyncio import functools import random import socket import sys import traceback import warnings from collections import OrderedDict, defaultdict, deque from collections.abc import Awaitable, Callable, Iterator, Sequence from contextlib import suppress from http import HTTPStatus from itertools import chain, cyc...
# Tests of http client with custom Connector import asyncio import gc import hashlib import platform import socket import ssl import sys import uuid import warnings from collections import defaultdict, deque from collections.abc import Awaitable, Callable, Iterator, Sequence from concurrent import futures from contextl...
./temp_repos/aiohttp/aiohttp/connector.py
./temp_repos/aiohttp/tests/test_connector.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Connection'. Context: - Class Name: Connection - Dependencies to Mock: path, key, limit, loop, ttl, keepalive_timeout, force_close, connector, protocol, closed_future, limit_per_host - Key ...
Connection
python
"""Low level HTTP server.""" import asyncio import warnings from collections.abc import Awaitable, Callable from typing import Any, Generic, TypeVar, overload from .abc import AbstractStreamWriter from .http_parser import RawRequestMessage from .streams import StreamReader from .web_protocol import RequestHandler fro...
import asyncio import socket from contextlib import suppress from typing import NoReturn from unittest import mock import pytest from aiohttp import client, web from aiohttp.http_exceptions import BadHttpMethod, BadStatusLine from aiohttp.pytest_plugin import AiohttpClient, AiohttpRawServer async def test_simple_se...
./temp_repos/aiohttp/aiohttp/web_server.py
./temp_repos/aiohttp/tests/test_web_server.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Server'. Context: - Class Name: Server - Dependencies to Mock: handler - Key Imports: http_parser, streams, web_request, web_response, warnings, typing, collections.abc, asyncio, web_protoc...
Server
python
import asyncio import logging import warnings from collections.abc import ( AsyncIterator, Awaitable, Callable, Iterable, Iterator, Mapping, MutableMapping, Sequence, ) from functools import lru_cache, partial, update_wrapper from typing import Any, TypeVar, cast, final, overload from a...
import asyncio import sys from collections.abc import AsyncIterator, Callable, Iterator from typing import NoReturn from unittest import mock import pytest from aiohttp import log, web from aiohttp.pytest_plugin import AiohttpClient from aiohttp.typedefs import Handler async def test_app_ctor() -> None: app = w...
./temp_repos/aiohttp/aiohttp/web_app.py
./temp_repos/aiohttp/tests/test_web_app.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'Application'. Context: - Class Name: Application - Dependencies to Mock: None detected - Key Imports: web_exceptions, frozenlist, helpers, web_request, log, logging, warnings, typedefs, web...
Application
python
"""Http related parsers and protocol.""" import asyncio import sys from typing import ( # noqa TYPE_CHECKING, Any, Awaitable, Callable, Iterable, List, NamedTuple, Optional, Union, ) from multidict import CIMultiDict from .abc import AbstractStreamWriter from .base_protocol impor...
# Tests for aiohttp/http_writer.py import array import asyncio import zlib from collections.abc import Generator, Iterable from typing import Any from unittest import mock import pytest from multidict import CIMultiDict from aiohttp import ClientConnectionResetError, hdrs, http from aiohttp.base_protocol import BaseP...
./temp_repos/aiohttp/aiohttp/http_writer.py
./temp_repos/aiohttp/tests/test_http_writer.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'HttpVersion'. Context: - Class Name: HttpVersion - Dependencies to Mock: on_headers_sent, on_chunk_sent, protocol, loop - Key Imports: aiohttp._http_writer, client_exceptions, helpers, typi...
HttpVersion
python
""" Digest authentication middleware for aiohttp client. This middleware implements HTTP Digest Authentication according to RFC 7616, providing a more secure alternative to Basic Authentication. It supports all standard hash algorithms including MD5, SHA, SHA-256, SHA-512 and their session variants, as well as both 'a...
"""Test digest authentication middleware for aiohttp client.""" import io import re from collections.abc import Generator from hashlib import md5, sha1 from typing import Literal from unittest import mock import pytest from yarl import URL from aiohttp import ClientSession, hdrs from aiohttp.client_exceptions import...
./temp_repos/aiohttp/aiohttp/client_middleware_digest_auth.py
./temp_repos/aiohttp/tests/test_client_middleware_digest_auth.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'DigestAuthChallenge'. Context: - Class Name: DigestAuthChallenge - Dependencies to Mock: password, preemptive, login - Key Imports: yarl, time, client_middlewares, client_exceptions, typing...
DigestAuthChallenge
python
"""Async gunicorn worker for aiohttp.web""" import asyncio import inspect import os import re import signal import sys from types import FrameType from typing import Any, Optional from gunicorn.config import AccessLogFormat as GunicornAccessLogFormat from gunicorn.workers import base from aiohttp import web from .h...
# Tests for aiohttp/worker.py import asyncio import os import socket import ssl from typing import TYPE_CHECKING from unittest import mock import pytest from _pytest.fixtures import SubRequest from aiohttp import web if TYPE_CHECKING: from aiohttp import worker as base_worker else: base_worker = pytest.impor...
./temp_repos/aiohttp/aiohttp/worker.py
./temp_repos/aiohttp/tests/test_worker.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'GunicornWebWorker'. Context: - Class Name: GunicornWebWorker - Dependencies to Mock: None detected - Key Imports: inspect, helpers, gunicorn.workers, web_app, web_log, gunicorn.config, typi...
GunicornWebWorker
python
import abc import asyncio import re import string from contextlib import suppress from enum import IntEnum from re import Pattern from typing import Any, ClassVar, Final, Generic, Literal, NamedTuple, TypeVar from multidict import CIMultiDict, CIMultiDictProxy, istr from yarl import URL from . import hdrs from .base_...
# Tests for aiohttp/protocol.py import asyncio import re import sys from collections.abc import Iterable from contextlib import suppress from typing import Any from unittest import mock from urllib.parse import quote import pytest from multidict import CIMultiDict from yarl import URL import aiohttp from aiohttp imp...
./temp_repos/aiohttp/aiohttp/http_parser.py
./temp_repos/aiohttp/tests/test_http_parser.py
aiohttp
You are an expert Python testing engineer using unittest and unittest.mock. Task: Write a robust unit test for the class 'RawRequestMessage'. Context: - Class Name: RawRequestMessage - Dependencies to Mock: lax, timer, compression, loop, read_until_eof, protocol, max_field_size, encoding, auto_decompress, code...
RawRequestMessage