prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
_LENGTH)
self.assertEqual(len(secret), CSRF_SECRET_LENGTH)
self.assertTrue(
set(masked_secret).issubset(set(CSRF_ALLOWED_CHARS)),
msg=f"invalid characters in {masked_secret!r}",
)
actual = _unmask_cipher_token(masked_secret)
self.assertEqual(actual, secret... | orbidden (%s): " % reason)
self.assertEqual(record.levelno, levelno)
self.assertEqual(record.status_code, 403)
self.assertEqual(response.status_code, 403)
class CsrfFunctionTests(CsrfFunctionTestMixin, SimpleTestCase):
def tes | 1,
f"Unexpected number of records for {logger_cm=} in {levelno=} (expected 1, "
f"got {records_len}).",
)
record = logger_cm.records[0]
self.assertEqual(record.getMessage(), "F | {
"filepath": "tests/csrf_tests/tests.py",
"language": "python",
"file_size": 58764,
"cut_index": 2151,
"middle_length": 229
} |
type.
"""
import uuid
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
from .base import BaseModel
try:
from PIL import Image # NOQA
except ImportError:
ImageData = None
else:
class... | .Model):
data = models.DateTimeField(null=True)
class DecimalData(models.Model):
data = models.DecimalField(null=True, decimal_places=3, max_digits=5)
class EmailData(models.Model):
data = models.EmailField(null=True)
class FileData(model | odels.BooleanField(default=False, null=True)
class CharData(models.Model):
data = models.CharField(max_length=30, null=True)
class DateData(models.Model):
data = models.DateField(null=True)
class DateTimeData(models | {
"filepath": "tests/serializers/models/data.py",
"language": "python",
"file_size": 7571,
"cut_index": 716,
"middle_length": 229
} |
m django.db import migrations
def assert_foo_contenttype_not_cached(apps, schema_editor):
ContentType = apps.get_model("contenttypes", "ContentType")
try:
content_type = ContentType.objects.get_by_natural_key(
"contenttypes_tests", "foo"
)
except ContentType.DoesNotExist:
... | "its model set to 'foo'."
)
class Migration(migrations.Migration):
dependencies = [
("contenttypes_tests", "0001_initial"),
]
operations = [
migrations.RenameModel("Foo", "RenamedFoo"),
migrati | contenttypes_tests.Foo ContentType should not be cached."
)
elif content_type.model != "foo":
raise AssertionError(
"The cached contenttypes_tests.Foo ContentType should have "
| {
"filepath": "tests/contenttypes_tests/operations_migrations/0002_rename_foo.py",
"language": "python",
"file_size": 1105,
"cut_index": 515,
"middle_length": 229
} |
e defaults are working (#20158)
def assert_pickles(self, qs):
self.assertEqual(list(pickle.loads(pickle.dumps(qs))), list(qs))
def test_binaryfield(self):
BinaryFieldModel.objects.create(data=b"binary data")
self.assert_pickles(BinaryFieldModel.objects.all())
def test_related_fiel... | self.assert_pickles(Happening.objects.filter(name="test"))
def test_standalone_method_as_default(self):
self.assert_pickles(Happening.objects.filter(number1=1))
def test_staticmethod_as_default(self):
self.assert_pickles(Happe | self.assert_pickles(Happening.objects.all())
def test_datetime_callable_default_filter(self):
self.assert_pickles(Happening.objects.filter(when=datetime.datetime.now()))
def test_string_as_default(self):
| {
"filepath": "tests/queryset_pickle/tests.py",
"language": "python",
"file_size": 16076,
"cut_index": 921,
"middle_length": 229
} |
article",
pub_date=datetime.date(2005, 7, 27),
reporter_id=self.r.id,
)
a3.save()
self.assertEqual(a3.reporter.id, self.r.id)
# Similarly, the reporter ID can be a string.
a4 = Article(
headline="Fourth article",
pub_date=datetime.... | rticle: John's second story>")
self.assertEqual(new_article.reporter.id, self.r.id)
# Create a new article, and add it to the article set.
new_article2 = Article(
headline="Paul's story", pub_date=datetime.date(2006, 1, | Create an Article via the Reporter object.
new_article = self.r.article_set.create(
headline="John's second story", pub_date=datetime.date(2005, 7, 29)
)
self.assertEqual(repr(new_article), "<A | {
"filepath": "tests/many_to_one/tests.py",
"language": "python",
"file_size": 39942,
"cut_index": 2151,
"middle_length": 229
} |
nt = models.IntegerField()
weight = models.FloatField()
# use a non-default name for the default manager
specimens = models.Manager()
def __str__(self):
return self.name
class Plant(models.Model):
name = models.CharField(max_length=150)
class Meta:
# For testing when upper c... | el):
name = models.CharField(max_length=10)
class Meta:
ordering = ("id",)
class Child(Parent):
data = models.CharField(max_length=10)
# Models to regression test #7572, #20820
class Channel(models.Model):
name = models.CharFie | oreignKey(User, models.SET_NULL, null=True)
def __str__(self):
return self.name + " is owned by " + str(self.owner)
class Absolute(models.Model):
name = models.CharField(max_length=40)
class Parent(models.Mod | {
"filepath": "tests/fixtures_regress/models.py",
"language": "python",
"file_size": 8809,
"cut_index": 716,
"middle_length": 229
} |
re.management import call_command
from django.test import TestCase, TransactionTestCase
from django.test.utils import extend_sys_path
from .models import (
ConcreteModel,
ConcreteModelSubclass,
ConcreteModelSubclassProxy,
ProxyModel,
)
class ProxyModelInheritanceTests(TransactionTestCase):
"""
... | INSTALLED_APPS={"append": ["app1", "app2"]}):
call_command("migrate", verbosity=0, run_syncdb=True)
from app1.models import ProxyModel
from app2.models import NiceModel
self.assertEqual(NiceM | hen verifies that the table has been
created.
"""
available_apps = []
def test_table_exists(self):
with extend_sys_path(os.path.dirname(os.path.abspath(__file__))):
with self.modify_settings( | {
"filepath": "tests/proxy_model_inheritance/tests.py",
"language": "python",
"file_size": 1989,
"cut_index": 537,
"middle_length": 229
} |
rom django.db import models
class Author(models.Model):
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
class Editor(models.Model):
name = models.CharField(max_length=128)
bestselling_author = models.ForeignKey(Author, models.CASCADE)
class Book(models.Mo... | name = "%(app_label)s_%(model_name)ss"
class BookStore(Store):
available_books = models.ManyToManyField(Book)
class EditorStore(Store):
editor = models.ForeignKey(Editor, models.CASCADE)
available_books = models.ManyToManyField(Book)
c | eta:
default_related_name = "books"
class Store(models.Model):
name = models.CharField(max_length=128)
address = models.CharField(max_length=128)
class Meta:
abstract = True
default_related_ | {
"filepath": "tests/model_options/models/default_related_name.py",
"language": "python",
"file_size": 1056,
"cut_index": 513,
"middle_length": 229
} |
ype
from django.core.management import call_command
from django.db import migrations, models
from django.test import TransactionTestCase, override_settings
@override_settings(
MIGRATION_MODULES=dict(
settings.MIGRATION_MODULES,
contenttypes_tests="contenttypes_tests.operations_migrations",
),
... |
self.assertOperationsInjected, sender=app_config
)
self.addCleanup(
models.signals.post_migrate.disconnect,
self.assertOperationsInjected,
sender=app_config,
)
def assertOperatio |
class TestRouter:
def db_for_write(self, model, **hints):
return "default"
def setUp(self):
app_config = apps.get_app_config("contenttypes_tests")
models.signals.post_migrate.connect( | {
"filepath": "tests/contenttypes_tests/test_operations.py",
"language": "python",
"file_size": 7080,
"cut_index": 716,
"middle_length": 229
} |
StatDetails,
User,
UserProfile,
UserStat,
UserStatResult,
)
class ReverseSelectRelatedTestCase(TestCase):
@classmethod
def setUpTestData(cls):
user = User.objects.create(username="test")
UserProfile.objects.create(user=user, state="KS", city="Lawrence")
results = Use... | =5, results=results2
)
StatDetails.objects.create(base_stats=advstat, comments=250)
p1 = Parent1(name1="Only Parent1")
p1.save()
c1 = Child1(name1="Child1 Parent1", name2="Child1 Parent2", value=1)
c1.save()
| mments=259)
user2 = User.objects.create(username="bob")
results2 = UserStatResult.objects.create(results="moar results")
advstat = AdvancedUserStat.objects.create(
user=user2, posts=200, karma | {
"filepath": "tests/select_related_onetoone/tests.py",
"language": "python",
"file_size": 12281,
"cut_index": 921,
"middle_length": 229
} |
ss Person(models.Model):
name = models.CharField(max_length=128)
class Meta:
ordering = ("name",)
class PersonChild(Person):
pass
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through="Membership")
custom_members = models... | dels.CASCADE)
date_joined = models.DateTimeField(default=datetime.now)
invite_reason = models.CharField(max_length=64, null=True)
class Meta:
ordering = ("date_joined", "invite_reason", "group")
def __str__(self):
return " | ",
related_name="testnodefaultsnonulls",
)
class Meta:
ordering = ("name",)
class Membership(models.Model):
person = models.ForeignKey(Person, models.CASCADE)
group = models.ForeignKey(Group, mo | {
"filepath": "tests/m2m_through/models.py",
"language": "python",
"file_size": 4645,
"cut_index": 614,
"middle_length": 229
} |
"admin_scripts",
]
settings_file.write("INSTALLED_APPS = %s\n" % apps)
if sdict:
for k, v in sdict.items():
settings_file.write("%s = %s\n" % (k, v))
def _ext_backend_paths(self):
"""
Returns the paths... | est(self, args, settings_file=None, apps=None, umask=-1):
base_dir = os.path.dirname(self.test_dir)
# The base dir for Django's tests is one level up.
tests_dir = os.path.dirname(os.path.dirname(__file__))
# The base dir for | age != "django":
backend_pkg = __import__(package)
backend_dir = os.path.dirname(backend_pkg.__file__)
paths.append(os.path.dirname(backend_dir))
return paths
def run_t | {
"filepath": "tests/admin_scripts/tests.py",
"language": "python",
"file_size": 126321,
"cut_index": 3790,
"middle_length": 229
} |
code = models.CharField(max_length=10)
class Employee(models.Model):
name = models.CharField(max_length=40, blank=False, null=False)
salary = models.PositiveIntegerField()
department = models.CharField(max_length=40, blank=False, null=False)
hire_date = models.DateField(blank=False, null=False)
a... | stEmployeeDepartment(models.Model):
employee = models.ForeignKey(
Employee, related_name="past_departments", on_delete=models.CASCADE
)
department = models.CharField(max_length=40, blank=False, null=False)
class Detail(models.Model):
| cimal_places=2, max_digits=15, null=True)
class Pa | {
"filepath": "tests/expressions_window/models.py",
"language": "python",
"file_size": 993,
"cut_index": 582,
"middle_length": 52
} |
publisher=cls.p1,
pubdate=datetime.date(2008, 6, 23),
)
cls.b4 = Book.objects.create(
isbn="013235613",
name="Python Web Development with Django",
pages=350,
rating=4.0,
price=Decimal("29.69"),
contact=cls.a... | weight=4.5,
)
cls.b6 = HardbackBook.objects.create(
isbn="155860191",
name=(
"Paradigms of Artificial Intelligence Programming: Case Studies in "
"Common Lisp"
) | ial Intelligence: A Modern Approach",
pages=1132,
rating=4.0,
price=Decimal("82.80"),
contact=cls.a8,
publisher=cls.p3,
pubdate=datetime.date(1995, 1, 15),
| {
"filepath": "tests/aggregation_regress/tests.py",
"language": "python",
"file_size": 74024,
"cut_index": 3790,
"middle_length": 229
} |
ge(RemovedInDjango70Warning, msg_use):
self.assertIs(backend.fail_silently, value)
def test_unknown_kwargs_error(self):
msg = "MAILERS['test_alias']: Unknown options 'oops_typo', 'unknown'."
with self.assertRaisesMessage(InvalidMailer, msg):
BaseEmailBackend(alias="t... | r for unknown keyword arguments."
)
with self.assertWarnsMessage(RemovedInDjango70Warning, msg):
backend = BaseEmailBackend(oops_typo="foo", unknown="foo")
self.assertIsInstance(backend, BaseEmailBackend)
| e
# ignored with a deprecation warning.
msg = (
"BaseEmailBackend.__init__() does not support 'oops_typo', "
"'unknown'. In Django 7.0, BaseEmailBackend will raise a "
"TypeErro | {
"filepath": "tests/mail/test_backends.py",
"language": "python",
"file_size": 45822,
"cut_index": 2151,
"middle_length": 229
} |
"""
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=15)
text = models.TextField(default="xyzzy")
value = models.IntegerField()
other_value = models.IntegerField(default=0)
source = models.OneToOneField(
"self",
related_name="destination",... | Key(Child, models.CASCADE)
second_child = models.ForeignKey(
Child, models.SET_NULL, related_name="other", null=True
)
value = models.IntegerField(default=42)
class ResolveThis(models.Model):
num = models.FloatField()
name = m | eta:
proxy = True
class Child(models.Model):
name = models.CharField(max_length=10)
value = models.IntegerField()
class Leaf(models.Model):
name = models.CharField(max_length=10)
child = models.Foreign | {
"filepath": "tests/defer_regress/models.py",
"language": "python",
"file_size": 2550,
"cut_index": 563,
"middle_length": 229
} |
vent, Genre, GrandChild, Parent, ProxyUser, Swallow
site = admin.AdminSite(name="admin")
site.register(User, UserAdmin)
class CustomPaginator(Paginator):
def __init__(self, queryset, page_size, orphans=0, allow_empty_first_page=True):
super().__init__(
queryset, 5, orphans=2, allow_empty_fir... | = ["child__name"]
list_select_related = ["child"]
class ParentAdminTwoSearchFields(admin.ModelAdmin):
list_filter = ["child__name"]
search_fields = ["child__name", "child__age"]
list_select_related = ["child"]
class ChildAdmin(admin.Mod | lf, event):
return event.date
def has_add_permission(self, request):
return False
site.register(Event, EventAdmin)
class ParentAdmin(admin.ModelAdmin):
list_filter = ["child__name"]
search_fields | {
"filepath": "tests/admin_changelist/admin.py",
"language": "python",
"file_size": 5882,
"cut_index": 716,
"middle_length": 229
} |
django.contrib.auth.models import User
from django.test import RequestFactory, TestCase, override_settings
from django.urls import reverse
from django.utils.timezone import make_aware
from .admin import EventAdmin
from .admin import site as custom_site
from .models import Event
class DateHierarchyTests(TestCase):
... | r = self.superuser
changelist = EventAdmin(Event, custom_site).get_changelist_instance(request)
_, _, lookup_params, *_ = changelist.get_filters(request)
self.assertEqual(lookup_params["date__gte"], [expected_from_date])
sel |
)
def assertDateParams(self, query, expected_from_date, expected_to_date):
query = {"date__%s" % field: val for field, val in query.items()}
request = self.factory.get("/", query)
request.use | {
"filepath": "tests/admin_changelist/test_date_hierarchy.py",
"language": "python",
"file_size": 4181,
"cut_index": 614,
"middle_length": 229
} |
rom .tests import MailTestsMixin
class DeprecationWarningTests(MailTestsMixin, SimpleTestCase):
def test_deprecated_on_import(self):
"""
These items are not typically called from user code,
so generate deprecation warnings immediately at the time
they are imported from django.core.... | "SafeMIMEMultipart",
"SafeMIMEMultipart is deprecated. The return value of"
" EmailMessage.message() is an email.message.EmailMessage.",
),
]
for name, msg in cases:
with sel | ),
(
"SafeMIMEText",
"SafeMIMEText is deprecated. The return value of"
" EmailMessage.message() is an email.message.EmailMessage.",
),
(
| {
"filepath": "tests/mail/test_deprecated.py",
"language": "python",
"file_size": 19954,
"cut_index": 1331,
"middle_length": 229
} |
.test import SimpleTestCase, override_settings
@override_settings(
ADMINS=["admin@example.com", "admin_and_manager@example.com"],
MANAGERS=["manager@example.com", "admin_and_manager@example.com"],
MAILERS={"default": {"BACKEND": "django.core.mail.backends.locmem.EmailBackend"}},
)
class SendTestEmailManag... | self.assertEqual(mail_message.subject[0:15], "Test email from")
self.assertEqual(mail_message.recipients(), [recipient])
def test_multiple_receivers(self):
"""
The mail may be sent with multiple recipients.
"""
| with the correct subject and recipient.
"""
recipient = "joe@example.com"
call_command("sendtestemail", recipient)
self.assertEqual(len(mail.outbox), 1)
mail_message = mail.outbox[0]
| {
"filepath": "tests/mail/test_sendtestemail.py",
"language": "python",
"file_size": 3726,
"cut_index": 614,
"middle_length": 229
} |
k = Person.objects.create(name="Chuck")
cls.daisy = Person.objects.create(name="Daisy")
def setUp(self):
self.m2m_changed_messages = []
def m2m_changed_signal_receiver(self, signal, sender, **kwargs):
message = {
"instance": kwargs["instance"],
"action": kwargs[... | ignals.m2m_changed.disconnect(
self.m2m_changed_signal_receiver, Car.default_parts.through
)
models.signals.m2m_changed.disconnect(
self.m2m_changed_signal_receiver, Car.optional_parts.through
)
model | "] = list(
kwargs["model"].objects.filter(pk__in=kwargs["pk_set"])
)
self.m2m_changed_messages.append(message)
def tearDown(self):
# disconnect all signal handlers
models.s | {
"filepath": "tests/m2m_signals/tests.py",
"language": "python",
"file_size": 23204,
"cut_index": 1331,
"middle_length": 229
} |
jango.http import HttpResponse, StreamingHttpResponse
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin
from . import urlconf_inner
class ChangeURLconfMiddleware(MiddlewareMixin):
def process_request(self, request):
request.urlconf = urlconf_inner.__name__
class NullC... |
class ReverseInnerInStreaming(MiddlewareMixin):
def process_view(self, *args, **kwargs):
def stream():
yield reverse("inner")
return StreamingHttpResponse(stream())
class ReverseOuterInStreaming(MiddlewareMixin):
def | nse(self, *args, **kwargs):
return HttpResponse(reverse("inner"))
class ReverseOuterInResponseMiddleware(MiddlewareMixin):
def process_response(self, *args, **kwargs):
return HttpResponse(reverse("outer"))
| {
"filepath": "tests/urlpatterns_reverse/middleware.py",
"language": "python",
"file_size": 1146,
"cut_index": 518,
"middle_length": 229
} |
m . import views
from .utils import URLObject
testobj1 = URLObject("testapp", "test-ns1")
testobj2 = URLObject("testapp", "test-ns2")
default_testobj = URLObject("testapp", "testapp")
otherobj1 = URLObject("nodefault", "other-ns1")
otherobj2 = URLObject("nodefault", "other-ns2")
newappobj1 = URLObject("newapp")
app... | /([0-9]+)/(?P<arg2>[0-9]+)/$",
views.empty_view,
{"extra": True},
name="mixed-args",
),
re_path(r"^no_kwargs/([0-9]+)/([0-9]+)/$", views.empty_view, name="no-kwargs"),
re_path(
r"^view_class/(?P<arg1>[0-9]+)/(?P< | w,
name="normal-view",
),
path("resolver_match/", views.pass_resolver_match_view, name="test-resolver-match"),
re_path(r"^\+\\\$\*/$", views.empty_view, name="special-view"),
re_path(
r"^mixed_args | {
"filepath": "tests/urlpatterns_reverse/namespace_urls.py",
"language": "python",
"file_size": 2969,
"cut_index": 563,
"middle_length": 229
} |
port mock
from django.core.exceptions import ImproperlyConfigured
from django.test import SimpleTestCase, override_settings
from django.urls.resolvers import LocaleRegexDescriptor, RegexPattern
from django.utils import translation
here = os.path.dirname(os.path.abspath(__file__))
@override_settings(LOCALE_PATHS=[os... | de_compiled = provider.regex
# compiled only once per language
error = AssertionError(
"tried to compile url regex twice for the same language"
)
with mock.patch("django.urls.resolvers.re.com | translation.trans_real._translations = {}
def test_translated_regex_compiled_per_language(self):
provider = RegexPattern(translation.gettext_lazy("^foo/$"))
with translation.override("de"):
| {
"filepath": "tests/urlpatterns_reverse/test_localeregexdescriptor.py",
"language": "python",
"file_size": 2568,
"cut_index": 563,
"middle_length": 229
} |
tial, update_wrapper
from django.contrib.auth.decorators import user_passes_test
from django.http import HttpResponse
from django.urls import reverse_lazy
from django.views.generic import RedirectView, View
def empty_view(request, *args, **kwargs):
return HttpResponse()
def absolute_kwargs_view(request, arg1=1... | :
def __call__(self, request, *args, **kwargs):
return HttpResponse()
view_class_instance = ViewClass()
class LazyRedirectView(RedirectView):
url = reverse_lazy("named-lazy-url-redirected-to")
@user_passes_test(
lambda u: u.is_aut | f pass_resolver_match_view(request, *args, **kwargs):
response = HttpResponse()
response.resolver_match = request.resolver_match
return response
uncallable = None # neither a callable nor a string
class ViewClass | {
"filepath": "tests/urlpatterns_reverse/views.py",
"language": "python",
"file_size": 1722,
"cut_index": 537,
"middle_length": 229
} |
ponse(open(__file__, "rb"))
response.close()
self.assertEqual(
response.headers["Content-Length"], str(os.path.getsize(__file__))
)
def test_content_length_buffer(self):
response = FileResponse(io.BytesIO(b"binary content"))
self.assertEqual(response.headers["Con... |
("BytesIO", io.BytesIO),
("UnseekableBytesIO", UnseekableBytesIO),
)
for buffer_class_name, BufferClass in test_tuples:
with self.subTest(buffer_class_name=buffer_class_name):
buffer = Bu | response.close()
self.assertEqual(
response.headers["Content-Length"], str(os.path.getsize(__file__) - 10)
)
def test_content_length_nonzero_starting_position_buffer(self):
test_tuples = ( | {
"filepath": "tests/responses/test_fileresponse.py",
"language": "python",
"file_size": 11003,
"cut_index": 921,
"middle_length": 229
} |
rt SimpleTestCase
UTF8 = "utf-8"
ISO88591 = "iso-8859-1"
class HttpResponseBaseTests(SimpleTestCase):
def test_closed(self):
r = HttpResponseBase()
self.assertIs(r.closed, False)
r.close()
self.assertIs(r.closed, True)
def test_write(self):
r = HttpResponseBase()
... | with self.assertRaisesMessage(
OSError, "This HttpResponseBase instance cannot tell its position"
):
r.tell()
def test_setdefault(self):
"""
HttpResponseBase.setdefault() should not change an existing he | with self.assertRaisesMessage(
OSError, "This HttpResponseBase instance is not writable"
):
r.writelines(["asdf\n", "qwer\n"])
def test_tell(self):
r = HttpResponseBase()
| {
"filepath": "tests/responses/tests.py",
"language": "python",
"file_size": 6952,
"cut_index": 716,
"middle_length": 229
} |
import nullcontext
from django.conf import DEPRECATED_EMAIL_SETTINGS, EMAIL_SETTING_DEPRECATED_MSG
from django.core.mail.deprecation import NO_DEFAULT_MAILER_WARNING
from django.test import ignore_warnings, override_settings
from django.utils.deprecation import RemovedInDjango70Warning
# RemovedInDjango70Warning.
c... | f __init__(self, **kwargs):
super().__init__(**kwargs)
deprecated_names = [
name for name in kwargs if name in DEPRECATED_EMAIL_SETTINGS
]
if deprecated_names:
assert "{name}" in EMAIL_SETTING_DEPRECA | warnings related to
defining the overridden settings. Other settings can be included.
Warnings are ignored only while installing and restoring the settings
overrides, not for code within the context.
"""
de | {
"filepath": "tests/mail/__init__.py",
"language": "python",
"file_size": 1920,
"cut_index": 537,
"middle_length": 229
} |
lBackend
class EmailBackend(BaseEmailBackend):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.test_outbox = []
def send_messages(self, email_messages):
# Messages are stored in an instance variable for testing.
self.test_outbox.extend(email_message... | use the OptionsCapturingBackend.
"""
init_kwargs = []
sent_messages = []
@classmethod
def reset(cls):
cls.init_kwargs = []
cls.sent_messages = []
def __init__(self, **kwargs):
self.init_kwargs.append(k | kend _must_ ensure reset() is called::
def test_something(self):
self.addCleanup(OptionsCapturingBackend.reset)
...
Failing to call reset() will cause unexpected behavior in other tests that
| {
"filepath": "tests/mail/custombackend.py",
"language": "python",
"file_size": 2079,
"cut_index": 563,
"middle_length": 229
} |
SimpleItem,
SpecialFeature,
)
class DeferRegressionTest(TestCase):
def test_basic(self):
# Deferred fields should really be deferred and not accidentally use
# the field's default value just because they aren't passed to __init__
Item.objects.create(name="first", value=42)
... | rtNumQueries(1):
self.assertEqual(obj.text, "xyzzy")
with self.assertNumQueries(0):
self.assertEqual(obj.text, "xyzzy")
# Regression test for #10695. Make sure different instances don't
# inadvertently shar | elf.assertNumQueries(0):
self.assertEqual(obj.name, "first")
self.assertEqual(obj.other_value, 0)
with self.assertNumQueries(1):
self.assertEqual(obj.value, 42)
with self.asse | {
"filepath": "tests/defer_regress/tests.py",
"language": "python",
"file_size": 16100,
"cut_index": 921,
"middle_length": 229
} |
sertEqual(repr(cl), "<ChangeList: model=Child model_admin=ChildAdmin>")
def test_specified_ordering_by_f_expression(self):
class OrderedByFBandAdmin(admin.ModelAdmin):
list_display = ["name", "genres", "nr_of_members"]
ordering = (
F("nr_of_members").desc(nulls_last=... | desc(self):
class OrderedByFBandAdmin(admin.ModelAdmin):
list_display = ["name", "genres", "nr_of_members"]
ordering = (F("nr_of_members"), Upper("name"), F("genres"))
m = OrderedByFBandAdmin(Band, custom_site)
|
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertEqual(cl.get_ordering_field_columns(), {3: "desc", 2: "asc"})
def test_specified_ordering_by_f_expression_without_asc_ | {
"filepath": "tests/admin_changelist/tests.py",
"language": "python",
"file_size": 94573,
"cut_index": 3790,
"middle_length": 229
} |
up(OptionsCapturingBackend.reset)
@override_settings(
MAILERS={
"default": {"BACKEND": "django.core.mail.backends.locmem.EmailBackend"},
"custom": {"BACKEND": "django.core.mail.backends.locmem.EmailBackend"},
}
)
def test_getitem(self):
with self.subTest("def... | ail.mailers is a mapping, so unknown keys raise KeyError.
# (MailerDoesNotExist must be a KeyError.)
with self.assertRaises(KeyError):
_ = mailers["unknown"]
@override_settings(
MAILERS={
"on | msg = "The mailer 'unknown' is not configured."
with self.assertRaisesMessage(MailerDoesNotExist, msg):
_ = mailers["unknown"]
with self.subTest("raises KeyError"):
# m | {
"filepath": "tests/mail/test_handler.py",
"language": "python",
"file_size": 9255,
"cut_index": 921,
"middle_length": 229
} |
ews import empty_view
urlpatterns = [
# No kwargs
path("conflict/cannot-go-here/", empty_view, name="name-conflict"),
path("conflict/", empty_view, name="name-conflict"),
# One kwarg
re_path(r"^conflict-first/(?P<first>\w+)/$", empty_view, name="name-conflict"),
re_path(
r"^conflict-can... | # Two kwargs
re_path(
r"^conflict/(?P<another>\w+)/(?P<extra>\w+)/cannot-go-here/$",
empty_view,
name="name-conflict",
),
re_path(
r"^conflict/(?P<extra>\w+)/(?P<another>\w+)/$", empty_view, name="name-conflict"
| ast>\w+)/$", empty_view, name="name-conflict"),
| {
"filepath": "tests/urlpatterns_reverse/named_urls_conflict.py",
"language": "python",
"file_size": 876,
"cut_index": 559,
"middle_length": 52
} |
.ViewClass",
views.view_class_instance,
(),
{"arg1": "42", "arg2": "37"},
),
# If you have no kwargs, you get an args list.
(
"/no_kwargs/42/37/",
"no-kwargs",
"",
"",
"no-kwargs",
views.empty_view,
("42", "37"),
{},
... | mespace_urls:inc-no-kwargs",
views.empty_view,
("12", "42", "37"),
{},
),
# Namespaces
(
"/test1/inner/42/37/",
"urlobject-view",
"testapp",
"test-ns1",
"test-ns1:urlobject-view",
| views.empty_view,
("42", "37"),
{},
),
(
"/included/12/no_kwargs/42/37/",
"inc-no-kwargs",
"included_namespace_urls",
"included_namespace_urls",
"included_na | {
"filepath": "tests/urlpatterns_reverse/tests.py",
"language": "python",
"file_size": 70494,
"cut_index": 3790,
"middle_length": 229
} |
ango.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=50)
year = models.PositiveIntegerField(null=True, blank=True)
author = models.For... | verbose_name="Employee",
blank=True,
null=True,
)
is_best_seller = models.BooleanField(default=0, null=True)
date_registered = models.DateField(null=True)
availability = models.BooleanField(
choices=(
| dels.ManyToManyField(
User,
verbose_name="Verbose Contributors",
related_name="books_contributed",
blank=True,
)
employee = models.ForeignKey(
"Employee",
models.SET_NULL,
| {
"filepath": "tests/admin_filters/models.py",
"language": "python",
"file_size": 2792,
"cut_index": 563,
"middle_length": 229
} |
lobals())'
script_with_inline_function = (
"import django\ndef f():\n print(django.__version__)\nf()"
)
def test_command_option(self):
with self.assertLogs("test", "INFO") as cm:
with captured_stdout():
call_command(
"shell",
... | ty=0)
self.assertEqual(stdout.getvalue().strip(), "True")
def test_command_option_inline_function_call(self):
with captured_stdout() as stdout:
call_command("shell", command=self.script_with_inline_function, verbosity=0)
| )
self.assertEqual(cm.records[0].getMessage(), __version__)
def test_command_option_globals(self):
with captured_stdout() as stdout:
call_command("shell", command=self.script_globals, verbosi | {
"filepath": "tests/shell/tests.py",
"language": "python",
"file_size": 20290,
"cut_index": 1331,
"middle_length": 229
} |
ress headers.
continue
raw_value = raw_headers[header]
if RFC2047_PREFIX in raw_value:
# Headers should not appear more than once.
assert len(message.get_all(header)) == 1
# Reconstruct Address objects using legacy APIs.
unfolded = raw_value.re... | ge.
"""
# The modern email parser has a bug with adjacent rfc2047 encoded-words.
# This doesn't affect django.core.mail (which doesn't parse messages),
# but it can confuse our tests that try to verify sent content by reparsing
# the ge | ])
)
message.replace_header(header, corrected_addresses)
def message_from_bytes(s):
"""
email.message_from_bytes() using modern email.policy.default.
Returns a modern email.message.EmailMessa | {
"filepath": "tests/mail/tests.py",
"language": "python",
"file_size": 128815,
"cut_index": 3790,
"middle_length": 229
} |
ped,
nested_view,
view_func_from_cbv,
)
other_patterns = [
path("non_path_include/", empty_view, name="non_path_include"),
path("nested_path/", nested_view),
]
urlpatterns = [
re_path(r"^places/([0-9]+)/$", empty_view, name="places"),
re_path(r"^places?/$", empty_view, name="places?"),
re_... | ces4"),
re_path(r"^people/(?P<name>\w+)/$", empty_view, name="people"),
re_path(r"^people/(?:name/)$", empty_view, name="people2"),
re_path(r"^people/(?:name/(\w+)/)?$", empty_view, name="people2a"),
re_path(r"^people/(?P<name>\w+)-(?P=name | +$", empty_view, name="places2+"),
re_path(r"^(?:places/)*$", empty_view, name="places2*"),
re_path(r"^places/([0-9]+|[a-z_]+)/", empty_view, name="places3"),
re_path(r"^places/(?P<id>[0-9]+)/$", empty_view, name="pla | {
"filepath": "tests/urlpatterns_reverse/urls.py",
"language": "python",
"file_size": 5594,
"cut_index": 716,
"middle_length": 229
} |
title = "publication decade"
parameter_name = "decade__isnull" # Ends with '__isnull"
class DepartmentListFilterLookupWithNonStringValue(SimpleListFilter):
title = "department"
parameter_name = "department"
def lookups(self, request, model_admin):
return sorted(
{
... | derscoredParameter(
DepartmentListFilterLookupWithNonStringValue
):
parameter_name = "department__whatever"
class DepartmentListFilterLookupWithDynamicValue(DecadeListFilterWithTitleAndParameter):
def lookups(self, request, model_admin):
| del_admin.get_queryset(request)
}
)
def queryset(self, request, queryset):
if self.value():
return queryset.filter(department__id=self.value())
class DepartmentListFilterLookupWithUn | {
"filepath": "tests/admin_filters/tests.py",
"language": "python",
"file_size": 83791,
"cut_index": 3790,
"middle_length": 229
} |
jango.urls import include, path, re_path
from .utils import URLObject
from .views import empty_view, view_class_instance
testobj3 = URLObject("testapp", "test-ns3")
testobj4 = URLObject("testapp", "test-ns4")
app_name = "included_namespace_urls"
urlpatterns = [
path("normal/", empty_view, name="inc-normal-view")... | g1>[0-9]+)/(?P<arg2>[0-9]+)/$",
view_class_instance,
name="inc-view-class",
),
path("test3/", include(*testobj3.urls)),
path("test4/", include(*testobj4.urls)),
path(
"ns-included3/",
include(
("u | ),
re_path(
"^mixed_args/([0-9]+)/(?P<arg2>[0-9]+)/$", empty_view, name="inc-mixed-args"
),
re_path("^no_kwargs/([0-9]+)/([0-9]+)/$", empty_view, name="inc-no-kwargs"),
re_path(
"^view_class/(?P<ar | {
"filepath": "tests/urlpatterns_reverse/included_namespace_urls.py",
"language": "python",
"file_size": 1214,
"cut_index": 518,
"middle_length": 229
} |
o.test import SimpleTestCase
from django.test.utils import freeze_time
from django.utils.http import http_date
class SetCookieTests(SimpleTestCase):
def test_near_expiration(self):
"""Cookie will expire when a near expiration time is provided."""
response = HttpResponse()
# There's a timin... | medelta(seconds=10)
time.sleep(0.001)
response.set_cookie("datetime", expires=expires)
datetime_cookie = response.cookies["datetime"]
self.assertEqual(datetime_cookie["max-age"], 10)
def test_aware_expiration(self):
| _cookie(). If
# this difference doesn't exist, the cookie time will be 1 second
# larger. The sleep guarantees that there will be a time difference.
expires = datetime.now(tz=UTC).replace(tzinfo=None) + ti | {
"filepath": "tests/responses/test_cookie.py",
"language": "python",
"file_size": 6783,
"cut_index": 716,
"middle_length": 229
} |
dels.Model):
# Oracle can have problems with a column named "date"
date = models.DateField(db_column="event_date")
class Parent(models.Model):
name = models.CharField(max_length=128)
class Child(models.Model):
parent = models.ForeignKey(Parent, models.SET_NULL, editable=False, null=True)
name = ... | ain">{self.name}</h2>'
class Genre(models.Model):
name = models.CharField(max_length=20)
file = models.FileField(upload_to="documents/", blank=True, null=True)
url = models.URLField(blank=True, null=True)
class Band(models.Model):
name | = models.ForeignKey(Child, models.SET_NULL, editable=False, null=True)
name = models.CharField(max_length=30, blank=True)
def __str__(self):
return self.name
def __html__(self):
return f'<h2 class="m | {
"filepath": "tests/admin_changelist/models.py",
"language": "python",
"file_size": 3780,
"cut_index": 614,
"middle_length": 229
} |
Binder interface.
type DefaultBinder struct{}
// BindUnmarshaler is the interface used to wrap the UnmarshalParam method.
// Types that don't implement this, but do implement encoding.TextUnmarshaler
// will use that interface instead.
type BindUnmarshaler interface {
// UnmarshalParam decodes and assigns a value fro... | ]string) error
}
// BindPathValues binds path parameter values to bindable object
func BindPathValues(c *Context, target any) error {
params := map[string][]string{}
for _, param := range c.PathValues() {
params[param.Name] = []string{param.Value}
}
| erface. For example request could have multiple query fields `?a=1&a=2&b=test` in that case
// for `a` following slice `["1", "2"] will be passed to unmarshaller.
type bindMultipleUnmarshaler interface {
UnmarshalParams(params [ | {
"filepath": "bind.go",
"language": "go",
"file_size": 14910,
"cut_index": 921,
"middle_length": 229
} |
rrors in binder. Useful along with `FailFast()` method
to do binding and returns on first problem
`BindErrors()` returns all bind errors from binder and resets errors in binder.
Types that are supported:
* bool
* float32
* float64
* int
* int8
* int16
* int32
* int64
* uint
* uint8/byte (does ... | imeNano() - converts unix time with nanosecond precision (integer) to time.Time
* CustomFunc() - callback function for your custom conversion logic. Signature `func(values []string) []error`
*/
// BindingError represents an error that occurred while bin | rface
* TextUnmarshaler() interface
* JSONUnmarshaler() interface
* UnixTime() - converts unix time (integer) to time.Time
* UnixTimeMilli() - converts unix time with millisecond precision (integer) to time.Time
* UnixT | {
"filepath": "binder.go",
"language": "go",
"file_size": 43831,
"cut_index": 2151,
"middle_length": 229
} |
Name: cmp.Or(tc.givenKey, "key"),
Value: tc.givenValue,
}})
v, err := PathParam[bool](c, "key")
if tc.expectErr != "" {
assert.EqualError(t, err, tc.expectErr)
} else {
assert.NoError(t, err)
}
assert.Equal(t, tc.expect, v)
})
}
}
func TestPathParam_UnsupportedType(t *testing.T) {
c... |
expect bool
expectErr string
}{
{
name: "ok",
givenURL: "/?key=true",
expect: true,
},
{
name: "nok, non existent key",
givenURL: "/?different=true",
expect: false,
expectErr: ErrNonExistentKey.Error(),
| lue, err: unsupported value type: *[]bool, field=key"
assert.EqualError(t, err, expectErr)
assert.Equal(t, []bool(nil), v)
}
func TestQueryParam(t *testing.T) {
var testCases = []struct {
name string
givenURL string | {
"filepath": "binder_generic_test.go",
"language": "go",
"file_size": 37215,
"cut_index": 2151,
"middle_length": 229
} |
nse-Identifier: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
package echo
import "errors"
// ErrNonExistentKey is error that is returned when key does not exist
var ErrNonExistentKey = errors.New("non existent key")
// ErrInvalidKeyType is error that is returned when the value is not cas... | ErrNonExistentKey
}
typed, ok := val.(T)
if !ok {
var zero T
return zero, ErrInvalidKeyType
}
return typed, nil
}
// ContextGetOr retrieves a value from the context store or returns a default value when the key
// is missing. Returns ErrInvalid | ErrInvalidKeyType error if the value is not castable to type T.
func ContextGet[T any](c *Context, key string) (T, error) {
c.lock.RLock()
defer c.lock.RUnlock()
val, ok := c.store[key]
if !ok {
var zero T
return zero, | {
"filepath": "context_generic.go",
"language": "go",
"file_size": 1261,
"cut_index": 524,
"middle_length": 229
} |
ent = "invalid content"
userJSONInvalidType = `{"id":"1","name":"Jon Snow"}`
userXMLConvertNumberError = `<user><id>Number one</id><name>Jon Snow</name></user>`
userXMLUnsupportedTypeError = `<user><>Number one</><name>Jon Snow</name></user>`
)
const userJSONPretty = `{
"id": 1,
"name": "... | sInternalServerError, rec.Code)
}
func TestNewWithConfig(t *testing.T) {
e := NewWithConfig(Config{})
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
e.GET("/", func(c *Context) error {
return c.String(http.Status | req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
// Router
assert.NotNil(t, e.Router())
e.HTTPErrorHandler(c, errors.New("error"))
assert.Equal(t, http.Statu | {
"filepath": "echo_test.go",
"language": "go",
"file_size": 33660,
"cut_index": 1331,
"middle_length": 229
} |
package echo
import (
"errors"
"fmt"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
func TestHTTPError_StatusCode(t *testing.T) {
var err error = &HTTPError{Code: http.StatusBadRequest, Message: "my error message"}
code := 0
var sc HTTPStatusCoder
if errors.As(err, &sc) {
code = sc.StatusCod... | essage"},
expect: "code=400, message=my error message",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.expect, tc.error.Error())
})
}
}
func TestHTTPError_WrapUnwrap(t *testing.T) {
err := &HTTPE | ok, without message",
error: &HTTPError{Code: http.StatusBadRequest},
expect: "code=400, message=Bad Request",
},
{
name: "ok, with message",
error: &HTTPError{Code: http.StatusBadRequest, Message: "my error m | {
"filepath": "httperror_test.go",
"language": "go",
"file_size": 4615,
"cut_index": 614,
"middle_length": 229
} |
package echo
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestResponse(t *testing.T) {
e := New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
res := NewResponse(rec, e.Logger)
// Before
res... | res := NewResponse(rec, e.Logger)
res.Write([]byte("test"))
assert.Equal(t, http.StatusOK, rec.Code)
}
func TestResponse_Write_UsesSetResponseCode(t *testing.T) {
e := New()
rec := httptest.NewRecorder()
res := NewResponse(rec, e.Logger)
res.Stat | sert.Equal(t, "echo", rec.Header().Get(HeaderServer))
assert.Equal(t, "DENY", rec.Header().Get(HeaderXFrameOptions))
}
func TestResponse_Write_FallsBackToDefaultStatus(t *testing.T) {
e := New()
rec := httptest.NewRecorder()
| {
"filepath": "response_test.go",
"language": "go",
"file_size": 3102,
"cut_index": 614,
"middle_length": 229
} |
tx stdContext.Context, e *Echo) (string, error) {
addrChan := make(chan string)
errCh := make(chan error)
go func() {
errCh <- (&StartConfig{
Address: ":0",
GracefulTimeout: 100 * time.Millisecond,
ListenerAddrFunc: func(addr net.Addr) {
addrChan <- addr.String()
},
}).Start(ctx, e)
}()... | == http.ErrServerClosed { // was closed normally before listener callback was called. should not be possible
return "", nil
}
// failed to start and we did not manage to get even listener part.
return "", err
}
}
}
func doGet(url string) ( | kground(), 200*time.Millisecond)
defer cancel()
// wait for addr to arrive
for {
select {
case <-waitCtx.Done():
return "", waitCtx.Err()
case addr := <-addrChan:
return addr, nil
case err := <-errCh:
if err | {
"filepath": "server_test.go",
"language": "go",
"file_size": 16424,
"cut_index": 921,
"middle_length": 229
} |
o.Context) error {
c.Response().Write([]byte("test")) // For Content-Type sniffing
return nil
})
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := h(c)
assert.NoError(t, err)
assert.Equal(t, "test", rec.Body.String())
}
... | pScheme)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := h(c)
assert.NoError(t, err)
assert.Equal(t, gzipScheme, rec.Header().Get(echo.HeaderContentEncoding))
assert.Contains(t, rec.Header().Get(echo.HeaderContentType), echo.MIMET | nc(c *echo.Context) error {
c.Response().Write([]byte("test")) // For Content-Type sniffing
return nil
})
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderAcceptEncoding, gzi | {
"filepath": "middleware/compress_test.go",
"language": "go",
"file_size": 10852,
"cut_index": 921,
"middle_length": 229
} |
equest func() *http.Request
givenPathValues echo.PathValues
whenLookups string
whenLimit uint
expectValues []string
expectSource ExtractorSource
expectCreateError string
expectError string
}{
{
name: "ok, header",
givenRequest: func() *http.Request {
req :... | hodPost, "/", strings.NewReader(f.Encode()))
req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm)
return req
},
whenLookups: "form:name",
expectValues: []string{"Jon Snow"},
expectSource: ExtractorSourceForm,
},
{
na | es: []string{"token"},
expectSource: ExtractorSourceHeader,
},
{
name: "ok, form",
givenRequest: func() *http.Request {
f := make(url.Values)
f.Set("name", "Jon Snow")
req := httptest.NewRequest(http.Met | {
"filepath": "middleware/extractor_test.go",
"language": "go",
"file_size": 17007,
"cut_index": 921,
"middle_length": 229
} |
htText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"fmt"
"net/http"
"runtime"
"github.com/labstack/echo/v5"
)
// RecoverConfig defines the config for Recover middleware.
type RecoverConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Size of the st... | cover middleware config.
var DefaultRecoverConfig = RecoverConfig{
Skipper: DefaultSkipper,
StackSize: 4 << 10, // 4 KB
DisableStackAll: false,
DisablePrintStack: false,
}
// Recover returns a middleware which recovers from panics | goroutine.
// Optional. Default value false.
DisableStackAll bool
// DisablePrintStack disables printing stack trace.
// Optional. Default value as false.
DisablePrintStack bool
}
// DefaultRecoverConfig is the default Re | {
"filepath": "middleware/recover.go",
"language": "go",
"file_size": 2789,
"cut_index": 563,
"middle_length": 229
} |
d do not affect which route handler is matched
e.Use(RewriteWithConfig(RewriteConfig{
Rules: map[string]string{
"/old": "/new",
"/api/*": "/$1",
"/js/*": "/public/javascripts/$1",
"/users/*/orders/*": "/user/$1/order/$2",
},
}))
e.GET("/public/*", func(c *echo.Cont... | ers",
expectRequestRawPath: "",
},
{
whenPath: "/js/main.js",
expectRoutePath: "js/main.js",
expectRequestPath: "/public/javascripts/main.js",
expectRequestRawPath: "",
},
{
whenPath: "/users/jack/o | nPath string
expectRoutePath string
expectRequestPath string
expectRequestRawPath string
}{
{
whenPath: "/api/users",
expectRoutePath: "api/users",
expectRequestPath: "/us | {
"filepath": "middleware/rewrite_test.go",
"language": "go",
"file_size": 9227,
"cut_index": 921,
"middle_length": 229
} |
trI64" form:"PtrI64"`
PtrI *int `json:"PtrI" form:"PtrI"`
PtrI8 *int8 `json:"PtrI8" form:"PtrI8"`
PtrF64 *float64 `json:"PtrF64" form:"PtrF64"`
PtrUI8 *uint8 `json:"PtrUI8" form:"PtrUI8"`
PtrUI64 *uint64 `json:"PtrUI64" form:"PtrUI64"`
PtrUI16 *uint16 `json:"P... | `json:"UI64" form:"UI64"`
UI uint `json:"UI" form:"UI"`
I64 int64 `json:"I64" form:"I64"`
F32 float32 `json:"F32" form:"F32"`
UI32 uint32 `json:"UI32" form:"UI32"`
I32 int32 `json | g
DoesntExist string `json:"DoesntExist" form:"DoesntExist"`
SA StringArray `json:"SA" form:"SA"`
F64 float64 `json:"F64" form:"F64"`
I int `json:"I" form:"I"`
UI64 uint64 | {
"filepath": "bind_test.go",
"language": "go",
"file_size": 53023,
"cut_index": 2151,
"middle_length": 229
} |
// run tests as external package to get real feel for API
package echo_test
import (
"encoding/base64"
"fmt"
"log"
"net/http"
"net/http/httptest"
"github.com/labstack/echo/v5"
)
func ExampleValueBinder_BindErrors() {
// example route function that binds query params to different destinations and returns all b... | rror)
log.Printf("in case you want to access what field: %s values: %v failed", bErr.Field, bErr.Values)
}
return fmt.Errorf("%v fields failed to bind", len(errs))
}
fmt.Printf("active = %v, length = %v, ids = %v", opts.Active, length, opts.I | Binder(c)
errs := b.Int64("length", &length).
Int64s("ids", &opts.IDs).
Bool("active", &opts.Active).
BindErrors() // returns all errors
if errs != nil {
for _, err := range errs {
bErr := err.(*echo.BindingE | {
"filepath": "binder_external_test.go",
"language": "go",
"file_size": 3889,
"cut_index": 614,
"middle_length": 229
} |
g time.Time values
type TimeOpts struct {
// Layout specifies the format for parsing time values in request parameters.
// It can be a standard Go time layout string or one of the special Unix time layouts.
//
// Parsing layout defaults to: echo.TimeLayout(time.RFC3339Nano)
// - To convert to custom layout use `ec... | timezone information to set output time in given location.
// Defaults to time.UTC
ParseInLocation *time.Location
// ToInLocation is location to which parsed time is converted to after parsing.
// The parsed time will be converted using time.In(ToInL | outUnixTimeMilli`
// - To convert unix timestamp in nanoseconds to time.Time use `echo.TimeLayoutUnixTimeNano`
Layout TimeLayout
// ParseInLocation is location used with time.ParseInLocation for layout that do not contain
// | {
"filepath": "binder_generic.go",
"language": "go",
"file_size": 16934,
"cut_index": 921,
"middle_length": 229
} |
c := createTestContext(tc.whenURL, nil, map[string]string{"id": "999"})
b := QueryParamsBinder(c).FailFast(tc.givenFailFast)
id := int64(99)
nr := int64(88)
errs := b.Int64("id", &id).
Int64("nr", &nr).
BindErrors()
assert.Len(t, errs, len(tc.expectError))
for _, err := range errs {
asser... | req, rec)
b := FormFieldBinder(c)
var texta string
id := int64(99)
nr := int64(88)
var slice = make([]int64, 0)
var notExisting = make([]int64, 0)
err := b.
Int64s("slice", &slice).
Int64("id", &id).
Int64("nr", &nr).
String("texta", &text | search?id=1&nr=2&slice=3&slice=4", strings.NewReader(body))
req.Header.Set(HeaderContentLength, strconv.Itoa(len(body)))
req.Header.Set(HeaderContentType, MIMEApplicationForm)
rec := httptest.NewRecorder()
c := e.NewContext( | {
"filepath": "binder_test.go",
"language": "go",
"file_size": 95170,
"cut_index": 3790,
"middle_length": 229
} |
emory int64 = 32 << 20 // 32 MB
indexPage = "index.html"
)
// Context represents the context of the current HTTP request. It holds request and
// response objects, path, path parameters, data and registered handler.
type Context struct {
request *http.Request
orgResponse *Response
response http.Re... | nyway
// these arguments are useful when creating context for tests and cases like that.
func NewContext(r *http.Request, w http.ResponseWriter, opts ...any) *Context {
var e *Echo
for _, opt := range opts {
switch v := opt.(type) {
case *Echo:
e | string]any
echo *Echo
logger *slog.Logger
path string
lock sync.RWMutex
}
// NewContext returns a new Context instance.
//
// Note: request,response and e can be left to nil as Echo.ServeHTTP will call c.Reset(req,resp) a | {
"filepath": "context.go",
"language": "go",
"file_size": 21433,
"cut_index": 1331,
"middle_length": 229
} |
nse-Identifier: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
package echo
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestContextGetOK(t *testing.T) {
c := NewContext(nil, nil)
c.Set("key", int64(123))
v, err := ContextGet[int64](c, "key")
assert.NoError(t, err... | ErrInvalidKeyType)
assert.Equal(t, false, v)
}
func TestContextGetOrOK(t *testing.T) {
c := NewContext(nil, nil)
c.Set("key", int64(123))
v, err := ContextGetOr[int64](c, "key", 999)
assert.NoError(t, err)
assert.Equal(t, int64(123), v)
}
func T | rorIs(t, err, ErrNonExistentKey)
assert.Equal(t, int64(0), v)
}
func TestContextGetInvalidCast(t *testing.T) {
c := NewContext(nil, nil)
c.Set("key", int64(123))
v, err := ContextGet[bool](c, "key")
assert.ErrorIs(t, err, | {
"filepath": "context_generic_test.go",
"language": "go",
"file_size": 1455,
"cut_index": 524,
"middle_length": 229
} |
wardedFor: []string{"127.0.0.1, 127.0.1.1, "}},
}}
for i := 0; i < b.N; i++ {
c.RealIP()
}
}
func (t *Template) Render(c *Context, w io.Writer, name string, data any) error {
return t.templates.ExecuteTemplate(w, name, data)
}
func TestContextEcho(t *testing.T) {
e := New()
req := httptest.NewRequest(http.Met... | nse(t *testing.T) {
e := New()
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(userJSON))
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
assert.NotNil(t, c.Response())
}
func TestContextRenderTemplate(t *testing.T) {
| eq := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(userJSON))
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
assert.NotNil(t, c.Request())
assert.Equal(t, req, c.Request())
}
func TestContextRespo | {
"filepath": "context_test.go",
"language": "go",
"file_size": 39529,
"cut_index": 2151,
"middle_length": 229
} |
"errors"
"fmt"
"io/fs"
"log/slog"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"syscall"
)
// Echo is the top-level framework instance.
//
// Goroutine safety: Do not mutate Echo instance fields after server has started. Accessing these
// fields from handlers/middle... | .Open() already assumes that file names are relative to FS root path and considers name with prefix `/` as invalid
// so if you have `fs := os.DirFS("/tmp")` and you try to `fs.Open("/tmp/file.txt")` it will fail, but "file.txt"
// would succeed. `echo.N | e Echo struct {
serveHTTPFunc func(http.ResponseWriter, *http.Request)
Binder Binder
// Filesystem is the file system used for serving static files. Defaults to the current working directory (os.Getwd()).
//
// Note: fs.FS | {
"filepath": "echo.go",
"language": "go",
"file_size": 32080,
"cut_index": 1331,
"middle_length": 229
} |
It can be used for inner
// routes that share a common middleware or functionality that should be separate
// from the parent echo instance while still inheriting from it.
type Group struct {
echo *Echo
prefix string
middleware []MiddlewareFunc
}
// Use implements `Echo#Use()` for sub-routes within the Gr... | )
}
// DELETE implements `Echo#DELETE()` for sub-routes within the Group. Panics on error.
func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo {
return g.Add(http.MethodDelete, path, h, m...)
}
// GET implements `Echo#GET() | ...)
}
// CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. Panics on error.
func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo {
return g.Add(http.MethodConnect, path, h, m... | {
"filepath": "group.go",
"language": "go",
"file_size": 6999,
"cut_index": 716,
"middle_length": 229
} |
code by implementing HTTPStatusCoder interface
var (
ErrBadRequest = &httpError{http.StatusBadRequest} // 400
ErrUnauthorized = &httpError{http.StatusUnauthorized} // 401
ErrForbidden = &httpError{http.StatusForbidden} // 403
ErrNotF... |
ErrTooManyRequests = &httpError{http.StatusTooManyRequests} // 429
ErrInternalServerError = &httpError{http.StatusInternalServerError} // 500
ErrBadGateway = &httpError{http.StatusBadGateway} // 5 | = &httpError{http.StatusRequestTimeout} // 408
ErrStatusRequestEntityTooLarge = &httpError{http.StatusRequestEntityTooLarge} // 413
ErrUnsupportedMediaType = &httpError{http.StatusUnsupportedMediaType} // 415 | {
"filepath": "httperror.go",
"language": "go",
"file_size": 5278,
"cut_index": 716,
"middle_length": 229
} |
SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
// run tests as external package to get real feel for API
package echo_test
import (
"encoding/json"
"fmt"
"github.com/labstack/echo/v5"
"net/http"
"net/http/httptest"
)
func ExampleDefaultHTTPErrorHandler() {
e :... | pe apiError struct {
Code int
Body any
}
func (e *apiError) StatusCode() int {
return e.Code
}
func (e *apiError) MarshalJSON() ([]byte, error) {
type body struct {
Error any `json:"error"`
}
return json.Marshal(body{Error: e.Body})
}
func (e *a | test.NewRequest(http.MethodGet, "/api/endpoint?err=1", nil)
resp := httptest.NewRecorder()
e.ServeHTTP(resp, req)
fmt.Printf("%d %s", resp.Code, resp.Body.String())
// Output: 400 {"error":{"message":"custom error"}}
}
ty | {
"filepath": "httperror_external_test.go",
"language": "go",
"file_size": 1061,
"cut_index": 515,
"middle_length": 229
} |
utesWillNotExecuteMiddlewareFor404(t *testing.T) {
e := New()
called := false
mw := func(next HandlerFunc) HandlerFunc {
return func(c *Context) error {
called = true
return c.NoContent(http.StatusTeapot)
}
}
// even though group has middleware and routes when we have no match on some route the middlewa... | vate", func(c *Context) error {
return c.String(http.StatusTeapot, "OK")
})
status, body := request(http.MethodGet, "/api/users/activate", e)
assert.Equal(t, http.StatusTeapot, status)
assert.Equal(t, `OK`, body)
}
func TestGroupFile(t *testing.T) | ound, status)
assert.Equal(t, `{"message":"Not Found"}`+"\n", body)
assert.False(t, called)
}
func TestGroup_multiLevelGroup(t *testing.T) {
e := New()
api := e.Group("/api")
users := api.Group("/users")
users.GET("/acti | {
"filepath": "group_test.go",
"language": "go",
"file_size": 23556,
"cut_index": 1331,
"middle_length": 229
} |
ol, auditing, geo-based access analysis and more.
Echo provides handy method [`Context#RealIP()`](https://godoc.org/github.com/labstack/echo#Context) for that.
However, it is not trivial to retrieve the _real_ IP address from requests especially when you put L7 proxies before the application.
In such situation, _real_... | ow you why and how.
> Note: if you don't set `Echo#IPExtractor` explicitly, Echo fallback to legacy behavior, which is not a good choice.
Let's start from two questions to know the right direction:
1. Do you put any HTTP (L7) proxy in front of the appli | isk!**
To retrieve IP address reliably/securely, you must let your application be aware of the entire architecture of your infrastructure.
In Echo, this can be done by configuring `Echo#IPExtractor` appropriately.
This guides sh | {
"filepath": "ip.go",
"language": "go",
"file_size": 11190,
"cut_index": 921,
"middle_length": 229
} |
SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
package echo
import (
"encoding/json"
)
// DefaultJSONSerializer implements JSON encoding using encoding/json.
type DefaultJSONSerializer struct{}
// Serialize converts an interface into a json and writes it to the response.
// You can optionally us... | arget)
}
// Deserialize reads a JSON from a request body and converts it into an interface.
func (d DefaultJSONSerializer) Deserialize(c *Context, target any) error {
if err := json.NewDecoder(c.Request().Body).Decode(target); err != nil {
return ErrBa |
enc.SetIndent("", indent)
}
return enc.Encode(t | {
"filepath": "json.go",
"language": "go",
"file_size": 892,
"cut_index": 547,
"middle_length": 52
} |
tack LLC and Echo contributors
package echo
import "io"
// Renderer is the interface that wraps the Render function.
type Renderer interface {
Render(c *Context, w io.Writer, templateName string, data any) error
}
// TemplateRenderer is helper to ease creating renderers for `html/template` and `text/template` pack... | e("Hello, {{.}}!")),
// }
type TemplateRenderer struct {
Template interface {
ExecuteTemplate(wr io.Writer, name string, data any) error
}
}
// Render renders the template with given data.
func (t *TemplateRenderer) Render(c *Context, w io.Writer, na | Template: template.Must(template.New("hello").Pars | {
"filepath": "renderer.go",
"language": "go",
"file_size": 972,
"cut_index": 582,
"middle_length": 52
} |
00:0000:0000:0000:0000:0103
// Range start: 2001:0db8:0000:0000:0000:0000:0000:0000
// Range end: 2001:0db8:0000:ffff:ffff:ffff:ffff:ffff
TrustIPRange(mustParseCIDR("2001:db8::103/48")),
},
whenIP: "2001:0db8:0000:0000:0000:0000:0000:0103",
expect: true,
},
{
name: "ip is within trust r... |
})
}
}
func TestTrustIPRange(t *testing.T) {
var testCases = []struct {
name string
givenRange string
whenIP string
expect bool
}{
{
name: "ip is within trust range, IPV6 network range",
// CIDR Notation: 2001:0db8:0000 | expect: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
checker := newIPChecker(tc.givenOptions)
result := checker.trust(net.ParseIP(tc.whenIP))
assert.Equal(t, tc.expect, result) | {
"filepath": "ip_test.go",
"language": "go",
"file_size": 23690,
"cut_index": 1331,
"middle_length": 229
} |
n http.ResponseWriter and implements its interface to be used
// by an HTTP handler to construct an HTTP response.
// See: https://golang.org/pkg/net/http/#ResponseWriter
type Response struct {
http.ResponseWriter
logger *slog.Logger
// beforeFuncs are functions that are called just before the response (status) is w... | ter: w, logger: logger}
}
// Before registers a function which is called just before the response (status) is written.
func (r *Response) Before(fn func()) {
r.beforeFuncs = append(r.beforeFuncs, fn)
}
// After registers a function which is called just | terFuncs []func()
Status int
Size int64
Committed bool
}
// NewResponse creates a new instance of Response.
func NewResponse(w http.ResponseWriter, logger *slog.Logger) (r *Response) {
return &Response{ResponseWri | {
"filepath": "response.go",
"language": "go",
"file_size": 5614,
"cut_index": 716,
"middle_length": 229
} |
htText: © 2015 LabStack LLC and Echo contributors
package echo
import (
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// Note this test is deliberately simple as there's not a lot to test.
// Just need to ensure it writes JSONs. The heavy work is done by the context m... | e(c, user{ID: 1, Name: "Jon Snow"}, "")
if assert.NoError(t, err) {
assert.Equal(t, userJSON+"\n", rec.Body.String())
}
req = httptest.NewRequest(http.MethodPost, "/", nil)
rec = httptest.NewRecorder()
c = e.NewContext(req, rec)
err = enc.Serializ | o
assert.Equal(t, e, c.Echo())
// Request
assert.NotNil(t, c.Request())
// Response
assert.NotNil(t, c.Response())
//--------
// Default JSON encoder
//--------
enc := new(DefaultJSONSerializer)
err := enc.Serializ | {
"filepath": "json_test.go",
"language": "go",
"file_size": 2742,
"cut_index": 563,
"middle_length": 229
} |
package echo
import (
"bytes"
"errors"
"fmt"
"reflect"
"runtime"
)
// Route contains information to adding/registering new route with the router.
// Method+Path pair uniquely identifies the Route. It is mandatory to provide Method+Path+Handler fields.
type Route struct {
Method string
Path string
... | dded group prefix and group middlewares it is grouped to.
func (r Route) WithPrefix(pathPrefix string, middlewares []MiddlewareFunc) Route {
r.Path = pathPrefix + r.Path
if len(middlewares) > 0 {
m := make([]MiddlewareFunc, 0, len(middlewares)+len(r.M | if name == "" {
name = r.Method + ":" + r.Path
}
return RouteInfo{
Method: r.Method,
Path: r.Path,
Parameters: append([]string(nil), params...),
Name: name,
}
}
// WithPrefix recreates Route with a | {
"filepath": "route.go",
"language": "go",
"file_size": 5051,
"cut_index": 614,
"middle_length": 229
} |
with the Router and returns registered RouteInfo.
//
// Router may change Route.Path value in returned RouteInfo.Path.
// Router generates RouteInfo.Parameters values from Route.Path.
// Router generates RouteInfo.Name value if it is not provided.
Add(routable Route) (RouteInfo, error)
// Remove removes route fr... |
// handler function.
//
// Router must populate Context during Router.Route call with:
// - Context.InitializeRoute() (IMPORTANT! to reduce allocations use same slice that c.PathValues() returns)
// - optionally can set additional information to Cont | // Route searches Router for matching route and applies it to the given context. In case when no matching method
// was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404 | {
"filepath": "router.go",
"language": "go",
"file_size": 31612,
"cut_index": 1331,
"middle_length": 229
} |
th: "/initial1",
Handler: handlerFunc,
})
assert.NoError(t, err)
assert.Equal(t, len(router.Routes()), 1)
err = router.Remove(http.MethodGet, "/initial1")
assert.NoError(t, err)
assert.Equal(t, len(router.Routes()), 0)
}
func TestConcurrentRouter_ConcurrentReads(t *testing.T) {
router := NewConcurrentRout... | Int64
numGoroutines := 10
routeCallsPerGoroutine := 50
routesCallsPerGoroutine := 20
for i := range numGoroutines {
wg.Add(1)
go func(goroutineID int) {
defer wg.Done()
// Call Route() 50 times
for j := range routeCallsPerGoroutine {
| thodGet,
Path: path,
Handler: handlerFunc,
})
if err != nil {
t.Fatal(err)
}
}
// Launch 10 goroutines for concurrent reads
var wg sync.WaitGroup
var routeCallCount atomic.Int64
var routesCallCount atomic. | {
"filepath": "router_concurrent_test.go",
"language": "go",
"file_size": 9843,
"cut_index": 921,
"middle_length": 229
} |
/gopher/bumper320x180.png", ""},
{"GET", "/gopher/bumper480x270.png", ""},
{"GET", "/gopher/bumper640x360.png", ""},
{"GET", "/gopher/doc.png", ""},
{"GET", "/gopher/frontpage.png", ""},
{"GET", "/gopher/gopherbw.png", ""},
{"GET", "/gopher/gophercolor.png", ""},
{"GET", "/gopher/gophercolor16x16.png", ""... | pherrunning.jpg", ""},
{"GET", "/gopher/pencil/gopherswim.jpg", ""},
{"GET", "/gopher/pencil/gopherswrench.jpg", ""},
{"GET", "/play/", ""},
{"GET", "/play/fib.go", ""},
{"GET", "/play/hello.go", ""},
{"GET", "/play/life.go", ""},
{"GET", "/p | pher/talks.png", ""},
{"GET", "/gopher/pencil/", ""},
{"GET", "/gopher/pencil/gopherhat.jpg", ""},
{"GET", "/gopher/pencil/gopherhelmet.jpg", ""},
{"GET", "/gopher/pencil/gophermega.jpg", ""},
{"GET", "/gopher/pencil/go | {
"filepath": "router_test.go",
"language": "go",
"file_size": 105029,
"cut_index": 3790,
"middle_length": 229
} |
c(c *Context) error {
return nil
}
tmp := NameStruct{}
var testCases = []struct {
name string
whenHandlerFunc HandlerFunc
expect string
}{
{
name: "ok, func as anonymous func",
whenHandlerFunc: func(c *Context) error {
return nil
},
expect: "github.com/labstack/echo/v... | d",
whenHandlerFunc: tmp.getUsers,
expect: "github.com/labstack/echo/v5.(*NameStruct).getUsers-fm",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
name := HandlerName(tc.whenHandlerFunc)
assert.Equal(t, | },
{
name: "ok, func as named function variable",
whenHandlerFunc: myNameFuncVar,
expect: "github.com/labstack/echo/v5.TestHandlerName.func1",
},
{
name: "ok, func as struct metho | {
"filepath": "route_test.go",
"language": "go",
"file_size": 12151,
"cut_index": 921,
"middle_length": 229
} |
"
"net"
"net/http"
"os"
"sync"
"time"
)
const (
banner = "Echo (v%s). High performance, minimalist Go web framework https://echo.labstack.com"
)
// StartConfig is for creating configured http.Server instance to start serve http(s) requests with given Echo instance
type StartConfig struct {
// Address specifies... |
// TLSConfig is used to configure TLS. If Listener is set, TLSConfig is not used to create the listener.
TLSConfig *tls.Config
// Listener is used to start server with the custom listener.
Listener net.Listener
// ListenerNetwork is used configure | bool
// HidePort instructs Start* method not to print port when starting the Server.
HidePort bool
// CertFilesystem is filesystem is used to read `certFile` and `keyFile` when StartTLS method is called.
CertFilesystem fs.FS | {
"filepath": "server.go",
"language": "go",
"file_size": 6290,
"cut_index": 716,
"middle_length": 229
} |
/ NewConcurrentRouter creates concurrency safe Router which routes can be added/removed safely
// even after http.Server has been started.
func NewConcurrentRouter(r Router) Router {
return &concurrentRouter{
mu: sync.RWMutex{},
router: r,
}
}
type concurrentRouter struct {
mu sync.RWMutex
router Route... | )
}
func (r *concurrentRouter) Add(routable Route) (RouteInfo, error) {
r.mu.Lock()
defer r.mu.Unlock()
return r.router.Add(routable)
}
func (r *concurrentRouter) Remove(method string, path string) error {
r.mu.Lock()
defer r.mu.Unlock()
return r | fer r.mu.RUnlock()
return r.router.Routes().Clone( | {
"filepath": "router_concurrent.go",
"language": "go",
"file_size": 886,
"cut_index": 547,
"middle_length": 52
} |
package echo
import (
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
)
func TestVirtualHostHandler(t *testing.T) {
okHandler := func(c *Context) error { return c.String(http.StatusOK, http.StatusText(http.StatusOK)) }
teapotHandler := func(c *Context) error { return c.String(http.... | middle := New()
middle.Use(teapotMiddleware)
middle.GET("/", okHandler)
middle.GET("/foo", okHandler)
virtualHosts := NewVirtualHostHandler(map[string]*Echo{
"ok.com": ok,
"teapot.com": teapot,
"middleware.com": middle,
})
virtualH | MiddlewareFunc(func(next HandlerFunc) HandlerFunc { return teapotHandler })
ok := New()
ok.GET("/", okHandler)
ok.GET("/foo", okHandler)
teapot := New()
teapot.GET("/", teapotHandler)
teapot.GET("/foo", teapotHandler)
| {
"filepath": "vhost_test.go",
"language": "go",
"file_size": 3125,
"cut_index": 614,
"middle_length": 229
} |
test"
"strings"
"testing"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/assert"
)
func TestBasicAuth(t *testing.T) {
validatorFunc := func(c *echo.Context, u, p string) (bool, error) {
// Use constant-time comparison to prevent timing attacks
userMatch := subtle.ConstantTimeCompare([]byte(u), []... | nAuth []string
expectHeader string
expectErr string
}{
{
name: "ok",
givenConfig: defaultConfig,
whenAuth: []string{basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))},
},
{
name: "ok, multi | ng
if u == "error" {
return false, errors.New(p)
}
return false, nil
}
defaultConfig := BasicAuthConfig{Validator: validatorFunc}
var testCases = []struct {
name string
givenConfig BasicAuthConfig
whe | {
"filepath": "middleware/basic_auth_test.go",
"language": "go",
"file_size": 7043,
"cut_index": 716,
"middle_length": 229
} |
wReader(hw))
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
h := func(c *echo.Context) error {
body, err := io.ReadAll(c.Request().Body)
if err != nil {
return err
}
return c.String(http.StatusOK, string(body))
}
requestBody := ""
responseBody := ""
mw, err := BodyDumpConfig{Handler: func(... | isCalled := false
mw, err := BodyDumpConfig{
Skipper: func(c *echo.Context) bool {
return true
},
Handler: func(c *echo.Context, reqBody, resBody []byte, err error) {
isCalled = true
},
}.ToMiddleware()
assert.NoError(t, err)
req := http | c)) {
assert.Equal(t, requestBody, hw)
assert.Equal(t, responseBody, hw)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, hw, rec.Body.String())
}
}
func TestBodyDump_skipper(t *testing.T) {
e := echo.New()
| {
"filepath": "middleware/body_dump_test.go",
"language": "go",
"file_size": 16736,
"cut_index": 921,
"middle_length": 229
} |
htText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"io"
"net/http"
"sync"
"github.com/labstack/echo/v5"
)
// BodyLimitConfig defines the config for BodyLimitWithConfig middleware.
type BodyLimitConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Li... | both `Content-Length` request
// header and actual content read, which makes it super secure.
func BodyLimit(limitBytes int64) echo.MiddlewareFunc {
return BodyLimitWithConfig(BodyLimitConfig{LimitBytes: limitBytes})
}
// BodyLimitWithConfig returns a B | yLimit middleware.
//
// BodyLimit middleware sets the maximum allowed size for a request body, if the size exceeds the configured limit, it
// sends "413 - Request Entity Too Large" response. The BodyLimit is determined based on | {
"filepath": "middleware/body_limit.go",
"language": "go",
"file_size": 2752,
"cut_index": 563,
"middle_length": 229
} |
trings"
"sync"
"github.com/labstack/echo/v5"
)
const (
gzipScheme = "gzip"
)
// GzipConfig defines the config for Gzip middleware.
type GzipConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Gzip compression level.
// Optional. Default value -1.
Level int
// Length thresh... |
//
// See also:
// https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
MinLength int
}
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
wroteHeader bool
wr | nsmitted data because of the
// gzip format overhead. Compressing the response will also consume CPU
// and time on the server and the client (for decompressing). Depending on
// your use case such a threshold might be useful. | {
"filepath": "middleware/compress.go",
"language": "go",
"file_size": 6272,
"cut_index": 716,
"middle_length": 229
} |
m/labstack/echo/v5"
)
// BodyDumpConfig defines the config for BodyDump middleware.
type BodyDumpConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Handler receives request, response payloads and handler error if there are any.
// Required.
Handler BodyDumpHandler
// MaxReques... | limit, only the first MaxResponseBytes
// are dumped. The handler callback receives truncated data.
// Default: 5 * MB (5,242,880 bytes)
// Set to -1 to disable limits (not recommended in production).
MaxResponseBytes int64
}
// BodyDumpHandler receiv | Default: 5 * MB (5,242,880 bytes)
// Set to -1 to disable limits (not recommended in production).
MaxRequestBytes int64
// MaxResponseBytes limits how much of the response body to dump.
// If the response body exceeds this | {
"filepath": "middleware/body_dump.go",
"language": "go",
"file_size": 5642,
"cut_index": 716,
"middle_length": 229
} |
package middleware
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/assert"
)
func TestBodyLimitConfig_ToMiddleware(t *testing.T) {
e := echo.New()
hw := []byte("Hello, World!")
req := httptest.NewRequest(http.MethodPost, "/", bytes.N... | sert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, hw, rec.Body.Bytes())
}
// Based on content read (overlimit)
mw, err = BodyLimitConfig{LimitBytes: 2}.ToMiddleware()
assert.NoError(t, err)
he := mw(h)(c).(echo.HTTPStatusCoder)
assert.Equal(t | return c.String(http.StatusOK, string(body))
}
// Based on content length (within limit)
mw, err := BodyLimitConfig{LimitBytes: 2 * MB}.ToMiddleware()
assert.NoError(t, err)
err = mw(h)(c)
if assert.NoError(t, err) {
as | {
"filepath": "middleware/body_limit_test.go",
"language": "go",
"file_size": 4379,
"cut_index": 614,
"middle_length": 229
} |
package middleware
import (
"bytes"
"cmp"
"encoding/base64"
"errors"
"strconv"
"strings"
"github.com/labstack/echo/v5"
)
// BasicAuthConfig defines the config for BasicAuthWithConfig middleware.
//
// SECURITY: The Validator function is responsible for securely comparing credentials.
// See BasicAuthValidator... | // Realm is a string to define realm attribute of BasicAuthWithConfig.
// Default value "Restricted".
Realm string
// AllowedCheckLimit set how many headers are allowed to be checked. This is useful
// environments like corporate test environments wi | date BasicAuthWithConfig credentials. Note: if request contains multiple basic auth headers
// this function would be called once for each header until first valid result is returned
// Required.
Validator BasicAuthValidator
| {
"filepath": "middleware/basic_auth.go",
"language": "go",
"file_size": 4936,
"cut_index": 614,
"middle_length": 229
} |
r: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"context"
"errors"
"time"
"github.com/labstack/echo/v5"
)
// ContextTimeoutConfig defines the config for ContextTimeout middleware.
type ContextTimeoutConfig struct {
// Skipper defines a function to skip mi... | imeout time.Duration) echo.MiddlewareFunc {
return ContextTimeoutWithConfig(ContextTimeoutConfig{Timeout: timeout})
}
// ContextTimeoutWithConfig returns a Timeout middleware with config.
func ContextTimeoutWithConfig(config ContextTimeoutConfig) echo.Mi | the middleware
Timeout time.Duration
}
// ContextTimeout returns a middleware which returns error (503 Service Unavailable error) to client
// when underlying method returns context.DeadlineExceeded error.
func ContextTimeout(t | {
"filepath": "middleware/context_timeout.go",
"language": "go",
"file_size": 2000,
"cut_index": 537,
"middle_length": 229
} |
Access-Control-Allow-Origin
// response header. This header defines a list of origins that may access the
// resource.
//
// Origin consist of following parts: `scheme + "://" + host + optional ":" + port`
// Wildcard can be used, but has to be set explicitly []string{"*"}
// Example: `https://example.com`, `ht... | // UnsafeAllowOriginFunc is an optional custom function to validate the origin. It takes the
// origin as an argument and returns
// - string, allowed origin
// - bool, true if allowed or false otherwise.
// - error, if an error is returned, it is retu | See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
//
// Mandatory.
AllowOrigins []string
| {
"filepath": "middleware/cors.go",
"language": "go",
"file_size": 12043,
"cut_index": 921,
"middle_length": 229
} |
n value that can be used to render CSRF token for form by handlers.
//
// We know that the client is using a browser that supports Sec-Fetch-Site header, so when the form is submitted in
// the future with this dummy token value it is OK. Although the request is safe, the template rendered by the
// handler may need th... | gin header "scheme://host[:port]".
//
// See [Origin]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
// See [Sec-Fetch-Site]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#fetch- | pper defines a function to skip middleware.
Skipper Skipper
// TrustedOrigins permits any request with `Sec-Fetch-Site` header whose `Origin` header
// exactly matches a configured origin.
// Values should be formatted as Ori | {
"filepath": "middleware/csrf.go",
"language": "go",
"file_size": 10485,
"cut_index": 921,
"middle_length": 229
} |
package middleware
import (
"compress/gzip"
"io"
"net/http"
"sync"
"github.com/labstack/echo/v5"
)
// DecompressConfig defines the config for Decompress middleware.
type DecompressConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// GzipDecompressPool defines an interface to ... | ble limits (not recommended in production).
MaxDecompressedSize int64
}
// GZIPEncoding content-encoding header if set to "gzip", decompress body contents.
const GZIPEncoding string = "gzip"
// Decompressor is used to get the sync.Pool used by the middl | mpressed body exceeds this limit, the middleware returns HTTP 413 error.
// This prevents zip bomb attacks where small compressed payloads decompress to huge sizes.
// Default: 100 * MB (104,857,600 bytes)
// Set to -1 to disa | {
"filepath": "middleware/decompress.go",
"language": "go",
"file_size": 4679,
"cut_index": 614,
"middle_length": 229
} |
st (
// extractorLimit is arbitrary number to limit values extractor can return. this limits possible resource exhaustion
// attack vector
extractorLimit = 20
)
// ExtractorSource is type to indicate source for extracted value
type ExtractorSource string
const (
// ExtractorSourceHeader means value was extracted ... | eCookie ExtractorSource = "cookie"
// ExtractorSourceForm means value was extracted from request form values
ExtractorSourceForm ExtractorSource = "form"
)
// ValueExtractorError is error type when middleware extractor is unable to extract value from lo | query"
// ExtractorSourcePathParam means value was extracted from route path parameters
ExtractorSourcePathParam ExtractorSource = "param"
// ExtractorSourceCookie means value was extracted from request cookies
ExtractorSourc | {
"filepath": "middleware/extractor.go",
"language": "go",
"file_size": 8474,
"cut_index": 716,
"middle_length": 229
} |
p/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestContextTimeoutSkipper(t *testing.T) {
t.Parallel()
m := ContextTimeoutWithConfig(ContextTimeoutConfig{
Skipper: func(context *echo.Context) bool {
return true
},
Timeout: 10 * time.Millisecond,
})
req :... | ssert.EqualError(t, err, "response from handler")
}
func TestContextTimeoutWithTimeout0(t *testing.T) {
t.Parallel()
assert.Panics(t, func() {
ContextTimeout(time.Duration(0))
})
}
func TestContextTimeoutErrorOutInHandler(t *testing.T) {
t.Parallel | ext(c.Request().Context(), time.Duration(20*time.Millisecond)); err != nil {
return err
}
return errors.New("response from handler")
})(c)
// if not skipped we would have not returned error due context timeout logic
a | {
"filepath": "middleware/context_timeout_test.go",
"language": "go",
"file_size": 6301,
"cut_index": 716,
"middle_length": 229
} |
nLookup: "header:X-CSRF-Token,form:csrf",
givenCSRFCookie: "token",
givenMethod: http.MethodPost,
givenHeaderTokens: map[string][]string{
echo.HeaderXCSRFToken: {"invalid_token"},
},
givenFormTokens: map[string][]string{
"csrf": {"token"},
},
},
{
name: "ok, token from PO... | "token"},
},
expectError: "code=403, message=invalid csrf token",
},
{
name: "nok, invalid token from POST form",
whenTokenLookup: "form:csrf",
givenCSRFCookie: "token",
givenMethod: http.MethodPost,
givenFormTokens: | ame: "ok, token from POST form, second token passes",
whenTokenLookup: "form:csrf",
givenCSRFCookie: "token",
givenMethod: http.MethodPost,
givenFormTokens: map[string][]string{
"csrf": {"invalid", | {
"filepath": "middleware/csrf_test.go",
"language": "go",
"file_size": 25419,
"cut_index": 1331,
"middle_length": 229
} |
{
c.Response().Write([]byte("test")) // For Content-Type sniffing
return nil
})
// Decompress request body
body := `{"name": "echo"}`
gz, _ := gzipString(body)
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(string(gz)))
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
rec := htt... | NewRecorder()
c := e.NewContext(req, rec)
// Skip if no Content-Encoding header
h := Decompress()(func(c *echo.Context) error {
c.Response().Write([]byte("test")) // For Content-Type sniffing
return nil
})
err := h(c)
assert.NoError(t, err)
as | y)
assert.NoError(t, err)
assert.Equal(t, body, string(b))
}
func TestDecompress_skippedIfNoHeader(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("test"))
rec := httptest. | {
"filepath": "middleware/decompress_test.go",
"language": "go",
"file_size": 13852,
"cut_index": 921,
"middle_length": 229
} |
ses = []struct {
name string
givenConfig *CORSConfig
whenMethod string
whenHeaders map[string]string
expectHeaders map[string]string
notExpectHeaders map[string]string
expectErr string
}{
{
name: "ok, wildcard origin",
givenConfig: &CORSConfig{
AllowOrigi... | "ok, specific AllowOrigins and AllowCredentials",
givenConfig: &CORSConfig{
AllowOrigins: []string{"http://localhost", "http://localhost:8080"},
AllowCredentials: true,
MaxAge: 3600,
},
whenHeaders: map[string]string{echo | ok, wildcard AllowedOrigin with no Origin header in request",
givenConfig: &CORSConfig{
AllowOrigins: []string{"*"},
},
notExpectHeaders: map[string]string{echo.HeaderAccessControlAllowOrigin: ""},
},
{
name: | {
"filepath": "middleware/cors_test.go",
"language": "go",
"file_size": 20362,
"cut_index": 1331,
"middle_length": 229
} |
KeyAuthConfig defines the config for KeyAuth middleware.
//
// SECURITY: The Validator function is responsible for securely comparing API keys.
// See KeyAuthValidator documentation for guidance on preventing timing attacks.
type KeyAuthConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skippe... | uthorization: <auth-scheme> <authorisation-parameters>` where part that we
// want to cut is `<auth-scheme> ` note the space at the end.
// In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `.
// | zation".
// Possible values:
// - "header:<name>" or "header:<name>:<cut-prefix>"
// `<cut-prefix>` is argument value to cut/trim prefix of the extracted value. This is useful if header
// value has static prefix like `A | {
"filepath": "middleware/key_auth.go",
"language": "go",
"file_size": 7504,
"cut_index": 716,
"middle_length": 229
} |
htText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"net/http"
"github.com/labstack/echo/v5"
)
// MethodOverrideConfig defines the config for MethodOverride middleware.
type MethodOverrideConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Getter is a... | ethodOverrideConfig{
Skipper: DefaultSkipper,
Getter: MethodFromHeader(echo.HeaderXHTTPMethodOverride),
}
// MethodOverride returns a MethodOverride middleware.
// MethodOverride middleware checks for the overridden method from the request and
// uses | s a function that gets overridden method from the request
type MethodOverrideGetter func(c *echo.Context) string
// DefaultMethodOverrideConfig is the default MethodOverride middleware config.
var DefaultMethodOverrideConfig = M | {
"filepath": "middleware/method_override.go",
"language": "go",
"file_size": 2891,
"cut_index": 563,
"middle_length": 229
} |
htText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"net/http"
"regexp"
"strconv"
"strings"
"github.com/labstack/echo/v5"
)
// Skipper defines a function to skip middleware. Returning true skips processing the middleware.
type Skipper func(c *echo.Context) bool
// BeforeFunc defines ... | ] = v
}
return strings.NewReplacer(replace...)
}
func rewriteRulesRegex(rewrite map[string]string) map[*regexp.Regexp]string {
// Initialize
rulesRegex := map[*regexp.Regexp]string{}
for k, v := range rewrite {
k = regexp.QuoteMeta(k)
k = strings | FindAllStringSubmatch(input, -1)
if groups == nil {
return nil
}
values := groups[0][1:]
replace := make([]string, 2*len(values))
for i, v := range values {
j := 2 * i
replace[j] = "$" + strconv.Itoa(i+1)
replace[j+1 | {
"filepath": "middleware/middleware.go",
"language": "go",
"file_size": 2399,
"cut_index": 563,
"middle_length": 229
} |
e ProxyConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Balancer defines a load balancing technique.
// Required.
Balancer ProxyBalancer
// RetryCount defines the number of times a failed proxied request should be retried
// using the next available ProxyTarget. Defaults to ... | t is unavailable, the error will be an instance of
// echo.HTTPError with a code of http.StatusBadGateway. In all other cases, the error
// will indicate an internal error in the Proxy middleware. When a RetryFilter is not
// specified, all requests tha | ly be called when the number
// of previous retries is less than RetryCount. If the function returns true, the
// request will be retried. The provided error indicates the reason for the request
// failure. When the ProxyTarge | {
"filepath": "middleware/proxy.go",
"language": "go",
"file_size": 14718,
"cut_index": 921,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.