language
stringclasses
4 values
source_code
stringlengths
2
986k
test_code
stringlengths
125
758k
repo_name
stringclasses
97 values
instruction
stringlengths
156
643
python
from django import forms from .models import Event class EventForm(forms.Form): dt = forms.DateTimeField() class EventSplitForm(forms.Form): dt = forms.SplitDateTimeField() class EventLocalizedForm(forms.Form): dt = forms.DateTimeField(localize=True) class EventModelForm(forms.ModelForm): class...
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'EventLocalizedModelForm' using 'unittest' and 'unittest.mock'. Context: - Class Name: EventLocalizedModelForm - Dependencies to Mock: forms, Event Requirements: Use @patch for mocks, follow AAA pattern.
python
from django.db import models class Number(models.Model): num = models.IntegerField() def __str__(self): return str(self.num)
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....
django
You are an expert Python testing engineer. Task: Write a unit test for 'Number' using 'unittest' and 'unittest.mock'. Context: - Class Name: Number - Dependencies to Mock: models Requirements: Use @patch for mocks, follow AAA pattern.
python
from django.core import checks from django.utils.functional import cached_property NOT_PROVIDED = object() class FieldCacheMixin: """ An API for working with the model's fields value cache. Subclasses must set self.cache_name to a unique entry for the cache - typically the field’s name. """ ...
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'CheckFieldDefaultMixin' using 'unittest' and 'unittest.mock'. Context: - Class Name: CheckFieldDefaultMixin - Dependencies to Mock: checks, cached_property Requirements: Use @patch for mocks, follow AAA pattern.
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'PasswordResetTokenGenerator' using 'unittest' and 'unittest.mock'. Context: - Class Name: PasswordResetTokenGenerator - Dependencies to Mock: datetime, settings, salted_hmac, int_to_base36 Requirements: Use @patch for mocks, follow AAA pattern.
python
from django.db import models class Number(models.Model): num = models.IntegerField() def __str__(self): return str(self.num)
import unittest from django.core.checks import Error, Warning from django.core.checks.model_checks import _check_lazy_references from django.db import connection, connections, models from django.db.models.functions import Abs, Lower, Round from django.db.models.signals import post_init from django.test import SimpleTe...
django
You are an expert Python testing engineer. Task: Write a unit test for 'Number' using 'unittest' and 'unittest.mock'. Context: - Class Name: Number - Dependencies to Mock: models Requirements: Use @patch for mocks, follow AAA pattern.
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): ...
django
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: apps, Site, cache, override_settings, TestModel Requirements: Use @patch for mocks, follow AAA pattern.
python
from http import cookies # For backwards compatibility in Django 2.1. SimpleCookie = cookies.SimpleCookie def parse_cookie(cookie): """ Return a dictionary parsed from a `Cookie:` header string. """ cookiedict = {} for chunk in cookie.split(";"): if "=" in chunk: key, val = ch...
import json import random from unittest import TestCase from django.conf import settings from django.contrib.messages import Message, constants from django.contrib.messages.storage.cookie import ( CookieStorage, MessageDecoder, MessageEncoder, bisect_keep_left, bisect_keep_right, ) from django.test...
django
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: cookies Requirements: Use @patch for mocks, follow AAA pattern.
python
from asgiref.sync import iscoroutinefunction, markcoroutinefunction from django.http import Http404, HttpResponse from django.template import engines from django.template.response import TemplateResponse from django.utils.decorators import ( async_only_middleware, sync_and_async_middleware, sync_only_middl...
import unittest from django.contrib.messages.middleware import MessageMiddleware from django.http import HttpRequest, HttpResponse class MiddlewareTests(unittest.TestCase): def test_response_without_messages(self): """ MessageMiddleware is tolerant of messages not existing on request. """...
django
You are an expert Python testing engineer. Task: Write a unit test for 'NotSyncOrAsyncMiddleware' using 'unittest' and 'unittest.mock'. Context: - Class Name: NotSyncOrAsyncMiddleware - Dependencies to Mock: markcoroutinefunction, HttpResponse, engines, TemplateResponse, sync_only_middleware, ) Requirements: Use @patch...
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: connections, register Requirements: Use @patch for mocks, follow AAA pattern.
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: register Requirements: Use @patch for mocks, follow AAA pattern.
python
import itertools import math from django.core.exceptions import EmptyResultSet, FullResultSet from django.db.models.expressions import ( Case, ColPairs, Expression, ExpressionList, Func, Value, When, ) from django.db.models.fields import ( BooleanField, CharField, DateTimeField,...
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'UUIDTextMixin' using 'unittest' and 'unittest.mock'. Context: - Class Name: UUIDTextMixin - Dependencies to Mock: itertools, math, FullResultSet, When, ), UUIDField, ) Requirements: Use @patch for mocks, follow AAA pattern.
python
# Used by the ErrorHandlerResolutionTests test case. from .views import empty_view urlpatterns = [] handler400 = empty_view handler403 = empty_view handler404 = empty_view handler500 = empty_view
from unittest import TestCase from django.db.models.utils import AltersData from django.template import Context, Engine class CallableVariablesTests(TestCase): @classmethod def setUpClass(cls): cls.engine = Engine() super().setUpClass() def test_callable(self): class Doodad: ...
django
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: empty_view Requirements: Use @patch for mocks, follow AAA pattern.
python
from collections.abc import Iterable from functools import wraps from importlib import import_module from inspect import getfullargspec, unwrap from django.utils.html import conditional_escape from django.utils.inspect import lazy_annotations from .base import Node, Template, token_kwargs from .exceptions import Temp...
import functools import unittest from django.template import Library from django.template.base import Node from django.test import SimpleTestCase from django.utils.version import PY314 class FilterRegistrationTests(SimpleTestCase): def setUp(self): self.library = Library() def test_filter(self): ...
django
You are an expert Python testing engineer. Task: Write a unit test for 'InclusionNode' using 'unittest' and 'unittest.mock'. Context: - Class Name: InclusionNode - Dependencies to Mock: Iterable, wraps, import_module, unwrap, conditional_escape Requirements: Use @patch for mocks, follow AAA pattern.
python
import argparse from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): subparsers = parser.add_subparsers(parser_class=argparse.ArgumentParser) parser_foo = subparsers.add_parser("foo") parser_foo.add_argument("bar", type=int) ...
""" Testing some internals of the template processing. These are *not* examples to be copied in user code. """ import unittest from django.template import Library, TemplateSyntaxError from django.template.base import ( FilterExpression, Lexer, Parser, Token, TokenType, Variable, VariableDo...
django
You are an expert Python testing engineer. Task: Write a unit test for 'Command' using 'unittest' and 'unittest.mock'. Context: - Class Name: Command - Dependencies to Mock: argparse, BaseCommand Requirements: Use @patch for mocks, follow AAA pattern.
python
""" Parser and utilities for the smart 'if' tag """ # Using a simple top down parser, as described here: # https://11l-lang.org/archive/simple-top-down-parsing/ # 'led' = left denotation # 'nud' = null denotation # 'bp' = binding power (left = lbp, right = rbp) class TokenBase: """ Base class for operators a...
import unittest from django.template.smartif import IfParser class SmartIfTests(unittest.TestCase): def assertCalcEqual(self, expected, tokens): self.assertEqual(expected, IfParser(tokens).parse().eval({})) # We only test things here that are difficult to test elsewhere # Many other tests are fo...
django
You are an expert Python testing engineer. Task: Write a unit test for 'IfParser' using 'unittest' and 'unittest.mock'. Context: - Class Name: IfParser - Dependencies to Mock: None detected Requirements: Use @patch for mocks, follow AAA pattern.
python
def special(request): return {"path": request.special_path}
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: None detected Requirements: Use @patch for mocks, follow AAA pattern.
python
# Copyright (c) 2007, Robert Coup <robert.coup@onetrackmind.co.nz> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, #...
""" Distance and Area objects to allow for sensible and convenient calculation and conversions. Here are some tests. """ import unittest from django.contrib.gis.measure import A, Area, D, Distance from django.test import SimpleTestCase class DistanceTest(SimpleTestCase): "Testing the Distance object" def t...
django
You are an expert Python testing engineer. Task: Write a unit test for 'Area' using 'unittest' and 'unittest.mock'. Context: - Class Name: Area - Dependencies to Mock: Decimal, total_ordering Requirements: Use @patch for mocks, follow AAA pattern.
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): "...
django
You are an expert Python testing engineer. Task: Write a unit test for 'LengthModel' using 'unittest' and 'unittest.mock'. Context: - Class Name: LengthModel - Dependencies to Mock: uuid, GenericRelation, ContentType, models, BaseModel Requirements: Use @patch for mocks, follow AAA pattern.
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'CPointerBase' using 'unittest' and 'unittest.mock'. Context: - Class Name: CPointerBase - Dependencies to Mock: c_void_p Requirements: Use @patch for mocks, follow AAA pattern.
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'GeoIP2' using 'unittest' and 'unittest.mock'. Context: - Class Name: GeoIP2 - Dependencies to Mock: ipaddress, socket, settings, ValidationError, validate_ipv46_address Requirements: Use @patch for mocks, follow AAA pattern.
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", ) ...
django
You are an expert Python testing engineer. Task: Write a unit test for 'Driver' using 'unittest' and 'unittest.mock'. Context: - Class Name: Driver - Dependencies to Mock: c_void_p, GDALBase, GDALException, GDAL_VERSION, capi Requirements: Use @patch for mocks, follow AAA pattern.
python
""" The GDAL/OGR library uses an Envelope structure to hold the bounding box information for a geometry. The envelope (bounding box) contains two pairs of coordinates, one for the lower left coordinate and one for the upper right coordinate: +----------o Upper right; (max_x, max_y) ...
import unittest from django.contrib.gis.gdal import Envelope, GDALException class TestPoint: def __init__(self, x, y): self.x = x self.y = y class EnvelopeTest(unittest.TestCase): def setUp(self): self.e = Envelope(0, 0, 5, 5) def test01_init(self): "Testing Envelope in...
django
You are an expert Python testing engineer. Task: Write a unit test for 'Envelope' using 'unittest' and 'unittest.mock'. Context: - Class Name: Envelope - Dependencies to Mock: c_double, GDALException Requirements: Use @patch for mocks, follow AAA pattern.
python
from django.contrib.gis.db import models from django.db import migrations from django.db.models import deletion class Migration(migrations.Migration): dependencies = [ ("rasterapp", "0001_setup_extensions"), ] operations = [ migrations.CreateModel( name="RasterModel", ...
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'Migration' using 'unittest' and 'unittest.mock'. Context: - Class Name: Migration - Dependencies to Mock: models, migrations, deletion Requirements: Use @patch for mocks, follow AAA pattern.
python
""" This module houses the ctypes initialization procedures, as well as the notice and error handler function callbacks (get called when an error occurs in GEOS). This module also houses GEOS Pointer utilities, including get_pointer_arr(), and GEOM_PTR. """ import logging import os from ctypes import CDLL, CFUNCTYPE,...
import ctypes import itertools import json import math import pickle import random from binascii import a2b_hex from io import BytesIO from unittest import mock, skipIf from django.contrib.gis import gdal from django.contrib.gis.geos import ( GeometryCollection, GEOSException, GEOSGeometry, LinearRing,...
django
You are an expert Python testing engineer. Task: Write a unit test for 'GEOSFuncFactory' using 'unittest' and 'unittest.mock'. Context: - Class Name: GEOSFuncFactory - Dependencies to Mock: logging, c_char_p, find_library, ImproperlyConfigured, cached_property Requirements: Use @patch for mocks, follow AAA pattern.
python
from django.db.migrations.operations.base import Operation class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return (self.__class__.__name__, [], {}) @property def reversible(self): return True def state_forwards(self, app_label, state): ...
from unittest import skipUnless from django.contrib.gis.db.models import fields from django.contrib.gis.geos import MultiPolygon, Polygon from django.core.exceptions import ImproperlyConfigured from django.db import connection, migrations, models from django.db.migrations.migration import Migration from django.db.migr...
django
You are an expert Python testing engineer. Task: Write a unit test for 'ExpandArgsOperation' using 'unittest' and 'unittest.mock'. Context: - Class Name: ExpandArgsOperation - Dependencies to Mock: Operation Requirements: Use @patch for mocks, follow AAA pattern.
python
import functools from pathlib import Path from django.conf import settings from django.template.backends.django import DjangoTemplates from django.template.loader import get_template from django.utils.functional import cached_property from django.utils.module_loading import import_string @functools.lru_cache def get...
import os import unittest from django.forms.renderers import ( BaseRenderer, DjangoTemplates, Jinja2, TemplatesSetting, ) from django.test import SimpleTestCase try: import jinja2 except ImportError: jinja2 = None class SharedTests: expected_widget_dir = "templates" def test_install...
django
You are an expert Python testing engineer. Task: Write a unit test for 'TemplatesSetting' using 'unittest' and 'unittest.mock'. Context: - Class Name: TemplatesSetting - Dependencies to Mock: functools, Path, settings, DjangoTemplates, get_template Requirements: Use @patch for mocks, follow AAA pattern.
python
import re from django.core import validators from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _ @deconstructible class ASCIIUsernameValidator(validators.RegexValidator): regex = r"^[\w.@+-]+\Z" message = _( "Enter a valid username. This value m...
import re import types from unittest import TestCase from django import forms from django.core import validators from django.core.exceptions import ValidationError from django.core.files.uploadedfile import SimpleUploadedFile class TestFieldWithValidators(TestCase): def test_all_errors_get_reported(self): ...
django
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: validators, deconstructible Requirements: Use @patch for mocks, follow AAA pattern.
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 ( ...
django
You are an expert Python testing engineer. Task: Write a unit test for 'BaseFormSet' using 'unittest' and 'unittest.mock'. Context: - Class Name: BaseFormSet - Dependencies to Mock: ValidationError, IntegerField, Form, get_default_renderer, RenderableFormMixin Requirements: Use @patch for mocks, follow AAA pattern.
python
""" This encapsulates the logic for displaying filters in the Django admin. Filters are specified in models with the "list_filter" option. Each filter subclass knows how to display a filter for a field that passes a certain test -- e.g. being a DateField or ForeignKey. """ import datetime from django.contrib.admin.e...
from unittest.mock import patch from django.db import NotSupportedError, connection from django.db.models import ( Case, F, FilteredRelation, OuterRef, Q, Subquery, TextField, Value, When, ) from django.db.models.functions import Cast from django.db.models.lookups import Exact from ...
django
You are an expert Python testing engineer. Task: Write a unit test for 'EmptyFieldListFilter' using 'unittest' and 'unittest.mock'. Context: - Class Name: EmptyFieldListFilter - Dependencies to Mock: datetime, NotRegistered, IncorrectLookupParameters, reverse_field_path, ), ValidationError Requirements: Use @patch for ...
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'MigrationAutodetector' using 'unittest' and 'unittest.mock'. Context: - Class Name: MigrationAutodetector - Dependencies to Mock: functools, namedtuple, Enum, TopologicalSorter, chain Requirements: Use @patch for mocks, follow AAA pattern.
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'MigrationExecutor' using 'unittest' and 'unittest.mock'. Context: - Class Name: MigrationExecutor - Dependencies to Mock: global_apps, router, InvalidMigrationPlan, MigrationLoader, MigrationRecorder Requirements: Use @patch for mocks, follow AAA p...
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, ...
django
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: register Requirements: Use @patch for mocks, follow AAA pattern.
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'MigrationWriter' using 'unittest' and 'unittest.mock'. Context: - Class Name: MigrationWriter - Dependencies to Mock: import_module, get_version, apps, SettingsReference, migrations Requirements: Use @patch for mocks, follow AAA pattern.
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'NonInteractiveMigrationQuestioner' using 'unittest' and 'unittest.mock'. Context: - Class Name: NonInteractiveMigrationQuestioner - Dependencies to Mock: datetime, importlib, sys, apps, OutputWrapper Requirements: Use @patch for mocks, follow AAA p...
python
from django.contrib.auth import validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auth", "0006_require_contenttypes_0002"), ] operations = [ migrations.AlterField( model_name="user", name="username", ...
from unittest import TestCase from django.core.exceptions import ValidationError from django.db import models class ValidationMessagesTest(TestCase): def _test_validation_messages(self, field, value, expected): with self.assertRaises(ValidationError) as cm: field.clean(value, None) se...
django
You are an expert Python testing engineer. Task: Write a unit test for 'Migration' using 'unittest' and 'unittest.mock'. Context: - Class Name: Migration - Dependencies to Mock: validators, models Requirements: Use @patch for mocks, follow AAA pattern.
python
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserWithUniqueConstraintManager(BaseUserManager): def create_superuser(self, username, password): user = self.model(username=username) user.set_password(password) user.save(usi...
import datetime import unittest from django.apps.registry import Apps from django.core.exceptions import ValidationError from django.db import models from django.test import TestCase from .models import ( CustomPKModel, FlexibleDatePost, ModelToValidate, Post, UniqueErrorsModel, UniqueFieldsMo...
django
You are an expert Python testing engineer. Task: Write a unit test for 'CustomUserWithUniqueConstraint' using 'unittest' and 'unittest.mock'. Context: - Class Name: CustomUserWithUniqueConstraint - Dependencies to Mock: BaseUserManager, models Requirements: Use @patch for mocks, follow AAA pattern.
python
from django.db.migrations.operations.base import Operation class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return (self.__class__.__name__, [], {}) @property def reversible(self): return True def state_forwards(self, app_label, state): ...
import unittest from migrations.test_base import OperationTestBase, OptimizerTestBase from django.db import IntegrityError, NotSupportedError, connection, transaction from django.db.migrations.operations import RemoveIndex, RenameIndex from django.db.migrations.state import ProjectState from django.db.migrations.writ...
django
You are an expert Python testing engineer. Task: Write a unit test for 'ExpandArgsOperation' using 'unittest' and 'unittest.mock'. Context: - Class Name: ExpandArgsOperation - Dependencies to Mock: Operation Requirements: Use @patch for mocks, follow AAA pattern.
python
import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("postgres_tests", "0001_initial"), ] operations = [ migrations.AddField( model_name="integerarraydefaultmodel", name="field_2", ...
import decimal import enum import json import unittest import uuid from django import forms from django.contrib.admin.utils import display_for_field from django.core import checks, exceptions, serializers, validators from django.core.exceptions import FieldError from django.core.management import call_command from dja...
django
You are an expert Python testing engineer. Task: Write a unit test for 'Migration' using 'unittest' and 'unittest.mock'. Context: - Class Name: Migration - Dependencies to Mock: django.contrib.postgres.fields, models Requirements: Use @patch for mocks, follow AAA pattern.
python
from django.apps import AppConfig class LoadingAppConfig(AppConfig): name = "i18n.loading_app"
import unittest from decimal import Decimal from django.db import connection from django.db.backends.signals import connection_created from django.db.migrations.writer import MigrationWriter from django.test import TestCase from django.test.utils import CaptureQueriesContext, modify_settings, override_settings try: ...
django
You are an expert Python testing engineer. Task: Write a unit test for 'LoadingAppConfig' using 'unittest' and 'unittest.mock'. Context: - Class Name: LoadingAppConfig - Dependencies to Mock: AppConfig Requirements: Use @patch for mocks, follow AAA pattern.
python
from enum import Enum from types import NoneType from django.core import checks from django.core.exceptions import FieldDoesNotExist, ValidationError from django.db import connections from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import Exists, ExpressionList, F, RawSQL from djang...
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'UniqueConstraint' using 'unittest' and 'unittest.mock'. Context: - Class Name: UniqueConstraint - Dependencies to Mock: Enum, NoneType, checks, ValidationError, connections Requirements: Use @patch for mocks, follow AAA pattern.
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: global_apps, settings, no_style, router Requirements: Use @patch for mocks, follow AAA pattern.
python
import datetime import decimal import logging import sys from pathlib import Path from django.core.exceptions import BadRequest, PermissionDenied, SuspiciousOperation from django.http import Http404, HttpResponse, JsonResponse from django.shortcuts import render from django.template import Context, Template, TemplateD...
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'Klass' using 'unittest' and 'unittest.mock'. Context: - Class Name: Klass - Dependencies to Mock: datetime, decimal, logging, sys, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from django.core.management.base import BaseCommand class Command(BaseCommand): requires_system_checks = [] def handle(self, *args, **options): pass
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...
django
You are an expert Python testing engineer. Task: Write a unit test for 'Command' using 'unittest' and 'unittest.mock'. Context: - Class Name: Command - Dependencies to Mock: BaseCommand Requirements: Use @patch for mocks, follow AAA pattern.
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...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'Pagination' using 'unittest' and 'unittest.mock'. Context: - Class Name: Pagination - Dependencies to Mock: path, randrange, sample, urlsplit, Environment Requirements: Use @patch for mocks, follow AAA pattern.
python
"""Shows how you can implement HTTP basic auth support without an additional component. """ from werkzeug.serving import run_simple from werkzeug.wrappers import Request from werkzeug.wrappers import Response class Application: def __init__(self, users, realm="login required"): self.users = users ...
import base64 import urllib.parse from datetime import date from datetime import datetime from datetime import timedelta from datetime import timezone import pytest from werkzeug import datastructures from werkzeug import http from werkzeug._internal import _wsgi_encoding_dance from werkzeug.datastructures import Aut...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'Application' using 'unittest' and 'unittest.mock'. Context: - Class Name: Application - Dependencies to Mock: run_simple, Request, Response Requirements: Use @patch for mocks, follow AAA pattern.
python
from __future__ import annotations import copy import math import operator import typing as t from contextvars import ContextVar from functools import partial from functools import update_wrapper from operator import attrgetter from .wsgi import ClosingIterator if t.TYPE_CHECKING: from _typeshed.wsgi import Star...
import asyncio import copy import math import operator import time from contextvars import ContextVar from threading import Thread import pytest from werkzeug import local # Since the tests are creating local instances, use global context vars # to avoid accumulating anonymous context vars that can't be collected. _...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'LocalProxy' using 'unittest' and 'unittest.mock'. Context: - Class Name: LocalProxy - Dependencies to Mock: copy, math, operator, ContextVar, partial Requirements: Use @patch for mocks, follow AAA pattern.
python
import click from werkzeug.serving import run_simple from i18nurls import make_app @click.group() def cli(): pass @cli.command() @click.option("-h", "--hostname", type=str, default="localhost", help="localhost") @click.option("-p", "--port", type=int, default=5000, help="5000") @click.option("--no-reloader", i...
import pytest from werkzeug import urls def test_iri_support(): assert urls.uri_to_iri("http://xn--n3h.net/") == "http://\u2603.net/" assert urls.iri_to_uri("http://☃.net/") == "http://xn--n3h.net/" assert ( urls.iri_to_uri("http://üser:pässword@☃.net/påth") == "http://%C3%BCser:p%C3%A4ss...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: click, run_simple, make_app Requirements: Use @patch for mocks, follow AAA pattern.
python
"""Implements a number of Python exceptions which can be raised from within a view to trigger a standard HTTP non-200 response. Usage Example ------------- .. code-block:: python from werkzeug.wrappers.request import Request from werkzeug.exceptions import HTTPException, NotFound def view(request): ...
from datetime import datetime import pytest from markupsafe import escape from markupsafe import Markup from werkzeug import exceptions from werkzeug.datastructures import Headers from werkzeug.datastructures import WWWAuthenticate from werkzeug.exceptions import default_exceptions from werkzeug.exceptions import HTT...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'Aborter' using 'unittest' and 'unittest.mock'. Context: - Class Name: Aborter - Dependencies to Mock: datetime, escape, Markup, _get_environ Requirements: Use @patch for mocks, follow AAA pattern.
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...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: hashlib, hmac, posixpath, secrets Requirements: Use @patch for mocks, follow AAA pattern.
python
from werkzeug.routing import EndpointPrefix from werkzeug.routing import Map from werkzeug.routing import Rule from werkzeug.routing import Subdomain from werkzeug.routing import Submount m = Map( [ # Static URLs EndpointPrefix( "static/", [ Rule("/", endpoin...
import gc import typing as t import uuid import pytest from werkzeug import routing as r from werkzeug.datastructures import ImmutableDict from werkzeug.datastructures import MultiDict from werkzeug.exceptions import MethodNotAllowed from werkzeug.exceptions import NotFound from werkzeug.test import create_environ fr...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: EndpointPrefix, Map, Rule, Subdomain, Submount Requirements: Use @patch for mocks, follow AAA pattern.
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...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'ForkingWSGIServer' using 'unittest' and 'unittest.mock'. Context: - Class Name: ForkingWSGIServer - Dependencies to Mock: errno, selectors, socket, socketserver, sys Requirements: Use @patch for mocks, follow AAA pattern.
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...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'MultiPartParser' using 'unittest' and 'unittest.mock'. Context: - Class Name: MultiPartParser - Dependencies to Mock: BytesIO, parse_qsl, _plain_int, FileStorage, Headers Requirements: Use @patch for mocks, follow AAA pattern.
python
from __future__ import annotations import io import typing as t from functools import partial from functools import update_wrapper from .exceptions import ClientDisconnected from .exceptions import RequestEntityTooLarge from .sansio import utils as _sansio_utils from .sansio.utils import host_is_trusted # noqa: F401...
from __future__ import annotations import io import json import os import typing as t import pytest from werkzeug import wsgi from werkzeug.exceptions import BadRequest from werkzeug.exceptions import ClientDisconnected from werkzeug.test import Client from werkzeug.test import create_environ from werkzeug.test impo...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'LimitedStream' using 'unittest' and 'unittest.mock'. Context: - Class Name: LimitedStream - Dependencies to Mock: partial, update_wrapper, ClientDisconnected, RequestEntityTooLarge, _sansio_utils Requirements: Use @patch for mocks, follow AAA patte...
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 ...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'ProxyFix' using 'unittest' and 'unittest.mock'. Context: - Class Name: ProxyFix - Dependencies to Mock: parse_list_header Requirements: Use @patch for mocks, follow AAA pattern.
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"...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'DispatcherMiddleware' using 'unittest' and 'unittest.mock'. Context: - Class Name: DispatcherMiddleware - Dependencies to Mock: None detected Requirements: Use @patch for mocks, follow AAA pattern.
python
""" WSGI Protocol Linter ==================== This module provides a middleware that performs sanity checks on the behavior of the WSGI server and application. It checks that the :pep:`3333` WSGI spec is properly implemented. It also warns on some common HTTP errors such as non-empty responses for 304 status codes. ....
import pytest from werkzeug.middleware.lint import HTTPWarning from werkzeug.middleware.lint import LintMiddleware from werkzeug.middleware.lint import WSGIWarning from werkzeug.test import create_environ from werkzeug.test import run_wsgi_app def dummy_application(environ, start_response): start_response("200 O...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'LintMiddleware' using 'unittest' and 'unittest.mock'. Context: - Class Name: LintMiddleware - Dependencies to Mock: TracebackType, urlparse, warn, Headers, is_entity_header Requirements: Use @patch for mocks, follow AAA pattern.
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): ...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'ProfilerMiddleware' using 'unittest' and 'unittest.mock'. Context: - Class Name: ProfilerMiddleware - Dependencies to Mock: os.path, sys, time, Stats Requirements: Use @patch for mocks, follow AAA pattern.
python
""" Basic HTTP Proxy ================ .. autoclass:: ProxyMiddleware :copyright: 2007 Pallets :license: BSD-3-Clause """ from __future__ import annotations import typing as t from http import client from urllib.parse import quote from urllib.parse import urlsplit from ..datastructures import EnvironHeaders from .....
import pytest from werkzeug.middleware.http_proxy import ProxyMiddleware from werkzeug.test import Client from werkzeug.wrappers import Response @pytest.mark.dev_server def test_http_proxy(standard_app): app = ProxyMiddleware( Response("ROOT"), { "/foo": { "target": st...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'ProxyMiddleware' using 'unittest' and 'unittest.mock'. Context: - Class Name: ProxyMiddleware - Dependencies to Mock: client, quote, urlsplit, EnvironHeaders, is_hop_by_hop_header Requirements: Use @patch for mocks, follow AAA pattern.
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 pytest from werkzeug.sansio.utils import get_content_length from werkzeug.sansio.utils import get_host @pytest.mark.parametrize( ("scheme", "host_header", "server", "expected"), [ ("http", "spam", None, "spam"), ("http", "spam:80", None, "spam"), ...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'Pagination' using 'unittest' and 'unittest.mock'. Context: - Class Name: Pagination - Dependencies to Mock: path, randrange, sample, urlsplit, Environment Requirements: Use @patch for mocks, follow AAA pattern.
python
from __future__ import annotations import re import typing as t from dataclasses import dataclass from enum import auto from enum import Enum from ..datastructures import Headers from ..exceptions import RequestEntityTooLarge from ..http import parse_options_header class Event: pass @dataclass(frozen=True) cl...
import pytest from werkzeug.datastructures import Headers from werkzeug.sansio.multipart import Data from werkzeug.sansio.multipart import Epilogue from werkzeug.sansio.multipart import Field from werkzeug.sansio.multipart import File from werkzeug.sansio.multipart import MultipartDecoder from werkzeug.sansio.multipar...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'MultipartEncoder' using 'unittest' and 'unittest.mock'. Context: - Class Name: MultipartEncoder - Dependencies to Mock: dataclass, auto, Enum, Headers, RequestEntityTooLarge Requirements: Use @patch for mocks, follow AAA pattern.
python
from __future__ import annotations import typing as t from datetime import datetime from urllib.parse import parse_qsl from ..datastructures import Accept from ..datastructures import Authorization from ..datastructures import CharsetAccept from ..datastructures import ETags from ..datastructures import Headers from ...
import typing as t import pytest from werkzeug.datastructures import Headers from werkzeug.sansio.request import Request @pytest.mark.parametrize( "headers, expected", [ (Headers({"Transfer-Encoding": "chunked", "Content-Length": "6"}), None), (Headers({"Transfer-Encoding": "something", "Con...
werkzeug
You are an expert Python testing engineer. Task: Write a unit test for 'Request' using 'unittest' and 'unittest.mock'. Context: - Class Name: Request - Dependencies to Mock: datetime, parse_qsl, Accept, Authorization, CharsetAccept Requirements: Use @patch for mocks, follow AAA pattern.
python
from fastapi import FastAPI from .config import settings app = FastAPI() @app.get("/info") async def info(): return { "app_name": settings.app_name, "admin_email": settings.admin_email, "items_per_user": settings.items_per_user, }
import pytest from httpx import ASGITransport, AsyncClient from .main import app @pytest.mark.anyio async def test_root(): async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as ac: response = await ac.get("/") assert response.status_code == 200 assert r...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: FastAPI, settings Requirements: Use @patch for mocks, follow AAA pattern.
python
from enum import Enum from typing import ( Any, Awaitable, Callable, Coroutine, Dict, List, Optional, Sequence, Type, TypeVar, Union, ) from annotated_doc import Doc from fastapi import routing from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.excep...
import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from .main import app client = TestClient(app) @pytest.mark.parametrize( "path,expected_status,expected_response", [ ("/api_route", 200, {"message": "Hello World"}), ("/non_decorated_route", 200, {"messag...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'FastAPI' using 'unittest' and 'unittest.mock'. Context: - Class Name: FastAPI - Dependencies to Mock: Enum, Union, ), Doc, routing, DefaultPlaceholder Requirements: Use @patch for mocks, follow AAA pattern.
python
from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import is_body_allowed_for_status_code from fastapi.websockets import WebSocket from starlette.exceptions import HTTPException from starlette.requests import Request fr...
import pytest from fastapi import Depends, FastAPI, HTTPException from fastapi.exceptions import RequestValidationError from fastapi.testclient import TestClient from starlette.responses import JSONResponse def http_exception_handler(request, exception): return JSONResponse({"exception": "http-exception"}) def ...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: jsonable_encoder, WebSocketRequestValidationError, is_body_allowed_for_status_code, WebSocket, HTTPException Requirements: Use @patch fo...
python
from typing import ( Any, BinaryIO, Callable, Dict, Iterable, Optional, Type, TypeVar, cast, ) from annotated_doc import Doc from fastapi._compat import ( CoreSchema, GetJsonSchemaHandler, JsonSchemaValue, ) from starlette.datastructures import URL as URL # noqa: F401 f...
import io from pathlib import Path from typing import List import pytest from fastapi import FastAPI, UploadFile from fastapi.datastructures import Default from fastapi.testclient import TestClient # TODO: remove when deprecating Pydantic v1 def test_upload_file_invalid(): with pytest.raises(ValueError): ...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'DefaultPlaceholder' using 'unittest' and 'unittest.mock'. Context: - Class Name: DefaultPlaceholder - Dependencies to Mock: cast, ), Doc, JsonSchemaValue, ), URL, Address Requirements: Use @patch for mocks, follow AAA pattern.
python
from fastapi import FastAPI from .config import settings app = FastAPI() @app.get("/info") async def info(): return { "app_name": settings.app_name, "admin_email": settings.admin_email, "items_per_user": settings.items_per_user, }
import pytest from fastapi.testclient import TestClient from .app.main import app client = TestClient(app) @pytest.mark.parametrize( "path", ["/a/compute", "/a/compute/", "/b/compute", "/b/compute/"] ) def test_post(path): data = {"a": 2, "b": "foo"} response = client.post(path, json=data) assert re...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: FastAPI, settings Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get")], q: str ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import importlib import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture( name="app", params=[ "tutorial003", "tutorial003_an", pytest.param("tutorial003_py39", marks=needs_py39), pytest.param("tutori...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import importlib import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture( name="client", params=[ "tutorial001", "tutorial001_an", pytest.param("tutorial001_an_py39", marks=needs_py39), ], ) def get_c...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( q: str, item_id: Annotated[int, Path(title="The ID of the item to get")] ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import importlib import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture( name="app", params=[ "tutorial002", "tutorial002_an", pytest.param("tutorial002_py39", marks=needs_py3...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} CommonsDep = Annotated[dict, Depends(common_parame...
import importlib from pathlib import Path import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39, needs_py310 @pytest.fixture( name="client", params=[ "tutorial001_02", pytest.param("tutorial001_02_py310", marks=needs_py310), ...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: Annotated[bytes, File(description="A file read as bytes")]): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file( file: Annotated[U...
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture( name="client", params=[ "tutorial001_03", "tutorial001_03_an", pytest.param("tutorial001_03_an_py39", marks=needs_py39), ], ) def get_client(request: pytest.F...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, UploadFile Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
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...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import importlib import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture( name="app", params=[ "tutorial001", "tutorial001_an", pytest.param("tutorial001_an_py39", marks=needs_...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import os from pathlib import Path import pytest from fastapi.testclient import TestClient @pytest.fixture(scope="module") def client(): static_dir: Path = Path(os.getcwd()) / "static" print(static_dir) static_dir.mkdir(exist_ok=True) from docs_src.custom_docs_ui.tutorial001 import app with Test...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( q: str, item_id: Annotated[int, Path(title="The ID of the item to get")] ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import os from pathlib import Path import pytest from fastapi.testclient import TestClient @pytest.fixture(scope="module") def client(): static_dir: Path = Path(os.getcwd()) / "static" print(static_dir) static_dir.mkdir(exist_ok=True) from docs_src.custom_docs_ui.tutorial002 import app with Test...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import importlib import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39, needs_py310 @pytest.fixture( name="client", params=[ "tutorial001", pytest.param("tutorial001_py310", marks=needs_py310), "tutorial001_an", ...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get")], q: str ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import importlib import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ "tutorial003", pytest.param("tutorial003_py310", marks=needs_py310), ], ) def get_client(request: py...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( *, item_id: int = Path(title="The ID of the item to get", gt=0, le=1000), q: str, ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import importlib import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ "tutorial005", pytest.param("tutorial005_py310", marks=needs_py310), ], ) def get_client(request: py...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from fastapi import FastAPI, Response from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/portal", response_model=None) async def get_portal(teleport: bool = False) -> Response | dict: if teleport: return RedirectResponse(url="https://www.youtube.com/watch?v=dQw4w9WgXcQ") return...
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ "tutorial003_05", pytest.param("tutorial003_05_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = imp...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Response, RedirectResponse Requirements: Use @patch for mocks, follow AAA pattern.
python
from fastapi import FastAPI, Path from typing_extensions import Annotated app = FastAPI() @app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str ): results = {"item_id": item_id} if q: results.update({"q": q}) return r...
import importlib import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py39, needs_py310 @pytest.fixture( name="client", params=[ "tutorial004", pytest.param("tutorial004_py39", marks=needs_py39), pytest.param("tut...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Path, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from fastapi import FastAPI, Path, Query from typing_extensions import Annotated app = FastAPI() @app.get("/items/{item_id}") async def read_items( *, item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)], q: str, size: Annotated[float, Query(gt=0, lt=10.5)], ): results ...
import importlib import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ "tutorial006", pytest.param("tutorial006_py310", marks=needs_py310), ], ) def get_client(request: py...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Query, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import FastAPI from pydantic import BaseModel, EmailStr app = FastAPI() class BaseUser(BaseModel): username: str email: EmailStr full_name: Union[str, None] = None class UserIn(BaseUser): password: str @app.post("/user/") async def create_user(user: UserIn) ...
import importlib import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ "tutorial003_01", pytest.param("tutorial003_01_py310", marks=needs_py310), ], ) def get_client(reque...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'UserIn' using 'unittest' and 'unittest.mock'. Context: - Class Name: UserIn - Dependencies to Mock: Union, FastAPI, EmailStr Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import FastAPI, Response from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/portal") async def get_portal(teleport: bool = False) -> Union[Response, dict]: if teleport: return RedirectResponse(url="https://www.youtube.com/watch?v=dQw4w9WgXcQ")...
import importlib import pytest from fastapi.exceptions import FastAPIError from ...utils import needs_py310 @pytest.mark.parametrize( "module_name", [ "tutorial003_04", pytest.param("tutorial003_04_py310", marks=needs_py310), ], ) def test_invalid_response_model(module_name: str) -> None...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, Response, RedirectResponse Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get")], q: str ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import importlib import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39, needs_py310 @pytest.fixture( name="client", params=[ "tutorial003", pytest.param("tutorial003_py310", marks=needs_py310), "tutorial003_an", ...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import importlib import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39, needs_py310 @pytest.fixture( name="client", params=[ "tutorial001", pytest.param("tutorial001_py310", marks=needs_py310), "tutorial001_an", ...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py39, needs_py310, needs_pydanticv2 @pytest.fixture( name="client", params=[ "tutorial001", pytest.param("tutorial001_py310", marks=needs_py310), pytest.param("tutorial001_py39", marks...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( q: str, item_id: Annotated[int, Path(title="The ID of the item to get")] ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py39, needs_py310, needs_pydanticv2 @pytest.fixture( name="client", params=[ "tutorial002", pytest.param("tutorial002_py310", marks=needs_py310), pytest.param("tutorial002_py39", marks...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import importlib import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from inline_snapshot import snapshot from tests.utils import needs_py39, needs_py310 @pytest.fixture( name="client", params=[ "tutorial001", pytest.param("tutorial001_py39", marks=needs_p...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( q: str, item_id: Annotated[int, Path(title="The ID of the item to get")] ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import importlib import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from inline_snapshot import snapshot from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 @pytest.fixture( name="client", params=[ pytest.param("tutorial002", marks...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py39, needs_py310 @pytest.fixture( name="client", params=[ "tutorial001", pytest.param("tutorial001_py310", marks=needs_py310), "tutorial001_an", pytest.param("tutorial001_an_p...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files( files: list[bytes] = File(description="Multiple files as bytes"), ): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async de...
import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture(name="app") def get_app(): from docs_src.websockets.tutorial003_py39 import app return app @pytest.fixture(name="html") def get_html(): from docs_src.websockets.tutorial0...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: UploadFile, HTMLResponse Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import pytest from fastapi.testclient import TestClient from fastapi.websockets import WebSocketDisconnect from docs_src.websockets.tutorial001 import app client = TestClient(app) def test_main(): response = client.get("/") assert response.status_code == 200, response.text assert b"<!DOCTYPE html>" in r...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( q: str, item_id: Annotated[int, Path(title="The ID of the item to get")] ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import importlib import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi.websockets import WebSocketDisconnect from ...utils import needs_py39, needs_py310 @pytest.fixture( name="app", params=[ "tutorial002", pytest.param("tutorial002_py310", marks=ne...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( q: str, item_id: Annotated[int, Path(title="The ID of the item to get")] ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import importlib import os from pathlib import Path import pytest from fastapi.testclient import TestClient from ...utils import needs_py39, needs_py310 @pytest.fixture( name="client", params=[ "tutorial002", pytest.param("tutorial002_py310", marks=needs_py310), "tutorial002_an", ...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 @pytest.fixture( name="client", params=[ "tutorial001", pytest.param("tutorial001_py310", marks=needs_py310), pytest.param("tutori...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Union from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from typing_extensions import Annotated app = FastAPI() async def common_parameters( q: Union[str, None] = None, skip: int = 0, limit: int = 100 ): return {"q": q, "skip": skip, "limit": limit} @app.get...
import importlib import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture( name="client", params=[ "tutorial001", "tutorial001_an", pytest.param("tutorial001_an_py39", marks=needs_py39), ], ) def get_c...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Union, FastAPI, TestClient, Annotated Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import List from fastapi import FastAPI, Query from pydantic import BaseModel, Field from typing_extensions import Annotated, Literal app = FastAPI() class FilterParams(BaseModel): class Config: extra = "forbid" limit: int = Field(100, gt=0, le=100) offset: int = Field(0, ge=0) ...
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py39, needs_pydanticv1 @pytest.fixture( name="client", params=[ "tutorial002_pv1", "tutorial002_pv1_an", pytest.param("tutorial002_pv1_an_py39", marks=needs_py39), ], ) def get_cli...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'FilterParams' using 'unittest' and 'unittest.mock'. Context: - Class Name: FilterParams - Dependencies to Mock: List, Query, Field, Literal Requirements: Use @patch for mocks, follow AAA pattern.
python
from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( q: str, item_id: Annotated[int, Path(title="The ID of the item to get")] ): results = {"item_id": item_id} if q: results.update({"q": q}) return results
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py39, needs_pydanticv2 @pytest.fixture( name="client", params=[ "tutorial002", "tutorial002_an", pytest.param("tutorial002_an_py39", marks=needs_py39), ], ) def get_client(request:...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: Annotated, Path Requirements: Use @patch for mocks, follow AAA pattern.
python
from fastapi import FastAPI from .config import settings app = FastAPI() @app.get("/info") async def info(): return { "app_name": settings.app_name, "admin_email": settings.admin_email, "items_per_user": settings.items_per_user, }
import pytest from docs_src.async_tests.test_main import test_root @pytest.mark.anyio async def test_async_testing(): await test_root()
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: FastAPI, settings Requirements: Use @patch for mocks, follow AAA pattern.
python
from fastapi import FastAPI from .config import settings app = FastAPI() @app.get("/info") async def info(): return { "app_name": settings.app_name, "admin_email": settings.admin_email, "items_per_user": settings.items_per_user, }
import importlib import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient from ...utils import needs_py39 @pytest.fixture( name="client", params=[ "app_an.main", pytest.param("app_an_py39.main", marks=needs_py39), "app.main", ], ) def get_client(req...
fastapi
You are an expert Python testing engineer. Task: Write a unit test for 'TargetModule' using 'unittest' and 'unittest.mock'. Context: - Class Name: TargetModule - Dependencies to Mock: FastAPI, settings Requirements: Use @patch for mocks, follow AAA pattern.